0% found this document useful (0 votes)
13 views11 pages

Blockchain LAB FILE

The document outlines a series of experiments focused on blockchain technology, including creating blocks, implementing SHA-256, validating blockchain integrity, and constructing digital signatures. Each experiment provides objectives, theoretical background, algorithms, sample code, expected outputs, and conclusions related to various blockchain functionalities. The experiments cover topics such as Proof of Work, crypto wallets, Ethereum smart contracts, and data encryption standards.

Uploaded by

sammy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views11 pages

Blockchain LAB FILE

The document outlines a series of experiments focused on blockchain technology, including creating blocks, implementing SHA-256, validating blockchain integrity, and constructing digital signatures. Each experiment provides objectives, theoretical background, algorithms, sample code, expected outputs, and conclusions related to various blockchain functionalities. The experiments cover topics such as Proof of Work, crypto wallets, Ethereum smart contracts, and data encryption standards.

Uploaded by

sammy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Experiment 1: Create a Block in a Blockchain using Hash Function

Objective:
To implement a simple block structure and simulate the process of adding it to a blockchain
using cryptographic hash functions.

Theory:
A blockchain is a chain of blocks, each containing data, a timestamp, the hash of the current
block, and the hash of the previous block. Cryptographic hash functions (like SHA-256)
ensure the integrity of data by producing a fixed-size hash value for any input. Even a slight
change in the input results in a completely different hash. This makes blockchain secure
against tampering.

Algorithm:
1. Define a Block class with attributes: index, timestamp, data, previous_hash, and hash.
2. Create a function to generate SHA-256 hash from block content.
3. Initialize the genesis block with default values.
4. Create new blocks, link them with the previous block's hash.
5. Append each new block to the blockchain list.

Sample Code (Python/Solidity):

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):
value = str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash)
return hashlib.sha256(value.encode()).hexdigest()

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

def create_next_block(last_block, data="Block Data"):


index = last_block.index + 1
return Block(index, time.time(), data, last_block.hash)
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

for i in range(5):
new_block = create_next_block(previous_block, f"Block #{i+1} Data")
blockchain.append(new_block)
previous_block = new_block
print(f"Block #{new_block.index} added with hash: {new_block.hash}")

Expected Output:
Each block will be printed with its index and corresponding hash. The hash must change for
each block, and each block must contain the hash of its previous block.

Conclusion:
This experiment demonstrates how blocks are linked using hash functions, ensuring
immutability and integrity in a blockchain.
Experiment 2: Binary Merkle Tree in a Blockchain

Objective:
To implement a binary Merkle tree in a blockchain and perform various operations with
complexity analysis.

Theory:
A Merkle tree is a binary tree where each leaf node represents a hash of a data block, and
each internal node is a hash of the concatenation of its child hashes. Merkle trees provide
efficient and secure verification of large data structures.

Algorithm:
6. Input data blocks.
7. Compute SHA-256 hash of each data block.
8. Pair and concatenate the hashes to compute parent hashes recursively until the root is
obtained.
9. Traverse the tree and perform search, insertion, deletion, and update operations.
10. Calculate complexity: O(log n) for most operations.

Sample Code (Python/Solidity):

import hashlib

def hash_data(data):
return hashlib.sha256(data.encode()).hexdigest()

def build_merkle_tree(leaves):
if len(leaves) % 2 != 0:
leaves.append(leaves[-1]) # Duplicate last hash if odd number
if len(leaves) == 1:
return leaves[0]
new_level = []
for i in range(0, len(leaves), 2):
combined = leaves[i] + leaves[i+1]
new_level.append(hash_data(combined))
return build_merkle_tree(new_level)

data_blocks = ['a', 'b', 'c', 'd']


hashed_blocks = [hash_data(block) for block in data_blocks]
root = build_merkle_tree(hashed_blocks)
print("Merkle Root:", root)
Expected Output:
The output shows the Merkle root of the tree formed from the hashed data block

Experiment 3: Implement SHA-256 Algorithm

Objective:
To understand and implement SHA-256, a cryptographic hash function used in blockchain
systems.

Theory:
SHA-256 (Secure Hash Algorithm 256-bit) generates a fixed-size 256-bit (32-byte) hash. It
is used in blockchain to secure data, ensure integrity, and link blocks together.

Algorithm:
11. Take input data.
12. Use hashlib library to compute SHA-256 hash.
13. Return hexadecimal digest of the hash.

Sample Code (Python/Solidity):

import hashlib

data = input("Enter data to hash: ")


hash_result = hashlib.sha256(data.encode()).hexdigest()
print("SHA-256 Hash:", hash_result)

Expected Output:
The program outputs the SHA-256 hash of the given input data.

Conclusion:
This experiment demonstrates the working of SHA-256 used to secure blockchain data.
Experiment 4: Validate Block Hash from Genesis Block

Objective:
To validate the integrity of a blockchain by verifying the hash from the genesis block.

Theory:
Each block in a blockchain contains the hash of the previous block. By recalculating and
matching hashes from the genesis block, we can validate the blockchain’s integrity.

Algorithm:
14. Traverse the blockchain from the genesis block.
15. Recalculate each block's hash and compare with the stored hash.
16. If all match, the blockchain is valid.

Sample Code (Python/Solidity):

# Reusing Block class from Experiment 1


def validate_chain(blockchain):
for i in range(1, len(blockchain)):
if blockchain[i].previous_hash != blockchain[i-1].hash:
return False
return True

# Assuming blockchain is already created


is_valid = validate_chain(blockchain)
print("Blockchain Valid:", is_valid)

