2RD PROGRAM
import hashlib
class MerkleTree:
def init(self, transactions):
self.transactions = transactions
self.tree = self.build_tree()
def build_tree(self):
tree = [self.hash_transaction(transaction) for transaction in self.transactions]
return self.construct_tree(tree)
def hash_transaction(self, transaction):
return hashlib.sha256(transaction.encode()).hexdigest()
def construct_tree(self, transactions):
if len(transactions) == 1:
return transactions
next_level = []
for i in range(0, len(transactions), 2):
if i + 1 < len(transactions):
combined_hash = transactions[i] + transactions[i + 1]
else:
combined_hash = transactions[i] + transactions[i] # Duplicate last item if odd
next_level.append(self.hash_transaction(combined_hash))
return self.construct_tree(next_level)
def get_root(self):
return self.tree[0] if self.tree else None
Test Merkle Tree
transactions = ["Transaction 1", "Transaction 2", "Transaction 3", "Transaction 4"]
merkle_tree = MerkleTree(transactions)
print("Merkle Tree:", merkle_tree.tree)
print("Root Hash:", merkle_tree.get_root())