Blockchain Record - Kathir
Blockchain Record - Kathir
Blockchain Record - Kathir
Reg. No.
This is to certify that the Bona-fide Record of this Practical Work was
completed by Mr. / Ms............................................of B.TECH
INFORMATION TECHNOLOGY (CLOUD AND MOBILE BASED
APPLICATION) in the Fundamentals of blockchain and usecases
Laboratory during the academic year of 2024-2025
3 IMPLEMENTATION
OF MERKLE TREE IN
BLOCKCHAIN
4 IMPLEMENTATION
OF PROOF OF
WORK
5 IMPLEMENTATION
OF PROOF OF STAKE
6 APPLICATION OF
BLOCKCHAIN
7 MINI PROJECT
INTRODUCTION TO BLOCKCHAIN
What is Blockchain?
At its core, a blockchain is a type of digital ledger technology that allows data to
be stored across a network of computers in a way that is secure, transparent, and
tamper-resistant.
Key Concepts
1. Blocks: Data is organized into chunks called blocks. Each block contains
a list of transactions or data records.
2. Chain: Blocks are linked together in chronological order to form a chain.
Each block has a reference to the previous block, creating a secure and
unalterable sequence.
3. Decentralization: Instead of a single central authority managing the
ledger, the blockchain is maintained by a distributed network of
computers (nodes). Each node has a copy of the entire blockchain.
4. Consensus Mechanisms: To ensure that all copies of the blockchain are
synchronized and agree on the data, blockchain networks use consensus
mechanisms. The most common are Proof of Work (PoW) and Proof of
Stake (PoS). These mechanisms validate and agree on new transactions or
blocks added to the chain.
5. Cryptographic Hashing: Each block contains a unique code called a
hash, which is generated based on the data within the block. Hashing
ensures that if any data in the block is altered, the hash will change,
making it clear that the data has been tampered with.
6. Smart Contracts: Some blockchains, like Ethereum, support smart
contracts—self-executing contracts with the terms directly written into
code. These contracts automatically enforce and execute agreements
based on predetermined conditions.
Applications of Blockchain
Advantages:
Challenges:
TYPES OF BLOCKCHAIN
There are several types of blockchains, each serving different purposes and
designed with various features. Here’s a breakdown of the main types:
1. Public Blockchains
2. Private Blockchains
3. Consortium Blockchains
4. Hybrid Blockchains
5. Sidechains
6. Permissioned Blockchains
Understanding these types helps in choosing the right blockchain for specific
needs and applications. Each type offers different trade-offs in terms of security,
transparency, efficiency, and control.
RESULT:
Thus introduction to blockchain has studied.
IMPLEMENTATION OF BLOCKCHAIN
AIM:
To implement a program in blockchain using python
ALGORITHM:
1. Create Block:
3. Initialize Blockchain:
4. Add Block:
Link the new block to the last block by setting its previous_hash
to the last block's hash.
Add the new block to the blockchain.
5. Verify Blockchain:
For each block, verify if the hash is correct and if the previous_hash
points to the correct previous block.
PROGRAM:
import hashlib
import time
class Block:
def init (self, index, timestamp, data,
previous_hash=''): self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.calculate_hash()
def calculate_hash(self):
block_string = str(self.index) + str(self.timestamp) + str(self.data) +
str(self.previous_hash)
return hashlib.sha256(block_string.encode()).hexdigest()
def create_genesis_block(self):
return Block(0, time.time(), "Genesis Block", "0")
def get_latest_block(self):
return self.chain[-1]
def is_chain_valid(self):
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i - 1]
return True
# Create a blockchain
my_blockchain = Blockchain()
OUTPUT:
Block(index: 0, timestamp: 1726568860.6551957, data: Genesis Block,
previous_hash: 0, hash:
6549a6d203278d4facd3daef3c2e0089743fb4147a37252a25319f1b02c74169)
Block(index: 1, timestamp: 1726568860.6553698, data: {'amount': 4},
previous_hash:
6549a6d203278d4facd3daef3c2e0089743fb4147a37252a25319f1b02c74169, hash:
844c171ca988e2d12554e9db98c5f3281358bfaa85003171524d22ea2ef8e6c7)
Block(index: 2, timestamp: 1726568860.6554894, data: {'amount': 10},
previous_hash:
844c171ca988e2d12554e9db98c5f3281358bfaa85003171524d22ea2ef8e6c7, hash:
ce1405b428db2cdbeea2316f8167af0d96a858a2fea3f0dd30e6d52e06f92d3c)
Is blockchain valid? True
RESULT:
Thus the program in blockchain is executed successfully
IMPLEMENTATION OF MERKLE TREE IN BLOCKCHAIN
AIM:
To implement merkle tree in blockchain using python
ALGORITHM:
1. Create Block: Define block’s index, data, and previous_hash
and compute its hash.
2. Create Genesis Block: Make the first block with predefined
values and hash it.
3. Initialize Blockchain: Start the blockchain by adding the
Genesis Block.
4. Add Block: Create a new block linked to the last one by setting
its previous_hash and calculating its hash.
5. Validate Blockchain: Check if all blocks have valid hashes
and links to previous blocks.
PROGRAM:
import hashlib
def hash_function(data):
return hashlib.sha256(data.encode()).hexdigest()
class MerkleNode:
def init (self, left=None, right=None, data=None):
self.left = left
self.right = right
self.data = data
self.hash = self.calculate_hash()
def calculate_hash(self):
if self.data:
return hash_function(self.data)
combined_hash = self.left.hash + self.right.hash
return hash_function(combined_hash)
def build_merkle_tree(leaves):
nodes = [MerkleNode(data=leaf) for leaf in leaves]
new_level = []
for i in range(0, len(nodes), 2):
left = nodes[i]
right = nodes[i + 1]
new_level.append(MerkleNode(left, right))
nodes = new_level
OUTPUT:
Merkle Tree Root Hash:
51a0d54f81dcc317ea21d2125c65d796eac64e7c52b886d40388cf1f1abf93eb
RESULT:
Thus merkle tree is executed successfully in blockchain
IMPLEMENTATION OF PROOF OF WORK
AIM:
To implement proof of stake in blockchain
ALGORITHM:
1. Initialization:
Define the block data which typically includes transaction data and the
previous block's hash.
Set the difficulty level, which determines the number of leading zeros required in
the hash.
2. Hash Function:
Use a cryptographic hash function (e.g., SHA-256) to generate hashes of the data
combined with a nonce.
3. Nonce Initialization:
4. Iterative Hashing:
5. Validation:
If the hash meets the difficulty criteria, stop the iteration. The current nonce and
hash are the solution.
If the hash does not meet the criteria, increment the nonce and repeat the
hashing process.
6. Output:
Return the valid nonce and the hash that meets the difficulty requirement.
PROGRAM:
import hashlib
def hash_function(data):
return hashlib.sha256(data.encode()).hexdigest()
def proof_of_work(block_data, difficulty):
"""
Perform Proof of Work to find a nonce that results in a hash with leading
zeros.
if hash_result.startswith(prefix):
return nonce, hash_result
nonce += 1
if name == " main ":
block_data = "block data"
difficulty = 4 # This means we need a hash with at least 4 leading zeros
OUTPUT:
Mining... Please wait.
Nonce: 226325
Hash: 0000b55ea7ba1265fc3c0405db5f68763eb81e9e91f2769424289e6d09e
RESULT:
Thus proof of work has been executed successfully.
IMPLEMENTATION OF PROOF OF STAKE
AIM:
To implement proof of stake successfully in blockchain
ALGORITHM:
3. Main Program:
PROGRAM:
import random
class Participant:
self.stake = stake
def choose_validator(participants):
current_sum = 0
current_sum += participant.stake
return participant
participants = [
Participant("Alice", 100),
Participant("Bob", 200),
Participant("Charlie", 300)
]
# Simulate choosing a validator
validator = choose_validator(participants)
OUTPUT:
The chosen validator is Bob with a stake of 200.
RESULT:
Thus proof of stake has been executed successfully
APPLICATION OF BLOCKCHAIN
AIM:
To implement a program in application of blockchain (Digital voting)
ALGORITHM:
Voter Registration: Register voters with unique voter IDs.
Cast Vote:
Vote Verification:
Votes are stored with a timestamp and are linked using cryptographic hashes to prevent
tampering.
Display Results: After voting ends, display the number of votes for each candidate.
Integrity Check: Ensure that the chain of votes remains intact by verifying the cryptographic
hashes.
PROGRAM:
import hashlib
import time
class VoteBlock:
self.timestamp = time.time()
self.voter_id = voter_id
self.candidate = candidate
self.previous_hash = previous_hash
self.hash = self.calculate_hash()
def calculate_hash(self):
vote_data = f"{self.voter_id}{self.candidate}{self.timestamp}{self.previous_hash}"
return hashlib.sha256(vote_data.encode()).hexdigest()
class VotingBlockchain:
def __init__(self):
self.chain = [genesis_block]
self.votes = {}
def get_last_block(self):
return self.chain[-1]
last_block = self.get_last_block()
self.chain.append(new_block)
self.votes[voter_id] = candidate
def verify_integrity(self):
previous_block = self.chain[i - 1]
if current_block.hash != current_block.calculate_hash():
return False
# Check if the current block's previous hash matches the previous block's hash
if current_block.previous_hash != previous_block.hash:
return False
return True
def display_results(self):
results = {}
if candidate in results:
results[candidate] += 1
else:
results[candidate] = 1
print("\nVoting Results:")
# Example Usage
if __name__ == "__main__":
voting_system = VotingBlockchain()
voting_system.display_results()
if voting_system.verify_integrity():
else:
OUTPUT:
Voting Results:
Candidate A: 2 votes
Candidate B: 1 vote
AIM:
To implement a mini project (Media Right Recommendation System using Blockchain)
ALGORITHM:
1. Initialize Blockchain:
o Start the blockchain by creating a genesis block that records the start of the media rights
system
2. Collect User Input:
o Take input from the user regarding the media they want to use, its purpose (commercial/non-
commercial), and the user's location.
3. Feature Extraction:
o Extract relevant features like media type, user location, usage purpose, and region-specific
licensing rules from user input.
4. Train Recommendation System:
o Train a simple recommendation system using rules or machine learning to predict suitable
licenses/rights based on past patterns or predefined criteria.
5. License Recommendation:
o Recommend the appropriate license or media rights (e.g., Creative Commons, Commercial
License) based on the extracted features and the recommendation model.
6. Add Recommended License to Blockchain:
o For every recommendation, create a new block that records:
Media ID
User ID
Recommended license or rights
Timestamp
Previous block hash (to ensure blockchain continuity)
7. Verify Blockchain Integrity:
o Ensure that each block's hash is valid and that it correctly references the previous block's
hash.
8. Display Recommendation:
o Output the recommended media rights or license to the user, along with any legal guidelines.
PROGRAM:
import hashlib
import time
def calculate_hash(self):
block_string = str(self.index) + str(self.timestamp) + self.media_id + self.user_id +
self.license_recommendation + self.previous_hash
return hashlib.sha256(block_string.encode()).hexdigest()
def create_genesis_block(self):
"""Create the first block in the blockchain."""
return Block(0, time.time(), "GENESIS", "SYSTEM", "Start of Media Rights Blockchain", "0")
def get_latest_block(self):
return self.chain[-1]
# Initialize blockchain
media_rights_blockchain = Blockchain()
# Example usage
media_id = "Media001"
user_id = "User123"
media_type = "image"
usage_purpose = "non-commercial"
user_location = "US"
OUTPUT: