0% found this document useful (0 votes)
2 views

Assignment 2

The document outlines the structure of a block in a blockchain, detailing its components such as the block header, block body, and block hash. It explains how blocks are linked to ensure security and immutability, and includes a code implementation for a simple blockchain using Flask and SQLite. The conclusion emphasizes the benefits of blockchain technology in providing a secure and transparent ledger system.

Uploaded by

JAY PATIL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Assignment 2

The document outlines the structure of a block in a blockchain, detailing its components such as the block header, block body, and block hash. It explains how blocks are linked to ensure security and immutability, and includes a code implementation for a simple blockchain using Flask and SQLite. The conclusion emphasizes the benefits of blockchain technology in providing a secure and transparent ledger system.

Uploaded by

JAY PATIL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

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()
self.chain = self.load_blocks()
if len(self.chain) == 0:
self.create_genesis_block()

def create_database(self):
conn = sqlite3.connect("blockchain.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS blocks (
index INTEGER PRIMARY KEY,
timestamp TEXT,
transactions TEXT,
previous_hash TEXT,
hash TEXT
)
""")
conn.commit()
conn.close()

def load_blocks(self):
conn = sqlite3.connect("blockchain.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM blocks")
rows = cursor.fetchall()
conn.close()

return [
{"index": row[0], "timestamp": row[1], "transactions": json.loads(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(self.chain)
timestamp = str(time.time())
block_data = {
"index": index,
"timestamp": timestamp,
"transactions": transactions,
"previous_hash": previous_hash
}
block_hash = self.hash_block(block_data)
block_data["hash"] = block_hash
self.chain.append(block_data)

# Save to database
conn = sqlite3.connect("blockchain.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO blocks VALUES (?, ?, ?, ?, ?)",
(index, timestamp, json.dumps(transactions), previous_hash, block_hash))
conn.commit()
conn.close()

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 = json.dumps(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()

@app.route("/")
def home():
return render_template("index.html")

@app.route("/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

@app.route("/mine", methods=["GET"])
def mine_block():
if len(blockchain.chain) > 0:
last_block = blockchain.chain[-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

@app.route("/chain", methods=["GET"])
def get_chain():
return jsonify({"chain": blockchain.chain}), 200

if __name__ == "__main__":
app.run(debug=True)

<!DOCTYPE html>
<html>
<head>
<title>Simple Blockchain</title>
<script>
function fetchBlockchain() {
fetch("/chain")
.then(response => response.json())
.then(data => {
document.getElementById("blockchain").innerHTML = JSON.stringify(data.chain, null, 4);
});
}

function mineBlock() {
fetch("/mine")
.then(response => response.json())
.then(data => {
alert(data.message);
fetchBlockchain();
});
}

function addTransaction() {
let sender = document.getElementById("sender").value;
let receiver = document.getElementById("receiver").value;
let amount = document.getElementById("amount").value;

fetch("/transactions/new", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sender, receiver, amount })
})
.then(response => response.json())
.then(data => {
alert(data.message);
});
}
</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.

You might also like