2
0

transaction.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import hashlib
  2. import json
  3. import time
  4. import uuid
  5. from lib.contract import Contract
  6. class Transaction:
  7. def __init__(self):
  8. self.id = None
  9. self.data = None
  10. self.hash_value = None
  11. self.locked = False
  12. self.timestamp = 0
  13. self.sender = None
  14. self.receiver = None
  15. def set_serialized_contract(self, serialized):
  16. if not self.locked:
  17. self.id = str(uuid.uuid1())
  18. self.data = serialized
  19. self.log('Serialized contract set')
  20. return True
  21. return False
  22. def set_contract(self, contract: Contract):
  23. if not self.locked:
  24. self.id = str(uuid.uuid1())
  25. self.data = contract.serialize()
  26. self.log(f'Contract set: {contract.id} | {contract.title}')
  27. return True
  28. return False
  29. def serialize(self, out_json=False):
  30. obj = {
  31. 'id': self.id,
  32. 'timestamp': self.timestamp,
  33. 'data': self.data,
  34. 'sender': self.sender,
  35. 'receiver': self.receiver
  36. }
  37. self.log(f'Serialized')
  38. if out_json:
  39. return json.dumps(obj, sort_keys=True)
  40. return obj
  41. def lock_hash_finish(self):
  42. if not self.locked:
  43. self.timestamp = int(time.time())
  44. self.locked = True
  45. self.hash()
  46. self.log('Locked')
  47. return True
  48. return False
  49. def hash(self):
  50. string_object = json.dumps(self.data, sort_keys=True)
  51. block_string = string_object.encode()
  52. raw_hash = hashlib.sha256(block_string)
  53. hex_hash = raw_hash.hexdigest()
  54. self.hash_value = hex_hash
  55. self.log(f'Hashed: {self.hash_value}')
  56. return hex_hash
  57. def log(self, text):
  58. print(f'[ TRANS ] {text}')