Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import hashlib
- import datetime
- class Block:
- def __init__(self, index: int, timestamp: datetime.datetime, data: str, previous_hash: str):
- self.index = index
- self.timestamp = timestamp
- self.data = data
- self.previous_hash = previous_hash
- self.hash = self.calculate_hash()
- def calculate_hash(self):
- sha = hashlib.sha256()
- sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash)).encode('utf-8'))
- return sha.hexdigest()
- class Blockchain:
- def __init__(self):
- self.chain = [self.create_genesis_block()]
- def create_genesis_block(self) -> Block:
- return Block(0, datetime.datetime.now(), "Genesis Block", "0")
- def get_latest_block(self) -> Block:
- return self.chain[-1]
- def add_block(self, new_block: 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) -> bool:
- 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
- def print_blockchain(self):
- for block in blockchain.chain:
- print("Index:", block.index)
- print("Timestamp:", block.timestamp)
- print("Data:", block.data)
- print("Previous Hash:", block.previous_hash)
- print("Current Hash:", block.hash)
- print()
- # Example usage
- blockchain = Blockchain()
- blockchain.add_block(Block(1, datetime.datetime.now(), "Data 1", ""))
- blockchain.add_block(Block(2, datetime.datetime.now(), "Data 2", ""))
- blockchain.add_block(Block(3, datetime.datetime.now(), "Data 3", ""))
- blockchain.add_block(Block(4, datetime.datetime.now(), "Data 4", ""))
- # Print blockchain
- blockchain.print_blockchain()
- print("Blockchain is valid:", blockchain.is_chain_valid())
- # Modify data to demonstrate tampering
- blockchain.chain[2].data = "Tampered Data"
- print("Blockchain is valid after tampering:", blockchain.is_chain_valid())
Advertisement
Comments
-
- https://indiawalkthrough.com/category/ghummakkad/
Add Comment
Please, Sign In to add comment
Advertisement