Department of Information Technology
Semester B.E. Semester VIII – INFT (A)
Subject BC & DLT
Laboratory Teacher Prof. VINITA BHANDIWAD
Student Name Jay Patil
Roll Number 21101A0062
Assignment 02
Theory
Structure of a Block in Blockchain
A block in a blockchain is a fundamental unit that stores transaction data and other critical information in a
secure and immutable manner. Each block is linked to the previous block, forming a continuous chain. The
structure of a block generally consists of the following key components:
1. Block Header
The block header contains metadata about the block and ensures the integrity of the blockchain. It includes:
Previous Block Hash: A cryptographic hash of the previous block, ensuring a secure link between
blocks.
Merkle Root: A hash representing all transactions in the block, allowing efficient verification.
Timestamp: The exact time when the block was created.
Nonce: A number used in the mining process to find a valid block hash.
Difficulty Target: The difficulty level that determines how hard it is to mine a new block.
Version Number: Specifies the protocol version of the blockchain.
2. Block Body
The block body contains the actual data of the block:
Transactions: A list of all transactions included in the block. Each transaction contains:
o Sender and receiver addresses
o Transaction amount
o Digital signatures
o Unique transaction ID (hash)
3. Block Hash
The block hash is a unique identifier for the block, generated by hashing the block header. This ensures
immutability and prevents tampering.
How Blocks are Linked in a Blockchain
Each block contains the hash of the previous block, creating a chain-like structure. If any block is altered, its
hash changes, breaking the link and making tampering evident.
CODE:-
pip install flask sqlite3 hashlib json datetime requests
import hashlib
import json
import time
import sqlite3
class Blockchain:
def __init__(self):
self.create_database()
[Link] = self.load_blocks()
if len([Link]) == 0:
self.create_genesis_block()
def create_database(self):
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS blocks (
index INTEGER PRIMARY KEY,
timestamp TEXT,
transactions TEXT,
previous_hash TEXT,
hash TEXT
)
""")
[Link]()
[Link]()
def load_blocks(self):
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT * FROM blocks")
rows = [Link]()
[Link]()
return [
{"index": row[0], "timestamp": row[1], "transactions": [Link](row[2]), "previous_hash": row[3], "hash": row[4]}
for row in rows
]
def create_genesis_block(self):
genesis_block = self.create_block(transactions=[], previous_hash="0")
return genesis_block
def create_block(self, transactions, previous_hash):
index = len([Link])
timestamp = str([Link]())
block_data = {
"index": index,
"timestamp": timestamp,
"transactions": transactions,
"previous_hash": previous_hash
}
block_hash = self.hash_block(block_data)
block_data["hash"] = block_hash
[Link](block_data)
# Save to database
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("INSERT INTO blocks VALUES (?, ?, ?, ?, ?)",
(index, timestamp, [Link](transactions), previous_hash, block_hash))
[Link]()
[Link]()
return block_data
def add_transaction(self, sender, receiver, amount):
return {"sender": sender, "receiver": receiver, "amount": amount}
@staticmethod
def hash_block(block_data):
encoded_block = [Link](block_data, sort_keys=True).encode()
return hashlib.sha256(encoded_block).hexdigest()
from flask import Flask, request, jsonify, render_template
from blockchain import Blockchain
app = Flask(__name__)
blockchain = Blockchain()
@[Link]("/")
def home():
return render_template("[Link]")
@[Link]("/transactions/new", methods=["POST"])
def new_transaction():
data = request.get_json()
transaction = blockchain.add_transaction(data["sender"], data["receiver"], data["amount"])
return jsonify({"message": "Transaction added", "transaction": transaction}), 201
@[Link]("/mine", methods=["GET"])
def mine_block():
if len([Link]) > 0:
last_block = [Link][-1]
previous_hash = last_block["hash"]
else:
previous_hash = "0"
new_block = blockchain.create_block([], previous_hash)
return jsonify({"message": "New block mined!", "block": new_block}), 200
@[Link]("/chain", methods=["GET"])
def get_chain():
return jsonify({"chain": [Link]}), 200
if __name__ == "__main__":
[Link](debug=True)
<!DOCTYPE html>
<html>
<head>
<title>Simple Blockchain</title>
<script>
function fetchBlockchain() {
fetch("/chain")
.then(response => [Link]())
.then(data => {
[Link]("blockchain").innerHTML = [Link]([Link], null, 4);
});
}
function mineBlock() {
fetch("/mine")
.then(response => [Link]())
.then(data => {
alert([Link]);
fetchBlockchain();
});
}
function addTransaction() {
let sender = [Link]("sender").value;
let receiver = [Link]("receiver").value;
let amount = [Link]("amount").value;
fetch("/transactions/new", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: [Link]({ sender, receiver, amount })
})
.then(response => [Link]())
.then(data => {
alert([Link]);
});
}
</script>
</head>
<body onload="fetchBlockchain()">
<h1>Simple Blockchain</h1>
<h2>Add Transaction</h2>
<input type="text" id="sender" placeholder="Sender">
<input type="text" id="receiver" placeholder="Receiver">
<input type="number" id="amount" placeholder="Amount">
<button onclick="addTransaction()">Add Transaction</button>
<h2>Mine a New Block</h2>
<button onclick="mineBlock()">Mine Block</button>
<h2>Blockchain</h2>
<pre id="blockchain"></pre>
</body>
</html>
RESULT:-
Conclusion The structure of a blockchain block ensures security, transparency, and decentralization. By leveraging
cryptographic hashing and linking blocks, blockchain technology provides a tamper-resistant ledger system
widely used in cryptocurrencies, smart contracts, and other applications.