import hashlib import json import time from lib.transaction import Transaction CURRENT = None class Block: class Current: @staticmethod def set(block): global CURRENT CURRENT = block @staticmethod def get(): global CURRENT return CURRENT def __init__(self, previous=None): self.proof = None self.previous_hash = previous.hash_value if previous is not None else None self.transactions = [] self.hash_value = None self.locked = False self.timestamp = 0 self.height = previous.height + 1 if previous is not None else 0 def add_transaction(self, trans: Transaction): if not self.locked: trans.lock_hash_finish() self.transactions.append(trans) self.log(f'Transaction added: {trans.id}') return True return False def lock_hash_finish(self): if not self.locked: self.timestamp = int(time.time()) self.hash() self.locked = True self.log('Locked') return True return False def serialize(self): trans_serialize = [] for transaction in self.transactions: trans_serialize.append(transaction.serialize()) obj = { 'timestamp': self.timestamp, 'previous': self.previous_hash, 'transactions': trans_serialize } self.log(f'Serialized: {len(trans_serialize)} transactions') return obj def hash(self): string_object = json.dumps(self.serialize(), sort_keys=True) block_string = string_object.encode() raw_hash = hashlib.sha256(block_string) hex_hash = raw_hash.hexdigest() self.hash_value = hex_hash self.log(f'Hashed: {self.hash_value}') return hex_hash def log(self, text): print(f'[ BLOCK ] {text}')