2
0

transaction.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import hashlib
  2. import json
  3. import time
  4. import uuid
  5. from create_keys import make_keys, get_keys
  6. from lib.contract import Contract
  7. from cryptography.hazmat.backends import default_backend
  8. from cryptography.hazmat.primitives import serialization
  9. from cryptography.hazmat.primitives import hashes
  10. from cryptography.hazmat.primitives.asymmetric import padding
  11. class Transaction:
  12. def __init__(self):
  13. self.id = None
  14. self.data = None
  15. self.hash_value = None
  16. self.locked = False
  17. self.timestamp = 0
  18. self.key = None
  19. def from_serialized(self, jsonobj: str):
  20. obj = json.loads(jsonobj)
  21. self.id = obj['id']
  22. self.data = obj['data']
  23. self.timestamp = obj['timestamp']
  24. self.key = obj['key']
  25. def set_serialized_contract(self, serialized):
  26. if not self.locked:
  27. self.id = str(uuid.uuid1())
  28. self.data = serialized
  29. self.log('Serialized contract set')
  30. return True
  31. return False
  32. def set_contract(self, contract: dict):
  33. if not self.locked:
  34. self.id = str(uuid.uuid1())
  35. # self.data = contract.serialize()
  36. self.data = contract
  37. self.timestamp = time.time()
  38. self.key = contract['id']
  39. # self.log(f'Contract set: {contract.id} | {contract.title}')'
  40. self.log(f'Contract set: {contract["id"]}')
  41. return True
  42. return False
  43. def serialize(self, out_json=False):
  44. obj = {
  45. 'id': self.id,
  46. 'timestamp': self.timestamp,
  47. 'data': self.data,
  48. 'key': self.key,
  49. }
  50. self.log(f'Serialized')
  51. if out_json:
  52. return json.dumps(obj, sort_keys=True)
  53. return obj
  54. def lock_hash_finish(self):
  55. if not self.locked:
  56. self.timestamp = int(time.time())
  57. self.locked = True
  58. self.hash()
  59. self.log('Locked')
  60. return True
  61. return False
  62. def hash(self, contract=None):
  63. string_object = json.dumps(self.data, sort_keys=True)
  64. block_string = string_object.encode()
  65. # open the public key file
  66. pubkey = get_keys(contract) #Sender public key - input field neccessary
  67. encrypted_data = pubkey.encrypt(
  68. block_string,
  69. padding.OAEP(
  70. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  71. algorithm=hashes.SHA256(),
  72. label=None
  73. )
  74. )
  75. self.hash_value = encrypted_data
  76. self.log(f'Hashed: {self.hash_value}')
  77. self.data = encrypted_data
  78. def log(self, text):
  79. print(f'[ TRANS ] {text}')