def run_test(self):
        """Main test logic"""

        cli_response = self.nodes[0].cli("-version").send_cli()
        assert("Bitcoin Core RPC client version" in cli_response)

        self.log.info("Compare responses from getwalletinfo RPC and `bitcoin-cli getwalletinfo`")
        if self.is_wallet_compiled():
            cli_response = self.nodes[0].cli.getwalletinfo()
            rpc_response = self.nodes[0].getwalletinfo()
            assert_equal(cli_response, rpc_response)

        self.log.info("Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`")
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(0, self.nodes[0].cli('-rpcuser=%s' % user, '-stdinrpcpass', input=password).getblockcount())
        assert_raises_process_error(1, "Incorrect rpcuser or rpcpassword", self.nodes[0].cli('-rpcuser=%s' % user, '-stdinrpcpass', input="foo").echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(["foo", "bar"], self.nodes[0].cli('-rpcuser=%s' % user, '-stdin', '-stdinrpcpass', input=password + "\nfoo\nbar").echo())
        assert_raises_process_error(1, "Incorrect rpcuser or rpcpassword", self.nodes[0].cli('-rpcuser=%s' % user, '-stdin', '-stdinrpcpass', input="foo").echo)

        self.log.info("Test connecting to a non-existing server")
        assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcport=1').echo)

        self.log.info("Test connecting with non-existing RPC cookie file")
        assert_raises_process_error(1, "Could not locate RPC credentials", self.nodes[0].cli('-rpccookiefile=does-not-exist', '-rpcpassword='******'-getinfo').help)

        self.log.info("Compare responses from `bitcoin-cli -getinfo` and the RPCs data is retrieved from.")
        cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
        if self.is_wallet_compiled():
            wallet_info = self.nodes[0].getwalletinfo()
        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()

        assert_equal(cli_get_info['version'], network_info['version'])
        assert_equal(cli_get_info['protocolversion'], network_info['protocolversion'])
        if self.is_wallet_compiled():
            assert_equal(cli_get_info['walletversion'], wallet_info['walletversion'])
            assert_equal(cli_get_info['balance'], wallet_info['balance'])
        assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
        assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
        assert_equal(cli_get_info['connections'], network_info['connections'])
        assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy'])
        assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
        assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test")
        if self.is_wallet_compiled():
            assert_equal(cli_get_info['balance'], wallet_info['balance'])
            assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest'])
            assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize'])
            assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
            assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
示例#2
0
    def run_test(self):
        """Main test logic"""

        self.log.info(
            "Compare responses from gewalletinfo RPC and `bitcoin-cli getwalletinfo`")
        cli_response = self.nodes[0].cli.getwalletinfo()
        rpc_response = self.nodes[0].getwalletinfo()
        assert_equal(cli_response, rpc_response)

        self.log.info(
            "Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`")
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(0, self.nodes[0].cli(
            '-rpcuser=%s' % user, '-stdinrpcpass', input=password).getblockcount())
        assert_raises_process_error(1, "incorrect rpcuser or rpcpassword", self.nodes[0].cli(
            '-rpcuser=%s' % user, '-stdinrpcpass', input="foo").echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(["foo", "bar"], self.nodes[0].cli('-rpcuser=%s' % user,
                                                       '-stdin', '-stdinrpcpass', input=password + "\nfoo\nbar").echo())
        assert_raises_process_error(1, "incorrect rpcuser or rpcpassword", self.nodes[0].cli(
            '-rpcuser=%s' % user, '-stdin', '-stdinrpcpass', input="foo").echo)
    def run_test(self):
        """Main test logic"""

        self.log.info("Compare responses from gewalletinfo RPC and `groincoin-cli getwalletinfo`")
        cli_response = self.nodes[0].cli.getwalletinfo()
        rpc_response = self.nodes[0].getwalletinfo()
        assert_equal(cli_response, rpc_response)

        self.log.info("Compare responses from getblockchaininfo RPC and `groincoin-cli getblockchaininfo`")
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(0, self.nodes[0].cli('-rpcuser=%s' % user, '-stdinrpcpass', input=password).getblockcount())
        assert_raises_process_error(1, "incorrect rpcuser or rpcpassword", self.nodes[0].cli('-rpcuser=%s' % user, '-stdinrpcpass', input="foo").echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(["foo", "bar"], self.nodes[0].cli('-rpcuser=%s' % user, '-stdin', '-stdinrpcpass', input=password + "\nfoo\nbar").echo())
        assert_raises_process_error(1, "incorrect rpcuser or rpcpassword", self.nodes[0].cli('-rpcuser=%s' % user, '-stdin', '-stdinrpcpass', input="foo").echo)

        self.log.info("Make sure that -getinfo with arguments fails")
        assert_raises_process_error(1, "-getinfo takes no arguments", self.nodes[0].cli('-getinfo').help)

        self.log.info("Compare responses from `groincoin-cli -getinfo` and the RPCs data is retrieved from.")
        cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
        wallet_info = self.nodes[0].getwalletinfo()
        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()

        assert_equal(cli_get_info['version'], network_info['version'])
        assert_equal(cli_get_info['protocolversion'], network_info['protocolversion'])
        assert_equal(cli_get_info['walletversion'], wallet_info['walletversion'])
        assert_equal(cli_get_info['balance'], wallet_info['balance'])
        assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
        assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
        assert_equal(cli_get_info['connections'], network_info['connections'])
        assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy'])
        assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
        assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test")
        assert_equal(cli_get_info['balance'], wallet_info['balance'])
        assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest'])
        assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize'])
        assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
        assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
    def run_test(self):
        """Main test logic"""

        self.log.info("Sleeping 30 seconds...")
        time.sleep(30)

        self.log.info("Compare responses from gewalletinfo RPC and `pivx-cli getwalletinfo`")
        cli_response = self.nodes[0].cli.getwalletinfo()
        rpc_response = self.nodes[0].getwalletinfo()
        assert_equal(cli_response, rpc_response)

        self.log.info("Compare responses from getblockchaininfo RPC and `pivx-cli getblockchaininfo`")
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir)

        self.log.info("Compare responses from `pivx-cli -getinfo` and the RPCs data is retrieved from.")
        cli_get_info = self.nodes[0].cli('getinfo').send_cli()
        wallet_info = self.nodes[0].getwalletinfo()
        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()

        assert_equal(cli_get_info['version'], network_info['version'])
        assert_equal(cli_get_info['protocolversion'], network_info['protocolversion'])
        assert_equal(cli_get_info['walletversion'], wallet_info['walletversion'])
        assert_equal(cli_get_info['balance'], wallet_info['balance'])
        assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
        assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
        assert_equal(cli_get_info['connections'], network_info['connections'])
        assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy'])
        assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
        assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test")
        assert_equal(cli_get_info['balance'], wallet_info['balance'])
        assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest'])
        assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize'])
        assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
        assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
    def run_test(self):
        """Main test logic"""

        self.log.info(
            "Compare responses from getinfo RPC and `cryptomiles-cli getinfo`")
        cli_get_info = self.nodes[0].cli.getinfo()
        rpc_get_info = self.nodes[0].getinfo()

        assert_equal(cli_get_info, rpc_get_info)

        user, password = get_auth_cookie(self.nodes[0].datadir)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(
            0, self.nodes[0].cli('-rpcuser=%s' % user,
                                 '-stdinrpcpass',
                                 input=password).getblockcount())
        assert_raises_process_error(
            1, "incorrect rpcuser or rpcpassword",
            self.nodes[0].cli('-rpcuser=%s' % user,
                              '-stdinrpcpass',
                              input="foo").echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(["foo", "bar"],
                     self.nodes[0].cli('-rpcuser=%s' % user,
                                       '-stdin',
                                       '-stdinrpcpass',
                                       input=password + "\nfoo\nbar").echo())
        assert_raises_process_error(
            1, "incorrect rpcuser or rpcpassword",
            self.nodes[0].cli('-rpcuser=%s' % user,
                              '-stdin',
                              '-stdinrpcpass',
                              input="foo").echo)

        self.log.info(
            "Compare responses from `cryptomiles-cli -getinfo` and the RPCs data is retrieved from."
        )
        cli_get_info = self.nodes[0].cli('-getinfo').help()
        wallet_info = self.nodes[0].getwalletinfo()
        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()

        assert_equal(cli_get_info['version'], network_info['version'])
        assert_equal(cli_get_info['protocolversion'],
                     network_info['protocolversion'])
        assert_equal(cli_get_info['walletversion'],
                     wallet_info['walletversion'])
        assert_equal(cli_get_info['balance'], wallet_info['balance'])
        assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
        assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
        assert_equal(cli_get_info['connections'], network_info['connections'])
        assert_equal(cli_get_info['proxy'],
                     network_info['networks'][0]['proxy'])
        assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
        assert_equal(cli_get_info['testnet'],
                     blockchain_info['chain'] == "test")
        assert_equal(cli_get_info['balance'], wallet_info['balance'])
        assert_equal(cli_get_info['keypoololdest'],
                     wallet_info['keypoololdest'])
        assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize'])
        assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
        assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
示例#6
0
    def run_test(self):
        """Main test logic"""
        self.nodes[0].generate(BLOCKS)

        cli_response = self.nodes[0].cli("-version").send_cli()
        assert "{} RPC client version".format(self.config['environment']['PACKAGE_NAME']) in cli_response

        self.log.info("Compare responses from getwalletinfo RPC and `BGL-cli getwalletinfo`")
        if self.is_wallet_compiled():
            self.log.info("Compare responses from getwalletinfo RPC and `BGL-cli getwalletinfo`")
            cli_response = self.nodes[0].cli.getwalletinfo()
            rpc_response = self.nodes[0].getwalletinfo()
            assert_equal(cli_response, rpc_response)

        self.log.info("Compare responses from getblockchaininfo RPC and `BGL-cli getblockchaininfo`")
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir, self.chain)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(BLOCKS, self.nodes[0].cli('-rpcuser={}'.format(user), '-stdinrpcpass', input=password).getblockcount())
        assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli('-rpcuser={}'.format(user), '-stdinrpcpass', input='foo').echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(['foo', 'bar'], self.nodes[0].cli('-rpcuser={}'.format(user), '-stdin', '-stdinrpcpass', input=password + '\nfoo\nbar').echo())
        assert_raises_process_error(1, 'Incorrect rpcuser or rpcpassword', self.nodes[0].cli('-rpcuser={}'.format(user), '-stdin', '-stdinrpcpass', input='foo').echo)

        self.log.info("Test connecting to a non-existing server")
        assert_raises_process_error(1, "Could not connect to the server", self.nodes[0].cli('-rpcport=1').echo)

        self.log.info("Test connecting with non-existing RPC cookie file")
        assert_raises_process_error(1, "Could not locate RPC credentials", self.nodes[0].cli('-rpccookiefile=does-not-exist', '-rpcpassword='******'-getinfo').help)

        self.log.info("Compare responses from `BGL-cli -getinfo` and the RPCs data is retrieved from.")
        if self.is_wallet_compiled():
            self.nodes[0].encryptwallet(password)
        cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()

        assert_equal(cli_get_info['version'], network_info['version'])
        assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
        assert_equal(cli_get_info['headers'], blockchain_info['headers'])
        assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
        assert_equal(
            cli_get_info['connections'],
            {
                'in': network_info['connections_in'],
                'out': network_info['connections_out'],
                'total': network_info['connections']
            }
        )
        assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy'])
        assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
        assert_equal(cli_get_info['chain'], blockchain_info['chain'])

        if self.is_wallet_compiled():
            self.log.info("Test -getinfo returns expected wallet info")
            assert_equal(cli_get_info['balance'], BALANCE)
            assert 'balances' not in cli_get_info.keys()
            wallet_info = self.nodes[0].getwalletinfo()
            assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize'])
            assert_equal(cli_get_info['unlocked_until'], wallet_info['unlocked_until'])
            assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
            assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
            assert_equal(self.nodes[0].cli.getwalletinfo(), wallet_info)

            # Setup to test -getinfo, -generate, and -rpcwallet= with multiple wallets.
            wallets = [self.default_wallet_name, 'Encrypted', 'secret']
            amounts = [BALANCE + Decimal('9.999928'), Decimal(9), Decimal(31)]
            self.nodes[0].createwallet(wallet_name=wallets[1])
            self.nodes[0].createwallet(wallet_name=wallets[2])
            w1 = self.nodes[0].get_wallet_rpc(wallets[0])
            w2 = self.nodes[0].get_wallet_rpc(wallets[1])
            w3 = self.nodes[0].get_wallet_rpc(wallets[2])
            rpcwallet2 = '-rpcwallet={}'.format(wallets[1])
            rpcwallet3 = '-rpcwallet={}'.format(wallets[2])
            w1.walletpassphrase(password, self.rpc_timeout)
            w2.encryptwallet(password)
            w1.sendtoaddress(w2.getnewaddress(), amounts[1])
            w1.sendtoaddress(w3.getnewaddress(), amounts[2])

            # Mine a block to confirm; adds a block reward (50 BTC) to the default wallet.
            self.nodes[0].generate(1)

            self.log.info("Test -getinfo with multiple wallets and -rpcwallet returns specified wallet balance")
            for i in range(len(wallets)):
                cli_get_info = self.nodes[0].cli('-getinfo', '-rpcwallet={}'.format(wallets[i])).send_cli()
                assert 'balances' not in cli_get_info.keys()
                assert_equal(cli_get_info['balance'], amounts[i])

            self.log.info("Test -getinfo with multiple wallets and -rpcwallet=non-existing-wallet returns no balances")
            cli_get_info_keys = self.nodes[0].cli('-getinfo', '-rpcwallet=does-not-exist').send_cli().keys()
            assert 'balance' not in cli_get_info_keys
            assert 'balances' not in cli_get_info_keys

            self.log.info("Test -getinfo with multiple wallets returns all loaded wallet names and balances")
            assert_equal(set(self.nodes[0].listwallets()), set(wallets))
            cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
            assert 'balance' not in cli_get_info.keys()
            assert_equal(cli_get_info['balances'], {k: v for k, v in zip(wallets, amounts)})

            # Unload the default wallet and re-verify.
            self.nodes[0].unloadwallet(wallets[0])
            assert wallets[0] not in self.nodes[0].listwallets()
            cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
            assert 'balance' not in cli_get_info.keys()
            assert_equal(cli_get_info['balances'], {k: v for k, v in zip(wallets[1:], amounts[1:])})

            self.log.info("Test -getinfo after unloading all wallets except a non-default one returns its balance")
            self.nodes[0].unloadwallet(wallets[2])
            assert_equal(self.nodes[0].listwallets(), [wallets[1]])
            cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
            assert 'balances' not in cli_get_info.keys()
            assert_equal(cli_get_info['balance'], amounts[1])

            self.log.info("Test -getinfo with -rpcwallet=remaining-non-default-wallet returns only its balance")
            cli_get_info = self.nodes[0].cli('-getinfo', rpcwallet2).send_cli()
            assert 'balances' not in cli_get_info.keys()
            assert_equal(cli_get_info['balance'], amounts[1])

            self.log.info("Test -getinfo with -rpcwallet=unloaded wallet returns no balances")
            cli_get_info = self.nodes[0].cli('-getinfo', rpcwallet3).send_cli()
            assert 'balance' not in cli_get_info_keys
            assert 'balances' not in cli_get_info_keys

            # Test BGL-cli -generate.
            n1 = 3
            n2 = 4
            w2.walletpassphrase(password, self.rpc_timeout)
            blocks = self.nodes[0].getblockcount()

            self.log.info('Test -generate with no args')
            generate = self.nodes[0].cli('-generate').send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), 1)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1)

            self.log.info('Test -generate with bad args')
            assert_raises_process_error(1, JSON_PARSING_ERROR, self.nodes[0].cli('-generate', 'foo').echo)
            assert_raises_process_error(1, BLOCKS_VALUE_OF_ZERO, self.nodes[0].cli('-generate', 0).echo)
            assert_raises_process_error(1, TOO_MANY_ARGS, self.nodes[0].cli('-generate', 1, 2, 3).echo)

            self.log.info('Test -generate with nblocks')
            generate = self.nodes[0].cli('-generate', n1).send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), n1)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1)

            self.log.info('Test -generate with nblocks and maxtries')
            generate = self.nodes[0].cli('-generate', n2, 1000000).send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), n2)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1 + n2)

            self.log.info('Test -generate -rpcwallet in single-wallet mode')
            generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), 1)
            assert_equal(self.nodes[0].getblockcount(), blocks + 2 + n1 + n2)

            self.log.info('Test -generate -rpcwallet=unloaded wallet raises RPC error')
            assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate').echo)
            assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 'foo').echo)
            assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 0).echo)
            assert_raises_rpc_error(-18, WALLET_NOT_LOADED, self.nodes[0].cli(rpcwallet3, '-generate', 1, 2, 3).echo)

            # Test BGL-cli -generate with -rpcwallet in multiwallet mode.
            self.nodes[0].loadwallet(wallets[2])
            n3 = 4
            n4 = 10
            blocks = self.nodes[0].getblockcount()

            self.log.info('Test -generate -rpcwallet with no args')
            generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), 1)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1)

            self.log.info('Test -generate -rpcwallet with bad args')
            assert_raises_process_error(1, JSON_PARSING_ERROR, self.nodes[0].cli(rpcwallet2, '-generate', 'foo').echo)
            assert_raises_process_error(1, BLOCKS_VALUE_OF_ZERO, self.nodes[0].cli(rpcwallet2, '-generate', 0).echo)
            assert_raises_process_error(1, TOO_MANY_ARGS, self.nodes[0].cli(rpcwallet2, '-generate', 1, 2, 3).echo)

            self.log.info('Test -generate -rpcwallet with nblocks')
            generate = self.nodes[0].cli(rpcwallet2, '-generate', n3).send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), n3)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3)

            self.log.info('Test -generate -rpcwallet with nblocks and maxtries')
            generate = self.nodes[0].cli(rpcwallet2, '-generate', n4, 1000000).send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), n4)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3 + n4)

            self.log.info('Test -generate without -rpcwallet in multiwallet mode raises RPC error')
            assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate').echo)
            assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 'foo').echo)
            assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 0).echo)
            assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED, self.nodes[0].cli('-generate', 1, 2, 3).echo)
        else:
            self.log.info("*** Wallet not compiled; cli getwalletinfo and -getinfo wallet tests skipped")
            self.nodes[0].generate(25)  # maintain block parity with the wallet_compiled conditional branch

        self.log.info("Test -version with node stopped")
        self.stop_node(0)
        cli_response = self.nodes[0].cli('-version').send_cli()
        assert "{} RPC client version".format(self.config['environment']['PACKAGE_NAME']) in cli_response

        self.log.info("Test -rpcwait option successfully waits for RPC connection")
        self.nodes[0].start()  # start node without RPC connection
        self.nodes[0].wait_for_cookie_credentials()  # ensure cookie file is available to avoid race condition
        blocks = self.nodes[0].cli('-rpcwait').send_cli('getblockcount')
        self.nodes[0].wait_for_rpc_connection()
        assert_equal(blocks, BLOCKS + 25)
