block.py 1.9 KB

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