def sendtransaction(self, request=None, response=None): """ Send transaction """ if request is None and response is None: # If no data is being passed on by command handler pass if response is not None: # Processing reaponse if "command" in response.keys(): mm = Mempool() tx = Transaction() mm.add_transaction(tx.from_json(response["body"]))
def addtransaction(self, data): tx = Transaction.from_json({"block": "Mempool", **data}) mempool = Mempool() print("adding to mempool") mempool.add_transaction(tx) UDPHandler.broadcastmessage( json.dumps({ "command": "sendtransaction", "body": tx.to_json() })) return json.dumps({"status": "ok"})
def test_get_transaction(self): tx = Transaction() input = TransactionInput() input.address = "" tx.add_input(input) tx.generate_hash() mp = Mempool() mp.flush_mempool() mp.add_transaction(tx) self.assertEqual(mp.get_transaction().to_json(), tx.to_json()) mp.close()
def from_json(data): """ Mapping data from JSON to object """ tmp = Block() tmp.hash = data['hash'] tmp.timestamp = data['timestamp'] tmp.transactions = [Transaction.from_json( tx) for tx in data['transactions']] tmp.previous_block_hash = data['previous_block_hash'] tmp.merkle_root = data['merkle_root'] tmp.height = data['height'] tmp.version = data['version'] tmp.size = data['size'] return tmp
def create_fake_transaction(address: Address): tmp_tx = Transaction() add = Address() add.load(add_data["sk"], add_data["vk"]) tmp_tx.inputs.append(TransactionInput.from_json({ 'previous_tx': "16e8dab3a9185d5329fac9cfdc0a81c7817826f701e747cb3751878061e4dc8c", 'index': 0, 'scriptSig': [add.sign_message(json.dumps({ 'previous_tx': "16e8dab3a9185d5329fac9cfdc0a81c7817826f701e747cb3751878061e4dc8c", 'index': 0 }).encode("utf-8")).hex()], 'address': add_data["address"], 'verifying_key': [add_data["vk"]] })) tmp_tx.outputs.append(TransactionOutput.from_json({ 'address': "12345", 'value': 25, 'n': 0 })) tmp_tx.generate_hash() return tmp_tx
def add_transaction(self, val: Transaction) -> bool: """ This function add transaction to the mempool for further processing Parameters: val(Any): The transaction object to add to the mempool. Returns: boolean: A boolean result to show if the transaction is added successfully or not. """ print("adding") self.redis_client.rpush("mempool", json.dumps(val.to_json())) print("added tx") return True
def gettxbyhash(self, request=None, response=None): """ Get transaction by hash """ if request is None and response is None: # If no data is being passed on by command handler pass if request is not None: # Processing requests UDPHandler.sendmessage(json.dumps({"hash": request["hash"]}), request["ip_addr"], request["receiver_port"]) elif response is not None: # Processing reaponse mempool = Mempool() mempool.add_transaction( Transaction.from_json(json.loads(response)["tx"]))
def test_remove_transaction(self): tx = Transaction() input = TransactionInput() input.address = "" tx.add_input(input) tx.generate_hash() mp = Mempool() mp.flush_mempool() mp.add_transaction(tx) self.assertEqual(mp.get_size(), 1) mp.remove_transaction(tx.hash) self.assertEqual(mp.get_size(), 0) mp.close()
def create_coinbase_transaction(self): # Adds coinbase transaction to each mined block tx = Transaction() output = TransactionOutput() read_file = open("node_data.json", "r") raw = read_file.read() my_node = json.loads(raw) output.value = 50 output.address = my_node["address"] output.n = 0 tx.add_output(output) tx.generate_hash() self.add_transaction(tx)
def getallmtxhash(self, request=None, response=None): """ Get all mempool transactiona by hash """ if request is None and response is None: # If no data is being passed on by command handler pass if request is not None: # Processing requests UDPHandler.broadcastmessage( json.dumps({"command": "getallmtxhash"})) if response is not None: # Processing reaponse redis_client = redis.Redis(host='localhost', port=6379, db=0) local_tx_hashes: set = set() remote_tx_hashes: set = set() for tx in redis_client.lrange("mempool", 0, -1): local_tx_hashes.add( Transaction.from_json(tx.decode("utf-8")).hash) response_data = json.loads(response) for tx in response_data["hashes"]: remote_tx_hashes.add(tx) remote_tx_hashes.difference_update(local_tx_hashes) receiver_port = settings.UDP_RECEIVER_PORT for raw in redis_client.lrange("nodes", 0, -1): info = json.loads(raw.decode("utf-8")) if info["ip_addr"] == response_data["ip_addr"]: receiver_port = info["receiver_port"] for tx_hash in remote_tx_hashes: self.gettxbyhash({ "hash": tx_hash, "ip_addr": response_data["ip_addr"], "receiver_port": receiver_port })
def create_tx(addr): add_data = { "address": "1d3f347aada53547142da8edea5e0019e6ef31bb15", "vk": "-----BEGIN PUBLIC KEY-----\nMEkwEwYHKoZIzj0CAQYIKoZIzj0DAQEDMgAEHxzkpgh/lqgd1/rb7d+D+srhlhzG\ncOAveBQafVnHkffNR2aCiFHVQZKzhyO7iC/p\n-----END PUBLIC KEY-----\n", "sk": "-----BEGIN EC PRIVATE KEY-----\nMF8CAQEEGKtkXJ8xlejSSOl4mzNTYiXmb70wRByW1aAKBggqhkjOPQMBAaE0AzIA\nBB8c5KYIf5aoHdf62+3fg/rK4ZYcxnDgL3gUGn1Zx5H3zUdmgohR1UGSs4cju4gv\n6Q==\n-----END EC PRIVATE KEY-----\n" } tx = Transaction() add = Address() add.load(add_data["sk"], add_data["vk"]) # print(addr) tx.inputs = [] tx.inputs.append( TransactionInput.from_json({ 'previous_tx': "16e8dab3a9185d5329fac9cfdc0a81c7817826f701e747cb3751878061e4dc8c", 'index': 0, 'scriptSig': [ add.sign_message( json.dumps({ 'previous_tx': "16e8dab3a9185d5329fac9cfdc0a81c7817826f701e747cb3751878061e4dc8c", 'index': 0 }).encode("utf-8")).hex() ], 'address': addr, 'verifying_key': [add_data["vk"]] })) tx.outputs.append( TransactionOutput.from_json({ 'address': "yikgyyf67rr68t887tfc", 'value': 25, 'n': 0 })) tx.generate_hash() txf = tx.to_json() # print(txf['inputs'][0]['address']) return txf
from trucoin.Block import Block from trucoin.Transaction import Transaction from trucoin.TransactionInput import TransactionInput from trucoin.TransactionOutput import TransactionOutput import time import sys from utils import getsize, getbytes output = TransactionOutput() output.address = "1d3f347aada53547142da8edea5e0019e6ef31bb15" output.n = 0 output.value = 50 transaction = Transaction() transaction.add_output(output) transaction.is_coinbase = True transaction.hash = "eef9fda50a6bf6c11c5078d8772d94jk" block = Block() block.add_transaction(transaction) block.calculate_merkle_root() block.compute_hash() block.miner = "1d3f347aada53547142da8edea5e0019e6ef31bb15jk" block.size = getbytes(block) print(block.__dict__) message = { "hash": block.hash, "timestamp": block.timestamp, "transaction": block.transactions[0].broadcast_transaction(), "previous_block_hash": block.previous_block_hash, "merkle_root": block.merkle_root, "height": block.height, "miner": block.miner, "version": block.version,
def test_txs_by_address(self): blockchain = BlockChain() blockchain.flush_chain() block = Block() tx = Transaction() input1 = TransactionInput() input1.address = "test_address" tx.add_input(input1) tx.generate_hash() block.add_transaction(tx) tx1 = Transaction() output = TransactionOutput() output.address = "fake_address" output1 = TransactionOutput() output1.address = "test_address" tx1.add_output(output) tx1.add_output(output1) tx1.generate_hash() block.add_transaction(tx1) tx2 = Transaction() output2 = TransactionOutput() output2.address = "fake_address" tx2.add_output(output2) tx2.generate_hash() block.add_transaction(tx2) block.compute_hash() blockchain.add_block(block) txs = blockchain.get_txs_by_addr("test_address") getb = blockchain.get_block(-1) print(getb.to_json()) for tx in txs: print(tx.hash, end='\n') self.assertEqual(len(txs), 2) blockchain.close()
if __name__ == '__main__': tx = { 'timestamp': time.time(), 'version': '0.0.2', 'inputs': [{ "previous_tx": "oihrsgiohsioj9ih05i0yu9u59y8o4yu54h", "index": 3, "address": "iuyfvuyfguyifguyff687", "scriptSig": ["segbikldrih95euy9u4509uyh90e9p4ujy"], "verifying_key": ["jlbuigfuiga89y89egyg8w4oig8gw"] }], 'outputs': [{ 'value': 50, 'n': 0, 'address': 'bb4c10de221933bb0aa1ab1897f5640592fc1fa4' }], 'hash': 'eef9fda50a6besdrhyaeeeeeeeeee5072d94df4f6sfrhdztrhewrhyf145eb047426ad0fb', 'block': 'testchain', 'is_coinbase': False } mm = Mempool() t = Transaction() ob = t.from_json(tx) print("Adding tx to own mempool only!!") mm.add_transaction(ob)
def test_merkle_root(self): block = Block() tx = Transaction() input = TransactionInput() input.address = "test_address" tx.add_input(input) tx.generate_hash() block.add_transaction(tx) block.calculate_merkle_root() initial_merkle_root = block.merkle_root tx1 = Transaction() input1 = TransactionInput() input1.address = "another_test_address" tx1.add_input(input1) tx1.generate_hash() block.add_transaction(tx1) block.calculate_merkle_root() final_merkle_root = block.merkle_root self.assertNotEqual(initial_merkle_root, final_merkle_root)
def get_transaction(self) -> Transaction: return Transaction.from_json(json.loads(self.redis_client.rpop("mempool").decode("utf-8")))