示例#7
0
    def run_test(self):
        """Main test logic"""

        cli_response = self.nodes[0].cli("-version").send_cli()
        assert ("Litecoingreen Core RPC client version" in cli_response)

        self.log.info(
            "Compare responses from getwalletinfo RPC and `litecoingreen-cli getwalletinfo`"
        )
        if self.is_wallet_compiled():
            cli_response = self.nodes[0].cli.getwalletinfo()
            rpc_response = self.nodes[0].getwalletinfo()
            assert_equal(cli_response, rpc_response)

        self.log.info(
            "Compare responses from getblockchaininfo RPC and `litecoingreen-cli getblockchaininfo`"
        )
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(
            0, self.nodes[0].cli('-rpcuser=%s' % user,
                                 '-stdinrpcpass',
                                 input=password).getblockcount())
        assert_raises_process_error(
            1, "Incorrect rpcuser or rpcpassword",
            self.nodes[0].cli('-rpcuser=%s' % user,
                              '-stdinrpcpass',
                              input="foo").echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(["foo", "bar"],
                     self.nodes[0].cli('-rpcuser=%s' % user,
                                       '-stdin',
                                       '-stdinrpcpass',
                                       input=password + "\nfoo\nbar").echo())
        assert_raises_process_error(
            1, "Incorrect rpcuser or rpcpassword",
            self.nodes[0].cli('-rpcuser=%s' % user,
                              '-stdin',
                              '-stdinrpcpass',
                              input="foo").echo)

        self.log.info("Test connecting to a non-existing server")
        assert_raises_process_error(1, "Could not connect to the server",
                                    self.nodes[0].cli('-rpcport=1').echo)

        self.log.info("Test connecting with non-existing RPC cookie file")
        assert_raises_process_error(
            1, "Could not locate RPC credentials",
            self.nodes[0].cli('-rpccookiefile=does-not-exist',
                              '-rpcpassword='******'-getinfo').help)

        self.log.info(
            "Compare responses from `litecoingreen-cli -getinfo` and the RPCs data is retrieved from."
        )
        cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
        if self.is_wallet_compiled():
            wallet_info = self.nodes[0].getwalletinfo()
        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()

        assert_equal(cli_get_info['version'], network_info['version'])
        assert_equal(cli_get_info['protocolversion'],
                     network_info['protocolversion'])
        if self.is_wallet_compiled():
            assert_equal(cli_get_info['walletversion'],
                         wallet_info['walletversion'])
            assert_equal(cli_get_info['balance'], wallet_info['balance'])
        assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
        assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
        assert_equal(cli_get_info['connections'], network_info['connections'])
        assert_equal(cli_get_info['proxy'],
                     network_info['networks'][0]['proxy'])
        assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
        assert_equal(cli_get_info['testnet'],
                     blockchain_info['chain'] == "test")
        if self.is_wallet_compiled():
            assert_equal(cli_get_info['balance'], wallet_info['balance'])
            assert_equal(cli_get_info['keypoololdest'],
                         wallet_info['keypoololdest'])
            assert_equal(cli_get_info['keypoolsize'],
                         wallet_info['keypoolsize'])
            assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
            assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
示例#8
0
    def setup_network(self, split=False):
        if self.options.parent_bitcoin and self.options.parent_binpath == "":
            raise Exception(
                "Can't run with --parent_bitcoin without specifying --parent_binpath"
            )

        self.nodes = []
        # Setup parent nodes
        parent_chain = "elementsregtest" if not self.options.parent_bitcoin else "regtest"
        parent_binary = [self.options.parent_binpath
                         ] if self.options.parent_binpath != "" else None
        for n in range(2):
            extra_args = [
                "-port=" + str(p2p_port(n)), "-rpcport=" + str(rpc_port(n))
            ]
            if self.options.parent_bitcoin:
                # bitcoind can't read elements.conf config files
                extra_args.extend([
                    "-regtest=1",
                    "-printtoconsole=0",
                    "-server=1",
                    "-discover=0",
                    "-keypool=1",
                    "-listenonion=0",
                    "-addresstype=legacy",  # To make sure bitcoind gives back p2pkh no matter version
                ])
            else:
                extra_args.extend([
                    "-validatepegin=0",
                    "-initialfreecoins=0",
                    "-anyonecanspendaremine=1",
                    "-signblockscript=51",  # OP_TRUE
                ])

            self.add_nodes(1, [extra_args],
                           chain=[parent_chain],
                           binary=parent_binary,
                           chain_in_args=[not self.options.parent_bitcoin])
            self.start_node(n)
            print("Node {} started".format(n))
        # set hard-coded mining keys for non-Elements chains
        if self.options.parent_bitcoin:
            self.nodes[0].set_deterministic_priv_key(
                '2Mysp7FKKe52eoC2JmU46irt1dt58TpCvhQ',
                'cTNbtVJmhx75RXomhYWSZAafuNNNKPd1cr2ZiUcAeukLNGrHWjvJ')
            self.nodes[1].set_deterministic_priv_key(
                '2N19ZHF3nEzBXzkaZ3N5sVBJXQ8jZ7Udpg5',
                'cRnDSw1JsjmYYEN6xxQvf5pqMENsRE584z6MdWfJ7v85c4ciitkk')

        connect_nodes_bi(self.nodes, 0, 1)
        self.parentgenesisblockhash = self.nodes[0].getblockhash(0)
        if not self.options.parent_bitcoin:
            parent_pegged_asset = self.nodes[0].getsidechaininfo(
            )['pegged_asset']

        # Setup sidechain nodes
        self.fedpeg_script = "512103dff4923d778550cc13ce0d887d737553b4b58f4e8e886507fc39f5e447b2186451ae"
        for n in range(2):
            extra_args = [
                "-printtoconsole=0",
                "-port=" + str(p2p_port(2 + n)),
                "-rpcport=" + str(rpc_port(2 + n)),
                '-validatepegin=1',
                '-fedpegscript=%s' % self.fedpeg_script,
                '-minrelaytxfee=0',
                '-blockmintxfee=0',
                '-initialfreecoins=0',
                '-peginconfirmationdepth=10',
                '-mainchainrpchost=127.0.0.1',
                '-mainchainrpcport=%s' % rpc_port(n),
                '-recheckpeginblockinterval=15',  # Long enough to allow failure and repair before timeout
                '-parentgenesisblockhash=%s' % self.parentgenesisblockhash,
                '-parentpubkeyprefix=111',
                '-parentscriptprefix=196',
                '-parent_bech32_hrp=bcrt',
                # Turn of consistency checks that can cause assert when parent node stops
                # and a peg-in transaction fails this belt-and-suspenders check.
                '-checkmempool=0',
            ]
            if not self.options.parent_bitcoin:
                extra_args.extend([
                    '-parentpubkeyprefix=235',
                    '-parentscriptprefix=75',
                    '-parent_bech32_hrp=ert',
                    '-con_parent_chain_signblockscript=51',
                    '-con_parent_pegged_asset=%s' % parent_pegged_asset,
                ])

            # Immediate activation of dynafed when requested versus "never" from conf
            if self.options.pre_transition or self.options.post_transition:
                extra_args.extend(["-con_dyna_deploy_start=-1"])

            # Use rpcuser auth only for first parent.
            if n == 0:
                # Extract username and password from cookie file and use directly.
                datadir = get_datadir_path(self.options.tmpdir, n)
                rpc_u, rpc_p = get_auth_cookie(datadir, parent_chain)
                extra_args.extend([
                    '-mainchainrpcuser=%s' % rpc_u,
                    '-mainchainrpcpassword=%s' % rpc_p,
                ])
            else:
                # Need to specify where to find parent cookie file
                datadir = get_datadir_path(self.options.tmpdir, n)
                extra_args.append('-mainchainrpccookiefile=' + datadir + "/" +
                                  parent_chain + "/.cookie")

            self.add_nodes(1, [extra_args], chain=["elementsregtest"])
            self.start_node(2 + n)
            print("Node {} started".format(2 + n))

        # We only connect the same-chain nodes, so sync_all works correctly
        connect_nodes_bi(self.nodes, 2, 3)
        self.node_groups = [[self.nodes[0], self.nodes[1]],
                            [self.nodes[2], self.nodes[3]]]
        self.sync_all(self.node_groups)
        print("Setting up network done")
示例#9
0
    def run_test(self):
        """Main test logic"""
        self.nodes[0].generate(BLOCKS)

        self.log.info(
            "Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`"
        )
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir, self.chain)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(
            BLOCKS, self.nodes[0].cli(f'-rpcuser={user}',
                                      '-stdinrpcpass',
                                      input=password).getblockcount())
        assert_raises_process_error(
            1, 'Incorrect rpcuser or rpcpassword',
            self.nodes[0].cli(f'-rpcuser={user}', '-stdinrpcpass',
                              input='foo').echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(['foo', 'bar'],
                     self.nodes[0].cli(f'-rpcuser={user}',
                                       '-stdin',
                                       '-stdinrpcpass',
                                       input=f'{password}\nfoo\nbar').echo())
        assert_raises_process_error(
            1, 'Incorrect rpcuser or rpcpassword',
            self.nodes[0].cli(f'-rpcuser={user}',
                              '-stdin',
                              '-stdinrpcpass',
                              input='foo').echo)

        self.log.info("Test connecting to a non-existing server")
        assert_raises_process_error(1, "Could not connect to the server",
                                    self.nodes[0].cli('-rpcport=1').echo)

        self.log.info("Test connecting with non-existing RPC cookie file")
        assert_raises_process_error(
            1, "Could not locate RPC credentials",
            self.nodes[0].cli('-rpccookiefile=does-not-exist',
                              '-rpcpassword='******'-getinfo').help)

        self.log.info(
            "Test -getinfo with -color=never does not return ANSI escape codes"
        )
        assert "\u001b[0m" not in self.nodes[0].cli('-getinfo',
                                                    '-color=never').send_cli()

        self.log.info(
            "Test -getinfo with -color=always returns ANSI escape codes")
        assert "\u001b[0m" in self.nodes[0].cli('-getinfo',
                                                '-color=always').send_cli()

        self.log.info("Test -getinfo with invalid value for -color option")
        assert_raises_process_error(
            1,
            "Invalid value for -color option. Valid values: always, auto, never.",
            self.nodes[0].cli('-getinfo', '-color=foo').send_cli)

        self.log.info(
            "Test -getinfo returns expected network and blockchain info")
        if self.is_wallet_compiled():
            self.nodes[0].encryptwallet(password)
        cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
        cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)

        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()
        assert_equal(int(cli_get_info['Version']), network_info['version'])
        assert_equal(
            cli_get_info['Verification progress'],
            "%.4f%%" % (blockchain_info['verificationprogress'] * 100))
        assert_equal(int(cli_get_info['Blocks']), blockchain_info['blocks'])
        assert_equal(int(cli_get_info['Headers']), blockchain_info['headers'])
        assert_equal(int(cli_get_info['Time offset (s)']),
                     network_info['timeoffset'])
        expected_network_info = f"in {network_info['connections_in']}, out {network_info['connections_out']}, total {network_info['connections']}"
        assert_equal(cli_get_info["Network"], expected_network_info)
        assert_equal(cli_get_info['Proxy'],
                     network_info['networks'][0]['proxy'])
        assert_equal(Decimal(cli_get_info['Difficulty']),
                     blockchain_info['difficulty'])
        assert_equal(cli_get_info['Chain'], blockchain_info['chain'])

        if self.is_wallet_compiled():
            self.log.info(
                "Test -getinfo and bitcoin-cli getwalletinfo return expected wallet info"
            )
            assert_equal(Decimal(cli_get_info['Balance']), BALANCE)
            assert 'Balances' not in cli_get_info_string
            wallet_info = self.nodes[0].getwalletinfo()
            assert_equal(int(cli_get_info['Keypool size']),
                         wallet_info['keypoolsize'])
            assert_equal(int(cli_get_info['Unlocked until']),
                         wallet_info['unlocked_until'])
            assert_equal(
                Decimal(
                    cli_get_info['Transaction fee rate (-paytxfee) (BTC/kvB)']
                ), wallet_info['paytxfee'])
            assert_equal(
                Decimal(cli_get_info['Min tx relay fee rate (BTC/kvB)']),
                network_info['relayfee'])
            assert_equal(self.nodes[0].cli.getwalletinfo(), wallet_info)

            # Setup to test -getinfo, -generate, and -rpcwallet= with multiple wallets.
            wallets = [self.default_wallet_name, 'Encrypted', 'secret']
            amounts = [BALANCE + Decimal('9.999928'), Decimal(9), Decimal(31)]
            self.nodes[0].createwallet(wallet_name=wallets[1])
            self.nodes[0].createwallet(wallet_name=wallets[2])
            w1 = self.nodes[0].get_wallet_rpc(wallets[0])
            w2 = self.nodes[0].get_wallet_rpc(wallets[1])
            w3 = self.nodes[0].get_wallet_rpc(wallets[2])
            rpcwallet2 = f'-rpcwallet={wallets[1]}'
            rpcwallet3 = f'-rpcwallet={wallets[2]}'
            w1.walletpassphrase(password, self.rpc_timeout)
            w2.encryptwallet(password)
            w1.sendtoaddress(w2.getnewaddress(), amounts[1])
            w1.sendtoaddress(w3.getnewaddress(), amounts[2])

            # Mine a block to confirm; adds a block reward (50 BTC) to the default wallet.
            self.nodes[0].generate(1)

            self.log.info(
                "Test -getinfo with multiple wallets and -rpcwallet returns specified wallet balance"
            )
            for i in range(len(wallets)):
                cli_get_info_string = self.nodes[0].cli(
                    '-getinfo', f'-rpcwallet={wallets[i]}').send_cli()
                cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
                assert 'Balances' not in cli_get_info_string
                assert_equal(cli_get_info["Wallet"], wallets[i])
                assert_equal(Decimal(cli_get_info['Balance']), amounts[i])

            self.log.info(
                "Test -getinfo with multiple wallets and -rpcwallet=non-existing-wallet returns no balances"
            )
            cli_get_info_string = self.nodes[0].cli(
                '-getinfo', '-rpcwallet=does-not-exist').send_cli()
            assert 'Balance' not in cli_get_info_string
            assert 'Balances' not in cli_get_info_string

            self.log.info(
                "Test -getinfo with multiple wallets returns all loaded wallet names and balances"
            )
            assert_equal(set(self.nodes[0].listwallets()), set(wallets))
            cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
            cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
            assert 'Balance' not in cli_get_info
            for k, v in zip(wallets, amounts):
                assert_equal(Decimal(cli_get_info['Balances'][k]), v)

            # Unload the default wallet and re-verify.
            self.nodes[0].unloadwallet(wallets[0])
            assert wallets[0] not in self.nodes[0].listwallets()
            cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
            cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
            assert 'Balance' not in cli_get_info
            assert 'Balances' in cli_get_info_string
            for k, v in zip(wallets[1:], amounts[1:]):
                assert_equal(Decimal(cli_get_info['Balances'][k]), v)
            assert wallets[0] not in cli_get_info

            self.log.info(
                "Test -getinfo after unloading all wallets except a non-default one returns its balance"
            )
            self.nodes[0].unloadwallet(wallets[2])
            assert_equal(self.nodes[0].listwallets(), [wallets[1]])
            cli_get_info_string = self.nodes[0].cli('-getinfo').send_cli()
            cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
            assert 'Balances' not in cli_get_info_string
            assert_equal(cli_get_info['Wallet'], wallets[1])
            assert_equal(Decimal(cli_get_info['Balance']), amounts[1])

            self.log.info(
                "Test -getinfo with -rpcwallet=remaining-non-default-wallet returns only its balance"
            )
            cli_get_info_string = self.nodes[0].cli('-getinfo',
                                                    rpcwallet2).send_cli()
            cli_get_info = cli_get_info_string_to_dict(cli_get_info_string)
            assert 'Balances' not in cli_get_info_string
            assert_equal(cli_get_info['Wallet'], wallets[1])
            assert_equal(Decimal(cli_get_info['Balance']), amounts[1])

            self.log.info(
                "Test -getinfo with -rpcwallet=unloaded wallet returns no balances"
            )
            cli_get_info_string = self.nodes[0].cli('-getinfo',
                                                    rpcwallet3).send_cli()
            cli_get_info_keys = cli_get_info_string_to_dict(
                cli_get_info_string)
            assert 'Balance' not in cli_get_info_keys
            assert 'Balances' not in cli_get_info_string

            # Test bitcoin-cli -generate.
            n1 = 3
            n2 = 4
            w2.walletpassphrase(password, self.rpc_timeout)
            blocks = self.nodes[0].getblockcount()

            self.log.info('Test -generate with no args')
            generate = self.nodes[0].cli('-generate').send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), 1)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1)

            self.log.info('Test -generate with bad args')
            assert_raises_process_error(
                1, JSON_PARSING_ERROR, self.nodes[0].cli('-generate',
                                                         'foo').echo)
            assert_raises_process_error(1, BLOCKS_VALUE_OF_ZERO,
                                        self.nodes[0].cli('-generate', 0).echo)
            assert_raises_process_error(
                1, TOO_MANY_ARGS, self.nodes[0].cli('-generate', 1, 2, 3).echo)

            self.log.info('Test -generate with nblocks')
            generate = self.nodes[0].cli('-generate', n1).send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), n1)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1)

            self.log.info('Test -generate with nblocks and maxtries')
            generate = self.nodes[0].cli('-generate', n2, 1000000).send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), n2)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n1 + n2)

            self.log.info('Test -generate -rpcwallet in single-wallet mode')
            generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), 1)
            assert_equal(self.nodes[0].getblockcount(), blocks + 2 + n1 + n2)

            self.log.info(
                'Test -generate -rpcwallet=unloaded wallet raises RPC error')
            assert_raises_rpc_error(
                -18, WALLET_NOT_LOADED,
                self.nodes[0].cli(rpcwallet3, '-generate').echo)
            assert_raises_rpc_error(
                -18, WALLET_NOT_LOADED,
                self.nodes[0].cli(rpcwallet3, '-generate', 'foo').echo)
            assert_raises_rpc_error(
                -18, WALLET_NOT_LOADED,
                self.nodes[0].cli(rpcwallet3, '-generate', 0).echo)
            assert_raises_rpc_error(
                -18, WALLET_NOT_LOADED,
                self.nodes[0].cli(rpcwallet3, '-generate', 1, 2, 3).echo)

            # Test bitcoin-cli -generate with -rpcwallet in multiwallet mode.
            self.nodes[0].loadwallet(wallets[2])
            n3 = 4
            n4 = 10
            blocks = self.nodes[0].getblockcount()

            self.log.info('Test -generate -rpcwallet with no args')
            generate = self.nodes[0].cli(rpcwallet2, '-generate').send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), 1)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1)

            self.log.info('Test -generate -rpcwallet with bad args')
            assert_raises_process_error(
                1, JSON_PARSING_ERROR,
                self.nodes[0].cli(rpcwallet2, '-generate', 'foo').echo)
            assert_raises_process_error(
                1, BLOCKS_VALUE_OF_ZERO,
                self.nodes[0].cli(rpcwallet2, '-generate', 0).echo)
            assert_raises_process_error(
                1, TOO_MANY_ARGS, self.nodes[0].cli(rpcwallet2, '-generate', 1,
                                                    2, 3).echo)

            self.log.info('Test -generate -rpcwallet with nblocks')
            generate = self.nodes[0].cli(rpcwallet2, '-generate',
                                         n3).send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), n3)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3)

            self.log.info(
                'Test -generate -rpcwallet with nblocks and maxtries')
            generate = self.nodes[0].cli(rpcwallet2, '-generate', n4,
                                         1000000).send_cli()
            assert_equal(set(generate.keys()), {'address', 'blocks'})
            assert_equal(len(generate["blocks"]), n4)
            assert_equal(self.nodes[0].getblockcount(), blocks + 1 + n3 + n4)

            self.log.info(
                'Test -generate without -rpcwallet in multiwallet mode raises RPC error'
            )
            assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED,
                                    self.nodes[0].cli('-generate').echo)
            assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED,
                                    self.nodes[0].cli('-generate', 'foo').echo)
            assert_raises_rpc_error(-19, WALLET_NOT_SPECIFIED,
                                    self.nodes[0].cli('-generate', 0).echo)
            assert_raises_rpc_error(
                -19, WALLET_NOT_SPECIFIED,
                self.nodes[0].cli('-generate', 1, 2, 3).echo)
        else:
            self.log.info(
                "*** Wallet not compiled; cli getwalletinfo and -getinfo wallet tests skipped"
            )
            self.nodes[0].generate(
                25
            )  # maintain block parity with the wallet_compiled conditional branch

        self.log.info("Test -version with node stopped")
        self.stop_node(0)
        cli_response = self.nodes[0].cli('-version').send_cli()
        assert f"{self.config['environment']['PACKAGE_NAME']} RPC client version" in cli_response

        self.log.info(
            "Test -rpcwait option successfully waits for RPC connection")
        self.nodes[0].start()  # start node without RPC connection
        self.nodes[0].wait_for_cookie_credentials(
        )  # ensure cookie file is available to avoid race condition
        blocks = self.nodes[0].cli('-rpcwait').send_cli('getblockcount')
        self.nodes[0].wait_for_rpc_connection()
        assert_equal(blocks, BLOCKS + 25)

        self.log.info(
            "Test -rpcwait option waits at most -rpcwaittimeout seconds for startup"
        )
        self.stop_node(0)  # stop the node so we time out
        start_time = time.time()
        assert_raises_process_error(
            1, "Could not connect to the server",
            self.nodes[0].cli('-rpcwait', '-rpcwaittimeout=5').echo)
        assert_greater_than_or_equal(time.time(), start_time + 5)
    def run_test(self):
        """Main test logic"""
        self.nodes[0].generate(BLOCKS)

        self.log.info(
            "Compare responses from getblockchaininfo RPC and `patentcoin-cli getblockchaininfo`"
        )
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir, self.chain)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(
            BLOCKS, self.nodes[0].cli('-rpcuser={}'.format(user),
                                      '-stdinrpcpass',
                                      input=password).getblockcount())
        assert_raises_process_error(
            1, 'Incorrect rpcuser or rpcpassword',
            self.nodes[0].cli('-rpcuser={}'.format(user),
                              '-stdinrpcpass',
                              input='foo').echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(['foo', 'bar'],
                     self.nodes[0].cli('-rpcuser={}'.format(user),
                                       '-stdin',
                                       '-stdinrpcpass',
                                       input=password + '\nfoo\nbar').echo())
        assert_raises_process_error(
            1, 'Incorrect rpcuser or rpcpassword',
            self.nodes[0].cli('-rpcuser={}'.format(user),
                              '-stdin',
                              '-stdinrpcpass',
                              input='foo').echo)

        self.log.info("Test connecting to a non-existing server")
        assert_raises_process_error(1, "Could not connect to the server",
                                    self.nodes[0].cli('-rpcport=1').echo)

        self.log.info("Test connecting with non-existing RPC cookie file")
        assert_raises_process_error(
            1, "Could not locate RPC credentials",
            self.nodes[0].cli('-rpccookiefile=does-not-exist',
                              '-rpcpassword='******'-getinfo').help)

        self.log.info(
            "Test -getinfo returns expected network and blockchain info")
        if self.is_wallet_compiled():
            self.nodes[0].encryptwallet(password)
        cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()
        assert_equal(cli_get_info['version'], network_info['version'])
        assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
        assert_equal(cli_get_info['headers'], blockchain_info['headers'])
        assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
        assert_equal(cli_get_info['connections'], network_info['connections'])
        assert_equal(cli_get_info['proxy'],
                     network_info['networks'][0]['proxy'])
        assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
        assert_equal(cli_get_info['chain'], blockchain_info['chain'])

        if self.is_wallet_compiled():
            self.log.info(
                "Test -getinfo and patentcoin-cli getwalletinfo return expected wallet info"
            )
            assert_equal(cli_get_info['balance'], BALANCE)
            wallet_info = self.nodes[0].getwalletinfo()
            assert_equal(cli_get_info['keypoolsize'],
                         wallet_info['keypoolsize'])
            assert_equal(cli_get_info['unlocked_until'],
                         wallet_info['unlocked_until'])
            assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
            assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
            assert_equal(self.nodes[0].cli.getwalletinfo(), wallet_info)

            # Setup to test -getinfo and -rpcwallet= with multiple wallets.
            wallets = ['', 'Encrypted', 'secret']
            amounts = [Decimal('59.999928'), Decimal(9), Decimal(31)]
            self.nodes[0].createwallet(wallet_name=wallets[1])
            self.nodes[0].createwallet(wallet_name=wallets[2])
            w1 = self.nodes[0].get_wallet_rpc(wallets[0])
            w2 = self.nodes[0].get_wallet_rpc(wallets[1])
            w3 = self.nodes[0].get_wallet_rpc(wallets[2])
            w1.walletpassphrase(password, self.rpc_timeout)
            w1.sendtoaddress(w2.getnewaddress(), amounts[1])
            w1.sendtoaddress(w3.getnewaddress(), amounts[2])

            # Mine a block to confirm; adds a block reward (50 PC) to the default wallet.
            self.nodes[0].generate(1)

            self.log.info(
                "Test -getinfo with multiple wallets loaded returns no balance"
            )
            assert_equal(set(self.nodes[0].listwallets()), set(wallets))
            assert 'balance' not in self.nodes[0].cli(
                '-getinfo').send_cli().keys()

            self.log.info(
                "Test -getinfo with multiple wallets and -rpcwallet returns specified wallet balance"
            )
            for i in range(len(wallets)):
                cli_get_info = self.nodes[0].cli('-getinfo').send_cli(
                    '-rpcwallet={}'.format(wallets[i]))
                assert_equal(cli_get_info['balance'], amounts[i])

            self.log.info(
                "Test -getinfo with multiple wallets and -rpcwallet=non-existing-wallet returns no balance"
            )
            assert 'balance' not in self.nodes[0].cli('-getinfo').send_cli(
                '-rpcwallet=does-not-exist').keys()

            self.log.info(
                "Test -getinfo after unloading all wallets except a non-default one returns its balance"
            )
            self.nodes[0].unloadwallet(wallets[0])
            self.nodes[0].unloadwallet(wallets[2])
            assert_equal(self.nodes[0].listwallets(), [wallets[1]])
            assert_equal(self.nodes[0].cli('-getinfo').send_cli()['balance'],
                         amounts[1])

            self.log.info(
                "Test -getinfo -rpcwallet=remaining-non-default-wallet returns its balance"
            )
            assert_equal(
                self.nodes[0].cli('-getinfo').send_cli('-rpcwallet={}'.format(
                    wallets[1]))['balance'], amounts[1])

            self.log.info(
                "Test -getinfo with -rpcwallet=unloaded wallet returns no balance"
            )
            assert 'balance' not in self.nodes[0].cli('-getinfo').send_cli(
                '-rpcwallet={}'.format(wallets[2])).keys()
        else:
            self.log.info(
                "*** Wallet not compiled; cli getwalletinfo and -getinfo wallet tests skipped"
            )
            self.nodes[0].generate(
                1
            )  # maintain block parity with the wallet_compiled conditional branch

        self.log.info("Test -version with node stopped")
        self.stop_node(0)
        cli_response = self.nodes[0].cli('-version').send_cli()
        assert "{} RPC client version".format(
            self.config['environment']['PACKAGE_NAME']) in cli_response

        self.log.info(
            "Test -rpcwait option successfully waits for RPC connection")
        self.nodes[0].start()  # start node without RPC connection
        self.nodes[0].wait_for_cookie_credentials(
        )  # ensure cookie file is available to avoid race condition
        blocks = self.nodes[0].cli('-rpcwait').send_cli('getblockcount')
        self.nodes[0].wait_for_rpc_connection()
        assert_equal(blocks, BLOCKS + 1)
示例#11
0
    def run_test(self):
        """Main test logic"""
        self.nodes[0].generate(BLOCKS)

        self.log.info(
            "Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`"
        )
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir, self.chain)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(
            BLOCKS, self.nodes[0].cli('-rpcuser={}'.format(user),
                                      '-stdinrpcpass',
                                      input=password).getblockcount())
        assert_raises_process_error(
            1, 'Incorrect rpcuser or rpcpassword',
            self.nodes[0].cli('-rpcuser={}'.format(user),
                              '-stdinrpcpass',
                              input='foo').echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(['foo', 'bar'],
                     self.nodes[0].cli('-rpcuser={}'.format(user),
                                       '-stdin',
                                       '-stdinrpcpass',
                                       input=password + '\nfoo\nbar').echo())
        assert_raises_process_error(
            1, 'Incorrect rpcuser or rpcpassword',
            self.nodes[0].cli('-rpcuser={}'.format(user),
                              '-stdin',
                              '-stdinrpcpass',
                              input='foo').echo)

        self.log.info("Test connecting to a non-existing server")
        assert_raises_process_error(1, "Could not connect to the server",
                                    self.nodes[0].cli('-rpcport=1').echo)

        self.log.info("Test connecting with non-existing RPC cookie file")
        assert_raises_process_error(
            1, "Could not locate RPC credentials",
            self.nodes[0].cli('-rpccookiefile=does-not-exist',
                              '-rpcpassword='******'-getinfo').help)

        self.log.info("Test -getinfo command parsing")

        self.log.debug("Test -getinfo=1 and -getinfo=-1 both succeed")
        for cmd in ['-getinfo=1', '-getinfo=-1']:
            assert_equal(rpc_response['blocks'],
                         self.nodes[0].cli(cmd).send_cli()['blocks'])

        self.log.debug(
            "Test -getinfo=0 and -nogetinfo both raise 'too few parameters'")
        err_msg = "error: too few parameters (need at least command)"
        for cmd in ['-getinfo=0', '-nogetinfo']:
            assert_raises_process_error(1, err_msg,
                                        self.nodes[0].cli(cmd).send_cli)

        self.log.debug(
            "Test -igetinfo and -getinfos both raise 'Invalid parameter'")
        err_msg = "Error parsing command line arguments: Invalid parameter"
        for cmd in ['-igetinfo', '-getinfos']:
            assert_raises_process_error(1, "{} {}".format(err_msg, cmd),
                                        self.nodes[0].cli(cmd).send_cli)

        self.log.info(
            "Test -getinfo returns expected network and blockchain info")
        if self.is_wallet_compiled():
            self.nodes[0].encryptwallet(password)
        cli_get_info = self.nodes[0].cli().send_cli('-getinfo')
        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()
        assert_equal(cli_get_info['chain'], self.chain)
        assert_equal(cli_get_info['version'], network_info['version'])
        assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
        assert_equal(cli_get_info['headers'], blockchain_info['headers'])
        assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
        assert_equal(
            cli_get_info['connections'], {
                'in': network_info['connections_in'],
                'out': network_info['connections_out'],
                'total': network_info['connections']
            })
        assert_equal(cli_get_info['proxy'],
                     network_info['networks'][0]['proxy'])
        assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
        assert_equal(cli_get_info['chain'], blockchain_info['chain'])
        for field in ['blocks', 'headers', 'timeoffset', 'version']:
            assert_scale(cli_get_info[field], expected_scale=0)
        for field in ('in', 'out', 'total'):
            assert_scale(cli_get_info['connections'][field], expected_scale=0)

        if self.is_wallet_compiled():
            self.log.info(
                "Test -getinfo and bitcoin-cli getwalletinfo return expected wallet info"
            )
            assert_equal(cli_get_info['balance'], BALANCE)
            assert 'balances' not in cli_get_info.keys()
            assert 'total_balance' not in cli_get_info.keys()
            wallet_info = self.nodes[0].getwalletinfo()
            assert_equal(cli_get_info['keypoolsize'],
                         wallet_info['keypoolsize'])
            assert_equal(cli_get_info['unlocked_until'],
                         wallet_info['unlocked_until'])
            assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
            assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
            assert_equal(self.nodes[0].cli.getwalletinfo(), wallet_info)
            for field in ['keypoolsize', 'timeoffset', 'unlocked_until']:
                assert_scale(cli_get_info[field], expected_scale=0)
            for field in ['balance', 'paytxfee', 'relayfee']:
                assert_scale(cli_get_info[field])

            # Setup to test -getinfo and -rpcwallet= with multiple wallets.
            wallets = ['', 'Encrypted', 'secret']
            amounts = [BALANCE + Decimal('9.999928'), Decimal(9), Decimal(31)]
            self.nodes[0].createwallet(wallet_name=wallets[1])
            self.nodes[0].createwallet(wallet_name=wallets[2])
            w1 = self.nodes[0].get_wallet_rpc(wallets[0])
            w2 = self.nodes[0].get_wallet_rpc(wallets[1])
            w3 = self.nodes[0].get_wallet_rpc(wallets[2])
            w1.walletpassphrase(password, self.rpc_timeout)
            w2.encryptwallet(password)
            w1.sendtoaddress(w2.getnewaddress(), amounts[1])
            w1.sendtoaddress(w3.getnewaddress(), amounts[2])

            # Mine a block to confirm; adds a block reward (50 BTC) to the default wallet.
            self.nodes[0].generate(1)

            self.log.info(
                "Test -getinfo with multiple wallets and -rpcwallet returns specified wallet balance"
            )
            for i in range(len(wallets)):
                cli_get_info = self.nodes[0].cli(
                    '-getinfo', '-rpcwallet={}'.format(wallets[i])).send_cli()
                assert 'balances' not in cli_get_info.keys()
                assert 'total_balance' not in cli_get_info.keys()
                assert_equal(cli_get_info['balance'], amounts[i])
                assert_scale(cli_get_info['balance'])

            self.log.info(
                "Test -getinfo with multiple wallets and -rpcwallet=non-existing-wallet returns no balances"
            )
            cli_get_info_keys = self.nodes[0].cli(
                '-getinfo', '-rpcwallet=does-not-exist').send_cli().keys()
            assert 'balance' not in cli_get_info_keys
            assert 'balances' not in cli_get_info_keys
            assert 'total_balance' not in cli_get_info.keys()

            self.log.info(
                "Test -getinfo with multiple wallets returns all loaded wallet names and balances"
            )
            assert_equal(set(self.nodes[0].listwallets()), set(wallets))
            cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
            assert 'balance' not in cli_get_info.keys()
            assert_equal(cli_get_info['balances'],
                         {k: v
                          for k, v in zip(wallets, amounts)})
            for wallet_name in wallets:
                assert_scale(cli_get_info['balances'][wallet_name])
            assert_equal(cli_get_info['total_balance'], sum(amounts))
            assert_scale(cli_get_info['total_balance'])

            # Unload the default wallet and re-verify.
            self.nodes[0].unloadwallet(wallets[0])
            assert wallets[0] not in self.nodes[0].listwallets()
            cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
            assert 'balance' not in cli_get_info.keys()
            assert_equal(cli_get_info['balances'],
                         {k: v
                          for k, v in zip(wallets[1:], amounts[1:])})
            assert_equal(cli_get_info['total_balance'], sum(amounts[1:]))
            assert_scale(cli_get_info['total_balance'])

            self.log.info(
                "Test -getinfo after unloading all wallets except a non-default one returns its balance"
            )
            self.nodes[0].unloadwallet(wallets[2])
            assert_equal(self.nodes[0].listwallets(), [wallets[1]])
            cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
            assert 'balances' not in cli_get_info.keys()
            assert 'total_balance' not in cli_get_info.keys()
            assert_equal(cli_get_info['balance'], amounts[1])
            assert_scale(cli_get_info['balance'])

            self.log.info(
                "Test -getinfo with -rpcwallet=remaining-non-default-wallet returns only its balance"
            )
            cli_get_info = self.nodes[0].cli(
                '-getinfo', '-rpcwallet={}'.format(wallets[1])).send_cli()
            assert 'balances' not in cli_get_info.keys()
            assert 'total_balance' not in cli_get_info.keys()
            assert_equal(cli_get_info['balance'], amounts[1])

            self.log.info(
                "Test -getinfo with -rpcwallet=unloaded wallet returns no balances"
            )
            cli_get_info = self.nodes[0].cli(
                '-getinfo', '-rpcwallet={}'.format(wallets[2])).send_cli()
            assert 'balance' not in cli_get_info_keys
            assert 'balances' not in cli_get_info_keys
            assert 'total_balance' not in cli_get_info.keys()
        else:
            self.log.info(
                "*** Wallet not compiled; cli getwalletinfo and -getinfo wallet tests skipped"
            )
            self.nodes[0].generate(
                1
            )  # maintain block parity with the wallet_compiled conditional branch

        self.log.info("Test -version with node stopped")
        self.stop_node(0)
        cli_response = self.nodes[0].cli().send_cli('-version')
        assert "{} RPC client version".format(
            self.config['environment']['PACKAGE_NAME']) in cli_response

        self.log.info(
            "Test -rpcwait option successfully waits for RPC connection")
        self.nodes[0].start()  # start node without RPC connection
        self.nodes[0].wait_for_cookie_credentials(
        )  # ensure cookie file is available to avoid race condition
        blocks = self.nodes[0].cli('-rpcwait').send_cli('getblockcount')
        self.nodes[0].wait_for_rpc_connection()
        assert_equal(blocks, BLOCKS + 1)
示例#12
0
    def setup_network(self, split=False):
        if self.options.parent_bitcoin and self.options.parent_binpath == "":
            raise Exception("Can't run with --parent_bitcoin without specifying --parent_binpath")

        self.nodes = []
        # Setup parent nodes
        parent_chain = "parent" if not self.options.parent_bitcoin else "regtest"
        parent_binary = [self.options.parent_binpath] if self.options.parent_binpath != "" else None
        for n in range(2):
            extra_args = [
                "-port="+str(p2p_port(n)),
                "-rpcport="+str(rpc_port(n))
            ]
            if self.options.parent_bitcoin:
                # bitcoind can't read elements.conf config files
                extra_args.extend([
                    "-regtest=1",
                    "-printtoconsole=0",
                    "-server=1",
                    "-discover=0",
                    "-keypool=1",
                    "-listenonion=0",
                    "-addresstype=legacy", # To make sure bitcoind gives back p2pkh no matter version
                ])
            else:
                extra_args.extend([
                    "-validatepegin=0",
                    "-initialfreecoins=0",
                    "-anyonecanspendaremine",
                    "-signblockscript=51", # OP_TRUE
                    '-con_blocksubsidy=5000000000',
                    "-pubkeyprefix=111",
                    "-scriptprefix=196",
                ])

            self.add_nodes(1, [extra_args], chain=[parent_chain], binary=parent_binary, chain_in_args=[not self.options.parent_bitcoin])
            self.start_node(n)
            print("Node {} started".format(n))

        connect_nodes_bi(self.nodes, 0, 1)
        self.parentgenesisblockhash = self.nodes[0].getblockhash(0)
        if not self.options.parent_bitcoin:
            parent_pegged_asset = self.nodes[0].getsidechaininfo()['pegged_asset']

        # Setup sidechain nodes
        self.fedpeg_script = "512103dff4923d778550cc13ce0d887d737553b4b58f4e8e886507fc39f5e447b2186451ae"
        for n in range(2):
            extra_args = [
                "-printtoconsole=0",
                "-port="+str(p2p_port(2+n)),
                "-rpcport="+str(rpc_port(2+n)),
                '-parentgenesisblockhash=%s' % self.parentgenesisblockhash,
                '-validatepegin=1',
                '-fedpegscript=%s' % self.fedpeg_script,
                '-anyonecanspendaremine=0',
                '-minrelaytxfee=0',
                '-blockmintxfee=0',
                '-initialfreecoins=0',
                '-peginconfirmationdepth=10',
                '-mainchainrpchost=127.0.0.1',
                '-mainchainrpcport=%s' % rpc_port(n),
                '-recheckpeginblockinterval=15', # Long enough to allow failure and repair before timeout
                '-parentpubkeyprefix=111',
                '-parentscriptprefix=196',
                # Turn of consistency checks that can cause assert when parent node stops
                # and a peg-in transaction fails this belt-and-suspenders check.
                '-checkmempool=0',
            ]
            if not self.options.parent_bitcoin:
                extra_args.extend([
                    '-parentpubkeyprefix=111',
                    '-parentscriptprefix=196',
                    "-parent_bech32_hrp=ert",
                    '-con_parent_chain_signblockscript=51',
                    '-con_parent_pegged_asset=%s' % parent_pegged_asset,
                ])

            # Use rpcuser auth only for first parent.
            if n==0:
                # Extract username and password from cookie file and use directly.
                datadir = get_datadir_path(self.options.tmpdir, n)
                rpc_u, rpc_p = get_auth_cookie(datadir, parent_chain)
                extra_args.extend([
                    '-mainchainrpcuser=%s' % rpc_u,
                    '-mainchainrpcpassword=%s' % rpc_p,
                ])
            else:
                # Need to specify where to find parent cookie file
                datadir = get_datadir_path(self.options.tmpdir, n)
                extra_args.append('-mainchainrpccookiefile='+datadir+"/" + parent_chain + "/.cookie")

            self.add_nodes(1, [extra_args], chain=["sidechain"])
            self.start_node(2+n)
            print("Node {} started".format(2+n))

        # We only connect the same-chain nodes, so sync_all works correctly
        connect_nodes_bi(self.nodes, 2, 3)
        self.node_groups = [[self.nodes[0], self.nodes[1]], [self.nodes[2], self.nodes[3]]]
        self.sync_all(self.node_groups)
        print("Setting up network done")
示例#13
0
    def setup_network(self, split=False):
        if self.options.parent_bitcoin and self.options.parent_binpath == "":
            raise Exception("Can't run with --parent_bitcoin without specifying --parent_binpath")

        self.nodes = []
        # Setup parent nodes
        parent_chain = "parent" if not self.options.parent_bitcoin else "regtest"
        parent_binary = [self.options.parent_binpath] if self.options.parent_binpath != "" else None
        for n in range(2):
            extra_args = [
                "-port="+str(p2p_port(n)),
                "-rpcport="+str(rpc_port(n))
            ]
            if self.options.parent_bitcoin:
                # bitcoind can't read elements.conf config files
                extra_args.extend([
                    "-regtest=1",
                    "-printtoconsole=0",
                    "-server=1",
                    "-discover=0",
                    "-keypool=1",
                    "-listenonion=0",
                    "-addresstype=legacy", # To make sure bitcoind gives back p2pkh no matter version
                ])
            else:
                extra_args.extend([
                    "-validatepegin=0",
                    "-initialfreecoins=0",
                    "-anyonecanspendaremine",
                    "-signblockscript=51", # OP_TRUE
                    '-con_blocksubsidy=5000000000',
                    "-pubkeyprefix=111",
                    "-scriptprefix=196",
                ])

            self.add_nodes(1, [extra_args], chain=[parent_chain], binary=parent_binary, chain_in_args=[not self.options.parent_bitcoin])
            self.start_node(n)
            print("Node {} started".format(n))

        connect_nodes_bi(self.nodes, 0, 1)
        self.parentgenesisblockhash = self.nodes[0].getblockhash(0)
        if not self.options.parent_bitcoin:
            parent_pegged_asset = self.nodes[0].getsidechaininfo()['pegged_asset']

        # Setup sidechain nodes
        self.fedpeg_script = "512103dff4923d778550cc13ce0d887d737553b4b58f4e8e886507fc39f5e447b2186451ae"
        for n in range(2):
            extra_args = [
                "-printtoconsole=0",
                "-port="+str(p2p_port(2+n)),
                "-rpcport="+str(rpc_port(2+n)),
                '-parentgenesisblockhash=%s' % self.parentgenesisblockhash,
                '-validatepegin=1',
                '-fedpegscript=%s' % self.fedpeg_script,
                '-anyonecanspendaremine=0',
                '-minrelaytxfee=0',
                '-blockmintxfee=0',
                '-initialfreecoins=0',
                '-peginconfirmationdepth=10',
                '-mainchainrpchost=127.0.0.1',
                '-mainchainrpcport=%s' % rpc_port(n),
                '-recheckpeginblockinterval=15', # Long enough to allow failure and repair before timeout
                '-parentpubkeyprefix=111',
                '-parentscriptprefix=196',
                # Turn of consistency checks that can cause assert when parent node stops
                # and a peg-in transaction fails this belt-and-suspenders check.
                '-checkmempool=0',
            ]
            if not self.options.parent_bitcoin:
                extra_args.extend([
                    '-parentpubkeyprefix=111',
                    '-parentscriptprefix=196',
                    "-parent_bech32_hrp=ert",
                    '-con_parent_chain_signblockscript=51',
                    '-con_parent_pegged_asset=%s' % parent_pegged_asset,
                ])

            # Use rpcuser auth only for first parent.
            if n==0:
                # Extract username and password from cookie file and use directly.
                datadir = get_datadir_path(self.options.tmpdir, n)
                rpc_u, rpc_p = get_auth_cookie(datadir, parent_chain)
                extra_args.extend([
                    '-mainchainrpcuser=%s' % rpc_u,
                    '-mainchainrpcpassword=%s' % rpc_p,
                ])
            else:
                # Need to specify where to find parent cookie file
                datadir = get_datadir_path(self.options.tmpdir, n)
                extra_args.append('-mainchainrpccookiefile='+datadir+"/" + parent_chain + "/.cookie")

            self.add_nodes(1, [extra_args], chain=["sidechain"])
            self.start_node(2+n)
            print("Node {} started".format(2+n))

        # We only connect the same-chain nodes, so sync_all works correctly
        connect_nodes_bi(self.nodes, 2, 3)
        self.node_groups = [[self.nodes[0], self.nodes[1]], [self.nodes[2], self.nodes[3]]]
        self.sync_all(self.node_groups)
        print("Setting up network done")
示例#14
0
    def run_test(self):
        """Main test logic"""
        self.nodes[0].generate(BLOCKS)

        self.log.info(
            "Compare responses from getblockchaininfo RPC and `bitcoin-cli getblockchaininfo`"
        )
        cli_response = self.nodes[0].cli.getblockchaininfo()
        rpc_response = self.nodes[0].getblockchaininfo()
        assert_equal(cli_response, rpc_response)

        user, password = get_auth_cookie(self.nodes[0].datadir, self.chain)

        self.log.info("Test -stdinrpcpass option")
        assert_equal(
            BLOCKS, self.nodes[0].cli('-rpcuser=%s' % user,
                                      '-stdinrpcpass',
                                      input=password).getblockcount())
        assert_raises_process_error(
            1, "Incorrect rpcuser or rpcpassword",
            self.nodes[0].cli('-rpcuser=%s' % user,
                              '-stdinrpcpass',
                              input="foo").echo)

        self.log.info("Test -stdin and -stdinrpcpass")
        assert_equal(["foo", "bar"],
                     self.nodes[0].cli('-rpcuser=%s' % user,
                                       '-stdin',
                                       '-stdinrpcpass',
                                       input=password + "\nfoo\nbar").echo())
        assert_raises_process_error(
            1, "Incorrect rpcuser or rpcpassword",
            self.nodes[0].cli('-rpcuser=%s' % user,
                              '-stdin',
                              '-stdinrpcpass',
                              input="foo").echo)

        self.log.info("Test connecting to a non-existing server")
        assert_raises_process_error(1, "Could not connect to the server",
                                    self.nodes[0].cli('-rpcport=1').echo)

        self.log.info("Test connecting with non-existing RPC cookie file")
        assert_raises_process_error(
            1, "Could not locate RPC credentials",
            self.nodes[0].cli('-rpccookiefile=does-not-exist',
                              '-rpcpassword='******'-getinfo').help)

        self.log.info(
            "Test -getinfo returns expected network and blockchain info")
        if self.is_wallet_compiled():
            self.nodes[0].encryptwallet(password)
        cli_get_info = self.nodes[0].cli('-getinfo').send_cli()
        network_info = self.nodes[0].getnetworkinfo()
        blockchain_info = self.nodes[0].getblockchaininfo()
        assert_equal(cli_get_info['version'], network_info['version'])
        assert_equal(cli_get_info['blocks'], blockchain_info['blocks'])
        assert_equal(cli_get_info['headers'], blockchain_info['headers'])
        assert_equal(cli_get_info['timeoffset'], network_info['timeoffset'])
        assert_equal(cli_get_info['connections'], network_info['connections'])
        assert_equal(cli_get_info['proxy'],
                     network_info['networks'][0]['proxy'])
        assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty'])
        assert_equal(cli_get_info['chain'], blockchain_info['chain'])

        if self.is_wallet_compiled():
            self.log.info(
                "Test -getinfo and bitcoin-cli getwalletinfo return expected wallet info"
            )
            assert_equal(cli_get_info['balance'], BALANCE)
            wallet_info = self.nodes[0].getwalletinfo()
            assert_equal(cli_get_info['keypoolsize'],
                         wallet_info['keypoolsize'])
            assert_equal(cli_get_info['unlocked_until'],
                         wallet_info['unlocked_until'])
            assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee'])
            assert_equal(cli_get_info['relayfee'], network_info['relayfee'])
            assert_equal(self.nodes[0].cli.getwalletinfo(), wallet_info)
        else:
            self.log.info(
                "*** Wallet not compiled; cli getwalletinfo and -getinfo wallet tests skipped"
            )

        self.stop_node(0)

        self.log.info("Test -version with node stopped")
        cli_response = self.nodes[0].cli("-version").send_cli()
        assert "{} RPC client version".format(
            self.config['environment']['PACKAGE_NAME']) in cli_response

        self.log.info(
            "Test -rpcwait option waits for RPC connection instead of failing")
        # Start node without RPC connection.
        self.nodes[0].start()
        # Verify failure without -rpcwait.
        assert_raises_process_error(1, "Could not connect to the server",
                                    self.nodes[0].cli('getblockcount').echo)
        # Verify success using -rpcwait.
        assert_equal(BLOCKS, self.nodes[0].cli('-rpcwait',
                                               'getblockcount').send_cli())
        self.nodes[0].wait_for_rpc_connection()