Exemplo n.º 1
0
    def handler(self, connection_handler, ip_port_tuple):
        try:
            while True:
                #data = connection_handler.recv(self.byte_size)
                data = recv_timeout(connection_handler)
                # Check if the peer wants to disconnect
                for connection in self.connections:
                    if data and data == 'cmd_show_peers':
                        connection.sendall(
                            ('---' + str(self.peers)).encode('utf-8'))
                    elif data and data[0:1] == "\x12":
                        print("==> New mined block.")
                        new_block_info = data[1:]
                        new_block = Block(serialization=new_block_info)

                        in_blockchain = False
                        for block in self.blockchain.blocks:
                            if new_block.equal_blocks(block):
                                print(
                                    "==> This block is already mined and is in your blockchain. It will not be added to server blockchain"
                                )
                                in_blockchain = True
                                break

                        if not in_blockchain:
                            print("\t", new_block.__dict__)
                            print("\tNew Block Hash:", new_block.get_hash())
                            self.blockchain.add_block(new_block)
                            update_blockchain_file(self.blockchain.serialize())

                        connection.sendall(data.encode("utf-8"))
                    elif data:
                        connection.sendall(data.encode("utf-8"))
        except ConnectionResetError:
            print("==> " + str(ip_port_tuple) + " disconnected")
            self.connections.remove(connection_handler)
            connection_handler.close()
            self.peers.remove(ip_port_tuple)
            self.send_peers()
Exemplo n.º 2
0
    def __init__(self, address):
        """
        Initialization method for Client class

        Convention:
        0x10 - New Transaction
        0x11 - New peers
        0x12 - New mined block
        0x13 - Blockchain
        """

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Make the connection
        self.socket.connect((address, 5000))
        self.byte_size = 1024
        self.peers = []
        print('==> Connected to server.')

        self.generate_key_pair()

        client_listener_thread = threading.Thread(target=self.send_message)
        client_listener_thread.start()

        while True:
            try:
                data = self.receive_message()
                if data[0:1] == '\x11':
                    print('==> Got peers.')
                    update_peers(data[1:])
                elif data[0:1] == '\x10':
                    print('==> New transaction.')
                    transaction_info = data[1:]
                    transaction = Transaction(serialization=transaction_info)

                    # Mining block
                    result = mine_block(transaction=transaction,
                                        blockchain=self.blockchain,
                                        miner_address=self.hash_pubkey())
                    if result["status"]:
                        message = "\x12" + result["new_block"].serialize()
                        print("==> Sending new mined block")
                        self.socket.sendall(message.encode("utf-8"))
                    else:
                        print(
                            "==> Invalid transaction. The block have not been mined"
                        )
                elif data[0:1] == '\x13':
                    print('==> Blockchain downloaded.')
                    blockchain_info = data[1:]
                    self.blockchain = Blockchain(serialization=blockchain_info)
                    update_blockchain_file(self.blockchain.serialize())
                elif data[0:1] == '\x12':
                    print('==> New mined block.')
                    block_info = data[1:]
                    new_block = Block(serialization=block_info)

                    in_blockchain = False
                    for block in self.blockchain.blocks:
                        if new_block.equal_blocks(block):
                            print(
                                "==> This block is already mined and is in your blockchain. It will not be added"
                            )
                            in_blockchain = True
                            break

                    if not in_blockchain:
                        print("\t", new_block.__dict__)
                        print("\tNew Block Hash:", new_block.get_hash())
                        self.blockchain.add_block(new_block)
                        update_blockchain_file(self.blockchain.serialize())

                elif data != "":
                    print("[#] " + data)
            except ConnectionError as error:
                print("==> Server disconnected. ")
                print('\t--' + str(error))
                break