2
0

transaction.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import hashlib
  2. import json
  3. import time
  4. import uuid
  5. from lib.contract import Contract
  6. from cryptography.fernet import Fernet
  7. import rsa
  8. class Transaction:
  9. def __init__(self):
  10. self.id = None
  11. self.data = None
  12. self.hash_value = None
  13. self.locked = False
  14. self.timestamp = 0
  15. self.sender = None
  16. self.receiver = None
  17. def from_serialized(self, jsonobj: str):
  18. obj = json.loads(jsonobj)
  19. self.id = obj['id']
  20. self.data = obj['data']
  21. self.timestamp = obj['timestamp']
  22. self.sender = obj['sender']
  23. self.receiver = obj['receiver']
  24. def set_serialized_contract(self, serialized):
  25. if not self.locked:
  26. self.id = str(uuid.uuid1())
  27. self.data = serialized
  28. self.log('Serialized contract set')
  29. return True
  30. return False
  31. def set_contract(self, contract: Contract):
  32. if not self.locked:
  33. self.id = str(uuid.uuid1())
  34. self.data = contract.serialize()
  35. self.log(f'Contract set: {contract.id} | {contract.title}')
  36. return True
  37. return False
  38. def serialize(self, out_json=False):
  39. obj = {
  40. 'id': self.id,
  41. 'timestamp': self.timestamp,
  42. 'data': self.data,
  43. 'sender': self.sender,
  44. 'receiver': self.receiver
  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 file_open(file):
  59. key_file = open(file, 'rb')
  60. key_data = key_file.read()
  61. key_file.close()
  62. return key_data
  63. def hash(self):
  64. string_object = json.dumps(self.data, sort_keys=True)
  65. block_string = string_object.encode()
  66. # open the public key file
  67. pubkey = rsa.PublicKey.load_pkcs1(file_open('publickey.key')) #Sender public key - input field neccessary
  68. # create the cipher
  69. cipher = Fernet(pubkey)
  70. # encrypt the data
  71. encrypted_data = cipher.encrypt(block_string)
  72. #these lines only neccessary for key_encryption - solve the problem of bytes
  73. # open the symmetric key file for encryoting the file
  74. #skey = open('symmetric.key','rb')
  75. #key = skey.read()
  76. # encrypt the symmetric key file with the public key
  77. #encrypted_key = rsa.encrypt(key,pubkey)
  78. self.hash_value = encrypted_data
  79. self.log(f'Hashed: {self.hash_value}')
  80. return encrypted_data
  81. def log(self, text):
  82. print(f'[ TRANS ] {text}')