Blockchain LAB FILE
Blockchain LAB FILE
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.
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")
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.
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)
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.
import hashlib
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.
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.
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.
# 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.
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.
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.
contract Voting {
mapping(string => uint) public votes;
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.
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.