Assignment 2
Assignment 2
Assignment 02
Theory
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.
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.
Transactions: A list of all transactions included in the block. Each transaction contains:
o Transaction amount
o Digital signatures
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.
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
# 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
@staticmethod
def hash_block(block_data):
encoded_block = json.dumps(block_data, sort_keys=True).encode()
return hashlib.sha256(encoded_block).hexdigest()
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"
@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>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.