4RD PROGRAM


import hashlib
import time

class Block:
def init(self, index, previous_hash, timestamp, data, nonce=0):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.nonce = nonce
self.hash = self.calculate_hash()

def calculate_hash(self):
    # Create a hash based on the block data
    return hashlib.sha256((str(self.index) + self.previous_hash +
                            str(self.timestamp) + self.data +
                            str(self.nonce)).encode()).hexdigest()

def mine_block(self, difficulty):
    # Mine the block by finding a hash that starts with difficulty number of zeros
    while self.hash[:difficulty] != '0' * difficulty:
        self.nonce += 1
        self.hash = self.calculate_hash()  # Recalculate the hash with the new nonce
    print("Block mined: " + self.hash)

class Blockchain:
def init(self):
self.chain = [self.create_genesis_block()] # Start with the Genesis block
self.difficulty = 4 # Define the mining difficulty

def create_genesis_block(self):
    # Create the first block in the chain (the genesis block)
    return Block(0, "0", time.time(), "Genesis Block")

def get_latest_block(self):
    # Get the last block in the chain
    return self.chain[-1]

def add_block(self, new_block):
    # Add a new block to the chain after mining it
    new_block.previous_hash = self.get_latest_block().hash
    new_block.mine_block(self.difficulty)
    self.chain.append(new_block)

Create the blockchain instance

blockchain = Blockchain()

Add blocks to the blockchain

blockchain.add_block(Block(1, "", time.time(), "First block"))
blockchain.add_block(Block(2, "", time.time(), "Second block"))

Print the blockchain data

for block in blockchain.chain:
print(f"Block #{block.index} with Hash: {block.hash}")