| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import hashlib
- import json
- import time
- import uuid
- from lib.contract import Contract
- class Transaction:
- def __init__(self):
- self.id = None
- self.data = None
- self.hash_value = None
- self.locked = False
- self.timestamp = 0
- self.sender = None
- self.receiver = None
- def from_serialized(self, jsonobj: str):
- obj = json.loads(jsonobj)
- self.id = obj['id']
- self.data = obj['data']
- self.timestamp = obj['timestamp']
- self.sender = obj['sender']
- self.receiver = obj['receiver']
- def set_serialized_contract(self, serialized):
- if not self.locked:
- self.id = str(uuid.uuid1())
- self.data = serialized
- self.log('Serialized contract set')
- return True
- return False
- def set_contract(self, contract: Contract):
- if not self.locked:
- self.id = str(uuid.uuid1())
- self.data = contract.serialize()
- self.log(f'Contract set: {contract.id} | {contract.title}')
- return True
- return False
- def serialize(self, out_json=False):
- obj = {
- 'id': self.id,
- 'timestamp': self.timestamp,
- 'data': self.data,
- 'sender': self.sender,
- 'receiver': self.receiver
- }
- self.log(f'Serialized')
- if out_json:
- return json.dumps(obj, sort_keys=True)
- return obj
- def lock_hash_finish(self):
- if not self.locked:
- self.timestamp = int(time.time())
- self.locked = True
- self.hash()
- self.log('Locked')
- return True
- return False
- def hash(self):
- string_object = json.dumps(self.data, sort_keys=True)
- block_string = string_object.encode()
- raw_hash = hashlib.sha256(block_string)
- hex_hash = raw_hash.hexdigest()
- self.hash_value = hex_hash
- self.log(f'Hashed: {self.hash_value}')
- return hex_hash
- def log(self, text):
- print(f'[ TRANS ] {text}')
|