IAR/12989 CE410P BT
Practical 2
Aim: Using python programming language create a blockchain
Implementation:
● A Block class to represent individual blocks in the chain
● A Blockchain class to manage the chain and perform operations on it
● Hashing using SHA-256 to ensure data integrity
● Timestamps to track when each block was created
● A is_valid method to verify the integrity of the chain
Input:
import hashlib
import time
class Block:
def __init__(self, index, previous_hash, transactions, nonce=0):
self.index = index
self.previous_hash = previous_hash
self.transactions = transactions
self.timestamp = int(time.time())
self.nonce = nonce
self.hash = self.calculate_hash()
def calculate_hash(self):
data_string = str(self.index) + self.previous_hash + str(self.transactions) + str(self.timestamp) +
str(self.nonce)
return hashlib.sha256(data_string.encode()).hexdigest()
def mine_block(self, difficulty):
while self.hash[:difficulty] != '0' * difficulty:
self.nonce += 1
self.hash = self.calculate_hash()
def __str__(self):
IAR/12989 CE410P BT
return f"Block {self.index}\nPrevious Hash: {self.previous_hash}\nTransactions:
{self.transactions}\nTimestamp: {self.timestamp}\nNonce: {self.nonce}\nHash: {self.hash}"
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block()]
self.difficulty = 2
def create_genesis_block(self):
return Block(0, "0", ["Genesis transaction"])
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.mine_block(self.difficulty)
self.chain.append(new_block)
def is_valid(self):
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i - 1]
if current_block.hash != current_block.calculate_hash():
return False
if current_block.previous_hash != previous_block.hash:
return False
return True
# Create a blockchain
blockchain = Blockchain()
# Add some blocks to the blockchain
blockchain.add_block(Block(1, blockchain.get_latest_block().hash, ["Transaction 1", "Transaction 2"]))
blockchain.add_block(Block(2, blockchain.get_latest_block().hash, ["Transaction 3", "Transaction 4"]))
# Print the blockchain
for block in blockchain.chain:
print(block)
IAR/12989 CE410P BT
Output: