transaction.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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: Contract):
  33. if not self.locked:
  34. self.id = str(uuid.uuid1())
  35. self.data = contract.serialize()
  36. self.log(f'Contract set: {contract.id} | {contract.title}')
  37. return True
  38. return False
  39. def serialize(self, out_json=False):
  40. obj = {
  41. 'id': self.id,
  42. 'timestamp': self.timestamp,
  43. 'data': self.data,
  44. 'key': self.key,
  45. }
  46. self.log(f'Serialized')
  47. if out_json:
  48. return json.dumps(obj, sort_keys=True)
  49. return obj
  50. def lock_hash_finish(self):
  51. if not self.locked:
  52. self.timestamp = int(time.time())
  53. self.locked = True
  54. self.hash()
  55. self.log('Locked')
  56. return True
  57. return False
  58. def hash(self, recipient=None):
  59. string_object = json.dumps(self.data, sort_keys=True)
  60. block_string = string_object.encode()
  61. # open the public key file
  62. pubkey = get_keys(recipient) #Sender public key - input field neccessary
  63. encrypted_data = pubkey.encrypt(
  64. block_string,
  65. padding.OAEP(
  66. mgf=padding.MGF1(algorithm=hashes.SHA256()),
  67. algorithm=hashes.SHA256(),
  68. label=None
  69. )
  70. )
  71. self.hash_value = encrypted_data
  72. self.log(f'Hashed: {self.hash_value}')
  73. return encrypted_data
  74. def log(self, text):
  75. print(f'[ TRANS ] {text}')