Blockchain Record - Kathir

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

DEPARTMENT OF INFORMATION TECHNOLOGY

22CBIC53– FUNDAMENTALS OF BLOCKCHAIN AND USECASES


YEAR 2024 - 2025

NAME OF THE STUDENT :


REGISTER NUMBER :
COURSE :
YEAR :
SEMESTER :
BONAFIDE CERTIFICATE

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

HEAD OF THE DEPARTMENT STAFF-IN-CHARGE

Submitted for the Practical Examination held on ...............................

INTERNAL EXAMINER EXTERNALEXAMINER


INDEX

S.NO. DATE TITLE PAGES SIGNATURE


1 INTRODUCTION TO
BLOCKCHAIN
2 IMPLEMENTATION
OF BLOCKCHAIN

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.

How Blockchain Works

1. Transaction Initiation: A transaction or piece of data is initiated and


sent to the network.
2. Transaction Verification: Nodes in the network validate the transaction
based on consensus rules.
3. Block Creation: Verified transactions are grouped into a new block.
4. Block Validation: The new block is validated by the network, often
through consensus mechanisms like mining or staking.
5. Block Addition: Once validated, the new block is added to the existing
blockchain.
6. Distributed Ledger Update: All nodes update their copies of the
blockchain to include the new block.

Applications of Blockchain

 Cryptocurrencies: The most famous application of blockchain is Bitcoin


and other cryptocurrencies. Blockchain enables secure, transparent, and
decentralized financial transactions.
 Supply Chain Management: Blockchain can track the provenance of
goods, ensuring transparency and reducing fraud in supply chains.
 Healthcare: It can securely store and share patient records across
different healthcare providers, improving data integrity and
accessibility.
 Voting Systems: Blockchain can provide a secure and transparent
method for voting, reducing the risk of election fraud.
 Real Estate: It can simplify and secure property transactions and record-
keeping.

Advantages and Challenges

Advantages:

 Security: Blockchain's cryptographic nature makes it highly secure.


 Transparency: Transactions are visible to all participants in the network.
 Decentralization: Reduces the risk of a single point of failure or
centralized control.

Challenges:

 Scalability: Many blockchains face issues with scaling to handle large


volumes of transactions.
 Energy Consumption: Some consensus mechanisms, like Proof of
Work, are energy-intensive.
 Regulation: The regulatory environment for blockchain technology is
still evolving.

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

 Description: Public blockchains are open and decentralized. Anyone can


join the network, validate transactions, and participate in the consensus
process. They are designed to be transparent and accessible to everyone.
 Examples: Bitcoin, Ethereum.
 Characteristics:
o Transparency: All transactions are visible to anyone with access
to the network.
o Security: High security due to decentralized consensus
mechanisms like Proof of Work (PoW).
o Immutability: Once data is added, it is extremely difficult to alter
or delete.

2. Private Blockchains

 Description: Private blockchains are restricted and controlled by a single


organization or a consortium. Access to the network is permissioned,
meaning only authorized entities can participate.
 Examples: Hyperledger Fabric, R3 Corda.
 Characteristics:
o Access Control: Only authorized participants can join and validate
transactions.
o Speed and Efficiency: Generally faster and more efficient than
public blockchains due to fewer nodes and less computational
work.
o Customizable: The organization can customize the blockchain to
suit specific needs and requirements.

3. Consortium Blockchains

 Description: Consortium blockchains are semi-decentralized and


managed by a group of organizations rather than a single entity. They are
often used for business collaborations or inter-organizational transactions.
 Examples: Enterprise Ethereum Alliance, Hyperledger Consortium.
 Characteristics:
o Collaborative: Multiple organizations work together to maintain
the blockchain.
o Efficiency: Typically more efficient than public blockchains, as the
number of validators is limited.
o Governance: Decision-making is often shared among consortium
members.

4. Hybrid Blockchains

 Description: Hybrid blockchains combine features of both public and


private blockchains. They aim to offer the transparency of public
blockchains while maintaining the privacy and control of private
blockchains.
 Examples: Dragonchain, Hedera Hashgraph.
 Characteristics:
o Flexibility: Allows for both private and public interactions,
enabling private data to be handled in a private manner while still
leveraging public features.
o Security and Efficiency: Balances the security of public
blockchains with the efficiency of private ones.

5. Sidechains

 Description: Sidechains are separate blockchains that are linked to a


main blockchain. They enable the transfer of assets between the main
chain and the sidechain, often used to improve scalability or add new
features without altering the main blockchain.
 Examples: Liquid Network (linked to Bitcoin), Polygon (for Ethereum).
 Characteristics:
