示例#1
0
    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"]))
示例#2
0
    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"})
示例#3
0
    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()
示例#4
0
    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"]))
示例#5
0
def file_send(n, filehash, fileaddr, file_name, ips):
    stx = StorageTx()
    mem = Mempool()
    udp = UDPHandler()
    print(fileaddr)
    stx.add_input(filehash, fileaddr)
    part_filename = hashlib.sha256(file_name.encode('utf-8')).hexdigest()

    recv_hosts = ips
    for i in range(0, n):
        host = recv_hosts[i]
        port = 5001

        filename = settings.TEMP_STORAGE_PATH + part_filename + str(i)
        filesize = math.ceil(os.path.getsize(filename))
        filetype = "non-temp"

        send = socket.socket()
        print(f"[+] Connecting to {host}:{port}")
        send.connect((host, port))
        print("[+] Connected.")

        info = {
            "filename": filename,
            "filesize": filesize,
            "filetype": filetype,
            "filehash": filehash,
            "fileaddr": fileaddr,
        }
        # send.send(f"{filename}{SEPARATOR}{filesize}{SEPARATOR}{filetype}{SEPARATOR}{filehash}{SEPARATOR}{fileaddr}".encode())
        send.sendall(pickle.dumps(info))
        filehash = ""
        with open(filename, "rb") as f:
            filehash = get_hash(filename, 15)
            print(filehash)
            while True:
                bytes_read = f.read(BUFFER_SIZE)
                if not bytes_read:
                    break
                send.sendall(bytes_read)
        stx.add_output(filehash, host, filename)
        send.close()
        os.remove(filename)

    stx.gen_tx_hash()
    mem.add_transaction(stx)
    udp.broadcastmessage(json.dumps(stx.to_json()))
示例#6
0
    def synctx(self, request=None, response=None):
        """ Sync transaction command """

        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({
                    "command": "synctx",
                    "body": request["body"]
                }), request["ip_addr"])
        elif response is not None:
            # Processing reaponse
            mempool = Mempool()
            mempool.sync_transaction(json.loads(response["body"]))
示例#7
0
    def create_block(self):
        block = Block()
        block.create_coinbase_transaction()
        mempool = Mempool()
        blkc = BlockChain()

        mempool_size = mempool.get_len()
        if mempool_size == 0:
            return
        while mempool_size > 0:
            tx = mempool.get_transaction()
            block.add_transaction(tx)
            mempool_size -= 1
        
        block.calcalute_block_size()
        block.calculate_merkle_root()
        block.compute_hash()
        blkc.add_block(block)

        return block
示例#8
0
    def gettxbymindex(self, request=None, response=None):
        """ Get Mempool transaction by index """

        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({
                    "command": "gettxbymindex",
                    "body": request["index"]
                }), request["ip_addr"])
        if response is not None:
            # Processing reaponse
            if "command" in response.keys():
                mm = Mempool()
                tx = mm.get_tx_by_mindex(response["body"])
                UDPHandler.sendmessage(
                    json.dumps({
                        "prev_command": "gettxbymindex",
                        "data": tx
                    }), response["ip_addr"])
示例#9
0
    def getmempoollength(self, request=None, response=None):
        """ Get length of Mempool """

        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({
                    "command": "getmempoollength",
                    "body": ""
                }), request["ip_addr"])
        if response is not None:
            # Processing reaponse
            if "command" in response.keys():
                mm = Mempool()
                ln = mm.get_len()
                UDPHandler.sendmessage(
                    json.dumps({
                        "prev_command": "getmempoollength",
                        "data": ln
                    }), response["ip_addr"])
示例#10
0
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)
示例#11
0
    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()