2
0

block.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import hashlib
  2. import json
  3. import time
  4. from lib.transaction import Transaction
  5. class Block:
  6. def __init__(self, previous=None):
  7. self.proof = None
  8. self.previous_hash = previous.hash_value if previous is not None else None
  9. self.transactions = []
  10. self.hash_value = None
  11. self.locked = False
  12. self.timestamp = 0
  13. def add_transaction(self, trans: Transaction):
  14. if not self.locked:
  15. trans.lock_hash_finish()
  16. self.transactions.append(trans)
  17. self.log(f'Transaction added: {trans.id}')
  18. return True
  19. return False
  20. def lock_hash_finish(self):
  21. if not self.locked:
  22. self.timestamp = int(time.time())
  23. self.hash()
  24. self.locked = True
  25. self.log('Locked')
  26. return True
  27. return False
  28. def serialize(self):
  29. trans_serialize = []
  30. for transaction in self.transactions:
  31. trans_serialize.append(transaction.serialize())
  32. obj = {
  33. 'timestamp': self.timestamp,
  34. 'previous': self.previous_hash,
  35. 'transactions': trans_serialize
  36. }
  37. self.log(f'Serialized: {len(trans_serialize)} transactions')
  38. return obj
  39. def hash(self):
  40. string_object = json.dumps(self.serialize(), sort_keys=True)
  41. block_string = string_object.encode()
  42. raw_hash = hashlib.sha256(block_string)
  43. hex_hash = raw_hash.hexdigest()
  44. self.hash_value = hex_hash
  45. self.log(f'Hashed: {self.hash_value}')
  46. return hex_hash
  47. def log(self, text):
  48. print(f'[ BLOCK ] {text}')