K. J.
Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Title: Batch:
Blockchain implementation of the blocks created in previous BCT-3
experiment Roll No.: 16010121200
Objective: Blockchain implementation of the blocks created in Experiment No. 4
previous experiment
Expected Outcome of Experiment:
CO Outcome
CO1 Describe the basic concepts of Blockchain and Distributed Ledger Technology.
CO2 Apply cryptographic hash required for Blockchain.
CO3 Categorize and discuss the consensus in Blockchain.
Books/ Journals/ Websites referred:
https://www.geeksforgeeks.org/private-blockchain/
https://www.techtarget.com/searchcio/feature/What-are-the-4-different-types-of-blockchain-technology#:~:text=There%20are%20four
%20main%20types,consortium%20blockchains%20and%20hybrid%20blockchains.
https://www.geeksforgeeks.org/blockchain-chaining-blocks/
Abstract:
Blockchain technology is a decentralized digital ledger that maintains a secure, transparent record of transactions through a continuous chain of blocks.
Each block contains a batch of transaction data along with a unique cryptographic hash of the previous block, which links them together in an
immutable sequence. This design ensures that once data is recorded in a block and added to the chain, it cannot be altered without affecting all
subsequent blocks, making tampering exceedingly difficult. The decentralized nature of blockchain means that no single entity controls the ledger,
reducing the risk of fraud and unauthorized access. Instead, the network relies on consensus mechanisms, such as Proof of Work or Proof of Stake, to
validate and agree on new transactions. While blockchain offers robust security and data integrity, it also faces challenges such as scalability issues,
regulatory hurdles, and concerns about energy consumption, particularly with certain consensus methods. Despite these challenges, blockchain holds
significant potential for a wide range of applications, from financial transactions and supply chain management to digital identity verification and
beyond.
Related Theory:
Block chaining in blockchain technology relies on several foundational theories to ensure its integrity, security, and functionality. At its core,
cryptographic hash functions, such as SHA-256 used in Bitcoin, play a crucial role in securing the data within each block. These hash functions
generate a fixed-size string that uniquely represents the data, ensuring that any alteration of the block’s content would change its hash, thereby
signaling tampering. Each block in the chain contains the hash of the previous block, linking them in a secure and immutable sequence that forms the
blockchain. This linkage is vital for maintaining the chronological order and integrity of the blockchain. Consensus mechanisms, such as Proof of
Work (PoW) and Proof of Stake (PoS), further support the block chaining process by validating transactions and adding new blocks in a decentralized
manner. PoW requires computational effort to solve complex problems, making it costly for malicious actors to alter the blockchain, while PoS relies
on validators who stake tokens as collateral, offering a more energy-efficient alternative. Additionally, Merkle trees are utilized within blocks to
efficiently summarize and verify transaction integrity, enhancing data verification. The distributed ledger theory underpins blockchain’s decentralized
nature, where multiple nodes maintain identical copies of the blockchain, ensuring uniformity and preventing single points of control or failure. This
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 1
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
decentralization, combined with robust security measures, such as chain immutability and transaction validation rules, safeguards the blockchain from
tampering and fraud. The theory of economic incentives and game theory also plays a significant role by aligning participants’ interests with the
network’s integrity through rewards for honest behavior. Moreover, the concept of smart contracts extends the functionality of blockchain by enabling
automated, self-executing agreements based on predefined conditions. Collectively, these theoretical elements form the backbone of block chaining in
blockchain technology, ensuring its effectiveness and resilience across various applications.
Implementation:
The following is the app.py
import hashlib
import json
from flask import Flask, render_template, request, jsonify
# Utility function to hash data
def hash_data(data):
return hashlib.sha256(data.encode('utf-8')).hexdigest()
# Transaction class
class Transaction:
def __init__(self, transaction_id, value):
self.transaction_id = transaction_id
self.value = value
def to_dict(self):
return {
'transaction_id': self.transaction_id,
'value': self.value
# Block class
class Block:
def __init__(self, index, transactions, previous_hash):
self.index = index
self.transactions = transactions
self.previous_hash = previous_hash
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 2
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
self.nonce = 0
self.hash = self.compute_hash()
def compute_hash(self):
block_dict = self.__dict__.copy()
block_dict['transactions'] = [tx.to_dict() for tx in self.transactions]
block_string = json.dumps(block_dict, sort_keys=True)
return hash_data(block_string)
def mine_block(self, difficulty=4):
target = '0' * difficulty
while self.hash[:difficulty] != target:
self.nonce += 1
self.hash = self.compute_hash()
# Blockchain class
class Blockchain:
def __init__(self):
self.chain = []
self.create_genesis_block()
def create_genesis_block(self):
genesis_block = Block(0, [], "0")
genesis_block.hash = "0" # Set hash to "0" for genesis block
genesis_block.nonce = 0 # Set nonce to 0 for genesis block
self.chain.append(genesis_block)
def add_block(self, transactions):
previous_block = self.chain[-1]
new_block = Block(len(self.chain), transactions, previous_block.hash)
new_block.mine_block(4) # Mine with difficulty 4
self.chain.append(new_block)
def update_chain_hashes(self, start_index):
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 3
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
for i in range(start_index, len(self.chain)):
if i > 0: # Skip genesis block
self.chain[i].previous_hash = self.chain[i - 1].hash
self.chain[i].hash = self.chain[i].compute_hash()
self.chain[i].mine_block(4) # Re-mine the block
def get_chain(self):
chain_data = []
for block in self.chain:
block_dict = block.__dict__.copy()
block_dict['transactions'] = [tx.to_dict() for tx in block.transactions]
chain_data.append(block_dict)
return chain_data
app = Flask(__name__)
blockchain = Blockchain()
@app.route('/')
def index():
return render_template('index.html', chain=blockchain.get_chain())
@app.route('/add_transaction', methods=['POST'])
def add_transaction():
block_index = int(request.form['block_index'])
transaction_id = request.form['transaction_id']
value = float(request.form['value'])
if 0 < block_index < len(blockchain.chain): # Prevent adding to genesis block
new_transaction = Transaction(transaction_id, value)
blockchain.chain[block_index].transactions.append(new_transaction)
blockchain.update_chain_hashes(block_index) # Update from this block onwards
return jsonify(success=True)
else:
return jsonify(success=False, message="Invalid block index or cannot modify genesis block")
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.route('/create_block', methods=['POST'])
def create_block():
blockchain.add_block([])
return jsonify(success=True)
@app.route('/get_chain')
def get_chain():
return jsonify(chain=blockchain.get_chain())
if __name__ == '__main__':
app.run(debug=True)
The following is the 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>Blockchain Simulation</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 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;
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 5
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
.block:hover {
transform: translateY(-5px);
box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15);
.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">Blockchain Simulation</h1>
<div class="text-center mb-4">
<button class="btn btn-primary" onclick="createBlock()">Create New Block</button>
</div>
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 6
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
<div id="blockchain" class="row"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
<script>
let blockchain = [];
function createBlock() {
fetch('/create_block', {method: 'POST'})
.then(response => response.json())
.then(data => {
if (data.success) {
renderBlockchain();
});
function addTransaction(blockIndex) {
const transactionId = document.getElementById(`transactionId-${blockIndex}`).value;
const value = parseFloat(document.getElementById(`value-${blockIndex}`).value);
if (transactionId && !isNaN(value)) {
fetch('/add_transaction', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `block_index=${blockIndex}&transaction_id=${transactionId}&value=${value}`
})
.then(response => response.json())
.then(data => {
if (data.success) {
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 7
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
renderBlockchain();
} else {
alert('Failed to add transaction: ' + data.message);
});
function renderBlockchain() {
fetch('/get_chain')
.then(response => response.json())
.then(data => {
blockchain = data.chain;
const blockchainContainer = document.getElementById('blockchain');
blockchainContainer.innerHTML = '';
blockchain.forEach((block, blockIndex) => {
const blockElement = document.createElement('div');
blockElement.className = 'col-md-6 col-lg-4 mb-4';
blockElement.innerHTML = `
<div class="block">
<div class="block-header">
<h4 class="m-0">Block ${block.index}</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">${block.hash}</span></p>
<p><strong>Nonce:</strong> ${block.nonce}</p>
<h5>Transactions</h5>
<div class="transaction-list mb-3">
${block.transactions.map((tx) => `
<div class="mb-2">
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 8
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
<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="${tx.value}" readonly>
</div>
`).join('')}
</div>
${blockIndex > 0 ? `
<div class="input-group mb-2">
<input type="text" class="form-control" id="transactionId-${blockIndex}" placeholder="Transaction ID">
<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>
`;
blockchainContainer.appendChild(blockElement);
});
});
document.addEventListener('DOMContentLoaded', () => {
renderBlockchain();
});
</script>
</body>
</html>
Screenshots:
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 9
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 10
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 11
K. J. Somaiya College of Engineering, Mumbai-77
Department of Computer Engineering
Conclusion:-
Successfully implemented block chaining by ensuring each new block is connected to the previous block, forming a secure and continuous blockchain.
Department of Computer Engineering BCT Sem VII – July - Nov 2024 Page - 12