o Interoperability: Facilitates interaction between different
blockchains.
o Scalability: Helps in scaling applications by offloading work from
the main chain.
o Experimentation: Allows for the testing of new features without
impacting the main blockchain.

6. Permissioned Blockchains

 Description: Similar to private and consortium blockchains,


permissioned blockchains restrict who can access and participate in
the network. They can be managed by a single entity or a group.
 Examples: IBM Blockchain, Quorum (an Ethereum-based permissioned
blockchain).
 Characteristics:
o Access Control: Participants must be authorized to join and
interact with the blockchain.
o Governance: Controlled by the entity or entities that manage the
permissions.
Use Cases for Different Blockchains

 Public Blockchains: Ideal for decentralized applications (dApps),


cryptocurrencies, and projects where transparency and decentralization
are crucial.
 Private Blockchains: Suitable for enterprise solutions where privacy,
control, and efficiency are prioritized.
 Consortium Blockchains: Useful for collaborative efforts between
multiple organizations, such as supply chain management or
financial services.
 Hybrid Blockchains: Beneficial for projects needing a mix of public and
private features, like regulated financial services.
 Sidechains: Great for adding features, scaling, or experimenting without
affecting the main blockchain.

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:

 Generate block hash using index, timestamp, data, and


previous_hash.

2. Create Genesis Block:

 Create a block with index=0, data="Genesis Block",


previous_hash="0".

3. Initialize Blockchain:

 Start the blockchain by adding the genesis block.

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 str (self):


return f"Block(index: {self.index}, timestamp: {self.timestamp}, data:
{self.data}, previous_hash: {self.previous_hash}, hash: {self.hash})"
class Blockchain:
def init (self):
self.chain = [self.create_genesis_block()]

def create_genesis_block(self):
return Block(0, time.time(), "Genesis Block", "0")

def get_latest_block(self):
return self.chain[-1]

def add_block(self, new_block):


new_block.previous_hash = self.get_latest_block().hash
new_block.hash = new_block.calculate_hash()
self.chain.append(new_block)

def is_chain_valid(self):
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i - 1]

# Check if the current block's hash is correct


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
# Create a blockchain
my_blockchain = Blockchain()

# Add some blocks


my_blockchain.add_block(Block(1, time.time(), {"amount": 4}))
my_blockchain.add_block(Block(2, time.time(), {"amount": 10}))

# Display the blocks in the blockchain


for block in my_blockchain.chain:
print(block)

# Check if blockchain is valid


print("Is blockchain valid?", my_blockchain.is_chain_valid())

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]

while len(nodes) > 1:


if len(nodes) % 2 != 0:
nodes.append(nodes[-1]) # Duplicate last node if odd number of nodes

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

return nodes[0] # The root of the Merkle Tree


if name == " main ":
leaves = ['data1', 'data2', 'data3', 'data4']
merkle_root = build_merkle_tree(leaves)
print("Merkle Tree Root Hash:", merkle_root.hash)

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:

 Initialize a nonce value, starting from 0.

4. Iterative Hashing:

 Combine the block data with the current nonce.


 Compute the hash of the combined data.
 Check if the resulting hash meets the difficulty criteria (e.g., hash starts with
the required number of leading zeros).

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.

