| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- import hashlib
- import json
- import time
- from lib.transaction import Transaction
- class Block:
- def __init__(self, previous=None):
- self.proof = None
- self.previous_hash = previous.hash if previous is not None else None
- self.transactions = []
- self.hash_value = None
- self.locked = False
- self.timestamp = 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}')
|