| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- 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.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
- self.nonce = self.height
- def add_hashed_transaction(self, hashed: str):
- print(hashed)
- trans = Transaction()
- trans.from_serialized(hashed)
- self.transactions.append(trans)
- self.log(f'Hashed transaction added: {hashed}')
- return True
- 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}')
|