Expected Output:
Output will be True if all hashes match, indicating a valid blockchain.

Conclusion:
This validation ensures data integrity across the blockchain.
Experiment 5: Implement Proof of Work (POW)

Objective:
To implement a basic POW algorithm for mining a block in a peer-to-peer network.

Theory:
Proof of Work is a consensus algorithm where miners solve computational puzzles to
validate transactions and add new blocks. It requires finding a nonce such that the block
hash has leading zeroes.

Algorithm:
17. Set difficulty level (number of leading zeroes).
18. Iterate nonce values until hash starts with the required number of zeros.
19. Return the valid nonce and hash.

Sample Code (Python/Solidity):

def proof_of_work(block, difficulty):


prefix = '0' * difficulty
while not block.hash.startswith(prefix):
block.nonce += 1
block.hash = block.calculate_hash()
return block

difficulty = 4 # leading 4 zeroes


mined_block = proof_of_work(previous_block, difficulty)
print("Mined Block Hash:", mined_block.hash)

Expected Output:
Displays the mined block hash that satisfies the POW difficulty.

Conclusion:
Proof of Work makes blockchain secure by requiring computational effort to add new
blocks.
Experiment 6: Construct Digital Signature in Blockchain

Objective:
To implement digital signatures using public and private keys in blockchain.

Theory:
Digital signatures ensure data authenticity and integrity. They use public-key cryptography
to sign and verify messages.

Algorithm:
20. Generate public-private key pair.
21. Sign data using private key.
22. Verify signature using public key.

Sample Code (Python/Solidity):

from cryptography.hazmat.primitives.asymmetric import rsa, padding


from cryptography.hazmat.primitives import hashes

private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)


public_key = private_key.public_key()

message = b'Blockchain transaction'


signature = private_key.sign(message, padding.PKCS1v15(), hashes.SHA256())

# Verification
try:
public_key.verify(signature, message, padding.PKCS1v15(), hashes.SHA256())
print("Signature verified.")
except:
print("Verification failed.")

Expected Output:
The output confirms the signature verification status.

Conclusion:
Digital signatures provide security features like authentication and integrity in blockchain.
Experiment 7: Develop Crypto Wallet using Public & Private Keys

Objective:
To simulate a basic crypto wallet that stores keys and performs transactions.

Theory:
A crypto wallet holds the user’s public and private keys, enabling them to send and receive
cryptocurrency securely.

Algorithm:
23. Generate key pair.
24. Use public key as wallet address.
25. Sign transactions using private key.

Sample Code (Python/Solidity):

# Using keys from Experiment 6


wallet_address = public_key.public_bytes_encoding().hex()
print("Wallet Address:", wallet_address)
print("Private Key Stored Securely.")

Expected Output:
Displays the generated wallet address derived from the public key.

Conclusion:
Crypto wallets securely manage keys, enabling blockchain transactions.
Experiment 8: Build Ethereum Blockchain Cryptocurrency

Objective:
To understand the structure of Ethereum blockchain and simulate a cryptocurrency.

Theory:
Ethereum is a decentralized platform that supports smart contracts. Cryptocurrencies on
Ethereum are implemented as tokens.

Algorithm:
26. Set up Ethereum environment using Remix or web3.py.
27. Define a simple ERC-20 token contract.
28. Deploy and test transactions.

Sample Code (Python/Solidity):

// Solidity Code for ERC20 Token


pragma solidity ^0.8.0;

contract MyToken {
string public name = "MyToken";
string public symbol = "MTK";
uint public totalSupply = 1000;
mapping(address => uint) public balanceOf;

constructor() {
balanceOf[msg.sender] = totalSupply;
}
}

Expected Output:
Displays the token name, symbol, total supply, and user balances.

Conclusion:
This simulates creating and interacting with cryptocurrency using Ethereum.
Experiment 9: Smart Contracts on Ethereum Network

Objective:
To write and deploy smart contracts using Ethereum.

Theory:
Smart contracts are self-executing agreements with code on blockchain. They eliminate the
need for intermediaries.

Algorithm:
29. Write a smart contract in Solidity.
30. Deploy it using Remix IDE.
31. Interact with contract functions.

Sample Code (Python/Solidity):

pragma solidity ^0.8.0;

contract Voting {
mapping(string => uint) public votes;

function vote(string memory candidate) public {


votes[candidate] += 1;
}

function getVotes(string memory candidate) public view returns (uint) {


return votes[candidate];
}
}

Expected Output:
Interacting with the contract will show vote counts for each candidate.

Conclusion:
Smart contracts enable automated, tamper-proof digital agreements.
Experiment 10: Implement Data Encryption Standard (DES) in Blockchain

Objective:
To secure blockchain data using Data Encryption Standard (DES).

Theory:
DES is a symmetric-key algorithm used to encrypt and decrypt data blocks. It can be used to
secure blockchain transactions.

Algorithm:
32. Use pyDes or Crypto.Cipher for DES encryption.
33. Encrypt and decrypt a message.
34. Validate correctness of the decrypted message.

Sample Code (Python/Solidity):

from Crypto.Cipher import DES

key = b'8bytekey'
cipher = DES.new(key, DES.MODE_ECB)
message = b'8bytes!!'
encrypted = cipher.encrypt(message)
decrypted = cipher.decrypt(encrypted)
print("Encrypted:", encrypted)
print("Decrypted:", decrypted)

Expected Output:
Encrypted and decrypted data will be printed.

Conclusion:
DES can enhance security by encrypting blockchain data.

You might also like