예제 #1
0
def test_proto():
    reward_key = Key.generate_private_key()

    proto1 = Protocol([], GENESIS_BLOCK, 1337)
    proto2 = Protocol([("127.0.0.1", 1337)], GENESIS_BLOCK, 1338)
    miner1 = Miner(proto1, reward_key)
    miner2 = Miner(proto2, reward_key)
    miner2.start_mining()
    miner1.start_mining()

    try:
        sleep(5)
        target_key = Key.generate_private_key()
        chain = miner1.chainbuilder.primary_block_chain
        reward_trans = chain.blocks[20].transactions[0]

        trans_in = TransactionInput(reward_trans.get_hash(), 0)
        trans_targ = TransactionTarget(target_key,
                                       reward_trans.targets[0].amount)

        trans = Transaction([trans_in], [trans_targ], datetime.utcnow())
        trans.sign([reward_key])

        assert trans.verify(chain, set()), "transaction should be valid"

        proto1.received('transaction', trans.to_json_compatible(), None)
        print("============Transaction=============")

        sleep(10)

        chain_len1 = len(miner1.chainbuilder.primary_block_chain.blocks)
        chain_len2 = len(miner2.chainbuilder.primary_block_chain.blocks)
        print("Length of chain of miner 1: {}".format(chain_len1))
        print("Length of chain of miner 2: {}".format(chain_len2))
    finally:
        miner1.shutdown()
        miner2.shutdown()

    assert max(chain_len1, chain_len2) * 90 // 100 < min(
        chain_len1, chain_len2), "chain lengths are VERY different"

    chain1 = miner1.chainbuilder.primary_block_chain
    hashes1 = [b.hash for b in chain1.blocks[:chain_len1 * 90 // 100]]
    hashes2 = [
        b.hash
        for b in miner2.chainbuilder.primary_block_chain.blocks[:chain_len1 *
                                                                90 // 100]
    ]
    assert hashes1 == hashes2, "first 90% of chains should be identical"

    assert not trans.verify(
        miner1.chainbuilder.primary_block_chain,
        set()), "inserted transaction should be spent and therefore invalid"

    assert TransactionInput(
        trans.get_hash(),
        0) in chain1.unspent_coins, "someone spent our coins?"
예제 #2
0
    def recv(self, msg):
        try:
            r = Protocol(msg)
            head = r.get_int8()
            if head != 0x1:
                return

            code = r.get_int8()
            if code == 0x0:
                self.get_request()

            elif code == 0x2:
                self.get_fin_room_id(r)

            elif code == 0xe:
                logger.error('Bad Room ID')
                self.send_error()

            elif code == 0xf:
                self.send_error()

            else:
                self.send_error()
        except StructError:
            self.send_error()
예제 #3
0
def start_listener(rpc_port: int, bootstrap_peer: str, listen_port: int,
                   listen_address: str):
    """ Starts the RPC Server and initializes the protocol. """
    proto = Protocol([parse_addr_port(bootstrap_peer)], GENESIS_BLOCK,
                     listen_port, listen_address)
    chainbuilder = ChainBuilder(proto)
    rpc_server(rpc_port, chainbuilder, None)
예제 #4
0
def start_server(chain):
    """builds a chainbuilder from a Blockchain, appends and starts a rpc server"""
    proto = Protocol([], GENESIS_BLOCK, 1337)
    chainbuilder = ChainBuilder(proto)

    chainbuilder.primary_block_chain = chain

    return start_new_thread(rpc_server, (port, chainbuilder, None))
예제 #5
0
    def recv(self):
        res = self.room.recv()
        logger.debug('Register recv message: %s' % res)
        p = Protocol(res)
        first_code = p.get_int8()
        if first_code != 0x1:
            return b''  # ! bad idea

        return p
예제 #6
0
 def get_proto_head(self, code: int):
     bs = Protocol()
     bs.add_int8(0x1)
     bs.add_int8(code)
     return bs
예제 #7
0
def main():
    """
    Takes arguments:
    `listen-address`: The IP address where the P2P server should bind to. Default is: `\"\"`
    `listen-port`: The port where the P2P server should listen. Defaults a dynamically assigned port. Default is: `0`
    `mining-pubkey`: The public key where mining rewards should be sent to. No mining is performed if this is left unspecified.
    `bootstrap-peer`: Addresses of other P2P peers in the network. Default is: `[]`
    `rpc-port`: The port number where the wallet can find an RPC server. Default is: `40203`
    `persist-path`: The file where data is persisted.
    """
    parser = argparse.ArgumentParser(description="Blockchain Miner.")
    parser.add_argument(
        "--listen-address",
        default="",
        help="The IP address where the P2P server should bind to.")
    parser.add_argument(
        "--listen-port",
        default=0,
        type=int,
        help=
        "The port where the P2P server should listen. Defaults a dynamically assigned port."
    )
    parser.add_argument(
        "--mining-pubkey",
        type=argparse.FileType('rb'),
        help=
        "The public key where mining rewards should be sent to. No mining is performed if this is left unspecified."
    )
    parser.add_argument("--bootstrap-peer",
                        action='append',
                        type=parse_addr_port,
                        default=[],
                        help="Addresses of other P2P peers in the network.")
    parser.add_argument(
        "--rpc-port",
        type=int,
        default=40203,
        help="The port number where the wallet can find an RPC server.")
    parser.add_argument("--persist-path",
                        help="The file where data is persisted.")

    args = parser.parse_args()

    proto = Protocol(args.bootstrap_peer, GENESIS_BLOCK, args.listen_port,
                     args.listen_address)
    if args.mining_pubkey is not None:
        pubkey = Key(args.mining_pubkey.read())
        args.mining_pubkey.close()
        miner = Miner(proto, pubkey)
        miner.start_mining()
        chainbuilder = miner.chainbuilder
    else:
        chainbuilder = ChainBuilder(proto)

    if args.persist_path:
        persist = Persistence(args.persist_path, chainbuilder)
        try:
            persist.load()
        except FileNotFoundError:
            pass
    else:
        persist = None

    rpc_server(args.rpc_port, chainbuilder, persist)