:param block_data: The data to include in the block (e.g., transactions,


previous hash)
:param difficulty: The difficulty level (number of leading zeros required)
:return: The nonce and the resulting hash
"""
nonce = 0
prefix = '0' * difficulty # Difficulty level determines the number of leading
zeros
while True:
# Concatenate block data with nonce
text = f"{block_data}{nonce}"
hash_result = hash_function(text)

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

print("Mining... Please wait.")


nonce, hash_result = proof_of_work(block_data, difficulty)
print(f"Nonce: {nonce}")
print(f"Hash: {hash_result}")

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:

1. Define Participant Class:

 Create a class called Participant that has a name and a stake.

2. Choose Validator Function:

 Input: List of participants.


 Output: Randomly selected participant based on their stake.
 Steps:
1. If the list is empty, return an error.
2. Calculate the total stake.
3. Generate a random number between 0 and the total stake.
4. Loop through the participants:
 Keep a running total of stakes.
 If the running total exceeds the random number, select that
participant.

3. Main Program:

 Create a list of participants.


 Call the function to choose a validator.
 Print the name and stake of the chosen validator.

PROGRAM:
import random

class Participant:

def init (self, name,

stake): self.name = name

self.stake = stake

def choose_validator(participants):

total_stake = sum(participant.stake for participant in participants)

random_choice = random.uniform(0, total_stake)

current_sum = 0

for participant in participants:

current_sum += participant.stake

if current_sum >= random_choice:

return participant

if name == " main ":

# Create participants with their stakes

participants = [

Participant("Alice", 100),

Participant("Bob", 200),

Participant("Charlie", 300)

]
# Simulate choosing a validator

validator = choose_validator(participants)

print(f"The chosen validator is {validator.name} with a stake of


{validator.stake}.")

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:

 Each voter casts a vote by choosing a candidate.


 The vote is recorded as a transaction in a blockchain-like structure.

 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:

def __init__(self, previous_hash, voter_id, candidate):

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):

# Create the genesis block

genesis_block = VoteBlock("0", "Genesis", "None")

self.chain = [genesis_block]

self.votes = {}

def get_last_block(self):

return self.chain[-1]

def cast_vote(self, voter_id, candidate):

last_block = self.get_last_block()

new_block = VoteBlock(last_block.hash, voter_id, candidate)

self.chain.append(new_block)

self.votes[voter_id] = candidate

print(f"Vote casted by {voter_id} for {candidate}.")

def verify_integrity(self):

for i in range(1, len(self.chain)):


current_block = self.chain[i]

previous_block = self.chain[i - 1]

# Check if the current block's hash is correct

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 = {}

for voter, candidate in self.votes.items():

if candidate in results:

results[candidate] += 1

else:

results[candidate] = 1

print("\nVoting Results:")

for candidate, votes in results.items():

print(f"{candidate}: {votes} votes")

# Example Usage

if __name__ == "__main__":
voting_system = VotingBlockchain()

# Simulate casting votes

voting_system.cast_vote("Voter1", "Candidate A")

voting_system.cast_vote("Voter2", "Candidate B")

voting_system.cast_vote("Voter3", "Candidate A")

# Display voting results

voting_system.display_results()

# Verify blockchain integrity

if voting_system.verify_integrity():

print("\nBlockchain integrity is intact.")

else:

print("\nBlockchain integrity is compromised.")

OUTPUT:

Vote casted by Voter1 for Candidate A.


Vote casted by Voter2 for Candidate B.
Vote casted by Voter3 for Candidate A.

Voting Results:
Candidate A: 2 votes
Candidate B: 1 vote

Blockchain integrity is intact.


RESULT:
Thus the program in application of blockchain (digital
voting) is executed successfully
MINI PROJECT

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

# Define the block class for the blockchain


class Block:
def __init__(self, index, timestamp, media_id, user_id, license_recommendation, previous_hash=''):
self.index = index
self.timestamp = timestamp
self.media_id = media_id
self.user_id = user_id
self.license_recommendation = license_recommendation
self.previous_hash = previous_hash
self.hash = self.calculate_hash()

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()

# Blockchain class to handle the chain of blocks


class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]

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]

def add_block(self, new_block):


new_block.previous_hash = self.get_latest_block().hash
new_block.hash = new_block.calculate_hash()
self.chain.append(new_block)

# Initialize blockchain
media_rights_blockchain = Blockchain()

# Simple recommendation system based on media type and usage


def recommend_license(media_type, usage_purpose, user_location):
if usage_purpose == "non-commercial":
return "Creative Commons License"
elif usage_purpose == "commercial":
return "Commercial License"
else:
return "Public Domain License"
# Function to add a media rights recommendation to the blockchain
def add_recommendation(media_id, user_id, media_type, usage_purpose, user_location, blockchain):
license_recommendation = recommend_license(media_type, usage_purpose, user_location)
latest_block = blockchain.get_latest_block()
new_block = Block(len(blockchain.chain), time.time(), media_id, user_id, license_recommendation,
latest_block.hash)
blockchain.add_block(new_block)
return license_recommendation

# Function to track and display recommendations from the blockchain


def track_media(media_id, blockchain):
print(f"Tracking Media ID: {media_id}")
for block in blockchain.chain:
if block.media_id == media_id:
print(f"Recommended License: {block.license_recommendation} | Timestamp:
{time.ctime(block.timestamp)}")

# Example usage
media_id = "Media001"
user_id = "User123"
media_type = "image"
usage_purpose = "non-commercial"
user_location = "US"

# Add a recommendation to the blockchain


recommended_license = add_recommendation(media_id, user_id, media_type, usage_purpose,
user_location, media_rights_blockchain)
print(f"Recommended License: {recommended_license}")

# Track the media license recommendation


track_media(media_id, media_rights_blockchain)

OUTPUT:

Recommended License: Creative Commons License


Tracking Media ID: Media001
Recommended License: Creative Commons License | Timestamp: Wed Sep 15 12:30:45 2021
RESULT:
Thus the mini project has been executed sucessfully

You might also like