K. J.
Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Batch: BCT-3 Roll No: 16010121200
Experiment No. 3
Title: Creation of Merkle tree and Blocks
Objective:
Creation of Merkle tree and Blocks
Expected Outcome of Experiment:
CO Outcome
Describe the basic concepts of Blockchain and Distributed Ledger
CO1
Technology.
Apply cryptographic hash required for Blockchain.
CO2
Books/ Journals/ Websites referred:
1. [Link]
2. [Link]
Abstract:
A Merkle tree provides a digital fingerprint of all the transactions within a block,
enabling users to verify whether a specific transaction is part of the block. This
structure is built by repeatedly hashing pairs of nodes until a single hash remains,
known as the Merkle Root or Root Hash. Merkle trees are constructed from the bottom
up, with each leaf node representing a hash of transaction data, and each non-leaf node
containing a hash of its child nodes. Since Merkle trees are binary, they require an even
number of leaf nodes. If there is an odd number of transactions, the last hash is
duplicated to ensure an even count of leaf nodes.
Related Theory:
Blockchain is a distributed ledger technology that maintains the integrity and security
of data through a chain of interconnected blocks. Each block contains a list of
transactions, a timestamp, a cryptographic hash of the previous block, and a Merkle
root that summarizes the transactions within the block. The key features of blockchain
include immutability, decentralization, and consensus mechanisms. Immutability
ensures that once a block is added to the chain, it cannot be altered without changing all
subsequent blocks. Decentralization distributes data across a network of nodes,
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 1
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
enhancing security and transparency. Consensus mechanisms, such as proof of work or
proof of stake, are employed to validate transactions and blocks.
Cryptographic hash functions play a crucial role in blockchain technology by
converting input data into a fixed-size string of characters that appears random. These
functions are used to ensure data integrity, with SHA-256 being a commonly used hash
function in this context.
Implementation Details:
import hashlib
import json
from flask import Flask, render_template, request, jsonify
# Utility function to hash data
def hash_data(data):
return hashlib.sha256([Link]('utf-8')).hexdigest()
# Transaction class
class Transaction:
def __init__(self, transaction_id, value):
self.transaction_id = transaction_id
[Link] = value
def to_dict(self):
return {
'transaction_id': self.transaction_id,
'value': [Link]
# Block class
class Block:
def __init__(self, index, transactions, previous_hash):
[Link] = index
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 2
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
[Link] = transactions
self.previous_hash = previous_hash
[Link] = 0
self.merkle_root = self.compute_merkle_root()
[Link] = self.compute_hash()
def compute_hash(self):
block_dict = self.__dict__.copy()
block_dict['transactions'] = [tx.to_dict() for tx in [Link]]
block_string = [Link](block_dict, sort_keys=True)
return hash_data(block_string)
def compute_merkle_root(self):
if not [Link]:
return hash_data('')
transaction_hashes = [hash_data([Link](tx.to_dict(), sort_keys=True)) for
tx in [Link]]
return [Link](transaction_hashes)
def merkle(self, hashes):
if len(hashes) == 0:
return hash_data('')
if len(hashes) == 1:
return hashes[0]
if len(hashes) % 2 != 0:
[Link](hashes[-1])
new_hashes = []
for i in range(0, len(hashes), 2):
new_hashes.append(hash_data(hashes[i] + hashes[i + 1]))
return [Link](new_hashes)
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 3
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
def mine_block(self, difficulty=4):
target = '0' * difficulty
while [Link][:difficulty] != target:
[Link] += 1
[Link] = self.compute_hash()
# Blockchain class
class Blockchain:
def __init__(self):
[Link] = []
self.create_genesis_block()
def create_genesis_block(self):
genesis_block = Block(0, [], "0")
genesis_block.mine_block(4) # Mine genesis block with difficulty 4
[Link](genesis_block)
def add_block(self, transactions):
previous_block = [Link][-1]
new_block = Block(len([Link]), transactions, previous_block.hash)
new_block.mine_block(4) # Mine with difficulty 4
[Link](new_block)
def get_chain(self):
chain_data = []
for block in [Link]:
block_dict = block.__dict__.copy()
block_dict['transactions'] = [tx.to_dict() for tx in [Link]]
chain_data.append(block_dict)
return chain_data
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 4
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
app = Flask(__name__)
blockchain = Blockchain()
@[Link]('/')
def index():
return render_template('[Link]', chain=blockchain.get_chain())
@[Link]('/add_transaction', methods=['POST'])
def add_transaction():
transaction_id = [Link]['transaction_id']
value = float([Link]['value'])
new_transaction = Transaction(transaction_id, value)
[Link][-1].[Link](new_transaction)
[Link][-1].merkle_root = [Link][-1].compute_merkle_root()
[Link][-1].hash = [Link][-1].compute_hash()
# Re-mine the block after adding a transaction to meet the difficulty
requirement
[Link][-1].mine_block(4)
return jsonify(success=True)
@[Link]('/create_block', methods=['POST'])
def create_block():
blockchain.add_block([])
return jsonify(success=True)
@[Link]('/get_chain')
def get_chain():
return jsonify(chain=blockchain.get_chain())
if __name__ == '__main__':
[Link](debug=True)
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 5
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Now create a folder called templates/index. html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Merkle Tree Simulation</title>
<link
href="[Link]
rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
padding-top: 2rem;
.block {
background-color: #ffffff;
border-radius: 0.5rem;
box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
margin-bottom: 1.5rem;
transition: all 0.3s ease;
.block:hover {
transform: translateY(-5px);
box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15);
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 6
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
.block-header {
background-color: #007bff;
color: white;
padding: 0.75rem;
border-top-left-radius: 0.5rem;
border-top-right-radius: 0.5rem;
.block-content {
padding: 1rem;
.transaction-list {
max-height: 200px;
overflow-y: auto;
.hash-value {
word-break: break-all;
font-size: 0.8rem;
</style>
</head>
<body>
<div class="container">
<h1 class="text-center mb-4">Merkle Tree Simulation</h1>
<div class="text-center mb-4">
<button class="btn btn-primary" onclick="createBlock()">Create New
Block</button>
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 7
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
</div>
<div id="blockchain" class="row"></div>
</div>
<script
src="[Link]
.js"></script>
<script src="[Link]
[Link]"></script>
<script>
let blockchain = [];
function createBlock() {
fetch('/create_block', {method: 'POST'})
.then(response => [Link]())
.then(data => {
if ([Link]) {
renderBlockchain();
});
function addTransaction(blockIndex) {
const transactionId = [Link](`transactionId-$
{blockIndex}`).value;
const value = parseFloat([Link](`value-$
{blockIndex}`).value);
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 8
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
if (transactionId && !isNaN(value)) {
fetch('/add_transaction', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `transaction_id=${transactionId}&value=${value}`
})
.then(response => [Link]())
.then(data => {
if ([Link]) {
renderBlockchain();
});
function renderBlockchain() {
fetch('/get_chain')
.then(response => [Link]())
.then(data => {
blockchain = [Link];
const blockchainContainer = [Link]('blockchain');
[Link] = '';
[Link]((block, blockIndex) => {
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 9
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
const blockElement = [Link]('div');
[Link] = 'col-md-6 col-lg-4 mb-4';
[Link] = `
<div class="block">
<div class="block-header">
<h4 class="m-0">Block ${[Link]}</h4>
</div>
<div class="block-content">
<p><strong>Previous Hash:</strong> <br><span class="hash-value">$
{block.previous_hash}</span></p>
<p><strong>Hash:</strong> <br><span class="hash-value">$
{[Link]}</span></p>
<p><strong>Merkle Root:</strong> <br><span class="hash-value">$
{block.merkle_root}</span></p>
<p><strong>Nonce:</strong> ${[Link]}</p>
<h5>Transactions</h5>
<div class="transaction-list mb-3">
${[Link]((tx) => `
<div class="mb-2">
<input type="text" class="form-control form-control-sm mb-1" value="$
{tx.transaction_id}" readonly>
<input type="number" class="form-control form-control-sm" value="${[Link]}"
readonly>
</div>
`).join('')}
</div>
<div class="input-group mb-2">
<input type="text" class="form-control" id="transactionId-${blockIndex}"
placeholder="Transaction ID">
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 10
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
<input type="number" class="form-control" id="value-${blockIndex}"
placeholder="Value">
</div>
<button class="btn btn-success w-100" onclick="addTransaction($
{blockIndex})">Add Transaction</button>
</div>
</div>
`;
[Link](blockElement);
});
});
[Link]('DOMContentLoaded', () => {
renderBlockchain();
});
</script>
</body>
</html>
Screenshots:
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 11
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 12
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 13
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 14
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Conclusion:-
Successfully implemented Merkle tree using Flask for the backend and HTML/CSS for
the frontend demonstrates the effectiveness of blockchain principles in verifying and
maintaining transaction integrity. Also learnt the potential of distributed ledger
technology to enhance data security and transparency.
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 15