Beispiel #1
0
    def run_test(self):
        assert_raises_rpc_error(-5, "Invalid descriptor", self.nodes[0].deriveaddresses, "a")

        descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)#t6wfjs64"
        address = "bcrt1qjqmxmkpmxt80xz4y3746zgt0q3u3ferr34acd5"
        assert_equal(self.nodes[0].deriveaddresses(descriptor), [address])

        descriptor = descriptor[:-9]
        assert_raises_rpc_error(-5, "Invalid descriptor", self.nodes[0].deriveaddresses, descriptor)

        descriptor_pubkey = "wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0)#s9ga3alw"
        address = "bcrt1qjqmxmkpmxt80xz4y3746zgt0q3u3ferr34acd5"
        assert_equal(self.nodes[0].deriveaddresses(descriptor_pubkey), [address])

        ranged_descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)#kft60nuy"
        assert_equal(self.nodes[0].deriveaddresses(ranged_descriptor, 0, 2), [address, "bcrt1qhku5rq7jz8ulufe2y6fkcpnlvpsta7rq4442dy", "bcrt1qpgptk2gvshyl0s9lqshsmx932l9ccsv265tvaq"])

        assert_raises_rpc_error(-8, "Range should not be specified for an un-ranged descriptor", self.nodes[0].deriveaddresses, descsum_create("wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"), 0, 2)

        assert_raises_rpc_error(-8, "Range must be specified for a ranged descriptor", self.nodes[0].deriveaddresses, descsum_create("wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"))

        assert_raises_rpc_error(-8, "Missing range end parameter", self.nodes[0].deriveaddresses, descsum_create("wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"), 0)

        assert_raises_rpc_error(-8, "Range end should be equal to or greater than begin", self.nodes[0].deriveaddresses, descsum_create("wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"), 2, 0)

        assert_raises_rpc_error(-8, "Range should be greater or equal than 0", self.nodes[0].deriveaddresses, descsum_create("wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"), -1, 0)

        combo_descriptor = descsum_create("combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)")
        assert_equal(self.nodes[0].deriveaddresses(combo_descriptor), ["mtfUoUax9L4tzXARpw1oTGxWyoogp52KhJ", "mtfUoUax9L4tzXARpw1oTGxWyoogp52KhJ", address, "2NDvEwGfpEqJWfybzpKPHF2XH3jwoQV3D7x"])

        hardened_without_privkey_descriptor = descsum_create("wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1'/1/0)")
        assert_raises_rpc_error(-5, "Cannot derive script without private keys", self.nodes[0].deriveaddresses, hardened_without_privkey_descriptor)

        bare_multisig_descriptor = descsum_create("multi(1,tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0,tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/1)")
        assert_raises_rpc_error(-5, "Descriptor does not have a corresponding address", self.nodes[0].deriveaddresses, bare_multisig_descriptor)
    def test_desc(self, node, address, multisig, typ, utxo):
        """Run sanity checks on a descriptor reported by getaddressinfo."""
        info = self.nodes[node].getaddressinfo(address)
        assert('desc' in info)
        assert_equal(info['desc'], utxo['desc'])
        assert(self.nodes[node].validateaddress(address)['isvalid'])

        # Use a ridiculously roundabout way to find the key origin info through
        # the PSBT logic. However, this does test consistency between the PSBT reported
        # fingerprints/paths and the descriptor logic.
        psbt = self.nodes[node].createpsbt([{'txid':utxo['txid'], 'vout':utxo['vout']}],[{address:0.00010000}])
        psbt = self.nodes[node].walletprocesspsbt(psbt, False, "ALL", True)
        decode = self.nodes[node].decodepsbt(psbt['psbt'])
        key_descs = {}
        for deriv in decode['inputs'][0]['bip32_derivs']:
            assert_equal(len(deriv['master_fingerprint']), 8)
            assert_equal(deriv['path'][0], 'm')
            key_descs[deriv['pubkey']] = '[' + deriv['master_fingerprint'] + deriv['path'][1:] + ']' + deriv['pubkey']

        # Verify the descriptor checksum against the Python implementation
        assert(descsum_check(info['desc']))
        # Verify that stripping the checksum and recreating it using Python roundtrips
        assert(info['desc'] == descsum_create(info['desc'][:-9]))
        # Verify that stripping the checksum and feeding it to getdescriptorinfo roundtrips
        assert(info['desc'] == self.nodes[0].getdescriptorinfo(info['desc'][:-9])['descriptor'])

        if not multisig and typ == 'legacy':
            # P2PKH
            assert_equal(info['desc'], descsum_create("pkh(%s)" % key_descs[info['pubkey']]))
        elif not multisig and typ == 'p2sh-segwit':
            # P2SH-P2WPKH
            assert_equal(info['desc'], descsum_create("sh(wpkh(%s))" % key_descs[info['pubkey']]))
        elif not multisig and typ == 'bech32':
            # P2WPKH
            assert_equal(info['desc'], descsum_create("wpkh(%s)" % key_descs[info['pubkey']]))
        elif typ == 'legacy':
            # P2SH-multisig
            assert_equal(info['desc'], descsum_create("sh(multi(2,%s,%s))" % (key_descs[info['pubkeys'][0]], key_descs[info['pubkeys'][1]])))
        elif typ == 'p2sh-segwit':
            # P2SH-P2WSH-multisig
            assert_equal(info['desc'], descsum_create("sh(wsh(multi(2,%s,%s)))" % (key_descs[info['embedded']['pubkeys'][0]], key_descs[info['embedded']['pubkeys'][1]])))
        elif typ == 'bech32':
            # P2WSH-multisig
            assert_equal(info['desc'], descsum_create("wsh(multi(2,%s,%s))" % (key_descs[info['pubkeys'][0]], key_descs[info['pubkeys'][1]])))
        else:
            # Unknown type
            assert(False)
Beispiel #3
0
    def run_test(self):
        self.nodes[0].generatetoaddress(101, self.nodes[0].getnewaddress())

        sync_blocks(self.nodes)

        # Sanity check the test framework:
        res = self.nodes[self.num_nodes - 1].getblockchaininfo()
        assert_equal(res['blocks'], 101)

        node_master = self.nodes[self.num_nodes - 4]
        node_v19 = self.nodes[self.num_nodes - 3]
        node_v18 = self.nodes[self.num_nodes - 2]
        node_v17 = self.nodes[self.num_nodes - 1]

        self.log.info("Test wallet backwards compatibility...")
        # Create a number of wallets and open them in older versions:

        # w1: regular wallet, created on master: update this test when default
        #     wallets can no longer be opened by older versions.
        node_master.createwallet(wallet_name="w1")
        wallet = node_master.get_wallet_rpc("w1")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        # Create a confirmed transaction, receiving coins
        address = wallet.getnewaddress()
        self.nodes[0].sendtoaddress(address, 10)
        sync_mempools(self.nodes)
        self.nodes[0].generate(1)
        sync_blocks(self.nodes)
        # Create a conflicting transaction using RBF
        return_address = self.nodes[0].getnewaddress()
        tx1_id = self.nodes[1].sendtoaddress(return_address, 1)
        tx2_id = self.nodes[1].bumpfee(tx1_id)["txid"]
        # Confirm the transaction
        sync_mempools(self.nodes)
        self.nodes[0].generate(1)
        sync_blocks(self.nodes)
        # Create another conflicting transaction using RBF
        tx3_id = self.nodes[1].sendtoaddress(return_address, 1)
        tx4_id = self.nodes[1].bumpfee(tx3_id)["txid"]
        # Abandon transaction, but don't confirm
        self.nodes[1].abandontransaction(tx3_id)

        # w1_v19: regular wallet, created with v0.19
        node_v19.createwallet(wallet_name="w1_v19")
        wallet = node_v19.get_wallet_rpc("w1_v19")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        # Use addmultisigaddress (see #18075)
        address_18075 = wallet.addmultisigaddress(1, [
            "0296b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52",
            "037211a824f55b505228e4c3d5194c1fcfaa15a456abdf37f9b9d97a4040afc073"
        ], "", "legacy")["address"]
        assert wallet.getaddressinfo(address_18075)["solvable"]

        # w1_v18: regular wallet, created with v0.18
        node_v18.createwallet(wallet_name="w1_v18")
        wallet = node_v18.get_wallet_rpc("w1_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0

        # w2: wallet with private keys disabled, created on master: update this
        #     test when default wallets private keys disabled can no longer be
        #     opened by older versions.
        node_master.createwallet(wallet_name="w2", disable_private_keys=True)
        wallet = node_master.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # w2_v19: wallet with private keys disabled, created with v0.19
        node_v19.createwallet(wallet_name="w2_v19", disable_private_keys=True)
        wallet = node_v19.get_wallet_rpc("w2_v19")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # w2_v18: wallet with private keys disabled, created with v0.18
        node_v18.createwallet(wallet_name="w2_v18", disable_private_keys=True)
        wallet = node_v18.get_wallet_rpc("w2_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # w3: blank wallet, created on master: update this
        #     test when default blank wallets can no longer be opened by older versions.
        node_master.createwallet(wallet_name="w3", blank=True)
        wallet = node_master.get_wallet_rpc("w3")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # w3_v19: blank wallet, created with v0.19
        node_v19.createwallet(wallet_name="w3_v19", blank=True)
        wallet = node_v19.get_wallet_rpc("w3_v19")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # w3_v18: blank wallet, created with v0.18
        node_v18.createwallet(wallet_name="w3_v18", blank=True)
        wallet = node_v18.get_wallet_rpc("w3_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # Copy the wallets to older nodes:
        node_master_wallets_dir = os.path.join(node_master.datadir,
                                               "regtest/wallets")
        node_v19_wallets_dir = os.path.join(node_v19.datadir,
                                            "regtest/wallets")
        node_v18_wallets_dir = os.path.join(node_v18.datadir,
                                            "regtest/wallets")
        node_v17_wallets_dir = os.path.join(node_v17.datadir,
                                            "regtest/wallets")
        node_master.unloadwallet("w1")
        node_master.unloadwallet("w2")
        node_v19.unloadwallet("w1_v19")
        node_v19.unloadwallet("w2_v19")
        node_v18.unloadwallet("w1_v18")
        node_v18.unloadwallet("w2_v18")

        # Copy wallets to v0.17
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(os.path.join(node_master_wallets_dir, wallet),
                            os.path.join(node_v17_wallets_dir, wallet))
        for wallet in os.listdir(node_v18_wallets_dir):
            shutil.copytree(os.path.join(node_v18_wallets_dir, wallet),
                            os.path.join(node_v17_wallets_dir, wallet))

        # Copy wallets to v0.18
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(os.path.join(node_master_wallets_dir, wallet),
                            os.path.join(node_v18_wallets_dir, wallet))

        # Copy wallets to v0.19
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(os.path.join(node_master_wallets_dir, wallet),
                            os.path.join(node_v19_wallets_dir, wallet))

        # Open the wallets in v0.19
        node_v19.loadwallet("w1")
        wallet = node_v19.get_wallet_rpc("w1")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        txs = wallet.listtransactions()
        assert_equal(len(txs), 5)
        assert_equal(txs[1]["txid"], tx1_id)
        assert_equal(txs[2]["walletconflicts"], [tx1_id])
        assert_equal(txs[1]["replaced_by_txid"], tx2_id)
        assert not (txs[1]["abandoned"])
        assert_equal(txs[1]["confirmations"], -1)
        assert_equal(txs[2]["blockindex"], 1)
        assert txs[3]["abandoned"]
        assert_equal(txs[4]["walletconflicts"], [tx3_id])
        assert_equal(txs[3]["replaced_by_txid"], tx4_id)
        assert not (hasattr(txs[3], "blockindex"))

        node_v19.loadwallet("w2")
        wallet = node_v19.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        node_v19.loadwallet("w3")
        wallet = node_v19.get_wallet_rpc("w3")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # Open the wallets in v0.18
        node_v18.loadwallet("w1")
        wallet = node_v18.get_wallet_rpc("w1")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        txs = wallet.listtransactions()
        assert_equal(len(txs), 5)
        assert_equal(txs[1]["txid"], tx1_id)
        assert_equal(txs[2]["walletconflicts"], [tx1_id])
        assert_equal(txs[1]["replaced_by_txid"], tx2_id)
        assert not (txs[1]["abandoned"])
        assert_equal(txs[1]["confirmations"], -1)
        assert_equal(txs[2]["blockindex"], 1)
        assert txs[3]["abandoned"]
        assert_equal(txs[4]["walletconflicts"], [tx3_id])
        assert_equal(txs[3]["replaced_by_txid"], tx4_id)
        assert not (hasattr(txs[3], "blockindex"))

        node_v18.loadwallet("w2")
        wallet = node_v18.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        node_v18.loadwallet("w3")
        wallet = node_v18.get_wallet_rpc("w3")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # Open the wallets in v0.17
        node_v17.loadwallet("w1_v18")
        wallet = node_v17.get_wallet_rpc("w1_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0

        node_v17.loadwallet("w1")
        wallet = node_v17.get_wallet_rpc("w1")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0

        node_v17.loadwallet("w2_v18")
        wallet = node_v17.get_wallet_rpc("w2_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        node_v17.loadwallet("w2")
        wallet = node_v17.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # RPC loadwallet failure causes shirecoind to exit, in addition to the RPC
        # call failure, so the following test won't work:
        # assert_raises_rpc_error(-4, "Wallet loading failed.", node_v17.loadwallet, 'w3_v18')

        # Instead, we stop node and try to launch it with the wallet:
        self.stop_node(self.num_nodes - 1)
        node_v17.assert_start_raises_init_error([
            "-wallet=w3_v18"
        ], "Error: Error loading w3_v18: Wallet requires newer version of Shirecoin Core"
                                                )
        node_v17.assert_start_raises_init_error([
            "-wallet=w3"
        ], "Error: Error loading w3: Wallet requires newer version of Shirecoin Core"
                                                )
        self.start_node(self.num_nodes - 1)

        self.log.info("Test wallet upgrade path...")
        # u1: regular wallet, created with v0.17
        node_v17.createwallet(wallet_name="u1_v17")
        wallet = node_v17.get_wallet_rpc("u1_v17")
        address = wallet.getnewaddress("bech32")
        info = wallet.getaddressinfo(address)
        hdkeypath = info["hdkeypath"]
        pubkey = info["pubkey"]

        # Copy the 0.17 wallet to the last Shirecoin Core version and open it:
        node_v17.unloadwallet("u1_v17")
        shutil.copytree(os.path.join(node_v17_wallets_dir, "u1_v17"),
                        os.path.join(node_master_wallets_dir, "u1_v17"))
        node_master.loadwallet("u1_v17")
        wallet = node_master.get_wallet_rpc("u1_v17")
        info = wallet.getaddressinfo(address)
        descriptor = "wpkh([" + info["hdmasterfingerprint"] + hdkeypath[
            1:] + "]" + pubkey + ")"
        assert_equal(info["desc"], descsum_create(descriptor))

        # Copy the 0.19 wallet to the last Shirecoin Core version and open it:
        shutil.copytree(os.path.join(node_v19_wallets_dir, "w1_v19"),
                        os.path.join(node_master_wallets_dir, "w1_v19"))
        node_master.loadwallet("w1_v19")
        wallet = node_master.get_wallet_rpc("w1_v19")
        assert wallet.getaddressinfo(address_18075)["solvable"]
Beispiel #4
0
    def run_test(self):
        node0, node1, node2 = self.nodes
        self.wallet = MiniWallet(test_node=node0)

        if self.is_bdb_compiled():
            self.check_addmultisigaddress_errors()

        self.log.info('Generating blocks ...')
        self.generate(self.wallet, 149)

        self.moved = 0
        for self.nkeys in [3, 5]:
            for self.nsigs in [2, 3]:
                for self.output_type in ["bech32", "p2sh-segwit", "legacy"]:
                    self.get_keys()
                    self.do_multisig()
        if self.is_bdb_compiled():
            self.checkbalances()

        # Test mixed compressed and uncompressed pubkeys
        self.log.info(
            'Mixed compressed and uncompressed multisigs are not allowed')
        pk0, pk1, pk2 = [
            getnewdestination('bech32')[0].hex() for _ in range(3)
        ]

        # decompress pk2
        pk_obj = ECPubKey()
        pk_obj.set(bytes.fromhex(pk2))
        pk_obj.compressed = False
        pk2 = pk_obj.get_bytes().hex()

        if self.is_bdb_compiled():
            node0.createwallet(wallet_name='wmulti0',
                               disable_private_keys=True)
            wmulti0 = node0.get_wallet_rpc('wmulti0')

        # Check all permutations of keys because order matters apparently
        for keys in itertools.permutations([pk0, pk1, pk2]):
            # Results should be the same as this legacy one
            legacy_addr = node0.createmultisig(2, keys, 'legacy')['address']

            if self.is_bdb_compiled():
                result = wmulti0.addmultisigaddress(2, keys, '', 'legacy')
                assert_equal(legacy_addr, result['address'])
                assert 'warnings' not in result

            # Generate addresses with the segwit types. These should all make legacy addresses
            err_msg = [
                "Unable to make chosen address type, please ensure no uncompressed public keys are present."
            ]

            for addr_type in ['bech32', 'p2sh-segwit']:
                result = self.nodes[0].createmultisig(nrequired=2,
                                                      keys=keys,
                                                      address_type=addr_type)
                assert_equal(legacy_addr, result['address'])
                assert_equal(result['warnings'], err_msg)

                if self.is_bdb_compiled():
                    result = wmulti0.addmultisigaddress(nrequired=2,
                                                        keys=keys,
                                                        address_type=addr_type)
                    assert_equal(legacy_addr, result['address'])
                    assert_equal(result['warnings'], err_msg)

        self.log.info(
            'Testing sortedmulti descriptors with BIP 67 test vectors')
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               'data/rpc_bip67.json'),
                  encoding='utf-8') as f:
            vectors = json.load(f)

        for t in vectors:
            key_str = ','.join(t['keys'])
            desc = descsum_create('sh(sortedmulti(2,{}))'.format(key_str))
            assert_equal(self.nodes[0].deriveaddresses(desc)[0], t['address'])
            sorted_key_str = ','.join(t['sorted_keys'])
            sorted_key_desc = descsum_create(
                'sh(multi(2,{}))'.format(sorted_key_str))
            assert_equal(self.nodes[0].deriveaddresses(sorted_key_desc)[0],
                         t['address'])

        # Check that bech32m is currently not allowed
        assert_raises_rpc_error(
            -5, "createmultisig cannot create bech32m multisig addresses",
            self.nodes[0].createmultisig, 2, self.pub, "bech32m")
Beispiel #5
0
    def do_multisig(self):
        node0, node1, node2 = self.nodes

        if self.is_bdb_compiled():
            if 'wmulti' not in node1.listwallets():
                try:
                    node1.loadwallet('wmulti')
                except JSONRPCException as e:
                    path = os.path.join(self.options.tmpdir, "node1",
                                        "regtest", "wallets", "wmulti")
                    if e.error[
                            'code'] == -18 and "Wallet file verification failed. Failed to load database path '{}'. Path does not exist.".format(
                                path) in e.error['message']:
                        node1.createwallet(wallet_name='wmulti',
                                           disable_private_keys=True)
                    else:
                        raise
            wmulti = node1.get_wallet_rpc('wmulti')

        # Construct the expected descriptor
        desc = 'multi({},{})'.format(self.nsigs, ','.join(self.pub))
        if self.output_type == 'legacy':
            desc = 'sh({})'.format(desc)
        elif self.output_type == 'p2sh-segwit':
            desc = 'sh(wsh({}))'.format(desc)
        elif self.output_type == 'bech32':
            desc = 'wsh({})'.format(desc)
        desc = descsum_create(desc)

        msig = node2.createmultisig(self.nsigs, self.pub, self.output_type)
        assert 'warnings' not in msig
        madd = msig["address"]
        mredeem = msig["redeemScript"]
        assert_equal(desc, msig['descriptor'])
        if self.output_type == 'bech32':
            assert madd[0:4] == "bcrt"  # actually a bech32 address

        if self.is_bdb_compiled():
            # compare against addmultisigaddress
            msigw = wmulti.addmultisigaddress(self.nsigs, self.pub, None,
                                              self.output_type)
            maddw = msigw["address"]
            mredeemw = msigw["redeemScript"]
            assert_equal(desc, drop_origins(msigw['descriptor']))
            # addmultisigiaddress and createmultisig work the same
            assert maddw == madd
            assert mredeemw == mredeem
            wmulti.unloadwallet()

        spk = bytes.fromhex(node0.validateaddress(madd)["scriptPubKey"])
        txid, _ = self.wallet.send_to(from_node=self.nodes[0],
                                      scriptPubKey=spk,
                                      amount=1300)
        tx = node0.getrawtransaction(txid, True)
        vout = [
            v["n"] for v in tx["vout"] if madd == v["scriptPubKey"]["address"]
        ]
        assert len(vout) == 1
        vout = vout[0]
        scriptPubKey = tx["vout"][vout]["scriptPubKey"]["hex"]
        value = tx["vout"][vout]["value"]
        prevtxs = [{
            "txid": txid,
            "vout": vout,
            "scriptPubKey": scriptPubKey,
            "redeemScript": mredeem,
            "amount": value
        }]

        self.generate(node0, 1)

        outval = value - decimal.Decimal("0.00001000")
        rawtx = node2.createrawtransaction([{
            "txid": txid,
            "vout": vout
        }], [{
            self.final: outval
        }])

        prevtx_err = dict(prevtxs[0])
        del prevtx_err["redeemScript"]

        assert_raises_rpc_error(-8, "Missing redeemScript/witnessScript",
                                node2.signrawtransactionwithkey, rawtx,
                                self.priv[0:self.nsigs - 1], [prevtx_err])

        # if witnessScript specified, all ok
        prevtx_err["witnessScript"] = prevtxs[0]["redeemScript"]
        node2.signrawtransactionwithkey(rawtx, self.priv[0:self.nsigs - 1],
                                        [prevtx_err])

        # both specified, also ok
        prevtx_err["redeemScript"] = prevtxs[0]["redeemScript"]
        node2.signrawtransactionwithkey(rawtx, self.priv[0:self.nsigs - 1],
                                        [prevtx_err])

        # redeemScript mismatch to witnessScript
        prevtx_err["redeemScript"] = "6a"  # OP_RETURN
        assert_raises_rpc_error(
            -8, "redeemScript does not correspond to witnessScript",
            node2.signrawtransactionwithkey, rawtx,
            self.priv[0:self.nsigs - 1], [prevtx_err])

        # redeemScript does not match scriptPubKey
        del prevtx_err["witnessScript"]
        assert_raises_rpc_error(
            -8, "redeemScript/witnessScript does not match scriptPubKey",
            node2.signrawtransactionwithkey, rawtx,
            self.priv[0:self.nsigs - 1], [prevtx_err])

        # witnessScript does not match scriptPubKey
        prevtx_err["witnessScript"] = prevtx_err["redeemScript"]
        del prevtx_err["redeemScript"]
        assert_raises_rpc_error(
            -8, "redeemScript/witnessScript does not match scriptPubKey",
            node2.signrawtransactionwithkey, rawtx,
            self.priv[0:self.nsigs - 1], [prevtx_err])

        rawtx2 = node2.signrawtransactionwithkey(rawtx,
                                                 self.priv[0:self.nsigs - 1],
                                                 prevtxs)
        rawtx3 = node2.signrawtransactionwithkey(rawtx2["hex"],
                                                 [self.priv[-1]], prevtxs)

        self.moved += outval
        tx = node0.sendrawtransaction(rawtx3["hex"], 0)
        blk = self.generate(node0, 1)[0]
        assert tx in node0.getblock(blk)["tx"]

        txinfo = node0.getrawtransaction(tx, True, blk)
        self.log.info("n/m=%d/%d %s size=%d vsize=%d weight=%d" %
                      (self.nsigs, self.nkeys, self.output_type,
                       txinfo["size"], txinfo["vsize"], txinfo["weight"]))
Beispiel #6
0
 def get_descriptor(self):
     return descsum_create(f'raw({self._scriptPubKey.hex()})')
Beispiel #7
0
    def test_desc(self, node, address, multisig, typ, utxo):
        """Run sanity checks on a descriptor reported by getaddressinfo."""
        info = self.nodes[node].getaddressinfo(address)
        assert 'desc' in info
        assert_equal(info['desc'], utxo['desc'])
        assert self.nodes[node].validateaddress(address)['isvalid']

        # Use a ridiculously roundabout way to find the key origin info through
        # the PSBT logic. However, this does test consistency between the PSBT reported
        # fingerprints/paths and the descriptor logic.
        psbt = self.nodes[node].createpsbt([{
            'txid': utxo['txid'],
            'vout': utxo['vout']
        }], [{
            address: 0.00010000
        }])
        psbt = self.nodes[node].walletprocesspsbt(psbt, False, "ALL", True)
        decode = self.nodes[node].decodepsbt(psbt['psbt'])
        key_descs = {}
        for deriv in decode['inputs'][0]['bip32_derivs']:
            assert_equal(len(deriv['master_fingerprint']), 8)
            assert_equal(deriv['path'][0], 'm')
            key_descs[
                deriv['pubkey']] = '[' + deriv['master_fingerprint'] + deriv[
                    'path'][1:] + ']' + deriv['pubkey']

        # Verify the descriptor checksum against the Python implementation
        assert descsum_check(info['desc'])
        # Verify that stripping the checksum and recreating it using Python roundtrips
        assert info['desc'] == descsum_create(info['desc'][:-9])
        # Verify that stripping the checksum and feeding it to getdescriptorinfo roundtrips
        assert info['desc'] == self.nodes[0].getdescriptorinfo(
            info['desc'][:-9])['descriptor']

        if not multisig and typ == 'legacy':
            # P2PKH
            assert_equal(info['desc'],
                         descsum_create("pkh(%s)" % key_descs[info['pubkey']]))
        elif not multisig and typ == 'p2sh-segwit':
            # P2SH-P2WPKH
            assert_equal(
                info['desc'],
                descsum_create("sh(wpkh(%s))" % key_descs[info['pubkey']]))
        elif not multisig and typ == 'bech32':
            # P2WPKH
            assert_equal(
                info['desc'],
                descsum_create("wpkh(%s)" % key_descs[info['pubkey']]))
        elif typ == 'legacy':
            # P2SH-multisig
            assert_equal(
                info['desc'],
                descsum_create("sh(multi(2,%s,%s))" %
                               (key_descs[info['pubkeys'][0]],
                                key_descs[info['pubkeys'][1]])))
        elif typ == 'p2sh-segwit':
            # P2SH-P2WSH-multisig
            assert_equal(
                info['desc'],
                descsum_create("sh(wsh(multi(2,%s,%s)))" %
                               (key_descs[info['embedded']['pubkeys'][0]],
                                key_descs[info['embedded']['pubkeys'][1]])))
        elif typ == 'bech32':
            # P2WSH-multisig
            assert_equal(
                info['desc'],
                descsum_create("wsh(multi(2,%s,%s))" %
                               (key_descs[info['pubkeys'][0]],
                                key_descs[info['pubkeys'][1]])))
        else:
            # Unknown type
            assert False
Beispiel #8
0
    def run_test(self):
        self.log.info("Mining blocks...")
        self.nodes[0].generate(1)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        node0_address1 = self.nodes[0].getaddressinfo(
            self.nodes[0].getnewaddress())

        # Check only one address
        assert_equal(node0_address1['ismine'], True)

        # Node 1 sync test
        assert_equal(self.nodes[1].getblockcount(), 1)

        # Address Test - before import
        address_info = self.nodes[1].getaddressinfo(node0_address1['address'])
        assert_equal(address_info['iswatchonly'], False)
        assert_equal(address_info['ismine'], False)

        # RPC importmulti -----------------------------------------------

        # Freicoin Address (implicit non-internal)
        self.log.info("Should import an address")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp,
                     ischange=False)
        watchonly_address = key.p2pkh_addr
        watchonly_timestamp = timestamp

        self.log.info("Should not import an invalid address")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": "not valid address"
                },
                "timestamp": "now"
            },
            success=False,
            error_code=-5,
            error_message='Invalid address \"not valid address\"')

        # ScriptPubKey + internal
        self.log.info("Should import a scriptPubKey with internal flag")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "internal": True
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp,
                     ischange=True)

        # ScriptPubKey + internal + label
        self.log.info(
            "Should not allow a label to be specified when internal is true")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "internal": True,
                "label": "Example label"
            },
            success=False,
            error_code=-8,
            error_message='Internal addresses should not have a label')

        # Nonstandard scriptPubKey + !internal
        self.log.info(
            "Should not import a nonstandard scriptPubKey without internal flag"
        )
        nonstandardScriptPubKey = key.p2pkh_script + bytes_to_hex_str(
            CScript([OP_NOP]))
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": nonstandardScriptPubKey,
                "timestamp": "now"
            },
            success=False,
            error_code=-8,
            error_message=
            'Internal must be set to true for nonstandard scriptPubKey imports.'
        )
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=False,
                     timestamp=None)

        # Address + Public key + !Internal(explicit)
        self.log.info("Should import an address with public key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "pubkeys": [key.pubkey],
                "internal": False
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp)

        # ScriptPubKey + Public key + internal
        self.log.info(
            "Should import a scriptPubKey with internal and with public key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "pubkeys": [key.pubkey],
                "internal": True
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp)

        # Nonstandard scriptPubKey + Public key + !internal
        self.log.info(
            "Should not import a nonstandard scriptPubKey without internal and with public key"
        )
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": nonstandardScriptPubKey,
                "timestamp": "now",
                "pubkeys": [key.pubkey]
            },
            success=False,
            error_code=-8,
            error_message=
            'Internal must be set to true for nonstandard scriptPubKey imports.'
        )
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=False,
                     timestamp=None)

        # Address + Private key + !watchonly
        self.log.info("Should import an address with private key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "keys": [key.privkey]
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=True,
                     timestamp=timestamp)

        self.log.info(
            "Should not import an address with private key if is already imported"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "keys": [key.privkey]
            },
            success=False,
            error_code=-4,
            error_message=
            'The wallet already contains the private key for this address or script ("'
            + key.p2pkh_script + '")')

        # Address + Private key + watchonly
        self.log.info(
            "Should import an address with private key and with watchonly")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "keys": [key.privkey],
                "watchonly": True
            },
            success=True,
            warnings=[
                "All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=True,
                     timestamp=timestamp)

        # ScriptPubKey + Private key + internal
        self.log.info(
            "Should import a scriptPubKey with internal and with private key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "keys": [key.privkey],
                "internal": True
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=True,
                     timestamp=timestamp)

        # Nonstandard scriptPubKey + Private key + !internal
        self.log.info(
            "Should not import a nonstandard scriptPubKey without internal and with private key"
        )
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": nonstandardScriptPubKey,
                "timestamp": "now",
                "keys": [key.privkey]
            },
            success=False,
            error_code=-8,
            error_message=
            'Internal must be set to true for nonstandard scriptPubKey imports.'
        )
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=False,
                     timestamp=None)

        # P2SH address
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        self.log.info("Should import a p2sh")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2sh_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     isscript=True,
                     iswatchonly=True,
                     timestamp=timestamp)
        p2shunspent = self.nodes[1].listunspent(0, 999999,
                                                [multisig.p2sh_addr])[0]
        assert_equal(p2shunspent['spendable'], False)
        assert_equal(p2shunspent['solvable'], False)

        # P2SH + Redeem script
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        self.log.info("Should import a p2sh with respective redeem script")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2sh_addr
                },
                "timestamp": "now",
                "redeemscript": multisig.redeem_script
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     timestamp=timestamp,
                     iswatchonly=True,
                     ismine=False,
                     solvable=True)

        p2shunspent = self.nodes[1].listunspent(0, 999999,
                                                [multisig.p2sh_addr])[0]
        assert_equal(p2shunspent['spendable'], False)
        assert_equal(p2shunspent['solvable'], True)

        # P2SH + Redeem script + Private Keys + !Watchonly
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        self.log.info(
            "Should import a p2sh with respective redeem script and private keys"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2sh_addr
                },
                "timestamp": "now",
                "redeemscript": multisig.redeem_script,
                "keys": multisig.privkeys[0:2]
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     timestamp=timestamp,
                     ismine=False,
                     iswatchonly=True,
                     solvable=True)

        p2shunspent = self.nodes[1].listunspent(0, 999999,
                                                [multisig.p2sh_addr])[0]
        assert_equal(p2shunspent['spendable'], False)
        assert_equal(p2shunspent['solvable'], True)

        # P2SH + Redeem script + Private Keys + Watchonly
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        self.log.info(
            "Should import a p2sh with respective redeem script and private keys"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2sh_addr
                },
                "timestamp": "now",
                "redeemscript": multisig.redeem_script,
                "keys": multisig.privkeys[0:2],
                "watchonly": True
            },
            success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=True,
                     timestamp=timestamp)

        # Address + Public key + !Internal + Wrong pubkey
        self.log.info(
            "Should not import an address with the wrong public key as non-solvable"
        )
        key = get_key(self.nodes[0])
        wrong_key = get_key(self.nodes[0]).pubkey
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "pubkeys": [wrong_key]
            },
            success=True,
            warnings=[
                "Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.",
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # ScriptPubKey + Public key + internal + Wrong pubkey
        self.log.info(
            "Should import a scriptPubKey with internal and with a wrong public key as non-solvable"
        )
        key = get_key(self.nodes[0])
        wrong_key = get_key(self.nodes[0]).pubkey
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "pubkeys": [wrong_key],
                "internal": True
            },
            success=True,
            warnings=[
                "Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.",
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # Address + Private key + !watchonly + Wrong private key
        self.log.info(
            "Should import an address with a wrong private key as non-solvable"
        )
        key = get_key(self.nodes[0])
        wrong_privkey = get_key(self.nodes[0]).privkey
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "keys": [wrong_privkey]
            },
            success=True,
            warnings=[
                "Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.",
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # ScriptPubKey + Private key + internal + Wrong private key
        self.log.info(
            "Should import a scriptPubKey with internal and with a wrong private key as non-solvable"
        )
        key = get_key(self.nodes[0])
        wrong_privkey = get_key(self.nodes[0]).privkey
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "keys": [wrong_privkey],
                "internal": True
            },
            success=True,
            warnings=[
                "Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.",
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # Importing existing watch only address with new timestamp should replace saved timestamp.
        assert_greater_than(timestamp, watchonly_timestamp)
        self.log.info("Should replace previously saved watch only timestamp.")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": watchonly_address
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     watchonly_address,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp)
        watchonly_timestamp = timestamp

        # restart nodes to check for proper serialization/deserialization of watch only address
        self.stop_nodes()
        self.start_nodes()
        test_address(self.nodes[1],
                     watchonly_address,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=watchonly_timestamp)

        # Bad or missing timestamps
        self.log.info("Should throw on invalid or missing timestamp values")
        assert_raises_rpc_error(-3, 'Missing required timestamp field for key',
                                self.nodes[1].importmulti,
                                [{
                                    "scriptPubKey": key.p2pkh_script
                                }])
        assert_raises_rpc_error(
            -3,
            'Expected number or "now" timestamp value for key. got type string',
            self.nodes[1].importmulti, [{
                "scriptPubKey": key.p2pkh_script,
                "timestamp": ""
            }])

        # Import P2WPK address as watch only
        self.log.info("Should import a P2WPK address as watch only")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2wpk_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2wpk_addr,
                     iswatchonly=True,
                     solvable=False)

        # Import P2WPK address with public key but no private key
        self.log.info(
            "Should import a P2WPK address and public key as solvable but not spendable"
        )
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2wpk_addr
                },
                "timestamp": "now",
                "pubkeys": [key.pubkey]
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2wpk_addr,
                     ismine=False,
                     solvable=True)

        # Import P2WPK address with key and check it is spendable
        self.log.info("Should import a P2WPK address with key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2wpk_addr
                },
                "timestamp": "now",
                "keys": [key.privkey]
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2wpk_addr,
                     iswatchonly=False,
                     ismine=True)

        # P2WSH multisig address without scripts or keys
        multisig = get_multisig(self.nodes[0])
        self.log.info(
            "Should import a p2wsh multisig as watch only without respective redeem script and private keys"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2wsh_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1], multisig.p2sh_addr, solvable=False)

        # Same P2WSH multisig address as above, but now with witnessscript + private keys
        self.log.info(
            "Should import a p2wsh with respective witness script and private keys"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2wsh_addr
                },
                "timestamp": "now",
                "witnessscript": multisig.witness_script,
                "keys": multisig.privkeys
            },
            success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     solvable=True,
                     ismine=True,
                     sigsrequired=2)

        # P2WPK address with no public or private key
        key = get_key(self.nodes[0])
        self.log.info("Should import a p2wpk without keys")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2wpk_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2wpk_addr,
                     solvable=False,
                     ismine=False)

        # P2WPK address + public key with no private key
        self.log.info(
            "Should import a p2wpk with respective pubkey as solvable")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2wpk_addr
                },
                "timestamp": "now",
                "pubkeys": [key.pubkey]
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2wpk_addr,
                     solvable=True,
                     ismine=False)

        # P2WPK address + private key
        key = get_key(self.nodes[0])
        self.log.info("Should import a p2wpk with private keys")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2wpk_addr
                },
                "timestamp": "now",
                "keys": [key.privkey]
            },
            success=True)
        test_address(self.nodes[1], key.p2wpk_addr, solvable=True, ismine=True)

        # P2WSH multisig with no private key
        multisig = get_multisig(self.nodes[0])
        self.log.info(
            "Should import a p2wsh with respective redeem script but no private key"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2wsh_addr
                },
                "timestamp": "now",
                "witnessscript": multisig.witness_script
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     multisig.p2wsh_addr,
                     solvable=True,
                     ismine=False)

        # Test importing of a P2WPK address via descriptor + private key
        key = get_key(self.nodes[0])
        self.log.info(
            "Should not import a p2wpk address from descriptor without checksum and private key"
        )
        self.test_importmulti(
            {
                "desc": "wpk(" + key.pubkey + ")",
                "timestamp": "now",
                "label": "Descriptor import test",
                "keys": [key.privkey]
            },
            success=False,
            error_code=-5,
            error_message="Descriptor is invalid")

        # Test importing of a P2WPK address via descriptor + private key
        key = get_key(self.nodes[0])
        self.log.info(
            "Should import a p2wpk address from descriptor and private key")
        self.test_importmulti(
            {
                "desc": descsum_create("wpk(" + key.pubkey + ")"),
                "timestamp": "now",
                "label": "Descriptor import test",
                "keys": [key.privkey]
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2wpk_addr,
                     solvable=True,
                     ismine=True,
                     label="Descriptor import test")

        # Test ranged descriptor fails if range is not specified
        xpriv = "tprv8ZgxMBicQKsPeuVhWwi6wuMQGfPKi9Li5GtX35jVNknACgqe3CY4g5xgkfDDJcmtF7o1QnxWDRYw4H5P26PXq7sbcUkEqeR4fg3Kxp2tigg"
        addresses = [
            "2N7yv4p8G8yEaPddJxY41kPihnWvs39qCMf",
            "2MsHxyb2JS3pAySeNUsJ7mNnurtpeenDzLA"
        ]  # hdkeypath=m/0'/0'/0' and 1'
        desc = "wpk(" + xpriv + "/0'/0'/*'" + ")"
        self.log.info(
            "Ranged descriptor import should fail without a specified range")
        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now"
            },
            success=False,
            error_code=-8,
            error_message='Descriptor is ranged, please specify the range')

        # Test importing of a ranged descriptor without keys
        self.log.info(
            "Should import the ranged descriptor with specified range as solvable"
        )
        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": 1
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        for address in addresses:
            test_address(self.nodes[1], key.p2wpk_addr, solvable=True)

        # Test importing of a P2PKH address via descriptor
        key = get_key(self.nodes[0])
        self.log.info("Should import a p2pkh address from descriptor")
        self.test_importmulti(
            {
                "desc": descsum_create("pkh(" + key.pubkey + ")"),
                "timestamp": "now",
                "label": "Descriptor import test"
            },
            True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     solvable=True,
                     ismine=False,
                     label="Descriptor import test")

        # Test import fails if both desc and scriptPubKey are provided
        key = get_key(self.nodes[0])
        self.log.info(
            "Import should fail if both scriptPubKey and desc are provided")
        self.test_importmulti(
            {
                "desc": descsum_create("pkh(" + key.pubkey + ")"),
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now"
            },
            success=False,
            error_code=-8,
            error_message=
            'Both a descriptor and a scriptPubKey should not be provided.')

        # Test import fails if neither desc nor scriptPubKey are present
        key = get_key(self.nodes[0])
        self.log.info(
            "Import should fail if neither a descriptor nor a scriptPubKey are provided"
        )
        self.test_importmulti(
            {"timestamp": "now"},
            success=False,
            error_code=-8,
            error_message=
            'Either a descriptor or scriptPubKey must be provided.')

        # Test importing of a multisig via descriptor
        key1 = get_key(self.nodes[0])
        key2 = get_key(self.nodes[0])
        self.log.info("Should import a 1-of-2 bare multisig from descriptor")
        self.test_importmulti(
            {
                "desc":
                descsum_create("multi(1," + key1.pubkey + "," + key2.pubkey +
                               ")"),
                "timestamp":
                "now"
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        self.log.info(
            "Should not treat individual keys from the imported bare multisig as watchonly"
        )
        test_address(self.nodes[1],
                     key1.p2pkh_addr,
                     ismine=False,
                     iswatchonly=False)

        # Import pubkeys with key origin info
        self.log.info(
            "Addresses should have hd keypath and master key id after import with key origin"
        )
        pub_addr = self.nodes[1].getnewaddress()
        pub_addr = self.nodes[1].getnewaddress()
        info = self.nodes[1].getaddressinfo(pub_addr)
        pub = info['pubkey']
        pub_keypath = info['hdkeypath']
        pub_fpr = info['hdmasterfingerprint']
        result = self.nodes[0].importmulti([{
            'desc':
            descsum_create("wpk([" + pub_fpr + pub_keypath[1:] + "]" + pub +
                           ")"),
            "timestamp":
            "now",
        }])
        assert result[0]['success']
        pub_import_info = self.nodes[0].getaddressinfo(pub_addr)
        assert_equal(pub_import_info['hdmasterfingerprint'], pub_fpr)
        assert_equal(pub_import_info['pubkey'], pub)
        assert_equal(pub_import_info['hdkeypath'], pub_keypath)

        # Import privkeys with key origin info
        priv_addr = self.nodes[1].getnewaddress()
        info = self.nodes[1].getaddressinfo(priv_addr)
        priv = self.nodes[1].dumpprivkey(priv_addr)
        priv_keypath = info['hdkeypath']
        priv_fpr = info['hdmasterfingerprint']
        result = self.nodes[0].importmulti([{
            'desc':
            descsum_create("wpk([" + priv_fpr + priv_keypath[1:] + "]" + priv +
                           ")"),
            "timestamp":
            "now",
        }])
        assert result[0]['success']
        priv_import_info = self.nodes[0].getaddressinfo(priv_addr)
        assert_equal(priv_import_info['hdmasterfingerprint'], priv_fpr)
        assert_equal(priv_import_info['hdkeypath'], priv_keypath)

        # Make sure the key origin info are still there after a restart
        self.stop_nodes()
        self.start_nodes()
        import_info = self.nodes[0].getaddressinfo(pub_addr)
        assert_equal(import_info['hdmasterfingerprint'], pub_fpr)
        assert_equal(import_info['hdkeypath'], pub_keypath)
        import_info = self.nodes[0].getaddressinfo(priv_addr)
        assert_equal(import_info['hdmasterfingerprint'], priv_fpr)
        assert_equal(import_info['hdkeypath'], priv_keypath)

        # Check legacy import does not import key origin info
        self.log.info("Legacy imports don't have key origin info")
        pub_addr = self.nodes[1].getnewaddress()
        info = self.nodes[1].getaddressinfo(pub_addr)
        pub = info['pubkey']
        result = self.nodes[0].importmulti([{
            'scriptPubKey': {
                'address': pub_addr
            },
            'pubkeys': [pub],
            "timestamp": "now",
        }])
        assert result[0]['success']
        pub_import_info = self.nodes[0].getaddressinfo(pub_addr)
        assert_equal(pub_import_info['pubkey'], pub)
        assert 'hdmasterfingerprint' not in pub_import_info
        assert 'hdkeypath' not in pub_import_info

        # Import some public keys to the keypool of a no privkey wallet
        self.log.info("Adding pubkey to keypool of disableprivkey wallet")
        self.nodes[1].createwallet(wallet_name="noprivkeys",
                                   disable_private_keys=True)
        wrpc = self.nodes[1].get_wallet_rpc("noprivkeys")

        addr1 = self.nodes[0].getnewaddress()
        addr2 = self.nodes[0].getnewaddress()
        pub1 = self.nodes[0].getaddressinfo(addr1)['pubkey']
        pub2 = self.nodes[0].getaddressinfo(addr2)['pubkey']
        result = wrpc.importmulti([{
            'desc': descsum_create('wpk(' + pub1 + ')'),
            'keypool': True,
            "timestamp": "now",
        }, {
            'desc': descsum_create('wpk(' + pub2 + ')'),
            'keypool': True,
            "timestamp": "now",
        }])
        assert result[0]['success']
        assert result[1]['success']
        assert_equal(wrpc.getwalletinfo()["keypoolsize"], 2)
        newaddr1 = wrpc.getnewaddress()
        assert_equal(addr1, newaddr1)
        newaddr2 = wrpc.getnewaddress()
        assert_equal(addr2, newaddr2)

        # Import some public keys to the internal keypool of a no privkey wallet
        self.log.info(
            "Adding pubkey to internal keypool of disableprivkey wallet")
        addr1 = self.nodes[0].getnewaddress()
        addr2 = self.nodes[0].getnewaddress()
        pub1 = self.nodes[0].getaddressinfo(addr1)['pubkey']
        pub2 = self.nodes[0].getaddressinfo(addr2)['pubkey']
        result = wrpc.importmulti([{
            'desc': descsum_create('wpk(' + pub1 + ')'),
            'keypool': True,
            'internal': True,
            "timestamp": "now",
        }, {
            'desc': descsum_create('wpk(' + pub2 + ')'),
            'keypool': True,
            'internal': True,
            "timestamp": "now",
        }])
        assert result[0]['success']
        assert result[1]['success']
        assert_equal(wrpc.getwalletinfo()["keypoolsize_hd_internal"], 2)
        newaddr1 = wrpc.getrawchangeaddress()
        assert_equal(addr1, newaddr1)
        newaddr2 = wrpc.getrawchangeaddress()
        assert_equal(addr2, newaddr2)

        # Import a multisig and make sure the keys don't go into the keypool
        self.log.info(
            'Imported scripts with pubkeys shoud not have their pubkeys go into the keypool'
        )
        addr1 = self.nodes[0].getnewaddress()
        addr2 = self.nodes[0].getnewaddress()
        pub1 = self.nodes[0].getaddressinfo(addr1)['pubkey']
        pub2 = self.nodes[0].getaddressinfo(addr2)['pubkey']
        result = wrpc.importmulti([{
            'desc':
            descsum_create('wsh(multi(2,' + pub1 + ',' + pub2 + '))'),
            'keypool':
            True,
            "timestamp":
            "now",
        }])
        assert result[0]['success']
        assert_equal(wrpc.getwalletinfo()["keypoolsize"], 0)

        # Cannot import those pubkeys to keypool of wallet with privkeys
        self.log.info(
            "Pubkeys cannot be added to the keypool of a wallet with private keys"
        )
        wrpc = self.nodes[1].get_wallet_rpc("")
        assert wrpc.getwalletinfo()['private_keys_enabled']
        result = wrpc.importmulti([{
            'desc': descsum_create('wpk(' + pub1 + ')'),
            'keypool': True,
            "timestamp": "now",
        }])
        assert_equal(result[0]['error']['code'], -8)
        assert_equal(
            result[0]['error']['message'],
            "Keys can only be imported to the keypool when private keys are disabled"
        )

        # Make sure ranged imports import keys in order
        self.log.info('Key ranges should be imported in order')
        wrpc = self.nodes[1].get_wallet_rpc("noprivkeys")
        assert_equal(wrpc.getwalletinfo()["keypoolsize"], 0)
        assert_equal(wrpc.getwalletinfo()["private_keys_enabled"], False)
        xpub = "tpubDAXcJ7s7ZwicqjprRaEWdPoHKrCS215qxGYxpusRLLmJuT69ZSicuGdSfyvyKpvUNYBW1s2U3NSrT6vrCYB9e6nZUEvrqnwXPF8ArTCRXMY"
        addresses = [
            'fcrt1qpjdewptcahxy8vpnvr7ukevzx4a7zyhpfwut8s',  # m/0'/0'/0
            'fcrt1qq5m59csrvle2us5lj9c59etglje69yua48afzy',  # m/0'/0'/1
            'fcrt1qjxc9np7uux87shxkzgqy23ek8eap52xfwq7u7w',  # m/0'/0'/2
            'fcrt1qa5pwzv5wsxgddqltx77ljlfrsnf9rs5nyftff6',  # m/0'/0'/3
            'fcrt1qg3zm4zh6prq45r6hduznyl63f2upm5mjglpvz8',  # m/0'/0'/4
        ]
        result = wrpc.importmulti([{
            'desc':
            descsum_create('wpk([80002067/0h/0h]' + xpub + '/*)'),
            'keypool':
            True,
            'timestamp':
            'now',
            'range': [0, 4],
        }])
        for i in range(0, 5):
            addr = wrpc.getnewaddress('', 'bech32')
            assert_equal(addr, addresses[i])
Beispiel #9
0
    def run_test(self):
        self.log.info('Setting up wallets')
        self.nodes[0].createwallet(wallet_name='w0', disable_private_keys=False)
        w0 = self.nodes[0].get_wallet_rpc('w0')

        self.nodes[1].createwallet(wallet_name='w1', disable_private_keys=True, blank=True, descriptors=True)
        w1 = self.nodes[1].get_wallet_rpc('w1')
        assert_equal(w1.getwalletinfo()['keypoolsize'], 0)

        self.nodes[1].createwallet(wallet_name="wpriv", disable_private_keys=False, blank=True, descriptors=True)
        wpriv = self.nodes[1].get_wallet_rpc("wpriv")
        assert_equal(wpriv.getwalletinfo()['keypoolsize'], 0)

        self.log.info('Mining coins')
        w0.generatetoaddress(101, w0.getnewaddress())

        # RPC importdescriptors -----------------------------------------------

        # # Test import fails if no descriptor present
        key = get_generate_key()
        self.log.info("Import should fail if a descriptor is not provided")
        self.test_importdesc({"timestamp": "now"},
                             success=False,
                             error_code=-8,
                             error_message='Descriptor not found.')

        # # Test importing of a P2PKH descriptor
        key = get_generate_key()
        self.log.info("Should import a p2pkh descriptor")
        self.test_importdesc({"desc": descsum_create("pkh(" + key.pubkey + ")"),
                              "timestamp": "now",
                              "label": "Descriptor import test"},
                             success=True)
        test_address(w1,
                     key.p2pkh_addr,
                     solvable=True,
                     ismine=True,
                     labels=["Descriptor import test"])
        assert_equal(w1.getwalletinfo()['keypoolsize'], 0)

        self.log.info("Internal addresses cannot have labels")
        self.test_importdesc({"desc": descsum_create("pkh(" + key.pubkey + ")"),
                              "timestamp": "now",
                              "internal": True,
                              "label": "Descriptor import test"},
                             success=False,
                             error_code=-8,
                             error_message="Internal addresses should not have a label")

        # # Test importing of a P2SH-P2WPKH descriptor
        key = get_generate_key()
        self.log.info("Should not import a p2sh-p2wpkh descriptor without checksum")
        self.test_importdesc({"desc": "sh(wpkh(" + key.pubkey + "))",
                              "timestamp": "now"
                              },
                             success=False,
                             error_code=-5,
                             error_message="Missing checksum")

        self.log.info("Should not import a p2sh-p2wpkh descriptor that has range specified")
        self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"),
                               "timestamp": "now",
                               "range": 1,
                              },
                              success=False,
                              error_code=-8,
                              error_message="Range should not be specified for an un-ranged descriptor")

        self.log.info("Should not import a p2sh-p2wpkh descriptor and have it set to active")
        self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"),
                               "timestamp": "now",
                               "active": True,
                              },
                              success=False,
                              error_code=-8,
                              error_message="Active descriptors must be ranged")

        self.log.info("Should import a (non-active) p2sh-p2wpkh descriptor")
        self.test_importdesc({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"),
                               "timestamp": "now",
                               "active": False,
                              },
                              success=True)
        assert_equal(w1.getwalletinfo()['keypoolsize'], 0)

        test_address(w1,
                     key.p2sh_p2wpkh_addr,
                     ismine=True,
                     solvable=True)

        # # Test importing of a multisig descriptor
        key1 = get_generate_key()
        key2 = get_generate_key()
        self.log.info("Should import a 1-of-2 bare multisig from descriptor")
        self.test_importdesc({"desc": descsum_create("multi(1," + key1.pubkey + "," + key2.pubkey + ")"),
                              "timestamp": "now"},
                             success=True)
        self.log.info("Should not treat individual keys from the imported bare multisig as watchonly")
        test_address(w1,
                     key1.p2pkh_addr,
                     ismine=False)

        # # Test ranged descriptors
        xpriv = "tprv8ZgxMBicQKsPeuVhWwi6wuMQGfPKi9Li5GtX35jVNknACgqe3CY4g5xgkfDDJcmtF7o1QnxWDRYw4H5P26PXq7sbcUkEqeR4fg3Kxp2tigg"
        xpub = "tpubD6NzVbkrYhZ4YNXVQbNhMK1WqguFsUXceaVJKbmno2aZ3B6QfbMeraaYvnBSGpV3vxLyTTK9DYT1yoEck4XUScMzXoQ2U2oSmE2JyMedq3H"
        addresses = ["2N7yv4p8G8yEaPddJxY41kPihnWvs39qCMf", "2MsHxyb2JS3pAySeNUsJ7mNnurtpeenDzLA"] # hdkeypath=m/0'/0'/0' and 1'
        addresses += ["bcrt1qrd3n235cj2czsfmsuvqqpr3lu6lg0ju7scl8gn", "bcrt1qfqeppuvj0ww98r6qghmdkj70tv8qpchehegrg8"] # wpkh subscripts corresponding to the above addresses
        desc = "sh(wpkh(" + xpub + "/0/0/*" + "))"

        self.log.info("Ranged descriptors cannot have labels")
        self.test_importdesc({"desc":descsum_create(desc),
                              "timestamp": "now",
                              "range": [0, 100],
                              "label": "test"},
                              success=False,
                              error_code=-8,
                              error_message='Ranged descriptors should not have a label')

        self.log.info("Private keys required for private keys enabled wallet")
        self.test_importdesc({"desc":descsum_create(desc),
                              "timestamp": "now",
                              "range": [0, 100]},
                              success=False,
                              error_code=-4,
                              error_message='Cannot import descriptor without private keys to a wallet with private keys enabled',
                              wallet=wpriv)

        self.log.info("Ranged descriptor import should warn without a specified range")
        self.test_importdesc({"desc": descsum_create(desc),
                               "timestamp": "now"},
                              success=True,
                              warnings=['Range not given, using default keypool range'])
        assert_equal(w1.getwalletinfo()['keypoolsize'], 0)

        # # Test importing of a ranged descriptor with xpriv
        self.log.info("Should not import a ranged descriptor that includes xpriv into a watch-only wallet")
        desc = "sh(wpkh(" + xpriv + "/0'/0'/*'" + "))"
        self.test_importdesc({"desc": descsum_create(desc),
                              "timestamp": "now",
                              "range": 1},
                             success=False,
                             error_code=-4,
                             error_message='Cannot import private keys to a wallet with private keys disabled')
        for address in addresses:
            test_address(w1,
                         address,
                         ismine=False,
                         solvable=False)

        self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": -1},
                              success=False, error_code=-8, error_message='End of range is too high')

        self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [-1, 10]},
                              success=False, error_code=-8, error_message='Range should be greater or equal than 0')

        self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [(2 << 31 + 1) - 1000000, (2 << 31 + 1)]},
                              success=False, error_code=-8, error_message='End of range is too high')

        self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [2, 1]},
                              success=False, error_code=-8, error_message='Range specified as [begin,end] must not have begin after end')

        self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [0, 1000001]},
                              success=False, error_code=-8, error_message='Range is too large')

        # Make sure ranged imports import keys in order
        w1 = self.nodes[1].get_wallet_rpc('w1')
        self.log.info('Key ranges should be imported in order')
        xpub = "tpubDAXcJ7s7ZwicqjprRaEWdPoHKrCS215qxGYxpusRLLmJuT69ZSicuGdSfyvyKpvUNYBW1s2U3NSrT6vrCYB9e6nZUEvrqnwXPF8ArTCRXMY"
        addresses = [
            'bcrt1qtmp74ayg7p24uslctssvjm06q5phz4yrxucgnv', # m/0'/0'/0
            'bcrt1q8vprchan07gzagd5e6v9wd7azyucksq2xc76k8', # m/0'/0'/1
            'bcrt1qtuqdtha7zmqgcrr26n2rqxztv5y8rafjp9lulu', # m/0'/0'/2
            'bcrt1qau64272ymawq26t90md6an0ps99qkrse58m640', # m/0'/0'/3
            'bcrt1qsg97266hrh6cpmutqen8s4s962aryy77jp0fg0', # m/0'/0'/4
        ]

        self.test_importdesc({'desc': descsum_create('wpkh([80002067/0h/0h]' + xpub + '/*)'),
                              'active': True,
                              'range' : [0, 2],
                              'timestamp': 'now'
                             },
                             success=True)
        self.test_importdesc({'desc': descsum_create('sh(wpkh([abcdef12/0h/0h]' + xpub + '/*))'),
                              'active': True,
                              'range' : [0, 2],
                              'timestamp': 'now'
                             },
                             success=True)
        self.test_importdesc({'desc': descsum_create('pkh([12345678/0h/0h]' + xpub + '/*)'),
                              'active': True,
                              'range' : [0, 2],
                              'timestamp': 'now'
                             },
                             success=True)

        assert_equal(w1.getwalletinfo()['keypoolsize'], 5 * 3)
        for i, expected_addr in enumerate(addresses):
            received_addr = w1.getnewaddress('', 'bech32')
            assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'bech32')
            assert_equal(received_addr, expected_addr)
            bech32_addr_info = w1.getaddressinfo(received_addr)
            assert_equal(bech32_addr_info['desc'][:23], 'wpkh([80002067/0\'/0\'/{}]'.format(i))

            shwpkh_addr = w1.getnewaddress('', 'p2sh-segwit')
            shwpkh_addr_info = w1.getaddressinfo(shwpkh_addr)
            assert_equal(shwpkh_addr_info['desc'][:26], 'sh(wpkh([abcdef12/0\'/0\'/{}]'.format(i))

            pkh_addr = w1.getnewaddress('', 'legacy')
            pkh_addr_info = w1.getaddressinfo(pkh_addr)
            assert_equal(pkh_addr_info['desc'][:22], 'pkh([12345678/0\'/0\'/{}]'.format(i))

            assert_equal(w1.getwalletinfo()['keypoolsize'], 4 * 3) # After retrieving a key, we don't refill the keypool again, so it's one less for each address type
        w1.keypoolrefill()
        assert_equal(w1.getwalletinfo()['keypoolsize'], 5 * 3)

        # Check active=False default
        self.log.info('Check imported descriptors are not active by default')
        self.test_importdesc({'desc': descsum_create('pkh([12345678/0h/0h]' + xpub + '/*)'),
                              'range' : [0, 2],
                              'timestamp': 'now',
                              'internal': True
                             },
                             success=True)
        assert_raises_rpc_error(-4, 'This wallet has no available keys', w1.getrawchangeaddress, 'legacy')

        # # Test importing a descriptor containing a WIF private key
        wif_priv = "cTe1f5rdT8A8DFgVWTjyPwACsDPJM9ff4QngFxUixCSvvbg1x6sh"
        address = "2MuhcG52uHPknxDgmGPsV18jSHFBnnRgjPg"
        desc = "sh(wpkh(" + wif_priv + "))"
        self.log.info("Should import a descriptor with a WIF private key as spendable")
        self.test_importdesc({"desc": descsum_create(desc),
                               "timestamp": "now"},
                              success=True,
                              wallet=wpriv)
        test_address(wpriv,
                     address,
                     solvable=True,
                     ismine=True)
        txid = w0.sendtoaddress(address, 49.99995540)
        w0.generatetoaddress(6, w0.getnewaddress())
        self.sync_blocks()
        tx = wpriv.createrawtransaction([{"txid": txid, "vout": 0}], {w0.getnewaddress(): 49.999})
        signed_tx = wpriv.signrawtransactionwithwallet(tx)
        w1.sendrawtransaction(signed_tx['hex'])

        # Make sure that we can use import and use multisig as addresses
        self.log.info('Test that multisigs can be imported, signed for, and getnewaddress\'d')
        self.nodes[1].createwallet(wallet_name="wmulti_priv", disable_private_keys=False, blank=True, descriptors=True)
        wmulti_priv = self.nodes[1].get_wallet_rpc("wmulti_priv")
        assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 0)

        self.test_importdesc({"desc":"wsh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/0h/0h/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/0h/0h/*,tprv8ZgxMBicQKsPeonDt8Ka2mrQmHa61hQ5FQCsvWBTpSNzBFgM58cV2EuXNAHF14VawVpznnme3SuTbA62sGriwWyKifJmXntfNeK7zeqMCj1/84h/0h/0h/*))#m2sr93jn",
                            "active": True,
                            "range": 1000,
                            "next_index": 0,
                            "timestamp": "now"},
                            success=True,
                            wallet=wmulti_priv)
        self.test_importdesc({"desc":"wsh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/1h/0h/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/1h/0h/*,tprv8ZgxMBicQKsPeonDt8Ka2mrQmHa61hQ5FQCsvWBTpSNzBFgM58cV2EuXNAHF14VawVpznnme3SuTbA62sGriwWyKifJmXntfNeK7zeqMCj1/84h/1h/0h/*))#q3sztvx5",
                            "active": True,
                            "internal" : True,
                            "range": 1000,
                            "next_index": 0,
                            "timestamp": "now"},
                            success=True,
                            wallet=wmulti_priv)

        assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1001) # Range end (1000) is inclusive, so 1001 addresses generated
        addr = wmulti_priv.getnewaddress('', 'bech32')
        assert_equal(addr, 'bcrt1qdt0qy5p7dzhxzmegnn4ulzhard33s2809arjqgjndx87rv5vd0fq2czhy8') # Derived at m/84'/0'/0'/0
        change_addr = wmulti_priv.getrawchangeaddress('bech32')
        assert_equal(change_addr, 'bcrt1qt9uhe3a9hnq7vajl7a094z4s3crm9ttf8zw3f5v9gr2nyd7e3lnsy44n8e')
        assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1000)
        txid = w0.sendtoaddress(addr, 10)
        self.nodes[0].generate(6)
        self.sync_all()
        send_txid = wmulti_priv.sendtoaddress(w0.getnewaddress(), 8)
        decoded = wmulti_priv.decoderawtransaction(wmulti_priv.gettransaction(send_txid)['hex'])
        assert_equal(len(decoded['vin'][0]['txinwitness']), 4)
        self.nodes[0].generate(6)
        self.sync_all()

        self.nodes[1].createwallet(wallet_name="wmulti_pub", disable_private_keys=True, blank=True, descriptors=True)
        wmulti_pub = self.nodes[1].get_wallet_rpc("wmulti_pub")
        assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 0)

        self.test_importdesc({"desc":"wsh(multi(2,[7b2d0242/84h/0h/0h]tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*,[59b09cd6/84h/0h/0h]tpubDDBF2BTR6s8drwrfDei8WxtckGuSm1cyoKxYY1QaKSBFbHBYQArWhHPA6eJrzZej6nfHGLSURYSLHr7GuYch8aY5n61tGqgn8b4cXrMuoPH/*,[e81a0532/84h/0h/0h]tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E/*))#tsry0s5e",
                            "active": True,
                            "range": 1000,
                            "next_index": 0,
                            "timestamp": "now"},
                            success=True,
                            wallet=wmulti_pub)
        self.test_importdesc({"desc":"wsh(multi(2,[7b2d0242/84h/1h/0h]tpubDCXqdwWZcszwqYJSnZp8eARkxGJfHAk23KDxbztV4BbschfaTfYLTcSkSJ3TN64dRqwa1rnFUScsYormKkGqNbbPwkorQimVevXjxzUV9Gf/*,[59b09cd6/84h/1h/0h]tpubDCYfZY2ceyHzYzMMVPt9MNeiqtQ2T7Uyp9QSFwYXh8Vi9iJFYXcuphJaGXfF3jUQJi5Y3GMNXvM11gaL4txzZgNGK22BFAwMXynnzv4z2Jh/*,[e81a0532/84h/1h/0h]tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb/*))#c08a2rzv",
                            "active": True,
                            "internal" : True,
                            "range": 1000,
                            "next_index": 0,
                            "timestamp": "now"},
                            success=True,
                            wallet=wmulti_pub)

        assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 1000) # The first one was already consumed by previous import and is detected as used
        addr = wmulti_pub.getnewaddress('', 'bech32')
        assert_equal(addr, 'bcrt1qp8s25ckjl7gr6x2q3dx3tn2pytwp05upkjztk6ey857tt50r5aeqn6mvr9') # Derived at m/84'/0'/0'/1
        change_addr = wmulti_pub.getrawchangeaddress('bech32')
        assert_equal(change_addr, 'bcrt1qt9uhe3a9hnq7vajl7a094z4s3crm9ttf8zw3f5v9gr2nyd7e3lnsy44n8e')
        assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 999)
        txid = w0.sendtoaddress(addr, 10)
        vout = find_vout_for_address(self.nodes[0], txid, addr)
        self.nodes[0].generate(6)
        self.sync_all()
        assert_equal(wmulti_pub.getbalance(), wmulti_priv.getbalance())

        self.log.info("Multisig with distributed keys")
        self.nodes[1].createwallet(wallet_name="wmulti_priv1", descriptors=True)
        wmulti_priv1 = self.nodes[1].get_wallet_rpc("wmulti_priv1")
        res = wmulti_priv1.importdescriptors([
        {
            "desc": descsum_create("wsh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/0h/0h/*,[59b09cd6/84h/0h/0h]tpubDDBF2BTR6s8drwrfDei8WxtckGuSm1cyoKxYY1QaKSBFbHBYQArWhHPA6eJrzZej6nfHGLSURYSLHr7GuYch8aY5n61tGqgn8b4cXrMuoPH/*,[e81a0532/84h/0h/0h]tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E/*))"),
            "active": True,
            "range": 1000,
            "next_index": 0,
            "timestamp": "now"
        },
        {
            "desc": descsum_create("wsh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/1h/0h/*,[59b09cd6/84h/1h/0h]tpubDCYfZY2ceyHzYzMMVPt9MNeiqtQ2T7Uyp9QSFwYXh8Vi9iJFYXcuphJaGXfF3jUQJi5Y3GMNXvM11gaL4txzZgNGK22BFAwMXynnzv4z2Jh/*,[e81a0532/84h/1h/0h]tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb/*))"),
            "active": True,
            "internal" : True,
            "range": 1000,
            "next_index": 0,
            "timestamp": "now"
        }])
        assert_equal(res[0]['success'], True)
        assert_equal(res[0]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors')
        assert_equal(res[1]['success'], True)
        assert_equal(res[1]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors')

        self.nodes[1].createwallet(wallet_name='wmulti_priv2', blank=True, descriptors=True)
        wmulti_priv2 = self.nodes[1].get_wallet_rpc('wmulti_priv2')
        res = wmulti_priv2.importdescriptors([
        {
            "desc": descsum_create("wsh(multi(2,[7b2d0242/84h/0h/0h]tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/0h/0h/*,[e81a0532/84h/0h/0h]tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E/*))"),
            "active": True,
            "range": 1000,
            "next_index": 0,
            "timestamp": "now"
        },
        {
            "desc": descsum_create("wsh(multi(2,[7b2d0242/84h/1h/0h]tpubDCXqdwWZcszwqYJSnZp8eARkxGJfHAk23KDxbztV4BbschfaTfYLTcSkSJ3TN64dRqwa1rnFUScsYormKkGqNbbPwkorQimVevXjxzUV9Gf/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/1h/0h/*,[e81a0532/84h/1h/0h]tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb/*))"),
            "active": True,
            "internal" : True,
            "range": 1000,
            "next_index": 0,
            "timestamp": "now"
        }])
        assert_equal(res[0]['success'], True)
        assert_equal(res[0]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors')
        assert_equal(res[1]['success'], True)
        assert_equal(res[1]['warnings'][0], 'Not all private keys provided. Some wallet functionality may return unexpected errors')

        rawtx = self.nodes[1].createrawtransaction([{'txid': txid, 'vout': vout}], {w0.getnewaddress(): 9.999})
        tx_signed_1 = wmulti_priv1.signrawtransactionwithwallet(rawtx)
        assert_equal(tx_signed_1['complete'], False)
        tx_signed_2 = wmulti_priv2.signrawtransactionwithwallet(tx_signed_1['hex'])
        assert_equal(tx_signed_2['complete'], True)
        self.nodes[1].sendrawtransaction(tx_signed_2['hex'])

        self.log.info("Combo descriptors cannot be active")
        self.test_importdesc({"desc": descsum_create("combo(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"),
                              "active": True,
                              "range": 1,
                              "timestamp": "now"},
                              success=False,
                              error_code=-4,
                              error_message="Combo descriptors cannot be set to active")

        self.log.info("Descriptors with no type cannot be active")
        self.test_importdesc({"desc": descsum_create("pk(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"),
                              "active": True,
                              "range": 1,
                              "timestamp": "now"},
                              success=True,
                              warnings=["Unknown output type, cannot set descriptor to active."])
    def run_test(self):
        self.log.info('Setting up wallets')
        self.nodes[0].createwallet(wallet_name='w0',
                                   disable_private_keys=False)
        w0 = self.nodes[0].get_wallet_rpc('w0')

        self.nodes[1].createwallet(wallet_name='w1',
                                   disable_private_keys=True,
                                   blank=True,
                                   descriptors=True)
        w1 = self.nodes[1].get_wallet_rpc('w1')
        assert_equal(w1.getwalletinfo()['keypoolsize'], 0)

        self.nodes[1].createwallet(wallet_name="wpriv",
                                   disable_private_keys=False,
                                   blank=True,
                                   descriptors=True)
        wpriv = self.nodes[1].get_wallet_rpc("wpriv")
        assert_equal(wpriv.getwalletinfo()['keypoolsize'], 0)

        self.log.info('Mining coins')
        w0.generatetoaddress(101, w0.getnewaddress())

        # RPC importdescriptors -----------------------------------------------

        # # Test import fails if no descriptor present
        key = get_generate_key()
        self.log.info("Import should fail if a descriptor is not provided")
        self.test_importdesc({"timestamp": "now"},
                             success=False,
                             error_code=-8,
                             error_message='Descriptor not found.')

        # # Test importing of a P2PKH descriptor
        key = get_generate_key()
        self.log.info("Should import a p2pkh descriptor")
        self.test_importdesc(
            {
                "desc": descsum_create("pkh(" + key.pubkey + ")"),
                "timestamp": "now",
                "label": "Descriptor import test"
            },
            success=True)
        test_address(w1,
                     key.p2pkh_addr,
                     solvable=True,
                     ismine=True,
                     labels=["Descriptor import test"])
        assert_equal(w1.getwalletinfo()['keypoolsize'], 0)

        self.log.info("Internal addresses cannot have labels")
        self.test_importdesc(
            {
                "desc": descsum_create("pkh(" + key.pubkey + ")"),
                "timestamp": "now",
                "internal": True,
                "label": "Descriptor import test"
            },
            success=False,
            error_code=-8,
            error_message="Internal addresses should not have a label")

        assert_equal(w1.getwalletinfo()['keypoolsize'], 0)

        test_address(w1, key.p2pkh_addr, ismine=True, solvable=True)

        # # Test importing of a multisig descriptor
        key1 = get_generate_key()
        key2 = get_generate_key()
        self.log.info("Should import a 1-of-2 bare multisig from descriptor")
        self.test_importdesc(
            {
                "desc":
                descsum_create("multi(1," + key1.pubkey + "," + key2.pubkey +
                               ")"),
                "timestamp":
                "now"
            },
            success=True)
        self.log.info(
            "Should not treat individual keys from the imported bare multisig as watchonly"
        )
        test_address(w1, key1.p2pkh_addr, ismine=False)

        # # Test ranged descriptors
        xpriv = "tprv8ZgxMBicQKsPeuVhWwi6wuMQGfPKi9Li5GtX35jVNknACgqe3CY4g5xgkfDDJcmtF7o1QnxWDRYw4H5P26PXq7sbcUkEqeR4fg3Kxp2tigg"
        xpub = "tpubD6NzVbkrYhZ4YNXVQbNhMK1WqguFsUXceaVJKbmno2aZ3B6QfbMeraaYvnBSGpV3vxLyTTK9DYT1yoEck4XUScMzXoQ2U2oSmE2JyMedq3H"
        addresses = [
            "2N7yv4p8G8yEaPddJxY41kPihnWvs39qCMf",
            "2MsHxyb2JS3pAySeNUsJ7mNnurtpeenDzLA"
        ]  # hdkeypath=m/0'/0'/0' and 1'
        # wpkh subscripts corresponding to the above addresses
        addresses += [
            "ecregtest:prvn9ycvgr5atuyh49sua3mapskh2mnnzg7t9yp6dt",
            "ecregtest:pp3n087yx0njv2e5wcvltahfxqst7l66rutz8ceeat"
        ]
        desc = "sh(pkh(" + xpub + "/0/0/*" + "))"

        self.log.info("Ranged descriptors cannot have labels")
        self.test_importdesc(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [0, 100],
                "label": "test"
            },
            success=False,
            error_code=-8,
            error_message='Ranged descriptors should not have a label')

        self.log.info("Private keys required for private keys enabled wallet")
        self.test_importdesc(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [0, 100]
            },
            success=False,
            error_code=-4,
            error_message=
            'Cannot import descriptor without private keys to a wallet with private keys enabled',
            wallet=wpriv)

        self.log.info(
            "Ranged descriptor import should warn without a specified range")
        self.test_importdesc(
            {
                "desc": descsum_create(desc),
                "timestamp": "now"
            },
            success=True,
            warnings=['Range not given, using default keypool range'])
        assert_equal(w1.getwalletinfo()['keypoolsize'], 0)

        # # Test importing of a ranged descriptor with xpriv
        self.log.info(
            "Should not import a ranged descriptor that includes xpriv into a watch-only wallet"
        )
        desc = "sh(pkh(" + xpriv + "/0'/0'/*'" + "))"
        self.test_importdesc(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": 1
            },
            success=False,
            error_code=-4,
            error_message=
            'Cannot import private keys to a wallet with private keys disabled'
        )

        for address in addresses:
            test_address(w1, address, ismine=False, solvable=False)

        self.test_importdesc(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": -1
            },
            success=False,
            error_code=-8,
            error_message='End of range is too high')

        self.test_importdesc(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [-1, 10]
            },
            success=False,
            error_code=-8,
            error_message='Range should be greater or equal than 0')

        self.test_importdesc(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [(2 << 31 + 1) - 1000000, (2 << 31 + 1)]
            },
            success=False,
            error_code=-8,
            error_message='End of range is too high')

        self.test_importdesc(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [2, 1]
            },
            success=False,
            error_code=-8,
            error_message=
            'Range specified as [begin,end] must not have begin after end')

        self.test_importdesc(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [0, 1000001]
            },
            success=False,
            error_code=-8,
            error_message='Range is too large')

        # Make sure ranged imports import keys in order
        w1 = self.nodes[1].get_wallet_rpc('w1')
        self.log.info('Key ranges should be imported in order')
        xpub = "tpubDAXcJ7s7ZwicqjprRaEWdPoHKrCS215qxGYxpusRLLmJuT69ZSicuGdSfyvyKpvUNYBW1s2U3NSrT6vrCYB9e6nZUEvrqnwXPF8ArTCRXMY"
        addresses = [
            'ecregtest:qp0v86h53rc92hjrlpwzpjtdlgzsxu25svv6g40fpl',  # m/0'/0'/0
            'ecregtest:qqasy0zlkdleqt4pkn8fs4ehm5gnnz6qpgdcpt90fq',  # m/0'/0'/1
            'ecregtest:qp0sp4wlhctvprqvdt2dgvqcfdjssu04xgey0l3syw',  # m/0'/0'/2
            'ecregtest:qrhn24tegn04cptfv4ldhtkduxq55zcwrycjfdj9vr',  # m/0'/0'/3
            'ecregtest:qzpqhett2uwltq803vrxv7zkqhft5vsnmcjeh50v0p',  # m/0'/0'/4
        ]

        self.test_importdesc(
            {
                'desc':
                descsum_create('sh(pkh([abcdef12/0h/0h]' + xpub + '/*))'),
                'active': True,
                'range': [0, 2],
                'timestamp': 'now'
            },
            success=True)
        self.test_importdesc(
            {
                'desc': descsum_create('pkh([12345678/0h/0h]' + xpub + '/*)'),
                'active': True,
                'range': [0, 2],
                'timestamp': 'now'
            },
            success=True)

        assert_equal(w1.getwalletinfo()['keypoolsize'], 5)
        for i, expected_addr in enumerate(addresses):
            pkh_addr = w1.getnewaddress('')
            assert_raises_rpc_error(-4, 'This wallet has no available keys',
                                    w1.getrawchangeaddress)

            assert_equal(pkh_addr, expected_addr)
            pkh_addr_info = w1.getaddressinfo(pkh_addr)
            assert_equal(pkh_addr_info['desc'][:22],
                         'pkh([12345678/0\'/0\'/{}]'.format(i))

            # After retrieving a key, we don't refill the keypool again, so
            # it's one less for each address type
            assert_equal(w1.getwalletinfo()['keypoolsize'], 4)
        w1.keypoolrefill()
        assert_equal(w1.getwalletinfo()['keypoolsize'], 5)

        # Check active=False default
        self.log.info('Check imported descriptors are not active by default')
        self.test_importdesc(
            {
                'desc': descsum_create('pkh([12345678/0h/0h]' + xpub + '/*)'),
                'range': [0, 2],
                'timestamp': 'now',
                'internal': True
            },
            success=True)
        assert_raises_rpc_error(-4, 'This wallet has no available keys',
                                w1.getrawchangeaddress)

        # # Test importing a descriptor containing a WIF private key
        wif_priv = "cTe1f5rdT8A8DFgVWTjyPwACsDPJM9ff4QngFxUixCSvvbg1x6sh"
        address = "ecregtest:ppn85zpvym8cdccmgw8km6e48jfhnpa435h3hkyfd6"
        desc = "sh(pkh(" + wif_priv + "))"
        self.log.info(
            "Should import a descriptor with a WIF private key as spendable")
        self.test_importdesc({
            "desc": descsum_create(desc),
            "timestamp": "now"
        },
                             success=True,
                             wallet=wpriv)
        test_address(wpriv, address, solvable=True, ismine=True)
        txid = w0.sendtoaddress(address, 49999996.00)
        w0.generatetoaddress(6, w0.getnewaddress())
        self.sync_blocks()
        tx = wpriv.createrawtransaction([{
            "txid": txid,
            "vout": 0
        }], {w0.getnewaddress(): 49999000})
        signed_tx = wpriv.signrawtransactionwithwallet(tx)
        w1.sendrawtransaction(signed_tx['hex'])

        # Make sure that we can use import and use multisig as addresses
        self.log.info(
            'Test that multisigs can be imported, signed for, and getnewaddress\'d'
        )
        self.nodes[1].createwallet(wallet_name="wmulti_priv",
                                   disable_private_keys=False,
                                   blank=True,
                                   descriptors=True)
        wmulti_priv = self.nodes[1].get_wallet_rpc("wmulti_priv")
        assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 0)

        self.test_importdesc(
            {
                "desc":
                "sh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/0h/0h/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/0h/0h/*,tprv8ZgxMBicQKsPeonDt8Ka2mrQmHa61hQ5FQCsvWBTpSNzBFgM58cV2EuXNAHF14VawVpznnme3SuTbA62sGriwWyKifJmXntfNeK7zeqMCj1/84h/0h/0h/*))#f5nqn4ax",
                "active": True,
                "range": 1000,
                "next_index": 0,
                "timestamp": "now"
            },
            success=True,
            wallet=wmulti_priv)
        self.test_importdesc(
            {
                "desc":
                "sh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/1h/0h/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/1h/0h/*,tprv8ZgxMBicQKsPeonDt8Ka2mrQmHa61hQ5FQCsvWBTpSNzBFgM58cV2EuXNAHF14VawVpznnme3SuTbA62sGriwWyKifJmXntfNeK7zeqMCj1/84h/1h/0h/*))#m4e4s5de",
                "active": True,
                "internal": True,
                "range": 1000,
                "next_index": 0,
                "timestamp": "now"
            },
            success=True,
            wallet=wmulti_priv)

        # Range end (1000) is inclusive, so 1001 addresses generated
        assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1001)
        addr = wmulti_priv.getnewaddress('')
        # Derived at m/84'/0'/0'/0
        assert_equal(addr,
                     'ecregtest:pzkcf26dw7np58jcspnpxaupgz9csnc3wsf5wdh2a3')
        change_addr = wmulti_priv.getrawchangeaddress()
        assert_equal(change_addr,
                     'ecregtest:prnkfg7pxe3kpyv3l4v00ft6q3sfseag7vnva0k49n')

        assert_equal(wmulti_priv.getwalletinfo()['keypoolsize'], 1000)
        txid = w0.sendtoaddress(addr, 10000000)
        self.nodes[0].generate(6)
        self.sync_all()

        self.nodes[1].createwallet(wallet_name="wmulti_pub",
                                   disable_private_keys=True,
                                   blank=True,
                                   descriptors=True)
        wmulti_pub = self.nodes[1].get_wallet_rpc("wmulti_pub")
        assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 0)

        self.test_importdesc(
            {
                "desc":
                "sh(multi(2,[7b2d0242/84h/0h/0h]tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*,[59b09cd6/84h/0h/0h]tpubDDBF2BTR6s8drwrfDei8WxtckGuSm1cyoKxYY1QaKSBFbHBYQArWhHPA6eJrzZej6nfHGLSURYSLHr7GuYch8aY5n61tGqgn8b4cXrMuoPH/*,[e81a0532/84h/0h/0h]tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E/*))#x75vpsak",
                "active": True,
                "range": 1000,
                "next_index": 0,
                "timestamp": "now"
            },
            success=True,
            wallet=wmulti_pub)
        self.test_importdesc(
            {
                "desc":
                "sh(multi(2,[7b2d0242/84h/1h/0h]tpubDCXqdwWZcszwqYJSnZp8eARkxGJfHAk23KDxbztV4BbschfaTfYLTcSkSJ3TN64dRqwa1rnFUScsYormKkGqNbbPwkorQimVevXjxzUV9Gf/*,[59b09cd6/84h/1h/0h]tpubDCYfZY2ceyHzYzMMVPt9MNeiqtQ2T7Uyp9QSFwYXh8Vi9iJFYXcuphJaGXfF3jUQJi5Y3GMNXvM11gaL4txzZgNGK22BFAwMXynnzv4z2Jh/*,[e81a0532/84h/1h/0h]tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb/*))#v0t48ucu",
                "active": True,
                "internal": True,
                "range": 1000,
                "next_index": 0,
                "timestamp": "now"
            },
            success=True,
            wallet=wmulti_pub)

        # The first one was already consumed by previous import and is detected
        # as used
        assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 1000)
        addr = wmulti_pub.getnewaddress('')
        # Derived at m/84'/0'/0'/1
        assert_equal(addr,
                     'ecregtest:pr5xql8r03jp5dvrep22dns59vf7hhykr5nmaucy2h')
        change_addr = wmulti_pub.getrawchangeaddress()
        assert_equal(change_addr,
                     'ecregtest:prnkfg7pxe3kpyv3l4v00ft6q3sfseag7vnva0k49n')

        assert_equal(wmulti_pub.getwalletinfo()['keypoolsize'], 999)
        txid = w0.sendtoaddress(addr, 10000000)
        vout = find_vout_for_address(self.nodes[0], txid, addr)
        self.nodes[0].generate(6)
        self.sync_all()
        assert_equal(wmulti_pub.getbalance(), wmulti_priv.getbalance())

        self.log.info("Multisig with distributed keys")
        self.nodes[1].createwallet(wallet_name="wmulti_priv1",
                                   descriptors=True)
        wmulti_priv1 = self.nodes[1].get_wallet_rpc("wmulti_priv1")
        res = wmulti_priv1.importdescriptors([{
            "desc":
            descsum_create(
                "sh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/0h/0h/*,[59b09cd6/84h/0h/0h]tpubDDBF2BTR6s8drwrfDei8WxtckGuSm1cyoKxYY1QaKSBFbHBYQArWhHPA6eJrzZej6nfHGLSURYSLHr7GuYch8aY5n61tGqgn8b4cXrMuoPH/*,[e81a0532/84h/0h/0h]tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E/*))"
            ),
            "active":
            True,
            "range":
            1000,
            "next_index":
            0,
            "timestamp":
            "now"
        }, {
            "desc":
            descsum_create(
                "sh(multi(2,tprv8ZgxMBicQKsPevADjDCWsa6DfhkVXicu8NQUzfibwX2MexVwW4tCec5mXdCW8kJwkzBRRmAay1KZya4WsehVvjTGVW6JLqiqd8DdZ4xSg52/84h/1h/0h/*,[59b09cd6/84h/1h/0h]tpubDCYfZY2ceyHzYzMMVPt9MNeiqtQ2T7Uyp9QSFwYXh8Vi9iJFYXcuphJaGXfF3jUQJi5Y3GMNXvM11gaL4txzZgNGK22BFAwMXynnzv4z2Jh/*,[e81a0532/84h/1h/0h]tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb/*))"
            ),
            "active":
            True,
            "internal":
            True,
            "range":
            1000,
            "next_index":
            0,
            "timestamp":
            "now"
        }])
        assert_equal(res[0]['success'], True)
        assert_equal(
            res[0]['warnings'][0],
            'Not all private keys provided. Some wallet functionality may return unexpected errors'
        )
        assert_equal(res[1]['success'], True)
        assert_equal(
            res[1]['warnings'][0],
            'Not all private keys provided. Some wallet functionality may return unexpected errors'
        )

        self.nodes[1].createwallet(wallet_name='wmulti_priv2',
                                   blank=True,
                                   descriptors=True)
        wmulti_priv2 = self.nodes[1].get_wallet_rpc('wmulti_priv2')
        res = wmulti_priv2.importdescriptors([{
            "desc":
            descsum_create(
                "sh(multi(2,[7b2d0242/84h/0h/0h]tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/0h/0h/*,[e81a0532/84h/0h/0h]tpubDCsWoW1kuQB9kG5MXewHqkbjPtqPueRnXju7uM2NK7y3JYb2ajAZ9EiuZXNNuE4661RAfriBWhL8UsnAPpk8zrKKnZw1Ug7X4oHgMdZiU4E/*))"
            ),
            "active":
            True,
            "range":
            1000,
            "next_index":
            0,
            "timestamp":
            "now"
        }, {
            "desc":
            descsum_create(
                "sh(multi(2,[7b2d0242/84h/1h/0h]tpubDCXqdwWZcszwqYJSnZp8eARkxGJfHAk23KDxbztV4BbschfaTfYLTcSkSJ3TN64dRqwa1rnFUScsYormKkGqNbbPwkorQimVevXjxzUV9Gf/*,tprv8ZgxMBicQKsPdSNWUhDiwTScDr6JfkZuLshTRwzvZGnMSnGikV6jxpmdDkC3YRc4T3GD6Nvg9uv6hQg73RVv1EiTXDZwxVbsLugVHU8B1aq/84h/1h/0h/*,[e81a0532/84h/1h/0h]tpubDC6UGqnsQStngYuGD4MKsMy7eD1Yg9NTJfPdvjdG2JE5oZ7EsSL3WHg4Gsw2pR5K39ZwJ46M1wZayhedVdQtMGaUhq5S23PH6fnENK3V1sb/*))"
            ),
            "active":
            True,
            "internal":
            True,
            "range":
            1000,
            "next_index":
            0,
            "timestamp":
            "now"
        }])
        assert_equal(res[0]['success'], True)
        assert_equal(
            res[0]['warnings'][0],
            'Not all private keys provided. Some wallet functionality may return unexpected errors'
        )
        assert_equal(res[1]['success'], True)
        assert_equal(
            res[1]['warnings'][0],
            'Not all private keys provided. Some wallet functionality may return unexpected errors'
        )

        rawtx = self.nodes[1].createrawtransaction([{
            'txid': txid,
            'vout': vout
        }], {w0.getnewaddress(): 9999000})
        tx_signed_1 = wmulti_priv1.signrawtransactionwithwallet(rawtx)
        assert_equal(tx_signed_1['complete'], False)
        tx_signed_2 = wmulti_priv2.signrawtransactionwithwallet(
            tx_signed_1['hex'])
        assert_equal(tx_signed_2['complete'], True)
        self.nodes[1].sendrawtransaction(tx_signed_2['hex'])

        self.log.info("Combo descriptors cannot be active")
        self.test_importdesc(
            {
                "desc":
                descsum_create(
                    "combo(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"
                ),
                "active":
                True,
                "range":
                1,
                "timestamp":
                "now"
            },
            success=False,
            error_code=-4,
            error_message="Combo descriptors cannot be set to active")

        self.log.info("Descriptors with no type cannot be active")
        self.test_importdesc(
            {
                "desc":
                descsum_create(
                    "pk(tpubDCJtdt5dgJpdhW4MtaVYDhG4T4tF6jcLR1PxL43q9pq1mxvXgMS9Mzw1HnXG15vxUGQJMMSqCQHMTy3F1eW5VkgVroWzchsPD5BUojrcWs8/*)"
                ),
                "active":
                True,
                "range":
                1,
                "timestamp":
                "now"
            },
            success=True,
            warnings=["Unknown output type, cannot set descriptor to active."])
    def run_test(self):
        assert_raises_rpc_error(-5, "Missing checksum",
                                self.nodes[0].deriveaddresses, "a")

        descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)#t6wfjs64"
        address = "rric1qjqmxmkpmxt80xz4y3746zgt0q3u3ferrp2nklm"
        assert_equal(self.nodes[0].deriveaddresses(descriptor), [address])

        descriptor = descriptor[:-9]
        assert_raises_rpc_error(-5, "Missing checksum",
                                self.nodes[0].deriveaddresses, descriptor)

        descriptor_pubkey = "wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0)#s9ga3alw"
        address = "rric1qjqmxmkpmxt80xz4y3746zgt0q3u3ferrp2nklm"
        assert_equal(self.nodes[0].deriveaddresses(descriptor_pubkey),
                     [address])

        ranged_descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)#kft60nuy"
        assert_equal(self.nodes[0].deriveaddresses(ranged_descriptor, [1, 2]),
                     [
                         "rric1qhku5rq7jz8ulufe2y6fkcpnlvpsta7rq92mylt",
                         "rric1qpgptk2gvshyl0s9lqshsmx932l9ccsv22t9z00"
                     ])
        assert_equal(self.nodes[0].deriveaddresses(ranged_descriptor, 2), [
            address, "rric1qhku5rq7jz8ulufe2y6fkcpnlvpsta7rq92mylt",
            "rric1qpgptk2gvshyl0s9lqshsmx932l9ccsv22t9z00"
        ])

        assert_raises_rpc_error(
            -8, "Range should not be specified for an un-ranged descriptor",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"
            ), [0, 2])

        assert_raises_rpc_error(
            -8, "Range must be specified for a ranged descriptor",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ))

        assert_raises_rpc_error(
            -8, "End of range is too high", self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), 10000000000)

        assert_raises_rpc_error(
            -8, "Range is too large", self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), [1000000000, 2000000000])

        assert_raises_rpc_error(
            -8, "Range specified as [begin,end] must not have begin after end",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), [2, 0])

        assert_raises_rpc_error(
            -8, "Range should be greater or equal than 0",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), [-1, 0])

        combo_descriptor = descsum_create(
            "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"
        )
        assert_equal(self.nodes[0].deriveaddresses(combo_descriptor), [
            "rKP7dfs7xKAXzHhP6YgJnexAuMe4cVRNVr",
            "rKP7dfs7xKAXzHhP6YgJnexAuMe4cVRNVr", address,
            "tTbczn6wFPL4F4z28NQHnNjzcwAiNXyvDG"
        ])

        hardened_without_privkey_descriptor = descsum_create(
            "wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1'/1/0)"
        )
        assert_raises_rpc_error(-5,
                                "Cannot derive script without private keys",
                                self.nodes[0].deriveaddresses,
                                hardened_without_privkey_descriptor)

        bare_multisig_descriptor = descsum_create(
            "multi(1,tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0,tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/1)"
        )
        assert_raises_rpc_error(
            -5, "Descriptor does not have a corresponding address",
            self.nodes[0].deriveaddresses, bare_multisig_descriptor)
Beispiel #12
0
    def run_test(self):
        node = self.nodes[0]
        assert_raises_rpc_error(-18, 'No wallet is loaded.',
                                node.listdescriptors)

        if self.is_bdb_compiled():
            self.log.info(
                'Test that the command is not available for legacy wallets.')
            node.createwallet(wallet_name='w1', descriptors=False)
            assert_raises_rpc_error(
                -4,
                'listdescriptors is not available for non-descriptor wallets',
                node.listdescriptors)

        self.log.info('Test the command for empty descriptors wallet.')
        node.createwallet(wallet_name='w2', blank=True, descriptors=True)
        assert_equal(
            0, len(node.get_wallet_rpc('w2').listdescriptors()['descriptors']))

        self.log.info('Test the command for a default descriptors wallet.')
        node.createwallet(wallet_name='w3', descriptors=True)
        result = node.get_wallet_rpc('w3').listdescriptors()
        assert_equal("w3", result['wallet_name'])
        assert_equal(6, len(result['descriptors']))
        assert_equal(6, len([d for d in result['descriptors'] if d['active']]))
        assert_equal(3,
                     len([d for d in result['descriptors'] if d['internal']]))
        for item in result['descriptors']:
            assert item['desc'] != ''
            assert item['next'] == 0
            assert item['range'] == [0, 0]
            assert item['timestamp'] is not None

        self.log.info(
            'Test descriptors with hardened derivations are listed in importable form.'
        )
        xprv = 'tprv8ZgxMBicQKsPeuVhWwi6wuMQGfPKi9Li5GtX35jVNknACgqe3CY4g5xgkfDDJcmtF7o1QnxWDRYw4H5P26PXq7sbcUkEqeR4fg3Kxp2tigg'
        xpub_acc = 'tpubDCMVLhErorrAGfApiJSJzEKwqeaf2z3NrkVMxgYQjZLzMjXMBeRw2muGNYbvaekAE8rUFLftyEar4LdrG2wXyyTJQZ26zptmeTEjPTaATts'
        hardened_path = '/84\'/1\'/0\''
        wallet = node.get_wallet_rpc('w2')
        wallet.importdescriptors([{
            'desc':
            descsum_create('wpkh(' + xprv + hardened_path + '/0/*)'),
            'timestamp':
            1296688602,
        }])
        expected = {
            'wallet_name':
            'w2',
            'descriptors': [
                {
                    'desc':
                    descsum_create('wpkh([80002067' + hardened_path + ']' +
                                   xpub_acc + '/0/*)'),
                    'timestamp':
                    1296688602,
                    'active':
                    False,
                    'range': [0, 0],
                    'next':
                    0
                },
            ],
        }
        assert_equal(expected, wallet.listdescriptors())
        assert_equal(expected, wallet.listdescriptors(False))

        self.log.info('Test list private descriptors')
        expected_private = {
            'wallet_name':
            'w2',
            'descriptors': [
                {
                    'desc':
                    descsum_create('wpkh(' + xprv + hardened_path + '/0/*)'),
                    'timestamp':
                    1296688602,
                    'active':
                    False,
                    'range': [0, 0],
                    'next':
                    0
                },
            ],
        }
        assert_equal(expected_private, wallet.listdescriptors(True))

        self.log.info("Test listdescriptors with encrypted wallet")
        wallet.encryptwallet("pass")
        assert_equal(expected, wallet.listdescriptors())

        self.log.info('Test list private descriptors with encrypted wallet')
        assert_raises_rpc_error(
            -13,
            'Please enter the wallet passphrase with walletpassphrase first.',
            wallet.listdescriptors, True)
        wallet.walletpassphrase(passphrase="pass", timeout=1000000)
        assert_equal(expected_private, wallet.listdescriptors(True))

        self.log.info('Test list private descriptors with watch-only wallet')
        node.createwallet(wallet_name='watch-only',
                          descriptors=True,
                          disable_private_keys=True)
        watch_only_wallet = node.get_wallet_rpc('watch-only')
        watch_only_wallet.importdescriptors([{
            'desc':
            descsum_create('wpkh(' + xpub_acc + ')'),
            'timestamp':
            1296688602,
        }])
        assert_raises_rpc_error(-4, 'Can\'t get descriptor string',
                                watch_only_wallet.listdescriptors, True)

        self.log.info('Test non-active non-range combo descriptor')
        node.createwallet(wallet_name='w4', blank=True, descriptors=True)
        wallet = node.get_wallet_rpc('w4')
        wallet.importdescriptors([{
            'desc':
            descsum_create('combo(' + node.get_deterministic_priv_key().key +
                           ')'),
            'timestamp':
            1296688602,
        }])
        expected = {
            'wallet_name':
            'w4',
            'descriptors': [
                {
                    'active': False,
                    'desc':
                    'combo(0227d85ba011276cf25b51df6a188b75e604b38770a462b2d0e9fb2fc839ef5d3f)#np574htj',
                    'timestamp': 1296688602
                },
            ]
        }
        assert_equal(expected, wallet.listdescriptors())
Beispiel #13
0
    def run_test(self):

        # Check that there's no UTXO on none of the nodes
        assert_equal(len(self.nodes[0].listunspent()), 0)
        assert_equal(len(self.nodes[1].listunspent()), 0)
        assert_equal(len(self.nodes[2].listunspent()), 0)

        self.log.info("Mining blocks...")

        self.generate(self.nodes[0], 1, sync_fun=self.no_op)

        walletinfo = self.nodes[0].getwalletinfo()
        assert_equal(walletinfo['immature_balance'], 50)
        assert_equal(walletinfo['balance'], 0)

        self.sync_all(self.nodes[0:3])
        self.generate(self.nodes[1], COINBASE_MATURITY + 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))

        assert_equal(self.nodes[0].getbalance(), 50)
        assert_equal(self.nodes[1].getbalance(), 50)
        assert_equal(self.nodes[2].getbalance(), 0)

        # Check that only first and second nodes have UTXOs
        utxos = self.nodes[0].listunspent()
        assert_equal(len(utxos), 1)
        assert_equal(len(self.nodes[1].listunspent()), 1)
        assert_equal(len(self.nodes[2].listunspent()), 0)

        self.log.info("Test gettxout")
        confirmed_txid, confirmed_index = utxos[0]["txid"], utxos[0]["vout"]
        # First, outputs that are unspent both in the chain and in the
        # mempool should appear with or without include_mempool
        txout = self.nodes[0].gettxout(txid=confirmed_txid, n=confirmed_index, include_mempool=False)
        assert_equal(txout['value'], 50)
        txout = self.nodes[0].gettxout(txid=confirmed_txid, n=confirmed_index, include_mempool=True)
        assert_equal(txout['value'], 50)

        # Send 21 BTC from 0 to 2 using sendtoaddress call.
        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11)
        mempool_txid = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 10)

        self.log.info("Test gettxout (second part)")
        # utxo spent in mempool should be visible if you exclude mempool
        # but invisible if you include mempool
        txout = self.nodes[0].gettxout(confirmed_txid, confirmed_index, False)
        assert_equal(txout['value'], 50)
        txout = self.nodes[0].gettxout(confirmed_txid, confirmed_index)  # by default include_mempool=True
        assert txout is None
        txout = self.nodes[0].gettxout(confirmed_txid, confirmed_index, True)
        assert txout is None
        # new utxo from mempool should be invisible if you exclude mempool
        # but visible if you include mempool
        txout = self.nodes[0].gettxout(mempool_txid, 0, False)
        assert txout is None
        txout1 = self.nodes[0].gettxout(mempool_txid, 0, True)
        txout2 = self.nodes[0].gettxout(mempool_txid, 1, True)
        # note the mempool tx will have randomly assigned indices
        # but 10 will go to node2 and the rest will go to node0
        balance = self.nodes[0].getbalance()
        assert_equal(set([txout1['value'], txout2['value']]), set([10, balance]))
        walletinfo = self.nodes[0].getwalletinfo()
        assert_equal(walletinfo['immature_balance'], 0)

        # Have node0 mine a block, thus it will collect its own fee.
        self.generate(self.nodes[0], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))

        # Exercise locking of unspent outputs
        unspent_0 = self.nodes[2].listunspent()[0]
        unspent_0 = {"txid": unspent_0["txid"], "vout": unspent_0["vout"]}
        # Trying to unlock an output which isn't locked should error
        assert_raises_rpc_error(-8, "Invalid parameter, expected locked output", self.nodes[2].lockunspent, True, [unspent_0])

        # Locking an already-locked output should error
        self.nodes[2].lockunspent(False, [unspent_0])
        assert_raises_rpc_error(-8, "Invalid parameter, output already locked", self.nodes[2].lockunspent, False, [unspent_0])

        # Restarting the node should clear the lock
        self.restart_node(2)
        self.nodes[2].lockunspent(False, [unspent_0])

        # Unloading and reloating the wallet should clear the lock
        assert_equal(self.nodes[0].listwallets(), [self.default_wallet_name])
        self.nodes[2].unloadwallet(self.default_wallet_name)
        self.nodes[2].loadwallet(self.default_wallet_name)
        assert_equal(len(self.nodes[2].listlockunspent()), 0)

        # Locking non-persistently, then re-locking persistently, is allowed
        self.nodes[2].lockunspent(False, [unspent_0])
        self.nodes[2].lockunspent(False, [unspent_0], True)

        # Restarting the node with the lock written to the wallet should keep the lock
        self.restart_node(2, ["-walletrejectlongchains=0"])
        assert_raises_rpc_error(-8, "Invalid parameter, output already locked", self.nodes[2].lockunspent, False, [unspent_0])

        # Unloading and reloading the wallet with a persistent lock should keep the lock
        self.nodes[2].unloadwallet(self.default_wallet_name)
        self.nodes[2].loadwallet(self.default_wallet_name)
        assert_raises_rpc_error(-8, "Invalid parameter, output already locked", self.nodes[2].lockunspent, False, [unspent_0])

        # Locked outputs should not be used, even if they are the only available funds
        assert_raises_rpc_error(-6, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20)
        assert_equal([unspent_0], self.nodes[2].listlockunspent())

        # Unlocking should remove the persistent lock
        self.nodes[2].lockunspent(True, [unspent_0])
        self.restart_node(2)
        assert_equal(len(self.nodes[2].listlockunspent()), 0)

        # Reconnect node 2 after restarts
        self.connect_nodes(1, 2)
        self.connect_nodes(0, 2)

        assert_raises_rpc_error(-8, "txid must be of length 64 (not 34, for '0000000000000000000000000000000000')",
                                self.nodes[2].lockunspent, False,
                                [{"txid": "0000000000000000000000000000000000", "vout": 0}])
        assert_raises_rpc_error(-8, "txid must be hexadecimal string (not 'ZZZ0000000000000000000000000000000000000000000000000000000000000')",
                                self.nodes[2].lockunspent, False,
                                [{"txid": "ZZZ0000000000000000000000000000000000000000000000000000000000000", "vout": 0}])
        assert_raises_rpc_error(-8, "Invalid parameter, unknown transaction",
                                self.nodes[2].lockunspent, False,
                                [{"txid": "0000000000000000000000000000000000000000000000000000000000000000", "vout": 0}])
        assert_raises_rpc_error(-8, "Invalid parameter, vout index out of bounds",
                                self.nodes[2].lockunspent, False,
                                [{"txid": unspent_0["txid"], "vout": 999}])

        # The lock on a manually selected output is ignored
        unspent_0 = self.nodes[1].listunspent()[0]
        self.nodes[1].lockunspent(False, [unspent_0])
        tx = self.nodes[1].createrawtransaction([unspent_0], { self.nodes[1].getnewaddress() : 1 })
        self.nodes[1].fundrawtransaction(tx,{"lockUnspents": True})

        # fundrawtransaction can lock an input
        self.nodes[1].lockunspent(True, [unspent_0])
        assert_equal(len(self.nodes[1].listlockunspent()), 0)
        tx = self.nodes[1].fundrawtransaction(tx,{"lockUnspents": True})['hex']
        assert_equal(len(self.nodes[1].listlockunspent()), 1)

        # Send transaction
        tx = self.nodes[1].signrawtransactionwithwallet(tx)["hex"]
        self.nodes[1].sendrawtransaction(tx)
        assert_equal(len(self.nodes[1].listlockunspent()), 0)

        # Have node1 generate 100 blocks (so node0 can recover the fee)
        self.generate(self.nodes[1], COINBASE_MATURITY, sync_fun=lambda: self.sync_all(self.nodes[0:3]))

        # node0 should end up with 100 btc in block rewards plus fees, but
        # minus the 21 plus fees sent to node2
        assert_equal(self.nodes[0].getbalance(), 100 - 21)
        assert_equal(self.nodes[2].getbalance(), 21)

        # Node0 should have two unspent outputs.
        # Create a couple of transactions to send them to node2, submit them through
        # node1, and make sure both node0 and node2 pick them up properly:
        node0utxos = self.nodes[0].listunspent(1)
        assert_equal(len(node0utxos), 2)

        # create both transactions
        txns_to_send = []
        for utxo in node0utxos:
            inputs = []
            outputs = {}
            inputs.append({"txid": utxo["txid"], "vout": utxo["vout"]})
            outputs[self.nodes[2].getnewaddress()] = utxo["amount"] - 3
            raw_tx = self.nodes[0].createrawtransaction(inputs, outputs)
            txns_to_send.append(self.nodes[0].signrawtransactionwithwallet(raw_tx))

        # Have node 1 (miner) send the transactions
        self.nodes[1].sendrawtransaction(hexstring=txns_to_send[0]["hex"], maxfeerate=0)
        self.nodes[1].sendrawtransaction(hexstring=txns_to_send[1]["hex"], maxfeerate=0)

        # Have node1 mine a block to confirm transactions:
        self.generate(self.nodes[1], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))

        assert_equal(self.nodes[0].getbalance(), 0)
        assert_equal(self.nodes[2].getbalance(), 94)

        # Verify that a spent output cannot be locked anymore
        spent_0 = {"txid": node0utxos[0]["txid"], "vout": node0utxos[0]["vout"]}
        assert_raises_rpc_error(-8, "Invalid parameter, expected unspent output", self.nodes[0].lockunspent, False, [spent_0])

        # Send 10 BTC normal
        address = self.nodes[0].getnewaddress("test")
        fee_per_byte = Decimal('0.001') / 1000
        self.nodes[2].settxfee(fee_per_byte * 1000)
        txid = self.nodes[2].sendtoaddress(address, 10, "", "", False)
        self.generate(self.nodes[2], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
        node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), Decimal('84'), fee_per_byte, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))
        assert_equal(self.nodes[0].getbalance(), Decimal('10'))

        # Send 10 BTC with subtract fee from amount
        txid = self.nodes[2].sendtoaddress(address, 10, "", "", True)
        self.generate(self.nodes[2], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
        node_2_bal -= Decimal('10')
        assert_equal(self.nodes[2].getbalance(), node_2_bal)
        node_0_bal = self.check_fee_amount(self.nodes[0].getbalance(), Decimal('20'), fee_per_byte, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))

        self.log.info("Test sendmany")

        # Sendmany 10 BTC
        txid = self.nodes[2].sendmany('', {address: 10}, 0, "", [])
        self.generate(self.nodes[2], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
        node_0_bal += Decimal('10')
        node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), node_2_bal - Decimal('10'), fee_per_byte, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))
        assert_equal(self.nodes[0].getbalance(), node_0_bal)

        # Sendmany 10 BTC with subtract fee from amount
        txid = self.nodes[2].sendmany('', {address: 10}, 0, "", [address])
        self.generate(self.nodes[2], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
        node_2_bal -= Decimal('10')
        assert_equal(self.nodes[2].getbalance(), node_2_bal)
        node_0_bal = self.check_fee_amount(self.nodes[0].getbalance(), node_0_bal + Decimal('10'), fee_per_byte, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))

        self.log.info("Test sendmany with fee_rate param (explicit fee rate in sat/vB)")
        fee_rate_sat_vb = 2
        fee_rate_btc_kvb = fee_rate_sat_vb * 1e3 / 1e8
        explicit_fee_rate_btc_kvb = Decimal(fee_rate_btc_kvb) / 1000

        # Test passing fee_rate as a string
        txid = self.nodes[2].sendmany(amounts={address: 10}, fee_rate=str(fee_rate_sat_vb))
        self.generate(self.nodes[2], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
        balance = self.nodes[2].getbalance()
        node_2_bal = self.check_fee_amount(balance, node_2_bal - Decimal('10'), explicit_fee_rate_btc_kvb, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))
        assert_equal(balance, node_2_bal)
        node_0_bal += Decimal('10')
        assert_equal(self.nodes[0].getbalance(), node_0_bal)

        # Test passing fee_rate as an integer
        amount = Decimal("0.0001")
        txid = self.nodes[2].sendmany(amounts={address: amount}, fee_rate=fee_rate_sat_vb)
        self.generate(self.nodes[2], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
        balance = self.nodes[2].getbalance()
        node_2_bal = self.check_fee_amount(balance, node_2_bal - amount, explicit_fee_rate_btc_kvb, self.get_vsize(self.nodes[2].gettransaction(txid)['hex']))
        assert_equal(balance, node_2_bal)
        node_0_bal += amount
        assert_equal(self.nodes[0].getbalance(), node_0_bal)

        for key in ["totalFee", "feeRate"]:
            assert_raises_rpc_error(-8, "Unknown named parameter key", self.nodes[2].sendtoaddress, address=address, amount=1, fee_rate=1, key=1)

        # Test setting explicit fee rate just below the minimum.
        self.log.info("Test sendmany raises 'fee rate too low' if fee_rate of 0.99999999 is passed")
        assert_raises_rpc_error(-6, "Fee rate (0.999 sat/vB) is lower than the minimum fee rate setting (1.000 sat/vB)",
            self.nodes[2].sendmany, amounts={address: 10}, fee_rate=0.999)

        self.log.info("Test sendmany raises if an invalid fee_rate is passed")
        # Test fee_rate with zero values.
        msg = "Fee rate (0.000 sat/vB) is lower than the minimum fee rate setting (1.000 sat/vB)"
        for zero_value in [0, 0.000, 0.00000000, "0", "0.000", "0.00000000"]:
            assert_raises_rpc_error(-6, msg, self.nodes[2].sendmany, amounts={address: 1}, fee_rate=zero_value)
        msg = "Invalid amount"
        # Test fee_rate values that don't pass fixed-point parsing checks.
        for invalid_value in ["", 0.000000001, 1e-09, 1.111111111, 1111111111111111, "31.999999999999999999999"]:
            assert_raises_rpc_error(-3, msg, self.nodes[2].sendmany, amounts={address: 1.0}, fee_rate=invalid_value)
        # Test fee_rate values that cannot be represented in sat/vB.
        for invalid_value in [0.0001, 0.00000001, 0.00099999, 31.99999999, "0.0001", "0.00000001", "0.00099999", "31.99999999"]:
            assert_raises_rpc_error(-3, msg, self.nodes[2].sendmany, amounts={address: 10}, fee_rate=invalid_value)
        # Test fee_rate out of range (negative number).
        assert_raises_rpc_error(-3, OUT_OF_RANGE, self.nodes[2].sendmany, amounts={address: 10}, fee_rate=-1)
        # Test type error.
        for invalid_value in [True, {"foo": "bar"}]:
            assert_raises_rpc_error(-3, NOT_A_NUMBER_OR_STRING, self.nodes[2].sendmany, amounts={address: 10}, fee_rate=invalid_value)

        self.log.info("Test sendmany raises if an invalid conf_target or estimate_mode is passed")
        for target, mode in product([-1, 0, 1009], ["economical", "conservative"]):
            assert_raises_rpc_error(-8, "Invalid conf_target, must be between 1 and 1008",  # max value of 1008 per src/policy/fees.h
                self.nodes[2].sendmany, amounts={address: 1}, conf_target=target, estimate_mode=mode)
        for target, mode in product([-1, 0], ["btc/kb", "sat/b"]):
            assert_raises_rpc_error(-8, 'Invalid estimate_mode parameter, must be one of: "unset", "economical", "conservative"',
                self.nodes[2].sendmany, amounts={address: 1}, conf_target=target, estimate_mode=mode)

        self.start_node(3, self.nodes[3].extra_args)
        self.connect_nodes(0, 3)
        self.sync_all()

        # check if we can list zero value tx as available coins
        # 1. create raw_tx
        # 2. hex-changed one output to 0.0
        # 3. sign and send
        # 4. check if recipient (node0) can list the zero value tx
        usp = self.nodes[1].listunspent(query_options={'minimumAmount': '49.998'})[0]
        inputs = [{"txid": usp['txid'], "vout": usp['vout']}]
        outputs = {self.nodes[1].getnewaddress(): 49.998, self.nodes[0].getnewaddress(): 11.11}

        raw_tx = self.nodes[1].createrawtransaction(inputs, outputs).replace("c0833842", "00000000")  # replace 11.11 with 0.0 (int32)
        signed_raw_tx = self.nodes[1].signrawtransactionwithwallet(raw_tx)
        decoded_raw_tx = self.nodes[1].decoderawtransaction(signed_raw_tx['hex'])
        zero_value_txid = decoded_raw_tx['txid']
        self.nodes[1].sendrawtransaction(signed_raw_tx['hex'])

        self.sync_all()
        self.generate(self.nodes[1], 1)  # mine a block

        unspent_txs = self.nodes[0].listunspent()  # zero value tx must be in listunspents output
        found = False
        for uTx in unspent_txs:
            if uTx['txid'] == zero_value_txid:
                found = True
                assert_equal(uTx['amount'], Decimal('0'))
        assert found

        self.log.info("Test -walletbroadcast")
        self.stop_nodes()
        self.start_node(0, ["-walletbroadcast=0"])
        self.start_node(1, ["-walletbroadcast=0"])
        self.start_node(2, ["-walletbroadcast=0"])
        self.connect_nodes(0, 1)
        self.connect_nodes(1, 2)
        self.connect_nodes(0, 2)
        self.sync_all(self.nodes[0:3])

        txid_not_broadcast = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 2)
        tx_obj_not_broadcast = self.nodes[0].gettransaction(txid_not_broadcast)
        self.generate(self.nodes[1], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))  # mine a block, tx should not be in there
        assert_equal(self.nodes[2].getbalance(), node_2_bal)  # should not be changed because tx was not broadcasted

        # now broadcast from another node, mine a block, sync, and check the balance
        self.nodes[1].sendrawtransaction(tx_obj_not_broadcast['hex'])
        self.generate(self.nodes[1], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
        node_2_bal += 2
        tx_obj_not_broadcast = self.nodes[0].gettransaction(txid_not_broadcast)
        assert_equal(self.nodes[2].getbalance(), node_2_bal)

        # create another tx
        self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 2)

        # restart the nodes with -walletbroadcast=1
        self.stop_nodes()
        self.start_node(0)
        self.start_node(1)
        self.start_node(2)
        self.connect_nodes(0, 1)
        self.connect_nodes(1, 2)
        self.connect_nodes(0, 2)
        self.sync_blocks(self.nodes[0:3])

        self.generate(self.nodes[0], 1, sync_fun=lambda: self.sync_blocks(self.nodes[0:3]))
        node_2_bal += 2

        # tx should be added to balance because after restarting the nodes tx should be broadcast
        assert_equal(self.nodes[2].getbalance(), node_2_bal)

        # send a tx with value in a string (PR#6380 +)
        txid = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "2")
        tx_obj = self.nodes[0].gettransaction(txid)
        assert_equal(tx_obj['amount'], Decimal('-2'))

        txid = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "0.0001")
        tx_obj = self.nodes[0].gettransaction(txid)
        assert_equal(tx_obj['amount'], Decimal('-0.0001'))

        # check if JSON parser can handle scientific notation in strings
        txid = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), "1e-4")
        tx_obj = self.nodes[0].gettransaction(txid)
        assert_equal(tx_obj['amount'], Decimal('-0.0001'))

        # General checks for errors from incorrect inputs
        # This will raise an exception because the amount is negative
        assert_raises_rpc_error(-3, OUT_OF_RANGE, self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "-1")

        # This will raise an exception because the amount type is wrong
        assert_raises_rpc_error(-3, "Invalid amount", self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "1f-4")

        # This will raise an exception since generate does not accept a string
        assert_raises_rpc_error(-1, "not of expected type number", self.generate, self.nodes[0], "2")

        if not self.options.descriptors:

            # This will raise an exception for the invalid private key format
            assert_raises_rpc_error(-5, "Invalid private key encoding", self.nodes[0].importprivkey, "invalid")

            # This will raise an exception for importing an address with the PS2H flag
            temp_address = self.nodes[1].getnewaddress("", "p2sh-segwit")
            assert_raises_rpc_error(-5, "Cannot use the p2sh flag with an address - use a script instead", self.nodes[0].importaddress, temp_address, "label", False, True)

            # This will raise an exception for attempting to dump the private key of an address you do not own
            assert_raises_rpc_error(-3, "Address does not refer to a key", self.nodes[0].dumpprivkey, temp_address)

            # This will raise an exception for attempting to get the private key of an invalid Bitcoin address
            assert_raises_rpc_error(-5, "Invalid Bitcoin address", self.nodes[0].dumpprivkey, "invalid")

            # This will raise an exception for attempting to set a label for an invalid Bitcoin address
            assert_raises_rpc_error(-5, "Invalid Bitcoin address", self.nodes[0].setlabel, "invalid address", "label")

            # This will raise an exception for importing an invalid address
            assert_raises_rpc_error(-5, "Invalid Bitcoin address or script", self.nodes[0].importaddress, "invalid")

            # This will raise an exception for attempting to import a pubkey that isn't in hex
            assert_raises_rpc_error(-5, "Pubkey must be a hex string", self.nodes[0].importpubkey, "not hex")

            # This will raise an exception for importing an invalid pubkey
            assert_raises_rpc_error(-5, "Pubkey is not a valid public key", self.nodes[0].importpubkey, "5361746f736869204e616b616d6f746f")

            # Bech32m addresses cannot be imported into a legacy wallet
            assert_raises_rpc_error(-5, "Bech32m addresses cannot be imported into legacy wallets", self.nodes[0].importaddress, "bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqc8gma6")

            # Import address and private key to check correct behavior of spendable unspents
            # 1. Send some coins to generate new UTXO
            address_to_import = self.nodes[2].getnewaddress()
            txid = self.nodes[0].sendtoaddress(address_to_import, 1)
            self.sync_mempools(self.nodes[0:3])
            vout = find_vout_for_address(self.nodes[2], txid, address_to_import)
            self.nodes[2].lockunspent(False, [{"txid": txid, "vout": vout}])
            self.generate(self.nodes[0], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))

            self.log.info("Test sendtoaddress with fee_rate param (explicit fee rate in sat/vB)")
            prebalance = self.nodes[2].getbalance()
            assert prebalance > 2
            address = self.nodes[1].getnewaddress()
            amount = 3
            fee_rate_sat_vb = 2
            fee_rate_btc_kvb = fee_rate_sat_vb * 1e3 / 1e8
            # Test passing fee_rate as an integer
            txid = self.nodes[2].sendtoaddress(address=address, amount=amount, fee_rate=fee_rate_sat_vb)
            tx_size = self.get_vsize(self.nodes[2].gettransaction(txid)['hex'])
            self.generate(self.nodes[0], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
            postbalance = self.nodes[2].getbalance()
            fee = prebalance - postbalance - Decimal(amount)
            assert_fee_amount(fee, tx_size, Decimal(fee_rate_btc_kvb))

            prebalance = self.nodes[2].getbalance()
            amount = Decimal("0.001")
            fee_rate_sat_vb = 1.23
            fee_rate_btc_kvb = fee_rate_sat_vb * 1e3 / 1e8
            # Test passing fee_rate as a string
            txid = self.nodes[2].sendtoaddress(address=address, amount=amount, fee_rate=str(fee_rate_sat_vb))
            tx_size = self.get_vsize(self.nodes[2].gettransaction(txid)['hex'])
            self.generate(self.nodes[0], 1, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
            postbalance = self.nodes[2].getbalance()
            fee = prebalance - postbalance - amount
            assert_fee_amount(fee, tx_size, Decimal(fee_rate_btc_kvb))

            for key in ["totalFee", "feeRate"]:
                assert_raises_rpc_error(-8, "Unknown named parameter key", self.nodes[2].sendtoaddress, address=address, amount=1, fee_rate=1, key=1)

            # Test setting explicit fee rate just below the minimum.
            self.log.info("Test sendtoaddress raises 'fee rate too low' if fee_rate of 0.99999999 is passed")
            assert_raises_rpc_error(-6, "Fee rate (0.999 sat/vB) is lower than the minimum fee rate setting (1.000 sat/vB)",
                self.nodes[2].sendtoaddress, address=address, amount=1, fee_rate=0.999)

            self.log.info("Test sendtoaddress raises if an invalid fee_rate is passed")
            # Test fee_rate with zero values.
            msg = "Fee rate (0.000 sat/vB) is lower than the minimum fee rate setting (1.000 sat/vB)"
            for zero_value in [0, 0.000, 0.00000000, "0", "0.000", "0.00000000"]:
                assert_raises_rpc_error(-6, msg, self.nodes[2].sendtoaddress, address=address, amount=1, fee_rate=zero_value)
            msg = "Invalid amount"
            # Test fee_rate values that don't pass fixed-point parsing checks.
            for invalid_value in ["", 0.000000001, 1e-09, 1.111111111, 1111111111111111, "31.999999999999999999999"]:
                assert_raises_rpc_error(-3, msg, self.nodes[2].sendtoaddress, address=address, amount=1.0, fee_rate=invalid_value)
            # Test fee_rate values that cannot be represented in sat/vB.
            for invalid_value in [0.0001, 0.00000001, 0.00099999, 31.99999999, "0.0001", "0.00000001", "0.00099999", "31.99999999"]:
                assert_raises_rpc_error(-3, msg, self.nodes[2].sendtoaddress, address=address, amount=10, fee_rate=invalid_value)
            # Test fee_rate out of range (negative number).
            assert_raises_rpc_error(-3, OUT_OF_RANGE, self.nodes[2].sendtoaddress, address=address, amount=1.0, fee_rate=-1)
            # Test type error.
            for invalid_value in [True, {"foo": "bar"}]:
                assert_raises_rpc_error(-3, NOT_A_NUMBER_OR_STRING, self.nodes[2].sendtoaddress, address=address, amount=1.0, fee_rate=invalid_value)

            self.log.info("Test sendtoaddress raises if an invalid conf_target or estimate_mode is passed")
            for target, mode in product([-1, 0, 1009], ["economical", "conservative"]):
                assert_raises_rpc_error(-8, "Invalid conf_target, must be between 1 and 1008",  # max value of 1008 per src/policy/fees.h
                    self.nodes[2].sendtoaddress, address=address, amount=1, conf_target=target, estimate_mode=mode)
            for target, mode in product([-1, 0], ["btc/kb", "sat/b"]):
                assert_raises_rpc_error(-8, 'Invalid estimate_mode parameter, must be one of: "unset", "economical", "conservative"',
                    self.nodes[2].sendtoaddress, address=address, amount=1, conf_target=target, estimate_mode=mode)

            # 2. Import address from node2 to node1
            self.nodes[1].importaddress(address_to_import)

            # 3. Validate that the imported address is watch-only on node1
            assert self.nodes[1].getaddressinfo(address_to_import)["iswatchonly"]

            # 4. Check that the unspents after import are not spendable
            assert_array_result(self.nodes[1].listunspent(),
                                {"address": address_to_import},
                                {"spendable": False})

            # 5. Import private key of the previously imported address on node1
            priv_key = self.nodes[2].dumpprivkey(address_to_import)
            self.nodes[1].importprivkey(priv_key)

            # 6. Check that the unspents are now spendable on node1
            assert_array_result(self.nodes[1].listunspent(),
                                {"address": address_to_import},
                                {"spendable": True})

        # Mine a block from node0 to an address from node1
        coinbase_addr = self.nodes[1].getnewaddress()
        block_hash = self.generatetoaddress(self.nodes[0], 1, coinbase_addr, sync_fun=lambda: self.sync_all(self.nodes[0:3]))[0]
        coinbase_txid = self.nodes[0].getblock(block_hash)['tx'][0]

        # Check that the txid and balance is found by node1
        self.nodes[1].gettransaction(coinbase_txid)

        # check if wallet or blockchain maintenance changes the balance
        self.sync_all(self.nodes[0:3])
        blocks = self.generate(self.nodes[0], 2, sync_fun=lambda: self.sync_all(self.nodes[0:3]))
        balance_nodes = [self.nodes[i].getbalance() for i in range(3)]
        block_count = self.nodes[0].getblockcount()

        # Check modes:
        #   - True: unicode escaped as \u....
        #   - False: unicode directly as UTF-8
        for mode in [True, False]:
            self.nodes[0].rpc.ensure_ascii = mode
            # unicode check: Basic Multilingual Plane, Supplementary Plane respectively
            for label in [u'б€б‹аБаА', u'№…Ё']:
                addr = self.nodes[0].getnewaddress()
                self.nodes[0].setlabel(addr, label)
                test_address(self.nodes[0], addr, labels=[label])
                assert label in self.nodes[0].listlabels()
        self.nodes[0].rpc.ensure_ascii = True  # restore to default

        # -reindex tests
        chainlimit = 6
        self.log.info("Test -reindex")
        self.stop_nodes()
        # set lower ancestor limit for later
        self.start_node(0, ['-reindex', "-walletrejectlongchains=0", "-limitancestorcount=" + str(chainlimit)])
        self.start_node(1, ['-reindex', "-limitancestorcount=" + str(chainlimit)])
        self.start_node(2, ['-reindex', "-limitancestorcount=" + str(chainlimit)])
        # reindex will leave rpc warm up "early"; Wait for it to finish
        self.wait_until(lambda: [block_count] * 3 == [self.nodes[i].getblockcount() for i in range(3)])
        assert_equal(balance_nodes, [self.nodes[i].getbalance() for i in range(3)])

        # Exercise listsinceblock with the last two blocks
        coinbase_tx_1 = self.nodes[0].listsinceblock(blocks[0])
        assert_equal(coinbase_tx_1["lastblock"], blocks[1])
        assert_equal(len(coinbase_tx_1["transactions"]), 1)
        assert_equal(coinbase_tx_1["transactions"][0]["blockhash"], blocks[1])
        assert_equal(len(self.nodes[0].listsinceblock(blocks[1])["transactions"]), 0)

        # ==Check that wallet prefers to use coins that don't exceed mempool limits =====

        # Get all non-zero utxos together
        chain_addrs = [self.nodes[0].getnewaddress(), self.nodes[0].getnewaddress()]
        singletxid = self.nodes[0].sendtoaddress(chain_addrs[0], self.nodes[0].getbalance(), "", "", True)
        self.generate(self.nodes[0], 1, sync_fun=self.no_op)
        node0_balance = self.nodes[0].getbalance()
        # Split into two chains
        rawtx = self.nodes[0].createrawtransaction([{"txid": singletxid, "vout": 0}], {chain_addrs[0]: node0_balance / 2 - Decimal('0.01'), chain_addrs[1]: node0_balance / 2 - Decimal('0.01')})
        signedtx = self.nodes[0].signrawtransactionwithwallet(rawtx)
        singletxid = self.nodes[0].sendrawtransaction(hexstring=signedtx["hex"], maxfeerate=0)
        self.generate(self.nodes[0], 1, sync_fun=self.no_op)

        # Make a long chain of unconfirmed payments without hitting mempool limit
        # Each tx we make leaves only one output of change on a chain 1 longer
        # Since the amount to send is always much less than the outputs, we only ever need one output
        # So we should be able to generate exactly chainlimit txs for each original output
        sending_addr = self.nodes[1].getnewaddress()
        txid_list = []
        for _ in range(chainlimit * 2):
            txid_list.append(self.nodes[0].sendtoaddress(sending_addr, Decimal('0.0001')))
        assert_equal(self.nodes[0].getmempoolinfo()['size'], chainlimit * 2)
        assert_equal(len(txid_list), chainlimit * 2)

        # Without walletrejectlongchains, we will still generate a txid
        # The tx will be stored in the wallet but not accepted to the mempool
        extra_txid = self.nodes[0].sendtoaddress(sending_addr, Decimal('0.0001'))
        assert extra_txid not in self.nodes[0].getrawmempool()
        assert extra_txid in [tx["txid"] for tx in self.nodes[0].listtransactions()]
        self.nodes[0].abandontransaction(extra_txid)
        total_txs = len(self.nodes[0].listtransactions("*", 99999))

        # Try with walletrejectlongchains
        # Double chain limit but require combining inputs, so we pass AttemptSelection
        self.stop_node(0)
        extra_args = ["-walletrejectlongchains", "-limitancestorcount=" + str(2 * chainlimit)]
        self.start_node(0, extra_args=extra_args)

        # wait until the wallet has submitted all transactions to the mempool
        self.wait_until(lambda: len(self.nodes[0].getrawmempool()) == chainlimit * 2)

        # Prevent potential race condition when calling wallet RPCs right after restart
        self.nodes[0].syncwithvalidationinterfacequeue()

        node0_balance = self.nodes[0].getbalance()
        # With walletrejectlongchains we will not create the tx and store it in our wallet.
        assert_raises_rpc_error(-6, "Transaction has too long of a mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01'))

        # Verify nothing new in wallet
        assert_equal(total_txs, len(self.nodes[0].listtransactions("*", 99999)))

        # Test getaddressinfo on external address. Note that these addresses are taken from disablewallet.py
        assert_raises_rpc_error(-5, "Invalid prefix for Base58-encoded address", self.nodes[0].getaddressinfo, "3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy")
        address_info = self.nodes[0].getaddressinfo("mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ")
        assert_equal(address_info['address'], "mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ")
        assert_equal(address_info["scriptPubKey"], "76a9144e3854046c7bd1594ac904e4793b6a45b36dea0988ac")
        assert not address_info["ismine"]
        assert not address_info["iswatchonly"]
        assert not address_info["isscript"]
        assert not address_info["ischange"]

        # Test getaddressinfo 'ischange' field on change address.
        self.generate(self.nodes[0], 1, sync_fun=self.no_op)
        destination = self.nodes[1].getnewaddress()
        txid = self.nodes[0].sendtoaddress(destination, 0.123)
        tx = self.nodes[0].gettransaction(txid=txid, verbose=True)['decoded']
        output_addresses = [vout['scriptPubKey']['address'] for vout in tx["vout"]]
        assert len(output_addresses) > 1
        for address in output_addresses:
            ischange = self.nodes[0].getaddressinfo(address)['ischange']
            assert_equal(ischange, address != destination)
            if ischange:
                change = address
        self.nodes[0].setlabel(change, 'foobar')
        assert_equal(self.nodes[0].getaddressinfo(change)['ischange'], False)

        # Test gettransaction response with different arguments.
        self.log.info("Testing gettransaction response with different arguments...")
        self.nodes[0].setlabel(change, 'baz')
        baz = self.nodes[0].listtransactions(label="baz", count=1)[0]
        expected_receive_vout = {"label":    "baz",
                                 "address":  baz["address"],
                                 "amount":   baz["amount"],
                                 "category": baz["category"],
                                 "vout":     baz["vout"]}
        expected_fields = frozenset({'amount', 'bip125-replaceable', 'confirmations', 'details', 'fee',
                                     'hex', 'time', 'timereceived', 'trusted', 'txid', 'wtxid', 'walletconflicts'})
        verbose_field = "decoded"
        expected_verbose_fields = expected_fields | {verbose_field}

        self.log.debug("Testing gettransaction response without verbose")
        tx = self.nodes[0].gettransaction(txid=txid)
        assert_equal(set([*tx]), expected_fields)
        assert_array_result(tx["details"], {"category": "receive"}, expected_receive_vout)

        self.log.debug("Testing gettransaction response with verbose set to False")
        tx = self.nodes[0].gettransaction(txid=txid, verbose=False)
        assert_equal(set([*tx]), expected_fields)
        assert_array_result(tx["details"], {"category": "receive"}, expected_receive_vout)

        self.log.debug("Testing gettransaction response with verbose set to True")
        tx = self.nodes[0].gettransaction(txid=txid, verbose=True)
        assert_equal(set([*tx]), expected_verbose_fields)
        assert_array_result(tx["details"], {"category": "receive"}, expected_receive_vout)
        assert_equal(tx[verbose_field], self.nodes[0].decoderawtransaction(tx["hex"]))

        self.log.info("Test send* RPCs with verbose=True")
        address = self.nodes[0].getnewaddress("test")
        txid_feeReason_one = self.nodes[2].sendtoaddress(address=address, amount=5, verbose=True)
        assert_equal(txid_feeReason_one["fee_reason"], "Fallback fee")
        txid_feeReason_two = self.nodes[2].sendmany(dummy='', amounts={address: 5}, verbose=True)
        assert_equal(txid_feeReason_two["fee_reason"], "Fallback fee")
        self.log.info("Test send* RPCs with verbose=False")
        txid_feeReason_three = self.nodes[2].sendtoaddress(address=address, amount=5, verbose=False)
        assert_equal(self.nodes[2].gettransaction(txid_feeReason_three)['txid'], txid_feeReason_three)
        txid_feeReason_four = self.nodes[2].sendmany(dummy='', amounts={address: 5}, verbose=False)
        assert_equal(self.nodes[2].gettransaction(txid_feeReason_four)['txid'], txid_feeReason_four)

        self.log.info("Testing 'listunspent' outputs the parent descriptor(s) of coins")
        # Create two multisig descriptors, and send a UTxO each.
        multi_a = descsum_create("wsh(multi(1,tpubD6NzVbkrYhZ4YBNjUo96Jxd1u4XKWgnoc7LsA1jz3Yc2NiDbhtfBhaBtemB73n9V5vtJHwU6FVXwggTbeoJWQ1rzdz8ysDuQkpnaHyvnvzR/*,tpubD6NzVbkrYhZ4YHdDGMAYGaWxMSC1B6tPRTHuU5t3BcfcS3nrF523iFm5waFd1pP3ZvJt4Jr8XmCmsTBNx5suhcSgtzpGjGMASR3tau1hJz4/*))")
        multi_b = descsum_create("wsh(multi(1,tpubD6NzVbkrYhZ4YHdDGMAYGaWxMSC1B6tPRTHuU5t3BcfcS3nrF523iFm5waFd1pP3ZvJt4Jr8XmCmsTBNx5suhcSgtzpGjGMASR3tau1hJz4/*,tpubD6NzVbkrYhZ4Y2RLiuEzNQkntjmsLpPYDm3LTRBYynUQtDtpzeUKAcb9sYthSFL3YR74cdFgF5mW8yKxv2W2CWuZDFR2dUpE5PF9kbrVXNZ/*))")
        addr_a = self.nodes[0].deriveaddresses(multi_a, 0)[0]
        addr_b = self.nodes[0].deriveaddresses(multi_b, 0)[0]
        txid_a = self.nodes[0].sendtoaddress(addr_a, 0.01)
        txid_b = self.nodes[0].sendtoaddress(addr_b, 0.01)
        self.generate(self.nodes[0], 1, sync_fun=self.no_op)
        # Now import the descriptors, make sure we can identify on which descriptor each coin was received.
        self.nodes[0].createwallet(wallet_name="wo", descriptors=True, disable_private_keys=True)
        wo_wallet = self.nodes[0].get_wallet_rpc("wo")
        wo_wallet.importdescriptors([
            {
                "desc": multi_a,
                "active": False,
                "timestamp": "now",
            },
            {
                "desc": multi_b,
                "active": False,
                "timestamp": "now",
            },
        ])
        coins = wo_wallet.listunspent(minconf=0)
        assert_equal(len(coins), 2)
        coin_a = next(c for c in coins if c["txid"] == txid_a)
        assert_equal(coin_a["parent_descs"][0], multi_a)
        coin_b = next(c for c in coins if c["txid"] == txid_b)
        assert_equal(coin_b["parent_descs"][0], multi_b)
        self.nodes[0].unloadwallet("wo")
Beispiel #14
0
    def run_test(self):
        self.nodes[0].generatetoaddress(101, self.nodes[0].getnewaddress())

        self.sync_blocks()

        # Sanity check the test framework:
        res = self.nodes[self.num_nodes - 1].getblockchaininfo()
        assert_equal(res['blocks'], 101)

        node_master = self.nodes[self.num_nodes - 5]
        node_v19 = self.nodes[self.num_nodes - 4]
        node_v18 = self.nodes[self.num_nodes - 3]
        node_v17 = self.nodes[self.num_nodes - 2]
        node_v16 = self.nodes[self.num_nodes - 1]

        self.log.info("Test wallet backwards compatibility...")
        # Create a number of wallets and open them in older versions:

        # w1: regular wallet, created on master: update this test when default
        #     wallets can no longer be opened by older versions.
        node_master.createwallet(wallet_name="w1")
        wallet = node_master.get_wallet_rpc("w1")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        # Create a confirmed transaction, receiving coins
        address = wallet.getnewaddress()
        self.nodes[0].sendtoaddress(address, 10)
        self.sync_mempools()
        self.nodes[0].generate(1)
        self.sync_blocks()
        # Create a conflicting transaction using RBF
        return_address = self.nodes[0].getnewaddress()
        tx1_id = self.nodes[1].sendtoaddress(return_address, 1)
        tx2_id = self.nodes[1].bumpfee(tx1_id)["txid"]
        # Confirm the transaction
        self.sync_mempools()
        self.nodes[0].generate(1)
        self.sync_blocks()
        # Create another conflicting transaction using RBF
        tx3_id = self.nodes[1].sendtoaddress(return_address, 1)
        tx4_id = self.nodes[1].bumpfee(tx3_id)["txid"]
        # Abandon transaction, but don't confirm
        self.nodes[1].abandontransaction(tx3_id)

        # w1_v19: regular wallet, created with v0.19
        node_v19.rpc.createwallet(wallet_name="w1_v19")
        wallet = node_v19.get_wallet_rpc("w1_v19")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0
        # Use addmultisigaddress (see #18075)
        address_18075 = wallet.rpc.addmultisigaddress(1, [
            "0296b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52",
            "037211a824f55b505228e4c3d5194c1fcfaa15a456abdf37f9b9d97a4040afc073"
        ], "", "legacy")["address"]
        assert wallet.getaddressinfo(address_18075)["solvable"]

        # w1_v18: regular wallet, created with v0.18
        node_v18.rpc.createwallet(wallet_name="w1_v18")
        wallet = node_v18.get_wallet_rpc("w1_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0

        # w2: wallet with private keys disabled, created on master: update this
        #     test when default wallets private keys disabled can no longer be
        #     opened by older versions.
        node_master.createwallet(wallet_name="w2", disable_private_keys=True)
        wallet = node_master.get_wallet_rpc("w2")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # w2_v19: wallet with private keys disabled, created with v0.19
        node_v19.rpc.createwallet(wallet_name="w2_v19",
                                  disable_private_keys=True)
        wallet = node_v19.get_wallet_rpc("w2_v19")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # w2_v18: wallet with private keys disabled, created with v0.18
        node_v18.rpc.createwallet(wallet_name="w2_v18",
                                  disable_private_keys=True)
        wallet = node_v18.get_wallet_rpc("w2_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # w3: blank wallet, created on master: update this
        #     test when default blank wallets can no longer be opened by older versions.
        node_master.createwallet(wallet_name="w3", blank=True)
        wallet = node_master.get_wallet_rpc("w3")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # w3_v19: blank wallet, created with v0.19
        node_v19.rpc.createwallet(wallet_name="w3_v19", blank=True)
        wallet = node_v19.get_wallet_rpc("w3_v19")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # w3_v18: blank wallet, created with v0.18
        node_v18.rpc.createwallet(wallet_name="w3_v18", blank=True)
        wallet = node_v18.get_wallet_rpc("w3_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] == 0

        # Copy the wallets to older nodes:
        node_master_wallets_dir = os.path.join(node_master.datadir,
                                               "regtest/wallets")
        node_v19_wallets_dir = os.path.join(node_v19.datadir,
                                            "regtest/wallets")
        node_v18_wallets_dir = os.path.join(node_v18.datadir,
                                            "regtest/wallets")
        node_v17_wallets_dir = os.path.join(node_v17.datadir,
                                            "regtest/wallets")
        node_v16_wallets_dir = os.path.join(node_v16.datadir, "regtest")
        node_master.unloadwallet("w1")
        node_master.unloadwallet("w2")
        node_v19.unloadwallet("w1_v19")
        node_v19.unloadwallet("w2_v19")
        node_v18.unloadwallet("w1_v18")
        node_v18.unloadwallet("w2_v18")

        # Copy wallets to v0.16
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(os.path.join(node_master_wallets_dir, wallet),
                            os.path.join(node_v16_wallets_dir, wallet))

        # Copy wallets to v0.17
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(os.path.join(node_master_wallets_dir, wallet),
                            os.path.join(node_v17_wallets_dir, wallet))
        for wallet in os.listdir(node_v18_wallets_dir):
            shutil.copytree(os.path.join(node_v18_wallets_dir, wallet),
                            os.path.join(node_v17_wallets_dir, wallet))

        # Copy wallets to v0.18
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(os.path.join(node_master_wallets_dir, wallet),
                            os.path.join(node_v18_wallets_dir, wallet))

        # Copy wallets to v0.19
        for wallet in os.listdir(node_master_wallets_dir):
            shutil.copytree(os.path.join(node_master_wallets_dir, wallet),
                            os.path.join(node_v19_wallets_dir, wallet))

        if not self.options.descriptors:
            # Descriptor wallets break compatibility, only run this test for legacy wallet
            # Open the wallets in v0.19
            node_v19.loadwallet("w1")
            wallet = node_v19.get_wallet_rpc("w1")
            info = wallet.getwalletinfo()
            assert info['private_keys_enabled']
            assert info['keypoolsize'] > 0
            txs = wallet.listtransactions()
            assert_equal(len(txs), 5)
            assert_equal(txs[1]["txid"], tx1_id)
            assert_equal(txs[2]["walletconflicts"], [tx1_id])
            assert_equal(txs[1]["replaced_by_txid"], tx2_id)
            assert not (txs[1]["abandoned"])
            assert_equal(txs[1]["confirmations"], -1)
            assert_equal(txs[2]["blockindex"], 1)
            assert txs[3]["abandoned"]
            assert_equal(txs[4]["walletconflicts"], [tx3_id])
            assert_equal(txs[3]["replaced_by_txid"], tx4_id)
            assert not (hasattr(txs[3], "blockindex"))

            node_v19.loadwallet("w2")
            wallet = node_v19.get_wallet_rpc("w2")
            info = wallet.getwalletinfo()
            assert info['private_keys_enabled'] == False
            assert info['keypoolsize'] == 0

            node_v19.loadwallet("w3")
            wallet = node_v19.get_wallet_rpc("w3")
            info = wallet.getwalletinfo()
            assert info['private_keys_enabled']
            assert info['keypoolsize'] == 0

            # Open the wallets in v0.18
            node_v18.loadwallet("w1")
            wallet = node_v18.get_wallet_rpc("w1")
            info = wallet.getwalletinfo()
            assert info['private_keys_enabled']
            assert info['keypoolsize'] > 0
            txs = wallet.listtransactions()
            assert_equal(len(txs), 5)
            assert_equal(txs[1]["txid"], tx1_id)
            assert_equal(txs[2]["walletconflicts"], [tx1_id])
            assert_equal(txs[1]["replaced_by_txid"], tx2_id)
            assert not (txs[1]["abandoned"])
            assert_equal(txs[1]["confirmations"], -1)
            assert_equal(txs[2]["blockindex"], 1)
            assert txs[3]["abandoned"]
            assert_equal(txs[4]["walletconflicts"], [tx3_id])
            assert_equal(txs[3]["replaced_by_txid"], tx4_id)
            assert not (hasattr(txs[3], "blockindex"))

            node_v18.loadwallet("w2")
            wallet = node_v18.get_wallet_rpc("w2")
            info = wallet.getwalletinfo()
            assert info['private_keys_enabled'] == False
            assert info['keypoolsize'] == 0

            node_v18.loadwallet("w3")
            wallet = node_v18.get_wallet_rpc("w3")
            info = wallet.getwalletinfo()
            assert info['private_keys_enabled']
            assert info['keypoolsize'] == 0

            node_v17.loadwallet("w1")
            wallet = node_v17.get_wallet_rpc("w1")
            info = wallet.getwalletinfo()
            assert info['private_keys_enabled']
            assert info['keypoolsize'] > 0

            node_v17.loadwallet("w2")
            wallet = node_v17.get_wallet_rpc("w2")
            info = wallet.getwalletinfo()
            assert info['private_keys_enabled'] == False
            assert info['keypoolsize'] == 0
        else:
            # Descriptor wallets appear to be corrupted wallets to old software
            assert_raises_rpc_error(
                -4,
                "Wallet file verification failed: wallet.dat corrupt, salvage failed",
                node_v19.loadwallet, "w1")
            assert_raises_rpc_error(
                -4,
                "Wallet file verification failed: wallet.dat corrupt, salvage failed",
                node_v19.loadwallet, "w2")
            assert_raises_rpc_error(
                -4,
                "Wallet file verification failed: wallet.dat corrupt, salvage failed",
                node_v19.loadwallet, "w3")
            assert_raises_rpc_error(
                -4,
                "Wallet file verification failed: wallet.dat corrupt, salvage failed",
                node_v18.loadwallet, "w1")
            assert_raises_rpc_error(
                -4,
                "Wallet file verification failed: wallet.dat corrupt, salvage failed",
                node_v18.loadwallet, "w2")
            assert_raises_rpc_error(
                -4,
                "Wallet file verification failed: wallet.dat corrupt, salvage failed",
                node_v18.loadwallet, "w3")

        # Open the wallets in v0.17
        node_v17.loadwallet("w1_v18")
        wallet = node_v17.get_wallet_rpc("w1_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled']
        assert info['keypoolsize'] > 0

        node_v17.loadwallet("w2_v18")
        wallet = node_v17.get_wallet_rpc("w2_v18")
        info = wallet.getwalletinfo()
        assert info['private_keys_enabled'] == False
        assert info['keypoolsize'] == 0

        # RPC loadwallet failure causes tngcd to exit, in addition to the RPC
        # call failure, so the following test won't work:
        # assert_raises_rpc_error(-4, "Wallet loading failed.", node_v17.loadwallet, 'w3_v18')

        # Instead, we stop node and try to launch it with the wallet:
        self.stop_node(4)
        node_v17.assert_start_raises_init_error([
            "-wallet=w3_v18"
        ], "Error: Error loading w3_v18: Wallet requires newer version of TNGC Core"
                                                )
        if self.options.descriptors:
            # Descriptor wallets appear to be corrupted wallets to old software
            node_v17.assert_start_raises_init_error(
                ["-wallet=w1"], "Error: wallet.dat corrupt, salvage failed")
            node_v17.assert_start_raises_init_error(
                ["-wallet=w2"], "Error: wallet.dat corrupt, salvage failed")
            node_v17.assert_start_raises_init_error(
                ["-wallet=w3"], "Error: wallet.dat corrupt, salvage failed")
        else:
            node_v17.assert_start_raises_init_error([
                "-wallet=w3"
            ], "Error: Error loading w3: Wallet requires newer version of TNGC Core"
                                                    )
        self.start_node(4)

        if not self.options.descriptors:
            # Descriptor wallets break compatibility, only run this test for legacy wallets
            # Open most recent wallet in v0.16 (no loadwallet RPC)
            self.restart_node(5, extra_args=["-wallet=w2"])
            wallet = node_v16.get_wallet_rpc("w2")
            info = wallet.getwalletinfo()
            assert info['keypoolsize'] == 1

        # Create upgrade wallet in v0.16
        self.restart_node(-1, extra_args=["-wallet=u1_v16"])
        wallet = node_v16.get_wallet_rpc("u1_v16")
        v16_addr = wallet.getnewaddress('', "bech32")
        v16_info = wallet.validateaddress(v16_addr)
        v16_pubkey = v16_info['pubkey']
        self.stop_node(-1)

        self.log.info("Test wallet upgrade path...")
        # u1: regular wallet, created with v0.17
        node_v17.rpc.createwallet(wallet_name="u1_v17")
        wallet = node_v17.get_wallet_rpc("u1_v17")
        address = wallet.getnewaddress("bech32")
        v17_info = wallet.getaddressinfo(address)
        hdkeypath = v17_info["hdkeypath"]
        pubkey = v17_info["pubkey"]

        # Copy the 0.16 wallet to the last TNGC Core version and open it:
        shutil.copyfile(os.path.join(node_v16_wallets_dir, "wallets/u1_v16"),
                        os.path.join(node_master_wallets_dir, "u1_v16"))
        load_res = node_master.loadwallet("u1_v16")
        # Make sure this wallet opens without warnings. See https://github.com/tngc/tngc/pull/19054
        assert_equal(load_res['warning'], '')
        wallet = node_master.get_wallet_rpc("u1_v16")
        info = wallet.getaddressinfo(v16_addr)
        descriptor = "wpkh([" + info["hdmasterfingerprint"] + hdkeypath[
            1:] + "]" + v16_pubkey + ")"
        assert_equal(info["desc"], descsum_create(descriptor))

        # Now copy that same wallet back to 0.16 to make sure no automatic upgrade breaks it
        os.remove(os.path.join(node_v16_wallets_dir, "wallets/u1_v16"))
        shutil.copyfile(os.path.join(node_master_wallets_dir, "u1_v16"),
                        os.path.join(node_v16_wallets_dir, "wallets/u1_v16"))
        self.start_node(-1, extra_args=["-wallet=u1_v16"])
        wallet = node_v16.get_wallet_rpc("u1_v16")
        info = wallet.validateaddress(v16_addr)
        assert_equal(info, v16_info)

        # Copy the 0.17 wallet to the last TNGC Core version and open it:
        node_v17.unloadwallet("u1_v17")
        shutil.copytree(os.path.join(node_v17_wallets_dir, "u1_v17"),
                        os.path.join(node_master_wallets_dir, "u1_v17"))
        node_master.loadwallet("u1_v17")
        wallet = node_master.get_wallet_rpc("u1_v17")
        info = wallet.getaddressinfo(address)
        descriptor = "wpkh([" + info["hdmasterfingerprint"] + hdkeypath[
            1:] + "]" + pubkey + ")"
        assert_equal(info["desc"], descsum_create(descriptor))

        # Now copy that same wallet back to 0.17 to make sure no automatic upgrade breaks it
        node_master.unloadwallet("u1_v17")
        shutil.rmtree(os.path.join(node_v17_wallets_dir, "u1_v17"))
        shutil.copytree(os.path.join(node_master_wallets_dir, "u1_v17"),
                        os.path.join(node_v17_wallets_dir, "u1_v17"))
        node_v17.loadwallet("u1_v17")
        wallet = node_v17.get_wallet_rpc("u1_v17")
        info = wallet.getaddressinfo(address)
        assert_equal(info, v17_info)

        # Copy the 0.19 wallet to the last TNGC Core version and open it:
        shutil.copytree(os.path.join(node_v19_wallets_dir, "w1_v19"),
                        os.path.join(node_master_wallets_dir, "w1_v19"))
        node_master.loadwallet("w1_v19")
        wallet = node_master.get_wallet_rpc("w1_v19")
        assert wallet.getaddressinfo(address_18075)["solvable"]

        # Now copy that same wallet back to 0.19 to make sure no automatic upgrade breaks it
        node_master.unloadwallet("w1_v19")
        shutil.rmtree(os.path.join(node_v19_wallets_dir, "w1_v19"))
        shutil.copytree(os.path.join(node_master_wallets_dir, "w1_v19"),
                        os.path.join(node_v19_wallets_dir, "w1_v19"))
        node_v19.loadwallet("w1_v19")
        wallet = node_v19.get_wallet_rpc("w1_v19")
        assert wallet.getaddressinfo(address_18075)["solvable"]
Beispiel #15
0
    def run_test(self):
        if self.is_wallet_compiled():
            # Setup the descriptors to be imported to the wallet
            seed = "cTdGmKFWpbvpKQ7ejrdzqYT2hhjyb3GPHnLAK7wdi5Em67YLwSm9"
            xpriv = "tprv8ZgxMBicQKsPfHCsTwkiM1KT56RXbGGTqvc2hgqzycpwbHqqpcajQeMRZoBD35kW4RtyCemu6j34Ku5DEspmgjKdt2qe4SvRch5Kk8B8A2v"
            desc_imports = [{
                "desc": descsum_create("wpkh(" + xpriv + "/0/*)"),
                "timestamp": 0,
                "active": True,
                "keypool": True,
            }, {
                "desc": descsum_create("wpkh(" + xpriv + "/1/*)"),
                "timestamp": 0,
                "active": True,
                "keypool": True,
                "internal": True,
            }]
            # Make the wallets and import the descriptors
            # Ensures that node 0 and node 1 share the same wallet for the conflicting transaction tests below.
            for i, name in enumerate(self.wallet_names):
                self.nodes[i].createwallet(
                    wallet_name=name,
                    descriptors=self.options.descriptors,
                    blank=True,
                    load_on_startup=True)
                if self.options.descriptors:
                    self.nodes[i].importdescriptors(desc_imports)
                else:
                    self.nodes[i].sethdseed(True, seed)

        self.log.info("test -blocknotify")
        block_count = 10
        blocks = self.nodes[1].generatetoaddress(
            block_count, self.nodes[1].getnewaddress()
            if self.is_wallet_compiled() else ADDRESS_BCRT1_UNSPENDABLE)

        # wait at most 10 seconds for expected number of files before reading the content
        self.wait_until(
            lambda: len(os.listdir(self.blocknotify_dir)) == block_count,
            timeout=10)

        # directory content should equal the generated blocks hashes
        assert_equal(sorted(blocks), sorted(os.listdir(self.blocknotify_dir)))

        if self.is_wallet_compiled():
            self.log.info("test -walletnotify")
            # wait at most 10 seconds for expected number of files before reading the content
            self.wait_until(
                lambda: len(os.listdir(self.walletnotify_dir)) == block_count,
                timeout=10)

            # directory content should equal the generated transaction hashes
            tx_details = list(
                map(lambda t: (t['txid'], t['blockheight'], t['blockhash']),
                    self.nodes[1].listtransactions("*", block_count)))
            self.stop_node(1)
            self.expect_wallet_notify(tx_details)

            self.log.info("test -walletnotify after rescan")
            # restart node to rescan to force wallet notifications
            self.start_node(1)
            self.connect_nodes(0, 1)

            self.wait_until(
                lambda: len(os.listdir(self.walletnotify_dir)) == block_count,
                timeout=10)

            # directory content should equal the generated transaction hashes
            tx_details = list(
                map(lambda t: (t['txid'], t['blockheight'], t['blockhash']),
                    self.nodes[1].listtransactions("*", block_count)))
            self.expect_wallet_notify(tx_details)

            # Conflicting transactions tests.
            # Generate spends from node 0, and check notifications
            # triggered by node 1
            self.log.info("test -walletnotify with conflicting transactions")
            self.nodes[0].rescanblockchain()
            self.nodes[0].generatetoaddress(100, ADDRESS_BCRT1_UNSPENDABLE)
            self.sync_blocks()

            # Generate transaction on node 0, sync mempools, and check for
            # notification on node 1.
            tx1 = self.nodes[0].sendtoaddress(
                address=ADDRESS_BCRT1_UNSPENDABLE, amount=1, replaceable=True)
            assert_equal(tx1 in self.nodes[0].getrawmempool(), True)
            self.sync_mempools()
            self.expect_wallet_notify([(tx1, -1, UNCONFIRMED_HASH_STRING)])

            # Generate bump transaction, sync mempools, and check for bump1
            # notification. In the future, per
            # https://github.com/MicroBitcoinOrg/MicroBitcoin/pull/9371, it might be better
            # to have notifications for both tx1 and bump1.
            bump1 = self.nodes[0].bumpfee(tx1)["txid"]
            assert_equal(bump1 in self.nodes[0].getrawmempool(), True)
            self.sync_mempools()
            self.expect_wallet_notify([(bump1, -1, UNCONFIRMED_HASH_STRING)])

            # Add bump1 transaction to new block, checking for a notification
            # and the correct number of confirmations.
            blockhash1 = self.nodes[0].generatetoaddress(
                1, ADDRESS_BCRT1_UNSPENDABLE)[0]
            blockheight1 = self.nodes[0].getblockcount()
            self.sync_blocks()
            self.expect_wallet_notify([(bump1, blockheight1, blockhash1)])
            assert_equal(self.nodes[1].gettransaction(bump1)["confirmations"],
                         1)

            # Generate a second transaction to be bumped.
            tx2 = self.nodes[0].sendtoaddress(
                address=ADDRESS_BCRT1_UNSPENDABLE, amount=1, replaceable=True)
            assert_equal(tx2 in self.nodes[0].getrawmempool(), True)
            self.sync_mempools()
            self.expect_wallet_notify([(tx2, -1, UNCONFIRMED_HASH_STRING)])

            # Bump tx2 as bump2 and generate a block on node 0 while
            # disconnected, then reconnect and check for notifications on node 1
            # about newly confirmed bump2 and newly conflicted tx2.
            self.disconnect_nodes(0, 1)
            bump2 = self.nodes[0].bumpfee(tx2)["txid"]
            blockhash2 = self.nodes[0].generatetoaddress(
                1, ADDRESS_BCRT1_UNSPENDABLE)[0]
            blockheight2 = self.nodes[0].getblockcount()
            assert_equal(self.nodes[0].gettransaction(bump2)["confirmations"],
                         1)
            assert_equal(tx2 in self.nodes[1].getrawmempool(), True)
            self.connect_nodes(0, 1)
            self.sync_blocks()
            self.expect_wallet_notify([(bump2, blockheight2, blockhash2),
                                       (tx2, -1, UNCONFIRMED_HASH_STRING)])
            assert_equal(self.nodes[1].gettransaction(bump2)["confirmations"],
                         1)
    def test_locked_wallet(self):
        self.log.info(
            "Test fundrawtxn with locked wallet and hardened derivation")

        self.nodes[1].encryptwallet("test")

        if self.options.descriptors:
            self.nodes[1].walletpassphrase('test', 10)
            self.nodes[1].importdescriptors([{
                'desc':
                descsum_create(
                    'pkh(tprv8ZgxMBicQKsPdYeeZbPSKd2KYLmeVKtcFA7kqCxDvDR13MQ6us8HopUR2wLcS2ZKPhLyKsqpDL2FtL73LMHcgoCL7DXsciA8eX8nbjCR2eG/0h/*h)'
                ),
                'timestamp':
                'now',
                'active':
                True
            }, {
                'desc':
                descsum_create(
                    'pkh(tprv8ZgxMBicQKsPdYeeZbPSKd2KYLmeVKtcFA7kqCxDvDR13MQ6us8HopUR2wLcS2ZKPhLyKsqpDL2FtL73LMHcgoCL7DXsciA8eX8nbjCR2eG/1h/*h)'
                ),
                'timestamp':
                'now',
                'active':
                True,
                'internal':
                True
            }])
            self.nodes[1].walletlock()

        # Drain the keypool.
        self.nodes[1].getnewaddress()
        self.nodes[1].getrawchangeaddress()
        inputs = []
        outputs = {self.nodes[0].getnewaddress(): 1099997.00}
        rawtx = self.nodes[1].createrawtransaction(inputs, outputs)
        # fund a transaction that does not require a new key for the change
        # output
        self.nodes[1].fundrawtransaction(rawtx)

        # fund a transaction that requires a new key for the change output
        # creating the key must be impossible because the wallet is locked
        outputs = {self.nodes[0].getnewaddress(): 1100000}
        rawtx = self.nodes[1].createrawtransaction(inputs, outputs)
        assert_raises_rpc_error(
            -4,
            "Transaction needs a change address, but we can't generate it. Please call keypoolrefill first.",
            self.nodes[1].fundrawtransaction, rawtx)

        # Refill the keypool.
        self.nodes[1].walletpassphrase("test", 100)
        # need to refill the keypool to get an internal change address
        self.nodes[1].keypoolrefill(8)
        self.nodes[1].walletlock()

        assert_raises_rpc_error(-13, "walletpassphrase",
                                self.nodes[1].sendtoaddress,
                                self.nodes[0].getnewaddress(), 1200000)

        oldBalance = self.nodes[0].getbalance()

        inputs = []
        outputs = {self.nodes[0].getnewaddress(): 1100000}
        rawTx = self.nodes[1].createrawtransaction(inputs, outputs)
        fundedTx = self.nodes[1].fundrawtransaction(rawTx)

        # Now we need to unlock.
        self.nodes[1].walletpassphrase("test", 600)
        signedTx = self.nodes[1].signrawtransactionwithwallet(fundedTx['hex'])
        self.nodes[1].sendrawtransaction(signedTx['hex'])
        self.nodes[1].generate(1)
        self.sync_all()

        # Make sure funds are received at node1.
        assert_equal(oldBalance + Decimal('51100000.00'),
                     self.nodes[0].getbalance())
Beispiel #17
0
    def run_test(self):
        assert_raises_rpc_error(-5, "Missing checksum",
                                self.nodes[0].deriveaddresses, "a")

        descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)#t6wfjs64"
        address = "bcrt1qjqmxmkpmxt80xz4y3746zgt0q3u3ferr34acd5"
        assert_equal(self.nodes[0].deriveaddresses(descriptor), [address])

        descriptor = descriptor[:-9]
        assert_raises_rpc_error(-5, "Missing checksum",
                                self.nodes[0].deriveaddresses, descriptor)

        descriptor_pubkey = "wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0)#s9ga3alw"
        address = "bcrt1qjqmxmkpmxt80xz4y3746zgt0q3u3ferr34acd5"
        assert_equal(self.nodes[0].deriveaddresses(descriptor_pubkey),
                     [address])

        ranged_descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)#kft60nuy"
        assert_equal(self.nodes[0].deriveaddresses(ranged_descriptor, [1, 2]),
                     [
                         "bcrt1qhku5rq7jz8ulufe2y6fkcpnlvpsta7rq4442dy",
                         "bcrt1qpgptk2gvshyl0s9lqshsmx932l9ccsv265tvaq"
                     ])
        assert_equal(self.nodes[0].deriveaddresses(ranged_descriptor, 2), [
            address, "bcrt1qhku5rq7jz8ulufe2y6fkcpnlvpsta7rq4442dy",
            "bcrt1qpgptk2gvshyl0s9lqshsmx932l9ccsv265tvaq"
        ])

        assert_raises_rpc_error(
            -8, "Range should not be specified for an un-ranged descriptor",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"
            ), [0, 2])

        assert_raises_rpc_error(
            -8, "Range must be specified for a ranged descriptor",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ))

        assert_raises_rpc_error(
            -8, "End of range is too high", self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), 10000000000)

        assert_raises_rpc_error(
            -8, "Range is too large", self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), [1000000000, 2000000000])

        assert_raises_rpc_error(
            -8, "Range specified as [begin,end] must not have begin after end",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), [2, 0])

        assert_raises_rpc_error(
            -8, "Range should be greater or equal than 0",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), [-1, 0])

        combo_descriptor = descsum_create(
            "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"
        )
        assert_equal(self.nodes[0].deriveaddresses(combo_descriptor), [
            "mtfUoUax9L4tzXARpw1oTGxWyoogp52KhJ",
            "mtfUoUax9L4tzXARpw1oTGxWyoogp52KhJ", address,
            "2NDvEwGfpEqJWfybzpKPHF2XH3jwoQV3D7x"
        ])

        hardened_without_privkey_descriptor = descsum_create(
            "wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1'/1/0)"
        )
        assert_raises_rpc_error(-5,
                                "Cannot derive script without private keys",
                                self.nodes[0].deriveaddresses,
                                hardened_without_privkey_descriptor)

        bare_multisig_descriptor = descsum_create(
            "multi(1,tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0,tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/1)"
        )
        assert_raises_rpc_error(
            -5, "Descriptor does not have a corresponding address",
            self.nodes[0].deriveaddresses, bare_multisig_descriptor)
Beispiel #18
0
    def run_test(self):
        self.generate(self.nodes[0], 161)  # block 161

        self.log.info(
            "Verify sigops are counted in GBT with pre-BIP141 rules before the fork"
        )
        txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
        tmpl = self.nodes[0].getblocktemplate({'rules': ['segwit']})
        assert_equal(tmpl['sizelimit'], 1000000)
        assert 'weightlimit' not in tmpl
        assert_equal(tmpl['sigoplimit'], 20000)
        assert_equal(tmpl['transactions'][0]['hash'], txid)
        assert_equal(tmpl['transactions'][0]['sigops'], 2)
        assert '!segwit' not in tmpl['rules']
        self.generate(self.nodes[0], 1)  # block 162

        balance_presetup = self.nodes[0].getbalance()
        self.pubkey = []
        p2sh_ids = [
        ]  # p2sh_ids[NODE][TYPE] is an array of txids that spend to P2WPKH (TYPE=0) or P2WSH (TYPE=1) scripts to an address for NODE embedded in p2sh
        wit_ids = [
        ]  # wit_ids[NODE][TYPE] is an array of txids that spend to P2WPKH (TYPE=0) or P2WSH (TYPE=1) scripts to an address for NODE via bare witness
        for i in range(3):
            key = get_generate_key()
            self.pubkey.append(key.pubkey)

            multiscript = keys_to_multisig_script([self.pubkey[-1]])
            p2sh_ms_addr = self.nodes[i].createmultisig(
                1, [self.pubkey[-1]], 'p2sh-segwit')['address']
            bip173_ms_addr = self.nodes[i].createmultisig(
                1, [self.pubkey[-1]], 'bech32')['address']
            assert_equal(p2sh_ms_addr, script_to_p2sh_p2wsh(multiscript))
            assert_equal(bip173_ms_addr, script_to_p2wsh(multiscript))

            p2sh_ms_desc = descsum_create(f"sh(wsh(multi(1,{key.privkey})))")
            bip173_ms_desc = descsum_create(f"wsh(multi(1,{key.privkey}))")
            assert_equal(self.nodes[i].deriveaddresses(p2sh_ms_desc)[0],
                         p2sh_ms_addr)
            assert_equal(self.nodes[i].deriveaddresses(bip173_ms_desc)[0],
                         bip173_ms_addr)

            sh_wpkh_desc = descsum_create(f"sh(wpkh({key.privkey}))")
            wpkh_desc = descsum_create(f"wpkh({key.privkey})")
            assert_equal(self.nodes[i].deriveaddresses(sh_wpkh_desc)[0],
                         key.p2sh_p2wpkh_addr)
            assert_equal(self.nodes[i].deriveaddresses(wpkh_desc)[0],
                         key.p2wpkh_addr)

            if self.options.descriptors:
                res = self.nodes[i].importdescriptors([
                    {
                        "desc": p2sh_ms_desc,
                        "timestamp": "now"
                    },
                    {
                        "desc": bip173_ms_desc,
                        "timestamp": "now"
                    },
                    {
                        "desc": sh_wpkh_desc,
                        "timestamp": "now"
                    },
                    {
                        "desc": wpkh_desc,
                        "timestamp": "now"
                    },
                ])
            else:
                # The nature of the legacy wallet is that this import results in also adding all of the necessary scripts
                res = self.nodes[i].importmulti([
                    {
                        "desc": p2sh_ms_desc,
                        "timestamp": "now"
                    },
                ])
            assert all([r["success"] for r in res])

            p2sh_ids.append([])
            wit_ids.append([])
            for _ in range(2):
                p2sh_ids[i].append([])
                wit_ids[i].append([])

        for _ in range(5):
            for n in range(3):
                for v in range(2):
                    wit_ids[n][v].append(
                        send_to_witness(v, self.nodes[0],
                                        find_spendable_utxo(self.nodes[0], 50),
                                        self.pubkey[n], False,
                                        Decimal("49.999")))
                    p2sh_ids[n][v].append(
                        send_to_witness(v, self.nodes[0],
                                        find_spendable_utxo(self.nodes[0], 50),
                                        self.pubkey[n], True,
                                        Decimal("49.999")))

        self.generate(self.nodes[0], 1)  # block 163

        # Make sure all nodes recognize the transactions as theirs
        assert_equal(self.nodes[0].getbalance(),
                     balance_presetup - 60 * 50 + 20 * Decimal("49.999") + 50)
        assert_equal(self.nodes[1].getbalance(), 20 * Decimal("49.999"))
        assert_equal(self.nodes[2].getbalance(), 20 * Decimal("49.999"))

        self.log.info(
            "Verify unsigned p2sh witness txs without a redeem script are invalid"
        )
        self.fail_accept(
            self.nodes[2],
            "mandatory-script-verify-flag-failed (Operation not valid with the current stack size)",
            p2sh_ids[NODE_2][P2WPKH][1],
            sign=False)
        self.fail_accept(
            self.nodes[2],
            "mandatory-script-verify-flag-failed (Operation not valid with the current stack size)",
            p2sh_ids[NODE_2][P2WSH][1],
            sign=False)

        self.generate(self.nodes[0], 1)  # block 164

        self.log.info(
            "Verify witness txs are mined as soon as segwit activates")

        send_to_witness(1,
                        self.nodes[2],
                        getutxo(wit_ids[NODE_2][P2WPKH][0]),
                        self.pubkey[0],
                        encode_p2sh=False,
                        amount=Decimal("49.998"),
                        sign=True)
        send_to_witness(1,
                        self.nodes[2],
                        getutxo(wit_ids[NODE_2][P2WSH][0]),
                        self.pubkey[0],
                        encode_p2sh=False,
                        amount=Decimal("49.998"),
                        sign=True)
        send_to_witness(1,
                        self.nodes[2],
                        getutxo(p2sh_ids[NODE_2][P2WPKH][0]),
                        self.pubkey[0],
                        encode_p2sh=False,
                        amount=Decimal("49.998"),
                        sign=True)
        send_to_witness(1,
                        self.nodes[2],
                        getutxo(p2sh_ids[NODE_2][P2WSH][0]),
                        self.pubkey[0],
                        encode_p2sh=False,
                        amount=Decimal("49.998"),
                        sign=True)

        assert_equal(len(self.nodes[2].getrawmempool()), 4)
        blockhash = self.generate(
            self.nodes[2], 1)[0]  # block 165 (first block with new rules)
        assert_equal(len(self.nodes[2].getrawmempool()), 0)
        segwit_tx_list = self.nodes[2].getblock(blockhash)["tx"]
        assert_equal(len(segwit_tx_list), 5)

        self.log.info(
            "Verify default node can't accept txs with missing witness")
        # unsigned, no scriptsig
        self.fail_accept(
            self.nodes[0],
            "non-mandatory-script-verify-flag (Witness program hash mismatch)",
            wit_ids[NODE_0][P2WPKH][0],
            sign=False)
        self.fail_accept(
            self.nodes[0],
            "non-mandatory-script-verify-flag (Witness program was passed an empty witness)",
            wit_ids[NODE_0][P2WSH][0],
            sign=False)
        self.fail_accept(
            self.nodes[0],
            "mandatory-script-verify-flag-failed (Operation not valid with the current stack size)",
            p2sh_ids[NODE_0][P2WPKH][0],
            sign=False)
        self.fail_accept(
            self.nodes[0],
            "mandatory-script-verify-flag-failed (Operation not valid with the current stack size)",
            p2sh_ids[NODE_0][P2WSH][0],
            sign=False)
        # unsigned with redeem script
        self.fail_accept(
            self.nodes[0],
            "non-mandatory-script-verify-flag (Witness program hash mismatch)",
            p2sh_ids[NODE_0][P2WPKH][0],
            sign=False,
            redeem_script=witness_script(False, self.pubkey[0]))
        self.fail_accept(
            self.nodes[0],
            "non-mandatory-script-verify-flag (Witness program was passed an empty witness)",
            p2sh_ids[NODE_0][P2WSH][0],
            sign=False,
            redeem_script=witness_script(True, self.pubkey[0]))

        self.log.info(
            "Verify block and transaction serialization rpcs return differing serializations depending on rpc serialization flag"
        )
        assert self.nodes[2].getblock(
            blockhash, False) != self.nodes[0].getblock(blockhash, False)
        assert self.nodes[1].getblock(blockhash,
                                      False) == self.nodes[2].getblock(
                                          blockhash, False)

        for tx_id in segwit_tx_list:
            tx = tx_from_hex(self.nodes[2].gettransaction(tx_id)["hex"])
            assert self.nodes[2].getrawtransaction(
                tx_id, False, blockhash) != self.nodes[0].getrawtransaction(
                    tx_id, False, blockhash)
            assert self.nodes[1].getrawtransaction(
                tx_id, False, blockhash) == self.nodes[2].getrawtransaction(
                    tx_id, False, blockhash)
            assert self.nodes[0].getrawtransaction(
                tx_id, False,
                blockhash) != self.nodes[2].gettransaction(tx_id)["hex"]
            assert self.nodes[1].getrawtransaction(
                tx_id, False,
                blockhash) == self.nodes[2].gettransaction(tx_id)["hex"]
            assert self.nodes[0].getrawtransaction(
                tx_id, False,
                blockhash) == tx.serialize_without_witness().hex()

        # Coinbase contains the witness commitment nonce, check that RPC shows us
        coinbase_txid = self.nodes[2].getblock(blockhash)['tx'][0]
        coinbase_tx = self.nodes[2].gettransaction(txid=coinbase_txid,
                                                   verbose=True)
        witnesses = coinbase_tx["decoded"]["vin"][0]["txinwitness"]
        assert_equal(len(witnesses), 1)
        assert_is_hex_string(witnesses[0])
        assert_equal(witnesses[0], '00' * 32)

        self.log.info(
            "Verify witness txs without witness data are invalid after the fork"
        )
        self.fail_accept(
            self.nodes[2],
            'non-mandatory-script-verify-flag (Witness program hash mismatch)',
            wit_ids[NODE_2][P2WPKH][2],
            sign=False)
        self.fail_accept(
            self.nodes[2],
            'non-mandatory-script-verify-flag (Witness program was passed an empty witness)',
            wit_ids[NODE_2][P2WSH][2],
            sign=False)
        self.fail_accept(
            self.nodes[2],
            'non-mandatory-script-verify-flag (Witness program hash mismatch)',
            p2sh_ids[NODE_2][P2WPKH][2],
            sign=False,
            redeem_script=witness_script(False, self.pubkey[2]))
        self.fail_accept(
            self.nodes[2],
            'non-mandatory-script-verify-flag (Witness program was passed an empty witness)',
            p2sh_ids[NODE_2][P2WSH][2],
            sign=False,
            redeem_script=witness_script(True, self.pubkey[2]))

        self.log.info("Verify default node can now use witness txs")
        self.success_mine(self.nodes[0], wit_ids[NODE_0][P2WPKH][0], True)
        self.success_mine(self.nodes[0], wit_ids[NODE_0][P2WSH][0], True)
        self.success_mine(self.nodes[0], p2sh_ids[NODE_0][P2WPKH][0], True)
        self.success_mine(self.nodes[0], p2sh_ids[NODE_0][P2WSH][0], True)

        self.log.info(
            "Verify sigops are counted in GBT with BIP141 rules after the fork"
        )
        txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
        raw_tx = self.nodes[0].getrawtransaction(txid, True)
        tmpl = self.nodes[0].getblocktemplate({'rules': ['segwit']})
        assert_greater_than_or_equal(
            tmpl['sizelimit'], 3999577
        )  # actual maximum size is lower due to minimum mandatory non-witness data
        assert_equal(tmpl['weightlimit'], 4000000)
        assert_equal(tmpl['sigoplimit'], 80000)
        assert_equal(tmpl['transactions'][0]['txid'], txid)
        expected_sigops = 9 if 'txinwitness' in raw_tx["vin"][0] else 8
        assert_equal(tmpl['transactions'][0]['sigops'], expected_sigops)
        assert '!segwit' in tmpl['rules']

        self.generate(self.nodes[0], 1)  # Mine a block to clear the gbt cache

        self.log.info(
            "Non-segwit miners are able to use GBT response after activation.")
        # Create a 3-tx chain: tx1 (non-segwit input, paying to a segwit output) ->
        #                      tx2 (segwit input, paying to a non-segwit output) ->
        #                      tx3 (non-segwit input, paying to a non-segwit output).
        # tx1 is allowed to appear in the block, but no others.
        txid1 = send_to_witness(1, self.nodes[0],
                                find_spendable_utxo(self.nodes[0], 50),
                                self.pubkey[0], False, Decimal("49.996"))
        hex_tx = self.nodes[0].gettransaction(txid)['hex']
        tx = tx_from_hex(hex_tx)
        assert tx.wit.is_null()  # This should not be a segwit input
        assert txid1 in self.nodes[0].getrawmempool()

        tx1_hex = self.nodes[0].gettransaction(txid1)['hex']
        tx1 = tx_from_hex(tx1_hex)

        # Check that wtxid is properly reported in mempool entry (txid1)
        assert_equal(int(self.nodes[0].getmempoolentry(txid1)["wtxid"], 16),
                     tx1.calc_sha256(True))

        # Check that weight and vsize are properly reported in mempool entry (txid1)
        assert_equal(self.nodes[0].getmempoolentry(txid1)["vsize"],
                     tx1.get_vsize())
        assert_equal(self.nodes[0].getmempoolentry(txid1)["weight"],
                     tx1.get_weight())

        # Now create tx2, which will spend from txid1.
        tx = CTransaction()
        tx.vin.append(CTxIn(COutPoint(int(txid1, 16), 0), b''))
        tx.vout.append(
            CTxOut(int(49.99 * COIN),
                   CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE])))
        tx2_hex = self.nodes[0].signrawtransactionwithwallet(
            tx.serialize().hex())['hex']
        txid2 = self.nodes[0].sendrawtransaction(tx2_hex)
        tx = tx_from_hex(tx2_hex)
        assert not tx.wit.is_null()

        # Check that wtxid is properly reported in mempool entry (txid2)
        assert_equal(int(self.nodes[0].getmempoolentry(txid2)["wtxid"], 16),
                     tx.calc_sha256(True))

        # Check that weight and vsize are properly reported in mempool entry (txid2)
        assert_equal(self.nodes[0].getmempoolentry(txid2)["vsize"],
                     tx.get_vsize())
        assert_equal(self.nodes[0].getmempoolentry(txid2)["weight"],
                     tx.get_weight())

        # Now create tx3, which will spend from txid2
        tx = CTransaction()
        tx.vin.append(CTxIn(COutPoint(int(txid2, 16), 0), b""))
        tx.vout.append(
            CTxOut(int(49.95 * COIN),
                   CScript([OP_TRUE, OP_DROP] * 15 + [OP_TRUE])))  # Huge fee
        tx.calc_sha256()
        txid3 = self.nodes[0].sendrawtransaction(
            hexstring=tx.serialize().hex(), maxfeerate=0)
        assert tx.wit.is_null()
        assert txid3 in self.nodes[0].getrawmempool()

        # Check that getblocktemplate includes all transactions.
        template = self.nodes[0].getblocktemplate({"rules": ["segwit"]})
        template_txids = [t['txid'] for t in template['transactions']]
        assert txid1 in template_txids
        assert txid2 in template_txids
        assert txid3 in template_txids

        # Check that wtxid is properly reported in mempool entry (txid3)
        assert_equal(int(self.nodes[0].getmempoolentry(txid3)["wtxid"], 16),
                     tx.calc_sha256(True))

        # Check that weight and vsize are properly reported in mempool entry (txid3)
        assert_equal(self.nodes[0].getmempoolentry(txid3)["vsize"],
                     tx.get_vsize())
        assert_equal(self.nodes[0].getmempoolentry(txid3)["weight"],
                     tx.get_weight())

        # Mine a block to clear the gbt cache again.
        self.generate(self.nodes[0], 1)

        if not self.options.descriptors:
            self.log.info("Verify behaviour of importaddress and listunspent")

            # Some public keys to be used later
            pubkeys = [
                "0363D44AABD0F1699138239DF2F042C3282C0671CC7A76826A55C8203D90E39242",  # cPiM8Ub4heR9NBYmgVzJQiUH1if44GSBGiqaeJySuL2BKxubvgwb
                "02D3E626B3E616FC8662B489C123349FECBFC611E778E5BE739B257EAE4721E5BF",  # cPpAdHaD6VoYbW78kveN2bsvb45Q7G5PhaPApVUGwvF8VQ9brD97
                "04A47F2CBCEFFA7B9BCDA184E7D5668D3DA6F9079AD41E422FA5FD7B2D458F2538A62F5BD8EC85C2477F39650BD391EA6250207065B2A81DA8B009FC891E898F0E",  # 91zqCU5B9sdWxzMt1ca3VzbtVm2YM6Hi5Rxn4UDtxEaN9C9nzXV
                "02A47F2CBCEFFA7B9BCDA184E7D5668D3DA6F9079AD41E422FA5FD7B2D458F2538",  # cPQFjcVRpAUBG8BA9hzr2yEzHwKoMgLkJZBBtK9vJnvGJgMjzTbd
                "036722F784214129FEB9E8129D626324F3F6716555B603FFE8300BBCB882151228",  # cQGtcm34xiLjB1v7bkRa4V3aAc9tS2UTuBZ1UnZGeSeNy627fN66
                "0266A8396EE936BF6D99D17920DB21C6C7B1AB14C639D5CD72B300297E416FD2EC",  # cTW5mR5M45vHxXkeChZdtSPozrFwFgmEvTNnanCW6wrqwaCZ1X7K
                "0450A38BD7F0AC212FEBA77354A9B036A32E0F7C81FC4E0C5ADCA7C549C4505D2522458C2D9AE3CEFD684E039194B72C8A10F9CB9D4764AB26FCC2718D421D3B84",  # 92h2XPssjBpsJN5CqSP7v9a7cf2kgDunBC6PDFwJHMACM1rrVBJ
            ]

            # Import a compressed key and an uncompressed key, generate some multisig addresses
            self.nodes[0].importprivkey(
                "92e6XLo5jVAVwrQKPNTs93oQco8f8sDNBcpv73Dsrs397fQtFQn")
            uncompressed_spendable_address = [
                "mvozP4UwyGD2mGZU4D2eMvMLPB9WkMmMQu"
            ]
            self.nodes[0].importprivkey(
                "cNC8eQ5dg3mFAVePDX4ddmPYpPbw41r9bm2jd1nLJT77e6RrzTRR")
            compressed_spendable_address = [
                "mmWQubrDomqpgSYekvsU7HWEVjLFHAakLe"
            ]
            assert not self.nodes[0].getaddressinfo(
                uncompressed_spendable_address[0])['iscompressed']
            assert self.nodes[0].getaddressinfo(
                compressed_spendable_address[0])['iscompressed']

            self.nodes[0].importpubkey(pubkeys[0])
            compressed_solvable_address = [key_to_p2pkh(pubkeys[0])]
            self.nodes[0].importpubkey(pubkeys[1])
            compressed_solvable_address.append(key_to_p2pkh(pubkeys[1]))
            self.nodes[0].importpubkey(pubkeys[2])
            uncompressed_solvable_address = [key_to_p2pkh(pubkeys[2])]

            spendable_anytime = [
            ]  # These outputs should be seen anytime after importprivkey and addmultisigaddress
            spendable_after_importaddress = [
            ]  # These outputs should be seen after importaddress
            solvable_after_importaddress = [
            ]  # These outputs should be seen after importaddress but not spendable
            unsolvable_after_importaddress = [
            ]  # These outputs should be unsolvable after importaddress
            solvable_anytime = [
            ]  # These outputs should be solvable after importpubkey
            unseen_anytime = []  # These outputs should never be seen

            uncompressed_spendable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    uncompressed_spendable_address[0],
                    compressed_spendable_address[0]
                ])['address'])
            uncompressed_spendable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    uncompressed_spendable_address[0],
                    uncompressed_spendable_address[0]
                ])['address'])
            compressed_spendable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    compressed_spendable_address[0],
                    compressed_spendable_address[0]
                ])['address'])
            uncompressed_solvable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    compressed_spendable_address[0],
                    uncompressed_solvable_address[0]
                ])['address'])
            compressed_solvable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    compressed_spendable_address[0],
                    compressed_solvable_address[0]
                ])['address'])
            compressed_solvable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    compressed_solvable_address[0],
                    compressed_solvable_address[1]
                ])['address'])

            # Test multisig_without_privkey
            # We have 2 public keys without private keys, use addmultisigaddress to add to wallet.
            # Money sent to P2SH of multisig of this should only be seen after importaddress with the BASE58 P2SH address.

            multisig_without_privkey_address = self.nodes[
                0].addmultisigaddress(2, [pubkeys[3], pubkeys[4]])['address']
            script = keys_to_multisig_script([pubkeys[3], pubkeys[4]])
            solvable_after_importaddress.append(script_to_p2sh_script(script))

            for i in compressed_spendable_address:
                v = self.nodes[0].getaddressinfo(i)
                if v['isscript']:
                    [bare, p2sh, p2wsh,
                     p2sh_p2wsh] = self.p2sh_address_to_script(v)
                    # p2sh multisig with compressed keys should always be spendable
                    spendable_anytime.extend([p2sh])
                    # bare multisig can be watched and signed, but is not treated as ours
                    solvable_after_importaddress.extend([bare])
                    # P2WSH and P2SH(P2WSH) multisig with compressed keys are spendable after direct importaddress
                    spendable_after_importaddress.extend([p2wsh, p2sh_p2wsh])
                else:
                    [
                        p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk,
                        p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk,
                        p2sh_p2wsh_p2pkh
                    ] = self.p2pkh_address_to_script(v)
                    # normal P2PKH and P2PK with compressed keys should always be spendable
                    spendable_anytime.extend([p2pkh, p2pk])
                    # P2SH_P2PK, P2SH_P2PKH with compressed keys are spendable after direct importaddress
                    spendable_after_importaddress.extend([
                        p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh,
                        p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh
                    ])
                    # P2WPKH and P2SH_P2WPKH with compressed keys should always be spendable
                    spendable_anytime.extend([p2wpkh, p2sh_p2wpkh])

            for i in uncompressed_spendable_address:
                v = self.nodes[0].getaddressinfo(i)
                if v['isscript']:
                    [bare, p2sh, p2wsh,
                     p2sh_p2wsh] = self.p2sh_address_to_script(v)
                    # p2sh multisig with uncompressed keys should always be spendable
                    spendable_anytime.extend([p2sh])
                    # bare multisig can be watched and signed, but is not treated as ours
                    solvable_after_importaddress.extend([bare])
                    # P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
                    unseen_anytime.extend([p2wsh, p2sh_p2wsh])
                else:
                    [
                        p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk,
                        p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk,
                        p2sh_p2wsh_p2pkh
                    ] = self.p2pkh_address_to_script(v)
                    # normal P2PKH and P2PK with uncompressed keys should always be spendable
                    spendable_anytime.extend([p2pkh, p2pk])
                    # P2SH_P2PK and P2SH_P2PKH are spendable after direct importaddress
                    spendable_after_importaddress.extend(
                        [p2sh_p2pk, p2sh_p2pkh])
                    # Witness output types with uncompressed keys are never seen
                    unseen_anytime.extend([
                        p2wpkh, p2sh_p2wpkh, p2wsh_p2pk, p2wsh_p2pkh,
                        p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh
                    ])

            for i in compressed_solvable_address:
                v = self.nodes[0].getaddressinfo(i)
                if v['isscript']:
                    # Multisig without private is not seen after addmultisigaddress, but seen after importaddress
                    [bare, p2sh, p2wsh,
                     p2sh_p2wsh] = self.p2sh_address_to_script(v)
                    solvable_after_importaddress.extend(
                        [bare, p2sh, p2wsh, p2sh_p2wsh])
                else:
                    [
                        p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk,
                        p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk,
                        p2sh_p2wsh_p2pkh
                    ] = self.p2pkh_address_to_script(v)
                    # normal P2PKH, P2PK, P2WPKH and P2SH_P2WPKH with compressed keys should always be seen
                    solvable_anytime.extend([p2pkh, p2pk, p2wpkh, p2sh_p2wpkh])
                    # P2SH_P2PK, P2SH_P2PKH with compressed keys are seen after direct importaddress
                    solvable_after_importaddress.extend([
                        p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh,
                        p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh
                    ])

            for i in uncompressed_solvable_address:
                v = self.nodes[0].getaddressinfo(i)
                if v['isscript']:
                    [bare, p2sh, p2wsh,
                     p2sh_p2wsh] = self.p2sh_address_to_script(v)
                    # Base uncompressed multisig without private is not seen after addmultisigaddress, but seen after importaddress
                    solvable_after_importaddress.extend([bare, p2sh])
                    # P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
                    unseen_anytime.extend([p2wsh, p2sh_p2wsh])
                else:
                    [
                        p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk,
                        p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk,
                        p2sh_p2wsh_p2pkh
                    ] = self.p2pkh_address_to_script(v)
                    # normal P2PKH and P2PK with uncompressed keys should always be seen
                    solvable_anytime.extend([p2pkh, p2pk])
                    # P2SH_P2PK, P2SH_P2PKH with uncompressed keys are seen after direct importaddress
                    solvable_after_importaddress.extend(
                        [p2sh_p2pk, p2sh_p2pkh])
                    # Witness output types with uncompressed keys are never seen
                    unseen_anytime.extend([
                        p2wpkh, p2sh_p2wpkh, p2wsh_p2pk, p2wsh_p2pkh,
                        p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh
                    ])

            op1 = CScript([OP_1])
            op0 = CScript([OP_0])
            # 2N7MGY19ti4KDMSzRfPAssP6Pxyuxoi6jLe is the P2SH(P2PKH) version of mjoE3sSrb8ByYEvgnC3Aox86u1CHnfJA4V
            unsolvable_address_key = bytes.fromhex(
                "02341AEC7587A51CDE5279E0630A531AEA2615A9F80B17E8D9376327BAEAA59E3D"
            )
            unsolvablep2pkh = key_to_p2pkh_script(unsolvable_address_key)
            unsolvablep2wshp2pkh = script_to_p2wsh_script(unsolvablep2pkh)
            p2shop0 = script_to_p2sh_script(op0)
            p2wshop1 = script_to_p2wsh_script(op1)
            unsolvable_after_importaddress.append(unsolvablep2pkh)
            unsolvable_after_importaddress.append(unsolvablep2wshp2pkh)
            unsolvable_after_importaddress.append(
                op1)  # OP_1 will be imported as script
            unsolvable_after_importaddress.append(p2wshop1)
            unseen_anytime.append(
                op0
            )  # OP_0 will be imported as P2SH address with no script provided
            unsolvable_after_importaddress.append(p2shop0)

            spendable_txid = []
            solvable_txid = []
            spendable_txid.append(
                self.mine_and_test_listunspent(spendable_anytime, 2))
            solvable_txid.append(
                self.mine_and_test_listunspent(solvable_anytime, 1))
            self.mine_and_test_listunspent(
                spendable_after_importaddress + solvable_after_importaddress +
                unseen_anytime + unsolvable_after_importaddress, 0)

            importlist = []
            for i in compressed_spendable_address + uncompressed_spendable_address + compressed_solvable_address + uncompressed_solvable_address:
                v = self.nodes[0].getaddressinfo(i)
                if v['isscript']:
                    bare = bytes.fromhex(v['hex'])
                    importlist.append(bare.hex())
                    importlist.append(script_to_p2wsh_script(bare).hex())
                else:
                    pubkey = bytes.fromhex(v['pubkey'])
                    p2pk = key_to_p2pk_script(pubkey)
                    p2pkh = key_to_p2pkh_script(pubkey)
                    importlist.append(p2pk.hex())
                    importlist.append(p2pkh.hex())
                    importlist.append(key_to_p2wpkh_script(pubkey).hex())
                    importlist.append(script_to_p2wsh_script(p2pk).hex())
                    importlist.append(script_to_p2wsh_script(p2pkh).hex())

            importlist.append(unsolvablep2pkh.hex())
            importlist.append(unsolvablep2wshp2pkh.hex())
            importlist.append(op1.hex())
            importlist.append(p2wshop1.hex())

            for i in importlist:
                # import all generated addresses. The wallet already has the private keys for some of these, so catch JSON RPC
                # exceptions and continue.
                try_rpc(
                    -4,
                    "The wallet already contains the private key for this address or script",
                    self.nodes[0].importaddress, i, "", False, True)

            self.nodes[0].importaddress(
                script_to_p2sh(op0))  # import OP_0 as address only
            self.nodes[0].importaddress(multisig_without_privkey_address
                                        )  # Test multisig_without_privkey

            spendable_txid.append(
                self.mine_and_test_listunspent(
                    spendable_anytime + spendable_after_importaddress, 2))
            solvable_txid.append(
                self.mine_and_test_listunspent(
                    solvable_anytime + solvable_after_importaddress, 1))
            self.mine_and_test_listunspent(unsolvable_after_importaddress, 1)
            self.mine_and_test_listunspent(unseen_anytime, 0)

            spendable_txid.append(
                self.mine_and_test_listunspent(
                    spendable_anytime + spendable_after_importaddress, 2))
            solvable_txid.append(
                self.mine_and_test_listunspent(
                    solvable_anytime + solvable_after_importaddress, 1))
            self.mine_and_test_listunspent(unsolvable_after_importaddress, 1)
            self.mine_and_test_listunspent(unseen_anytime, 0)

            # Repeat some tests. This time we don't add witness scripts with importaddress
            # Import a compressed key and an uncompressed key, generate some multisig addresses
            self.nodes[0].importprivkey(
                "927pw6RW8ZekycnXqBQ2JS5nPyo1yRfGNN8oq74HeddWSpafDJH")
            uncompressed_spendable_address = [
                "mguN2vNSCEUh6rJaXoAVwY3YZwZvEmf5xi"
            ]
            self.nodes[0].importprivkey(
                "cMcrXaaUC48ZKpcyydfFo8PxHAjpsYLhdsp6nmtB3E2ER9UUHWnw")
            compressed_spendable_address = [
                "n1UNmpmbVUJ9ytXYXiurmGPQ3TRrXqPWKL"
            ]

            self.nodes[0].importpubkey(pubkeys[5])
            compressed_solvable_address = [key_to_p2pkh(pubkeys[5])]
            self.nodes[0].importpubkey(pubkeys[6])
            uncompressed_solvable_address = [key_to_p2pkh(pubkeys[6])]

            unseen_anytime = []  # These outputs should never be seen
            solvable_anytime = [
            ]  # These outputs should be solvable after importpubkey
            unseen_anytime = []  # These outputs should never be seen

            uncompressed_spendable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    uncompressed_spendable_address[0],
                    compressed_spendable_address[0]
                ])['address'])
            uncompressed_spendable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    uncompressed_spendable_address[0],
                    uncompressed_spendable_address[0]
                ])['address'])
            compressed_spendable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    compressed_spendable_address[0],
                    compressed_spendable_address[0]
                ])['address'])
            uncompressed_solvable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    compressed_solvable_address[0],
                    uncompressed_solvable_address[0]
                ])['address'])
            compressed_solvable_address.append(
                self.nodes[0].addmultisigaddress(2, [
                    compressed_spendable_address[0],
                    compressed_solvable_address[0]
                ])['address'])

            premature_witaddress = []

            for i in compressed_spendable_address:
                v = self.nodes[0].getaddressinfo(i)
                if v['isscript']:
                    [bare, p2sh, p2wsh,
                     p2sh_p2wsh] = self.p2sh_address_to_script(v)
                    premature_witaddress.append(script_to_p2sh(p2wsh))
                else:
                    [
                        p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk,
                        p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk,
                        p2sh_p2wsh_p2pkh
                    ] = self.p2pkh_address_to_script(v)
                    # P2WPKH, P2SH_P2WPKH are always spendable
                    spendable_anytime.extend([p2wpkh, p2sh_p2wpkh])

            for i in uncompressed_spendable_address + uncompressed_solvable_address:
                v = self.nodes[0].getaddressinfo(i)
                if v['isscript']:
                    [bare, p2sh, p2wsh,
                     p2sh_p2wsh] = self.p2sh_address_to_script(v)
                    # P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
                    unseen_anytime.extend([p2wsh, p2sh_p2wsh])
                else:
                    [
                        p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk,
                        p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk,
                        p2sh_p2wsh_p2pkh
                    ] = self.p2pkh_address_to_script(v)
                    # P2WPKH, P2SH_P2WPKH with uncompressed keys are never seen
                    unseen_anytime.extend([p2wpkh, p2sh_p2wpkh])

            for i in compressed_solvable_address:
                v = self.nodes[0].getaddressinfo(i)
                if v['isscript']:
                    [bare, p2sh, p2wsh,
                     p2sh_p2wsh] = self.p2sh_address_to_script(v)
                    premature_witaddress.append(script_to_p2sh(p2wsh))
                else:
                    [
                        p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk,
                        p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk,
                        p2sh_p2wsh_p2pkh
                    ] = self.p2pkh_address_to_script(v)
                    # P2SH_P2PK, P2SH_P2PKH with compressed keys are always solvable
                    solvable_anytime.extend([p2wpkh, p2sh_p2wpkh])

            self.mine_and_test_listunspent(spendable_anytime, 2)
            self.mine_and_test_listunspent(solvable_anytime, 1)
            self.mine_and_test_listunspent(unseen_anytime, 0)

            # Check that createrawtransaction/decoderawtransaction with non-v0 Bech32 works
            v1_addr = program_to_witness(1, [3, 5])
            v1_tx = self.nodes[0].createrawtransaction(
                [getutxo(spendable_txid[0])], {v1_addr: 1})
            v1_decoded = self.nodes[1].decoderawtransaction(v1_tx)
            assert_equal(v1_decoded['vout'][0]['scriptPubKey']['address'],
                         v1_addr)
            assert_equal(v1_decoded['vout'][0]['scriptPubKey']['hex'],
                         "51020305")

            # Check that spendable outputs are really spendable
            self.create_and_mine_tx_from_txids(spendable_txid)

            # import all the private keys so solvable addresses become spendable
            self.nodes[0].importprivkey(
                "cPiM8Ub4heR9NBYmgVzJQiUH1if44GSBGiqaeJySuL2BKxubvgwb")
            self.nodes[0].importprivkey(
                "cPpAdHaD6VoYbW78kveN2bsvb45Q7G5PhaPApVUGwvF8VQ9brD97")
            self.nodes[0].importprivkey(
                "91zqCU5B9sdWxzMt1ca3VzbtVm2YM6Hi5Rxn4UDtxEaN9C9nzXV")
            self.nodes[0].importprivkey(
                "cPQFjcVRpAUBG8BA9hzr2yEzHwKoMgLkJZBBtK9vJnvGJgMjzTbd")
            self.nodes[0].importprivkey(
                "cQGtcm34xiLjB1v7bkRa4V3aAc9tS2UTuBZ1UnZGeSeNy627fN66")
            self.nodes[0].importprivkey(
                "cTW5mR5M45vHxXkeChZdtSPozrFwFgmEvTNnanCW6wrqwaCZ1X7K")
            self.create_and_mine_tx_from_txids(solvable_txid)

            # Test that importing native P2WPKH/P2WSH scripts works
            for use_p2wsh in [False, True]:
                if use_p2wsh:
                    scriptPubKey = "00203a59f3f56b713fdcf5d1a57357f02c44342cbf306ffe0c4741046837bf90561a"
                    transaction = "01000000000100e1f505000000002200203a59f3f56b713fdcf5d1a57357f02c44342cbf306ffe0c4741046837bf90561a00000000"
                else:
                    scriptPubKey = "a9142f8c469c2f0084c48e11f998ffbe7efa7549f26d87"
                    transaction = "01000000000100e1f5050000000017a9142f8c469c2f0084c48e11f998ffbe7efa7549f26d8700000000"

                self.nodes[1].importaddress(scriptPubKey, "", False)
                rawtxfund = self.nodes[1].fundrawtransaction(
                    transaction)['hex']
                rawtxfund = self.nodes[1].signrawtransactionwithwallet(
                    rawtxfund)["hex"]
                txid = self.nodes[1].sendrawtransaction(rawtxfund)

                assert_equal(self.nodes[1].gettransaction(txid, True)["txid"],
                             txid)
                assert_equal(
                    self.nodes[1].listtransactions("*", 1, 0, True)[0]["txid"],
                    txid)

                # Assert it is properly saved
                self.restart_node(1)
                assert_equal(self.nodes[1].gettransaction(txid, True)["txid"],
                             txid)
                assert_equal(
                    self.nodes[1].listtransactions("*", 1, 0, True)[0]["txid"],
                    txid)
Beispiel #19
0
    def run_test(self):
        self.log.info("Setup wallets...")
        # w0 is a wallet with coinbase rewards
        w0 = self.nodes[0].get_wallet_rpc(self.default_wallet_name)
        # w1 is a regular wallet
        self.nodes[1].createwallet(wallet_name="w1")
        w1 = self.nodes[1].get_wallet_rpc("w1")
        # w2 contains the private keys for w3
        self.nodes[1].createwallet(wallet_name="w2", blank=True)
        w2 = self.nodes[1].get_wallet_rpc("w2")
        xpriv = "tprv8ZgxMBicQKsPfHCsTwkiM1KT56RXbGGTqvc2hgqzycpwbHqqpcajQeMRZoBD35kW4RtyCemu6j34Ku5DEspmgjKdt2qe4SvRch5Kk8B8A2v"
        xpub = "tpubD6NzVbkrYhZ4YkEfMbRJkQyZe7wTkbTNRECozCtJPtdLRn6cT1QKb8yHjwAPcAr26eHBFYs5iLiFFnCbwPRsncCKUKCfubHDMGKzMVcN1Jg"
        if self.options.descriptors:
            w2.importdescriptors([{
                "desc":
                descsum_create("wpkh(" + xpriv + "/0/0/*)"),
                "timestamp":
                "now",
                "range": [0, 100],
                "active":
                True
            }, {
                "desc":
                descsum_create("wpkh(" + xpriv + "/0/1/*)"),
                "timestamp":
                "now",
                "range": [0, 100],
                "active":
                True,
                "internal":
                True
            }])
        else:
            w2.sethdseed(True)

        # w3 is a watch-only wallet, based on w2
        self.nodes[1].createwallet(wallet_name="w3", disable_private_keys=True)
        w3 = self.nodes[1].get_wallet_rpc("w3")
        if self.options.descriptors:
            # Match the privkeys in w2 for descriptors
            res = w3.importdescriptors([{
                "desc":
                descsum_create("wpkh(" + xpub + "/0/0/*)"),
                "timestamp":
                "now",
                "range": [0, 100],
                "keypool":
                True,
                "active":
                True,
                "watchonly":
                True
            }, {
                "desc":
                descsum_create("wpkh(" + xpub + "/0/1/*)"),
                "timestamp":
                "now",
                "range": [0, 100],
                "keypool":
                True,
                "active":
                True,
                "internal":
                True,
                "watchonly":
                True
            }])
            assert_equal(res, [{"success": True}, {"success": True}])

        for _ in range(3):
            a2_receive = w2.getnewaddress()
            if not self.options.descriptors:
                # Because legacy wallets use exclusively hardened derivation, we can't do a ranged import like we do for descriptors
                a2_change = w2.getrawchangeaddress(
                )  # doesn't actually use change derivation
                res = w3.importmulti([{
                    "desc":
                    w2.getaddressinfo(a2_receive)["desc"],
                    "timestamp":
                    "now",
                    "keypool":
                    True,
                    "watchonly":
                    True
                }, {
                    "desc":
                    w2.getaddressinfo(a2_change)["desc"],
                    "timestamp":
                    "now",
                    "keypool":
                    True,
                    "internal":
                    True,
                    "watchonly":
                    True
                }])
                assert_equal(res, [{"success": True}, {"success": True}])

        w0.sendtoaddress(a2_receive, 10)  # fund w3
        self.nodes[0].generate(1)
        self.sync_blocks()

        if not self.options.descriptors:
            # w4 has private keys enabled, but only contains watch-only keys (from w2)
            # This is legacy wallet behavior only as descriptor wallets don't allow watchonly and non-watchonly things in the same wallet.
            self.nodes[1].createwallet(wallet_name="w4",
                                       disable_private_keys=False)
            w4 = self.nodes[1].get_wallet_rpc("w4")
            for _ in range(3):
                a2_receive = w2.getnewaddress()
                res = w4.importmulti([{
                    "desc":
                    w2.getaddressinfo(a2_receive)["desc"],
                    "timestamp":
                    "now",
                    "keypool":
                    False,
                    "watchonly":
                    True
                }])
                assert_equal(res, [{"success": True}])

            w0.sendtoaddress(a2_receive, 10)  # fund w4
            self.nodes[0].generate(1)
            self.sync_blocks()

        self.log.info("Send to address...")
        self.test_send(from_wallet=w0, to_wallet=w1, amount=1)
        self.test_send(from_wallet=w0,
                       to_wallet=w1,
                       amount=1,
                       add_to_wallet=True)

        self.log.info("Don't broadcast...")
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             add_to_wallet=False)
        assert (res["hex"])

        self.log.info("Return PSBT...")
        res = self.test_send(from_wallet=w0, to_wallet=w1, amount=1, psbt=True)
        assert (res["psbt"])

        self.log.info(
            "Create transaction that spends to address, but don't broadcast..."
        )
        self.test_send(from_wallet=w0,
                       to_wallet=w1,
                       amount=1,
                       add_to_wallet=False)
        # conf_target & estimate_mode can be set as argument or option
        res1 = self.test_send(from_wallet=w0,
                              to_wallet=w1,
                              amount=1,
                              arg_conf_target=1,
                              arg_estimate_mode="economical",
                              add_to_wallet=False)
        res2 = self.test_send(from_wallet=w0,
                              to_wallet=w1,
                              amount=1,
                              conf_target=1,
                              estimate_mode="economical",
                              add_to_wallet=False)
        assert_equal(self.nodes[1].decodepsbt(res1["psbt"])["fee"],
                     self.nodes[1].decodepsbt(res2["psbt"])["fee"])
        # but not at the same time
        for mode in ["unset", "economical", "conservative"]:
            self.test_send(
                from_wallet=w0,
                to_wallet=w1,
                amount=1,
                arg_conf_target=1,
                arg_estimate_mode="economical",
                conf_target=1,
                estimate_mode=mode,
                add_to_wallet=False,
                expect_error=
                (-8,
                 "Pass conf_target and estimate_mode either as arguments or in the options object, but not both"
                 ))

        self.log.info("Create PSBT from watch-only wallet w3, sign with w2...")
        res = self.test_send(from_wallet=w3, to_wallet=w1, amount=1)
        res = w2.walletprocesspsbt(res["psbt"])
        assert res["complete"]

        if not self.options.descriptors:
            # Descriptor wallets do not allow mixed watch-only and non-watch-only things in the same wallet.
            # This is specifically testing that w4 ignores its own private keys and creates a psbt with send
            # which is not something that needs to be tested in descriptor wallets.
            self.log.info(
                "Create PSBT from wallet w4 with watch-only keys, sign with w2..."
            )
            self.test_send(from_wallet=w4,
                           to_wallet=w1,
                           amount=1,
                           expect_error=(-4, "Insufficient funds"))
            res = self.test_send(from_wallet=w4,
                                 to_wallet=w1,
                                 amount=1,
                                 include_watching=True,
                                 add_to_wallet=False)
            res = w2.walletprocesspsbt(res["psbt"])
            assert res["complete"]

        self.log.info("Create OP_RETURN...")
        self.test_send(from_wallet=w0, to_wallet=w1, amount=1)
        self.test_send(
            from_wallet=w0,
            data="Hello World",
            expect_error=(
                -8, "Data must be hexadecimal string (not 'Hello World')"))
        self.test_send(from_wallet=w0, data="23")
        res = self.test_send(from_wallet=w3, data="23")
        res = w2.walletprocesspsbt(res["psbt"])
        assert res["complete"]

        self.log.info("Test setting explicit fee rate")
        res1 = self.test_send(from_wallet=w0,
                              to_wallet=w1,
                              amount=1,
                              arg_fee_rate="1",
                              add_to_wallet=False)
        res2 = self.test_send(from_wallet=w0,
                              to_wallet=w1,
                              amount=1,
                              fee_rate="1",
                              add_to_wallet=False)
        assert_equal(self.nodes[1].decodepsbt(res1["psbt"])["fee"],
                     self.nodes[1].decodepsbt(res2["psbt"])["fee"])

        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             fee_rate=7,
                             add_to_wallet=False)
        fee = self.nodes[1].decodepsbt(res["psbt"])["fee"]
        assert_fee_amount(fee, Decimal(len(res["hex"]) / 2),
                          Decimal("0.00007"))

        # "unset" and None are treated the same for estimate_mode
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             fee_rate=2,
                             estimate_mode="unset",
                             add_to_wallet=False)
        fee = self.nodes[1].decodepsbt(res["psbt"])["fee"]
        assert_fee_amount(fee, Decimal(len(res["hex"]) / 2),
                          Decimal("0.00002"))

        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             arg_fee_rate=4.531,
                             add_to_wallet=False)
        fee = self.nodes[1].decodepsbt(res["psbt"])["fee"]
        assert_fee_amount(fee, Decimal(len(res["hex"]) / 2),
                          Decimal("0.00004531"))

        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             arg_fee_rate=3,
                             add_to_wallet=False)
        fee = self.nodes[1].decodepsbt(res["psbt"])["fee"]
        assert_fee_amount(fee, Decimal(len(res["hex"]) / 2),
                          Decimal("0.00003"))

        # Test that passing fee_rate as both an argument and an option raises.
        self.test_send(
            from_wallet=w0,
            to_wallet=w1,
            amount=1,
            arg_fee_rate=1,
            fee_rate=1,
            add_to_wallet=False,
            expect_error=
            (-8,
             "Pass the fee_rate either as an argument, or in the options object, but not both"
             ))

        assert_raises_rpc_error(-8, "Use fee_rate (sat/vB) instead of feeRate",
                                w0.send, {w1.getnewaddress(): 1}, 6,
                                "conservative", 1, {"feeRate": 0.01})

        assert_raises_rpc_error(-3, "Unexpected key totalFee", w0.send,
                                {w1.getnewaddress(): 1}, 6, "conservative", 1,
                                {"totalFee": 0.01})

        for target, mode in product([-1, 0, 1009],
                                    ["economical", "conservative"]):
            self.test_send(
                from_wallet=w0,
                to_wallet=w1,
                amount=1,
                conf_target=target,
                estimate_mode=mode,
                expect_error=(-8,
                              "Invalid conf_target, must be between 1 and 1008"
                              ))  # max value of 1008 per src/policy/fees.h
        msg = 'Invalid estimate_mode parameter, must be one of: "unset", "economical", "conservative"'
        for target, mode in product([-1, 0], ["btc/kb", "sat/b"]):
            self.test_send(from_wallet=w0,
                           to_wallet=w1,
                           amount=1,
                           conf_target=target,
                           estimate_mode=mode,
                           expect_error=(-8, msg))
        for mode in ["", "foo", Decimal("3.141592")]:
            self.test_send(from_wallet=w0,
                           to_wallet=w1,
                           amount=1,
                           conf_target=0.1,
                           estimate_mode=mode,
                           expect_error=(-8, msg))
            self.test_send(from_wallet=w0,
                           to_wallet=w1,
                           amount=1,
                           arg_conf_target=0.1,
                           arg_estimate_mode=mode,
                           expect_error=(-8, msg))
            assert_raises_rpc_error(-8, msg, w0.send, {w1.getnewaddress(): 1},
                                    0.1, mode)

        for mode in ["economical", "conservative", "btc/kb", "sat/b"]:
            self.log.debug("{}".format(mode))
            for k, v in {"string": "true", "object": {"foo": "bar"}}.items():
                self.test_send(
                    from_wallet=w0,
                    to_wallet=w1,
                    amount=1,
                    conf_target=v,
                    estimate_mode=mode,
                    expect_error=(
                        -3,
                        "Expected type number for conf_target, got {}".format(
                            k)))

        # Test setting explicit fee rate just below the minimum and at zero.
        self.log.info(
            "Explicit fee rate raises RPC error 'fee rate too low' if fee_rate of 0.99999999 is passed"
        )
        self.test_send(
            from_wallet=w0,
            to_wallet=w1,
            amount=1,
            fee_rate=0.99999999,
            expect_error=
            (-4,
             "Fee rate (0.999 sat/vB) is lower than the minimum fee rate setting (1.000 sat/vB)"
             ))
        self.test_send(
            from_wallet=w0,
            to_wallet=w1,
            amount=1,
            arg_fee_rate=0.99999999,
            expect_error=
            (-4,
             "Fee rate (0.999 sat/vB) is lower than the minimum fee rate setting (1.000 sat/vB)"
             ))
        self.test_send(
            from_wallet=w0,
            to_wallet=w1,
            amount=1,
            fee_rate=0,
            expect_error=
            (-4,
             "Fee rate (0.000 sat/vB) is lower than the minimum fee rate setting (1.000 sat/vB)"
             ))
        self.test_send(
            from_wallet=w0,
            to_wallet=w1,
            amount=1,
            arg_fee_rate=0,
            expect_error=
            (-4,
             "Fee rate (0.000 sat/vB) is lower than the minimum fee rate setting (1.000 sat/vB)"
             ))

        # TODO: Return hex if fee rate is below -maxmempool
        # res = self.test_send(from_wallet=w0, to_wallet=w1, amount=1, conf_target=0.1, estimate_mode="sat/b", add_to_wallet=False)
        # assert res["hex"]
        # hex = res["hex"]
        # res = self.nodes[0].testmempoolaccept([hex])
        # assert not res[0]["allowed"]
        # assert_equal(res[0]["reject-reason"], "...") # low fee
        # assert_fee_amount(fee, Decimal(len(res["hex"]) / 2), Decimal("0.000001"))

        self.log.info(
            "If inputs are specified, do not automatically add more...")
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=51,
                             inputs=[],
                             add_to_wallet=False)
        assert res["complete"]
        utxo1 = w0.listunspent()[0]
        assert_equal(utxo1["amount"], 50)
        self.test_send(from_wallet=w0,
                       to_wallet=w1,
                       amount=51,
                       inputs=[utxo1],
                       expect_error=(-4, "Insufficient funds"))
        self.test_send(from_wallet=w0,
                       to_wallet=w1,
                       amount=51,
                       inputs=[utxo1],
                       add_inputs=False,
                       expect_error=(-4, "Insufficient funds"))
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=51,
                             inputs=[utxo1],
                             add_inputs=True,
                             add_to_wallet=False)
        assert res["complete"]

        self.log.info("Manual change address and position...")
        self.test_send(
            from_wallet=w0,
            to_wallet=w1,
            amount=1,
            change_address="not an address",
            expect_error=(-5,
                          "Change address must be a valid bitcoin address"))
        change_address = w0.getnewaddress()
        self.test_send(from_wallet=w0,
                       to_wallet=w1,
                       amount=1,
                       add_to_wallet=False,
                       change_address=change_address)
        assert res["complete"]
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             add_to_wallet=False,
                             change_address=change_address,
                             change_position=0)
        assert res["complete"]
        assert_equal(
            self.nodes[0].decodepsbt(
                res["psbt"])["tx"]["vout"][0]["scriptPubKey"]["address"],
            change_address)
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             add_to_wallet=False,
                             change_type="legacy",
                             change_position=0)
        assert res["complete"]
        change_address = self.nodes[0].decodepsbt(
            res["psbt"])["tx"]["vout"][0]["scriptPubKey"]["address"]
        assert change_address[0] == "m" or change_address[0] == "n"

        self.log.info("Set lock time...")
        height = self.nodes[0].getblockchaininfo()["blocks"]
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             locktime=height + 1)
        assert res["complete"]
        assert res["txid"]
        txid = res["txid"]
        # Although the wallet finishes the transaction, it can't be added to the mempool yet:
        hex = self.nodes[0].gettransaction(res["txid"])["hex"]
        res = self.nodes[0].testmempoolaccept([hex])
        assert not res[0]["allowed"]
        assert_equal(res[0]["reject-reason"], "non-final")
        # It shouldn't be confirmed in the next block
        self.nodes[0].generate(1)
        assert_equal(self.nodes[0].gettransaction(txid)["confirmations"], 0)
        # The mempool should allow it now:
        res = self.nodes[0].testmempoolaccept([hex])
        assert res[0]["allowed"]
        # Don't wait for wallet to add it to the mempool:
        res = self.nodes[0].sendrawtransaction(hex)
        self.nodes[0].generate(1)
        assert_equal(self.nodes[0].gettransaction(txid)["confirmations"], 1)
        self.sync_all()

        self.log.info("Lock unspents...")
        utxo1 = w0.listunspent()[0]
        assert_greater_than(utxo1["amount"], 1)
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             inputs=[utxo1],
                             add_to_wallet=False,
                             lock_unspents=True)
        assert res["complete"]
        locked_coins = w0.listlockunspent()
        assert_equal(len(locked_coins), 1)
        # Locked coins are automatically unlocked when manually selected
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             inputs=[utxo1],
                             add_to_wallet=False)
        assert res["complete"]

        self.log.info("Replaceable...")
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             add_to_wallet=True,
                             replaceable=True)
        assert res["complete"]
        assert_equal(
            self.nodes[0].gettransaction(res["txid"])["bip125-replaceable"],
            "yes")
        res = self.test_send(from_wallet=w0,
                             to_wallet=w1,
                             amount=1,
                             add_to_wallet=True,
                             replaceable=False)
        assert res["complete"]
        assert_equal(
            self.nodes[0].gettransaction(res["txid"])["bip125-replaceable"],
            "no")

        self.log.info("Subtract fee from output")
        self.test_send(from_wallet=w0,
                       to_wallet=w1,
                       amount=1,
                       subtract_fee_from_outputs=[0])
Beispiel #20
0
    def run_test(self):
        self.log.info("Mining blocks...")
        self.nodes[0].generate(1)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        node0_address1 = self.nodes[0].getaddressinfo(
            self.nodes[0].getnewaddress())

        # Check only one address
        assert_equal(node0_address1['ismine'], True)

        # Node 1 sync test
        assert_equal(self.nodes[1].getblockcount(), 1)

        # Address Test - before import
        address_info = self.nodes[1].getaddressinfo(node0_address1['address'])
        assert_equal(address_info['iswatchonly'], False)
        assert_equal(address_info['ismine'], False)

        # RPC importmulti -----------------------------------------------

        # bitmonkey Address (implicit non-internal)
        self.log.info("Should import an address")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp,
                     ischange=False)
        watchonly_address = key.p2pkh_addr
        watchonly_timestamp = timestamp

        self.log.info("Should not import an invalid address")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": "not valid address"
                },
                "timestamp": "now"
            },
            success=False,
            error_code=-5,
            error_message='Invalid address \"not valid address\"')

        # ScriptPubKey + internal
        self.log.info("Should import a scriptPubKey with internal flag")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "internal": True
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp,
                     ischange=True)

        # ScriptPubKey + internal + label
        self.log.info(
            "Should not allow a label to be specified when internal is true")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "internal": True,
                "label": "Example label"
            },
            success=False,
            error_code=-8,
            error_message='Internal addresses should not have a label')

        # Nonstandard scriptPubKey + !internal
        self.log.info(
            "Should not import a nonstandard scriptPubKey without internal flag"
        )
        nonstandardScriptPubKey = key.p2pkh_script + CScript([OP_NOP]).hex()
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": nonstandardScriptPubKey,
                "timestamp": "now"
            },
            success=False,
            error_code=-8,
            error_message=
            'Internal must be set to true for nonstandard scriptPubKey imports.'
        )
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=False,
                     timestamp=None)

        # Address + Public key + !Internal(explicit)
        self.log.info("Should import an address with public key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "pubkeys": [key.pubkey],
                "internal": False
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp)

        # ScriptPubKey + Public key + internal
        self.log.info(
            "Should import a scriptPubKey with internal and with public key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "pubkeys": [key.pubkey],
                "internal": True
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp)

        # Nonstandard scriptPubKey + Public key + !internal
        self.log.info(
            "Should not import a nonstandard scriptPubKey without internal and with public key"
        )
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": nonstandardScriptPubKey,
                "timestamp": "now",
                "pubkeys": [key.pubkey]
            },
            success=False,
            error_code=-8,
            error_message=
            'Internal must be set to true for nonstandard scriptPubKey imports.'
        )
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=False,
                     timestamp=None)

        # Address + Private key + !watchonly
        self.log.info("Should import an address with private key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "keys": [key.privkey]
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=True,
                     timestamp=timestamp)

        self.log.info(
            "Should not import an address with private key if is already imported"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "keys": [key.privkey]
            },
            success=False,
            error_code=-4,
            error_message=
            'The wallet already contains the private key for this address or script ("'
            + key.p2pkh_script + '")')

        # Address + Private key + watchonly
        self.log.info(
            "Should import an address with private key and with watchonly")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "keys": [key.privkey],
                "watchonly": True
            },
            success=True,
            warnings=[
                "All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=True,
                     timestamp=timestamp)

        # ScriptPubKey + Private key + internal
        self.log.info(
            "Should import a scriptPubKey with internal and with private key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "keys": [key.privkey],
                "internal": True
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=True,
                     timestamp=timestamp)

        # Nonstandard scriptPubKey + Private key + !internal
        self.log.info(
            "Should not import a nonstandard scriptPubKey without internal and with private key"
        )
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": nonstandardScriptPubKey,
                "timestamp": "now",
                "keys": [key.privkey]
            },
            success=False,
            error_code=-8,
            error_message=
            'Internal must be set to true for nonstandard scriptPubKey imports.'
        )
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=False,
                     timestamp=None)

        # P2SH address
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        self.log.info("Should import a p2sh")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2sh_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     isscript=True,
                     iswatchonly=True,
                     timestamp=timestamp)
        p2shunspent = self.nodes[1].listunspent(0, 999999,
                                                [multisig.p2sh_addr])[0]
        assert_equal(p2shunspent['spendable'], False)
        assert_equal(p2shunspent['solvable'], False)

        # P2SH + Redeem script
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        self.log.info("Should import a p2sh with respective redeem script")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2sh_addr
                },
                "timestamp": "now",
                "redeemscript": multisig.redeem_script
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     timestamp=timestamp,
                     iswatchonly=True,
                     ismine=False,
                     solvable=True)

        p2shunspent = self.nodes[1].listunspent(0, 999999,
                                                [multisig.p2sh_addr])[0]
        assert_equal(p2shunspent['spendable'], False)
        assert_equal(p2shunspent['solvable'], True)

        # P2SH + Redeem script + Private Keys + !Watchonly
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        self.log.info(
            "Should import a p2sh with respective redeem script and private keys"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2sh_addr
                },
                "timestamp": "now",
                "redeemscript": multisig.redeem_script,
                "keys": multisig.privkeys[0:2]
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     timestamp=timestamp,
                     ismine=False,
                     iswatchonly=True,
                     solvable=True)

        p2shunspent = self.nodes[1].listunspent(0, 999999,
                                                [multisig.p2sh_addr])[0]
        assert_equal(p2shunspent['spendable'], False)
        assert_equal(p2shunspent['solvable'], True)

        # P2SH + Redeem script + Private Keys + Watchonly
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(
            self.nodes[1].getbestblockhash())['mediantime']

        self.log.info(
            "Should import a p2sh with respective redeem script and private keys"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2sh_addr
                },
                "timestamp": "now",
                "redeemscript": multisig.redeem_script,
                "keys": multisig.privkeys[0:2],
                "watchonly": True
            },
            success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=True,
                     timestamp=timestamp)

        # Address + Public key + !Internal + Wrong pubkey
        self.log.info(
            "Should not import an address with the wrong public key as non-solvable"
        )
        key = get_key(self.nodes[0])
        wrong_key = get_key(self.nodes[0]).pubkey
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "pubkeys": [wrong_key]
            },
            success=True,
            warnings=[
                "Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.",
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # ScriptPubKey + Public key + internal + Wrong pubkey
        self.log.info(
            "Should import a scriptPubKey with internal and with a wrong public key as non-solvable"
        )
        key = get_key(self.nodes[0])
        wrong_key = get_key(self.nodes[0]).pubkey
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "pubkeys": [wrong_key],
                "internal": True
            },
            success=True,
            warnings=[
                "Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.",
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # Address + Private key + !watchonly + Wrong private key
        self.log.info(
            "Should import an address with a wrong private key as non-solvable"
        )
        key = get_key(self.nodes[0])
        wrong_privkey = get_key(self.nodes[0]).privkey
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now",
                "keys": [wrong_privkey]
            },
            success=True,
            warnings=[
                "Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.",
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # ScriptPubKey + Private key + internal + Wrong private key
        self.log.info(
            "Should import a scriptPubKey with internal and with a wrong private key as non-solvable"
        )
        key = get_key(self.nodes[0])
        wrong_privkey = get_key(self.nodes[0]).privkey
        self.test_importmulti(
            {
                "scriptPubKey": key.p2pkh_script,
                "timestamp": "now",
                "keys": [wrong_privkey],
                "internal": True
            },
            success=True,
            warnings=[
                "Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.",
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # Importing existing watch only address with new timestamp should replace saved timestamp.
        assert_greater_than(timestamp, watchonly_timestamp)
        self.log.info("Should replace previously saved watch only timestamp.")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": watchonly_address
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     watchonly_address,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp)
        watchonly_timestamp = timestamp

        # restart nodes to check for proper serialization/deserialization of watch only address
        self.stop_nodes()
        self.start_nodes()
        test_address(self.nodes[1],
                     watchonly_address,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=watchonly_timestamp)

        # Bad or missing timestamps
        self.log.info("Should throw on invalid or missing timestamp values")
        assert_raises_rpc_error(-3, 'Missing required timestamp field for key',
                                self.nodes[1].importmulti,
                                [{
                                    "scriptPubKey": key.p2pkh_script
                                }])
        assert_raises_rpc_error(
            -3,
            'Expected number or "now" timestamp value for key. got type string',
            self.nodes[1].importmulti, [{
                "scriptPubKey": key.p2pkh_script,
                "timestamp": ""
            }])

        # Import P2WPKH address as watch only
        self.log.info("Should import a P2WPKH address as watch only")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2wpkh_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2wpkh_addr,
                     iswatchonly=True,
                     solvable=False)

        # Import P2WPKH address with public key but no private key
        self.log.info(
            "Should import a P2WPKH address and public key as solvable but not spendable"
        )
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2wpkh_addr
                },
                "timestamp": "now",
                "pubkeys": [key.pubkey]
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2wpkh_addr,
                     ismine=False,
                     solvable=True)

        # Import P2WPKH address with key and check it is spendable
        self.log.info("Should import a P2WPKH address with key")
        key = get_key(self.nodes[0])
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2wpkh_addr
                },
                "timestamp": "now",
                "keys": [key.privkey]
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2wpkh_addr,
                     iswatchonly=False,
                     ismine=True)

        # P2WSH multisig address without scripts or keys
        multisig = get_multisig(self.nodes[0])
        self.log.info(
            "Should import a p2wsh multisig as watch only without respective redeem script and private keys"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2wsh_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1], multisig.p2sh_addr, solvable=False)

        # Same P2WSH multisig address as above, but now with witnessscript + private keys
        self.log.info(
            "Should import a p2wsh with respective witness script and private keys"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2wsh_addr
                },
                "timestamp": "now",
                "witnessscript": multisig.redeem_script,
                "keys": multisig.privkeys
            },
            success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     solvable=True,
                     ismine=True,
                     sigsrequired=2)

        # P2SH-P2WPKH address with no redeemscript or public or private key
        key = get_key(self.nodes[0])
        self.log.info(
            "Should import a p2sh-p2wpkh without redeem script or keys")
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2sh_p2wpkh_addr
                },
                "timestamp": "now"
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2sh_p2wpkh_addr,
                     solvable=False,
                     ismine=False)

        # P2SH-P2WPKH address + redeemscript + public key with no private key
        self.log.info(
            "Should import a p2sh-p2wpkh with respective redeem script and pubkey as solvable"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2sh_p2wpkh_addr
                },
                "timestamp": "now",
                "redeemscript": key.p2sh_p2wpkh_redeem_script,
                "pubkeys": [key.pubkey]
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2sh_p2wpkh_addr,
                     solvable=True,
                     ismine=False)

        # P2SH-P2WPKH address + redeemscript + private key
        key = get_key(self.nodes[0])
        self.log.info(
            "Should import a p2sh-p2wpkh with respective redeem script and private keys"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": key.p2sh_p2wpkh_addr
                },
                "timestamp": "now",
                "redeemscript": key.p2sh_p2wpkh_redeem_script,
                "keys": [key.privkey]
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2sh_p2wpkh_addr,
                     solvable=True,
                     ismine=True)

        # P2SH-P2WSH multisig + redeemscript with no private key
        multisig = get_multisig(self.nodes[0])
        self.log.info(
            "Should import a p2sh-p2wsh with respective redeem script but no private key"
        )
        self.test_importmulti(
            {
                "scriptPubKey": {
                    "address": multisig.p2sh_p2wsh_addr
                },
                "timestamp": "now",
                "redeemscript": multisig.p2wsh_script,
                "witnessscript": multisig.redeem_script
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     multisig.p2sh_p2wsh_addr,
                     solvable=True,
                     ismine=False)

        # Test importing of a P2SH-P2WPKH address via descriptor + private key
        key = get_key(self.nodes[0])
        self.log.info(
            "Should not import a p2sh-p2wpkh address from descriptor without checksum and private key"
        )
        self.test_importmulti(
            {
                "desc": "sh(wpkh(" + key.pubkey + "))",
                "timestamp": "now",
                "label": "Descriptor import test",
                "keys": [key.privkey]
            },
            success=False,
            error_code=-5,
            error_message="Descriptor is invalid")

        # Test importing of a P2SH-P2WPKH address via descriptor + private key
        key = get_key(self.nodes[0])
        self.log.info(
            "Should import a p2sh-p2wpkh address from descriptor and private key"
        )
        self.test_importmulti(
            {
                "desc": descsum_create("sh(wpkh(" + key.pubkey + "))"),
                "timestamp": "now",
                "label": "Descriptor import test",
                "keys": [key.privkey]
            },
            success=True)
        test_address(self.nodes[1],
                     key.p2sh_p2wpkh_addr,
                     solvable=True,
                     ismine=True,
                     label="Descriptor import test")

        # Test ranged descriptor fails if range is not specified
        xpriv = "tprv8ZgxMBicQKsPeuVhWwi6wuMQGfPKi9Li5GtX35jVNknACgqe3CY4g5xgkfDDJcmtF7o1QnxWDRYw4H5P26PXq7sbcUkEqeR4fg3Kxp2tigg"
        addresses = [
            "2N7yv4p8G8yEaPddJxY41kPihnWvs39qCMf",
            "2MsHxyb2JS3pAySeNUsJ7mNnurtpeenDzLA"
        ]  # hdkeypath=m/0'/0'/0' and 1'
        addresses += [
            "bcrt1qrd3n235cj2czsfmsuvqqpr3lu6lg0ju7scl8gn",
            "bcrt1qfqeppuvj0ww98r6qghmdkj70tv8qpchehegrg8"
        ]  # wpkh subscripts corresponding to the above addresses
        desc = "sh(wpkh(" + xpriv + "/0'/0'/*'" + "))"
        self.log.info(
            "Ranged descriptor import should fail without a specified range")
        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now"
            },
            success=False,
            error_code=-8,
            error_message='Descriptor is ranged, please specify the range')

        # Test importing of a ranged descriptor with xpriv
        self.log.info(
            "Should import the ranged descriptor with specified range as solvable"
        )
        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": 1
            },
            success=True)
        for address in addresses:
            test_address(self.nodes[1], address, solvable=True, ismine=True)

        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": -1
            },
            success=False,
            error_code=-8,
            error_message='End of range is too high')

        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [-1, 10]
            },
            success=False,
            error_code=-8,
            error_message='Range should be greater or equal than 0')

        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [(2 << 31 + 1) - 1000000, (2 << 31 + 1)]
            },
            success=False,
            error_code=-8,
            error_message='End of range is too high')

        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [2, 1]
            },
            success=False,
            error_code=-8,
            error_message=
            'Range specified as [begin,end] must not have begin after end')

        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now",
                "range": [0, 1000001]
            },
            success=False,
            error_code=-8,
            error_message='Range is too large')

        # Test importing a descriptor containing a WIF private key
        wif_priv = "cTe1f5rdT8A8DFgVWTjyPwACsDPJM9ff4QngFxUixCSvvbg1x6sh"
        address = "2MuhcG52uHPknxDgmGPsV18jSHFBnnRgjPg"
        desc = "sh(wpkh(" + wif_priv + "))"
        self.log.info(
            "Should import a descriptor with a WIF private key as spendable")
        self.test_importmulti(
            {
                "desc": descsum_create(desc),
                "timestamp": "now"
            }, success=True)
        test_address(self.nodes[1], address, solvable=True, ismine=True)

        # dump the private key to ensure it matches what was imported
        privkey = self.nodes[1].dumpprivkey(address)
        assert_equal(privkey, wif_priv)

        # Test importing of a P2PKH address via descriptor
        key = get_key(self.nodes[0])
        self.log.info("Should import a p2pkh address from descriptor")
        self.test_importmulti(
            {
                "desc": descsum_create("pkh(" + key.pubkey + ")"),
                "timestamp": "now",
                "label": "Descriptor import test"
            },
            True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     solvable=True,
                     ismine=False,
                     label="Descriptor import test")

        # Test import fails if both desc and scriptPubKey are provided
        key = get_key(self.nodes[0])
        self.log.info(
            "Import should fail if both scriptPubKey and desc are provided")
        self.test_importmulti(
            {
                "desc": descsum_create("pkh(" + key.pubkey + ")"),
                "scriptPubKey": {
                    "address": key.p2pkh_addr
                },
                "timestamp": "now"
            },
            success=False,
            error_code=-8,
            error_message=
            'Both a descriptor and a scriptPubKey should not be provided.')

        # Test import fails if neither desc nor scriptPubKey are present
        key = get_key(self.nodes[0])
        self.log.info(
            "Import should fail if neither a descriptor nor a scriptPubKey are provided"
        )
        self.test_importmulti(
            {"timestamp": "now"},
            success=False,
            error_code=-8,
            error_message=
            'Either a descriptor or scriptPubKey must be provided.')

        # Test importing of a multisig via descriptor
        key1 = get_key(self.nodes[0])
        key2 = get_key(self.nodes[0])
        self.log.info("Should import a 1-of-2 bare multisig from descriptor")
        self.test_importmulti(
            {
                "desc":
                descsum_create("multi(1," + key1.pubkey + "," + key2.pubkey +
                               ")"),
                "timestamp":
                "now"
            },
            success=True,
            warnings=[
                "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."
            ])
        self.log.info(
            "Should not treat individual keys from the imported bare multisig as watchonly"
        )
        test_address(self.nodes[1],
                     key1.p2pkh_addr,
                     ismine=False,
                     iswatchonly=False)

        # Import pubkeys with key origin info
        self.log.info(
            "Addresses should have hd keypath and master key id after import with key origin"
        )
        pub_addr = self.nodes[1].getnewaddress()
        pub_addr = self.nodes[1].getnewaddress()
        info = self.nodes[1].getaddressinfo(pub_addr)
        pub = info['pubkey']
        pub_keypath = info['hdkeypath']
        pub_fpr = info['hdmasterfingerprint']
        result = self.nodes[0].importmulti([{
            'desc':
            descsum_create("wpkh([" + pub_fpr + pub_keypath[1:] + "]" + pub +
                           ")"),
            "timestamp":
            "now",
        }])
        assert result[0]['success']
        pub_import_info = self.nodes[0].getaddressinfo(pub_addr)
        assert_equal(pub_import_info['hdmasterfingerprint'], pub_fpr)
        assert_equal(pub_import_info['pubkey'], pub)
        assert_equal(pub_import_info['hdkeypath'], pub_keypath)

        # Import privkeys with key origin info
        priv_addr = self.nodes[1].getnewaddress()
        info = self.nodes[1].getaddressinfo(priv_addr)
        priv = self.nodes[1].dumpprivkey(priv_addr)
        priv_keypath = info['hdkeypath']
        priv_fpr = info['hdmasterfingerprint']
        result = self.nodes[0].importmulti([{
            'desc':
            descsum_create("wpkh([" + priv_fpr + priv_keypath[1:] + "]" +
                           priv + ")"),
            "timestamp":
            "now",
        }])
        assert result[0]['success']
        priv_import_info = self.nodes[0].getaddressinfo(priv_addr)
        assert_equal(priv_import_info['hdmasterfingerprint'], priv_fpr)
        assert_equal(priv_import_info['hdkeypath'], priv_keypath)

        # Make sure the key origin info are still there after a restart
        self.stop_nodes()
        self.start_nodes()
        import_info = self.nodes[0].getaddressinfo(pub_addr)
        assert_equal(import_info['hdmasterfingerprint'], pub_fpr)
        assert_equal(import_info['hdkeypath'], pub_keypath)
        import_info = self.nodes[0].getaddressinfo(priv_addr)
        assert_equal(import_info['hdmasterfingerprint'], priv_fpr)
        assert_equal(import_info['hdkeypath'], priv_keypath)

        # Check legacy import does not import key origin info
        self.log.info("Legacy imports don't have key origin info")
        pub_addr = self.nodes[1].getnewaddress()
        info = self.nodes[1].getaddressinfo(pub_addr)
        pub = info['pubkey']
        result = self.nodes[0].importmulti([{
            'scriptPubKey': {
                'address': pub_addr
            },
            'pubkeys': [pub],
            "timestamp": "now",
        }])
        assert result[0]['success']
        pub_import_info = self.nodes[0].getaddressinfo(pub_addr)
        assert_equal(pub_import_info['pubkey'], pub)
        assert 'hdmasterfingerprint' not in pub_import_info
        assert 'hdkeypath' not in pub_import_info

        # Import some public keys to the keypool of a no privkey wallet
        self.log.info("Adding pubkey to keypool of disableprivkey wallet")
        self.nodes[1].createwallet(wallet_name="noprivkeys",
                                   disable_private_keys=True)
        wrpc = self.nodes[1].get_wallet_rpc("noprivkeys")

        addr1 = self.nodes[0].getnewaddress()
        addr2 = self.nodes[0].getnewaddress()
        pub1 = self.nodes[0].getaddressinfo(addr1)['pubkey']
        pub2 = self.nodes[0].getaddressinfo(addr2)['pubkey']
        result = wrpc.importmulti([{
            'desc': descsum_create('wpkh(' + pub1 + ')'),
            'keypool': True,
            "timestamp": "now",
        }, {
            'desc': descsum_create('wpkh(' + pub2 + ')'),
            'keypool': True,
            "timestamp": "now",
        }])
        assert result[0]['success']
        assert result[1]['success']
        assert_equal(wrpc.getwalletinfo()["keypoolsize"], 2)
        newaddr1 = wrpc.getnewaddress()
        assert_equal(addr1, newaddr1)
        newaddr2 = wrpc.getnewaddress()
        assert_equal(addr2, newaddr2)

        # Import some public keys to the internal keypool of a no privkey wallet
        self.log.info(
            "Adding pubkey to internal keypool of disableprivkey wallet")
        addr1 = self.nodes[0].getnewaddress()
        addr2 = self.nodes[0].getnewaddress()
        pub1 = self.nodes[0].getaddressinfo(addr1)['pubkey']
        pub2 = self.nodes[0].getaddressinfo(addr2)['pubkey']
        result = wrpc.importmulti([{
            'desc': descsum_create('wpkh(' + pub1 + ')'),
            'keypool': True,
            'internal': True,
            "timestamp": "now",
        }, {
            'desc': descsum_create('wpkh(' + pub2 + ')'),
            'keypool': True,
            'internal': True,
            "timestamp": "now",
        }])
        assert result[0]['success']
        assert result[1]['success']
        assert_equal(wrpc.getwalletinfo()["keypoolsize_hd_internal"], 2)
        newaddr1 = wrpc.getrawchangeaddress()
        assert_equal(addr1, newaddr1)
        newaddr2 = wrpc.getrawchangeaddress()
        assert_equal(addr2, newaddr2)

        # Import a multisig and make sure the keys don't go into the keypool
        self.log.info(
            'Imported scripts with pubkeys should not have their pubkeys go into the keypool'
        )
        addr1 = self.nodes[0].getnewaddress()
        addr2 = self.nodes[0].getnewaddress()
        pub1 = self.nodes[0].getaddressinfo(addr1)['pubkey']
        pub2 = self.nodes[0].getaddressinfo(addr2)['pubkey']
        result = wrpc.importmulti([{
            'desc':
            descsum_create('wsh(multi(2,' + pub1 + ',' + pub2 + '))'),
            'keypool':
            True,
            "timestamp":
            "now",
        }])
        assert result[0]['success']
        assert_equal(wrpc.getwalletinfo()["keypoolsize"], 0)

        # Cannot import those pubkeys to keypool of wallet with privkeys
        self.log.info(
            "Pubkeys cannot be added to the keypool of a wallet with private keys"
        )
        wrpc = self.nodes[1].get_wallet_rpc("")
        assert wrpc.getwalletinfo()['private_keys_enabled']
        result = wrpc.importmulti([{
            'desc': descsum_create('wpkh(' + pub1 + ')'),
            'keypool': True,
            "timestamp": "now",
        }])
        assert_equal(result[0]['error']['code'], -8)
        assert_equal(
            result[0]['error']['message'],
            "Keys can only be imported to the keypool when private keys are disabled"
        )

        # Make sure ranged imports import keys in order
        self.log.info('Key ranges should be imported in order')
        wrpc = self.nodes[1].get_wallet_rpc("noprivkeys")
        assert_equal(wrpc.getwalletinfo()["keypoolsize"], 0)
        assert_equal(wrpc.getwalletinfo()["private_keys_enabled"], False)
        xpub = "tpubDAXcJ7s7ZwicqjprRaEWdPoHKrCS215qxGYxpusRLLmJuT69ZSicuGdSfyvyKpvUNYBW1s2U3NSrT6vrCYB9e6nZUEvrqnwXPF8ArTCRXMY"
        addresses = [
            'bcrt1qtmp74ayg7p24uslctssvjm06q5phz4yrxucgnv',  # m/0'/0'/0
            'bcrt1q8vprchan07gzagd5e6v9wd7azyucksq2xc76k8',  # m/0'/0'/1
            'bcrt1qtuqdtha7zmqgcrr26n2rqxztv5y8rafjp9lulu',  # m/0'/0'/2
            'bcrt1qau64272ymawq26t90md6an0ps99qkrse58m640',  # m/0'/0'/3
            'bcrt1qsg97266hrh6cpmutqen8s4s962aryy77jp0fg0',  # m/0'/0'/4
        ]
        result = wrpc.importmulti([{
            'desc':
            descsum_create('wpkh([80002067/0h/0h]' + xpub + '/*)'),
            'keypool':
            True,
            'timestamp':
            'now',
            'range': [0, 4],
        }])
        for i in range(0, 5):
            addr = wrpc.getnewaddress('', 'bech32')
            assert_equal(addr, addresses[i])
Beispiel #21
0
    def run_test(self):
        node = self.nodes[0]
        node.generate(1)  # Leave IBD for sethdseed

        self.nodes[0].createwallet(wallet_name='w0')
        w0 = node.get_wallet_rpc('w0')
        address1 = w0.getnewaddress()

        self.log.info("Test disableprivatekeys creation.")
        self.nodes[0].createwallet(wallet_name='w1', disable_private_keys=True)
        w1 = node.get_wallet_rpc('w1')
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w1.getnewaddress)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w1.getrawchangeaddress)
        w1.importpubkey(w0.getaddressinfo(address1)['pubkey'])

        self.log.info('Test that private keys cannot be imported')
        eckey = ECKey()
        eckey.generate()
        privkey = bytes_to_wif(eckey.get_bytes())
        assert_raises_rpc_error(
            -4,
            'Cannot import private keys to a wallet with private keys disabled',
            w1.importprivkey, privkey)
        if self.options.descriptors:
            result = w1.importdescriptors([{
                'desc':
                descsum_create('wpkh(' + privkey + ')'),
                'timestamp':
                'now'
            }])
        else:
            result = w1.importmulti([{
                'scriptPubKey': {
                    'address': key_to_p2wpkh(eckey.get_pubkey().get_bytes())
                },
                'timestamp': 'now',
                'keys': [privkey]
            }])
        assert not result[0]['success']
        assert 'warning' not in result[0]
        assert_equal(result[0]['error']['code'], -4)
        assert_equal(
            result[0]['error']['message'],
            'Cannot import private keys to a wallet with private keys disabled'
        )

        self.log.info("Test blank creation with private keys disabled.")
        self.nodes[0].createwallet(wallet_name='w2',
                                   disable_private_keys=True,
                                   blank=True)
        w2 = node.get_wallet_rpc('w2')
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w2.getnewaddress)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w2.getrawchangeaddress)
        w2.importpubkey(w0.getaddressinfo(address1)['pubkey'])

        self.log.info("Test blank creation with private keys enabled.")
        self.nodes[0].createwallet(wallet_name='w3',
                                   disable_private_keys=False,
                                   blank=True)
        w3 = node.get_wallet_rpc('w3')
        assert_equal(w3.getwalletinfo()['keypoolsize'], 0)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w3.getnewaddress)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w3.getrawchangeaddress)
        # Import private key
        w3.importprivkey(generate_wif_key())
        # Imported private keys are currently ignored by the keypool
        assert_equal(w3.getwalletinfo()['keypoolsize'], 0)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w3.getnewaddress)
        # Set the seed
        if self.options.descriptors:
            w3.importdescriptors([{
                'desc':
                descsum_create(
                    'wpkh(tprv8ZgxMBicQKsPcwuZGKp8TeWppSuLMiLe2d9PupB14QpPeQsqoj3LneJLhGHH13xESfvASyd4EFLJvLrG8b7DrLxEuV7hpF9uUc6XruKA1Wq/0h/*)'
                ),
                'timestamp':
                'now',
                'active':
                True
            }, {
                'desc':
                descsum_create(
                    'wpkh(tprv8ZgxMBicQKsPcwuZGKp8TeWppSuLMiLe2d9PupB14QpPeQsqoj3LneJLhGHH13xESfvASyd4EFLJvLrG8b7DrLxEuV7hpF9uUc6XruKA1Wq/1h/*)'
                ),
                'timestamp':
                'now',
                'active':
                True,
                'internal':
                True
            }])
        else:
            w3.sethdseed()
        assert_equal(w3.getwalletinfo()['keypoolsize'], 1)
        w3.getnewaddress()
        w3.getrawchangeaddress()

        self.log.info(
            "Test blank creation with privkeys enabled and then encryption")
        self.nodes[0].createwallet(wallet_name='w4',
                                   disable_private_keys=False,
                                   blank=True)
        w4 = node.get_wallet_rpc('w4')
        assert_equal(w4.getwalletinfo()['keypoolsize'], 0)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w4.getnewaddress)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w4.getrawchangeaddress)
        # Encrypt the wallet. Nothing should change about the keypool
        w4.encryptwallet('pass')
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w4.getnewaddress)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w4.getrawchangeaddress)
        # Now set a seed and it should work. Wallet should also be encrypted
        w4.walletpassphrase('pass', 60)
        if self.options.descriptors:
            w4.importdescriptors([{
                'desc':
                descsum_create(
                    'wpkh(tprv8ZgxMBicQKsPcwuZGKp8TeWppSuLMiLe2d9PupB14QpPeQsqoj3LneJLhGHH13xESfvASyd4EFLJvLrG8b7DrLxEuV7hpF9uUc6XruKA1Wq/0h/*)'
                ),
                'timestamp':
                'now',
                'active':
                True
            }, {
                'desc':
                descsum_create(
                    'wpkh(tprv8ZgxMBicQKsPcwuZGKp8TeWppSuLMiLe2d9PupB14QpPeQsqoj3LneJLhGHH13xESfvASyd4EFLJvLrG8b7DrLxEuV7hpF9uUc6XruKA1Wq/1h/*)'
                ),
                'timestamp':
                'now',
                'active':
                True,
                'internal':
                True
            }])
        else:
            w4.sethdseed()
        w4.getnewaddress()
        w4.getrawchangeaddress()

        self.log.info(
            "Test blank creation with privkeys disabled and then encryption")
        self.nodes[0].createwallet(wallet_name='w5',
                                   disable_private_keys=True,
                                   blank=True)
        w5 = node.get_wallet_rpc('w5')
        assert_equal(w5.getwalletinfo()['keypoolsize'], 0)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w5.getnewaddress)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w5.getrawchangeaddress)
        # Encrypt the wallet
        assert_raises_rpc_error(
            -16,
            "Error: wallet does not contain private keys, nothing to encrypt.",
            w5.encryptwallet, 'pass')
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w5.getnewaddress)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                w5.getrawchangeaddress)

        self.log.info('New blank and encrypted wallets can be created')
        self.nodes[0].createwallet(wallet_name='wblank',
                                   disable_private_keys=False,
                                   blank=True,
                                   passphrase='thisisapassphrase')
        wblank = node.get_wallet_rpc('wblank')
        assert_raises_rpc_error(
            -13,
            "Error: Please enter the wallet passphrase with walletpassphrase first.",
            wblank.signmessage, "needanargument", "test")
        wblank.walletpassphrase('thisisapassphrase', 60)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                wblank.getnewaddress)
        assert_raises_rpc_error(-4, "Error: This wallet has no available keys",
                                wblank.getrawchangeaddress)

        self.log.info('Test creating a new encrypted wallet.')
        # Born encrypted wallet is created (has keys)
        self.nodes[0].createwallet(wallet_name='w6',
                                   disable_private_keys=False,
                                   blank=False,
                                   passphrase='thisisapassphrase')
        w6 = node.get_wallet_rpc('w6')
        assert_raises_rpc_error(
            -13,
            "Error: Please enter the wallet passphrase with walletpassphrase first.",
            w6.signmessage, "needanargument", "test")
        w6.walletpassphrase('thisisapassphrase', 60)
        w6.signmessage(w6.getnewaddress('', 'legacy'), "test")
        w6.keypoolrefill(1)
        # There should only be 1 key for legacy, 3 for descriptors
        walletinfo = w6.getwalletinfo()
        keys = 3 if self.options.descriptors else 1
        assert_equal(walletinfo['keypoolsize'], keys)
        assert_equal(walletinfo['keypoolsize_hd_internal'], keys)
        # Allow empty passphrase, but there should be a warning
        resp = self.nodes[0].createwallet(wallet_name='w7',
                                          disable_private_keys=False,
                                          blank=False,
                                          passphrase='')
        assert 'Empty string given as passphrase, wallet will not be encrypted.' in resp[
            'warning']
        w7 = node.get_wallet_rpc('w7')
        assert_raises_rpc_error(
            -15,
            'Error: running with an unencrypted wallet, but walletpassphrase was called.',
            w7.walletpassphrase, '', 60)

        self.log.info('Test making a wallet with avoid reuse flag')
        self.nodes[0].createwallet(
            'w8', False, False, '', True
        )  # Use positional arguments to check for bug where avoid_reuse could not be set for wallets without needing them to be encrypted
        w8 = node.get_wallet_rpc('w8')
        assert_raises_rpc_error(
            -15,
            'Error: running with an unencrypted wallet, but walletpassphrase was called.',
            w7.walletpassphrase, '', 60)
        assert_equal(w8.getwalletinfo()["avoid_reuse"], True)

        self.log.info(
            'Using a passphrase with private keys disabled returns error')
        assert_raises_rpc_error(
            -4,
            'Passphrase provided but private keys are disabled. A passphrase is only used to encrypt private keys, so cannot be used for wallets with private keys disabled.',
            self.nodes[0].createwallet,
            wallet_name='w9',
            disable_private_keys=True,
            passphrase='thisisapassphrase')
    def run_test(self):
        node0, node1, node2 = self.nodes

        self.check_addmultisigaddress_errors()

        self.log.info('Generating blocks ...')
        node0.generate(149)
        self.sync_all()

        self.moved = 0
        for self.nkeys in [3, 5]:
            for self.nsigs in [2, 3]:
                for self.output_type in ["bech32", "p2sh-segwit", "legacy"]:
                    self.get_keys()
                    self.do_multisig()

        self.checkbalances()

        # Test mixed compressed and uncompressed pubkeys
        self.log.info(
            'Mixed compressed and uncompressed multisigs are not allowed')
        pk0 = node0.getaddressinfo(node0.getnewaddress())['pubkey']
        pk1 = node1.getaddressinfo(node1.getnewaddress())['pubkey']
        pk2 = node2.getaddressinfo(node2.getnewaddress())['pubkey']

        # decompress pk2
        pk_obj = ECPubKey()
        pk_obj.set(binascii.unhexlify(pk2))
        pk_obj.compressed = False
        pk2 = binascii.hexlify(pk_obj.get_bytes()).decode()

        node0.createwallet(wallet_name='wmulti0', disable_private_keys=True)
        wmulti0 = node0.get_wallet_rpc('wmulti0')

        # Check all permutations of keys because order matters apparently
        for keys in itertools.permutations([pk0, pk1, pk2]):
            # Results should be the same as this legacy one
            legacy_addr = node0.createmultisig(2, keys, 'legacy')['address']
            assert_equal(
                legacy_addr,
                wmulti0.addmultisigaddress(2, keys, '', 'legacy')['address'])

            # Generate addresses with the segwit types. These should all make legacy addresses
            assert_equal(legacy_addr,
                         wmulti0.createmultisig(2, keys, 'bech32')['address'])
            assert_equal(
                legacy_addr,
                wmulti0.createmultisig(2, keys, 'p2sh-segwit')['address'])
            assert_equal(
                legacy_addr,
                wmulti0.addmultisigaddress(2, keys, '', 'bech32')['address'])
            assert_equal(
                legacy_addr,
                wmulti0.addmultisigaddress(2, keys, '',
                                           'p2sh-segwit')['address'])

        self.log.info(
            'Testing sortedmulti descriptors with BIP 67 test vectors')
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               'data/rpc_bip67.json'),
                  encoding='utf-8') as f:
            vectors = json.load(f)

        for t in vectors:
            key_str = ','.join(t['keys'])
            desc = descsum_create('sh(sortedmulti(2,{}))'.format(key_str))
            assert_equal(self.nodes[0].deriveaddresses(desc)[0], t['address'])
            sorted_key_str = ','.join(t['sorted_keys'])
            sorted_key_desc = descsum_create(
                'sh(multi(2,{}))'.format(sorted_key_str))
            assert_equal(self.nodes[0].deriveaddresses(sorted_key_desc)[0],
                         t['address'])
    def run_test(self):
        self.log.info("Mining blocks...")
        self.nodes[0].generate(1)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']

        node0_address1 = self.nodes[0].getaddressinfo(self.nodes[0].getnewaddress())

        # Check only one address
        assert_equal(node0_address1['ismine'], True)

        # Node 1 sync test
        assert_equal(self.nodes[1].getblockcount(), 1)

        # Address Test - before import
        address_info = self.nodes[1].getaddressinfo(node0_address1['address'])
        assert_equal(address_info['iswatchonly'], False)
        assert_equal(address_info['ismine'], False)

        # RPC importmulti -----------------------------------------------

        # Bitcoin Address (implicit non-internal)
        self.log.info("Should import an address")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": {"address": key.p2pkh_addr},
                               "timestamp": "now"},
                              success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp,
                     ischange=False)
        watchonly_address = key.p2pkh_addr
        watchonly_timestamp = timestamp

        self.log.info("Should not import an invalid address")
        self.test_importmulti({"scriptPubKey": {"address": "not valid address"},
                               "timestamp": "now"},
                              success=False,
                              error_code=-5,
                              error_message='Invalid address \"not valid address\"')

        # ScriptPubKey + internal
        self.log.info("Should import a scriptPubKey with internal flag")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": key.p2pkh_script,
                               "timestamp": "now",
                               "internal": True},
                              success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp,
                     ischange=True)

        # ScriptPubKey + internal + label
        self.log.info("Should not allow a label to be specified when internal is true")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": key.p2pkh_script,
                               "timestamp": "now",
                               "internal": True,
                               "label": "Example label"},
                              success=False,
                              error_code=-8,
                              error_message='Internal addresses should not have a label')

        # Nonstandard scriptPubKey + !internal
        self.log.info("Should not import a nonstandard scriptPubKey without internal flag")
        nonstandardScriptPubKey = key.p2pkh_script + CScript([OP_NOP]).hex()
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": nonstandardScriptPubKey,
                               "timestamp": "now"},
                              success=False,
                              error_code=-8,
                              error_message='Internal must be set to true for nonstandard scriptPubKey imports.')
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=False,
                     timestamp=None)

        # Address + Public key + !Internal(explicit)
        self.log.info("Should import an address with public key")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": {"address": key.p2pkh_addr},
                               "timestamp": "now",
                               "pubkeys": [key.pubkey],
                               "internal": False},
                              success=True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp)

        # ScriptPubKey + Public key + internal
        self.log.info("Should import a scriptPubKey with internal and with public key")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": key.p2pkh_script,
                               "timestamp": "now",
                               "pubkeys": [key.pubkey],
                               "internal": True},
                              success=True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp)

        # Nonstandard scriptPubKey + Public key + !internal
        self.log.info("Should not import a nonstandard scriptPubKey without internal and with public key")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": nonstandardScriptPubKey,
                               "timestamp": "now",
                               "pubkeys": [key.pubkey]},
                              success=False,
                              error_code=-8,
                              error_message='Internal must be set to true for nonstandard scriptPubKey imports.')
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=False,
                     timestamp=None)

        # Address + Private key + !watchonly
        self.log.info("Should import an address with private key")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": {"address": key.p2pkh_addr},
                               "timestamp": "now",
                               "keys": [key.privkey]},
                              success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=True,
                     timestamp=timestamp)

        self.log.info("Should not import an address with private key if is already imported")
        self.test_importmulti({"scriptPubKey": {"address": key.p2pkh_addr},
                               "timestamp": "now",
                               "keys": [key.privkey]},
                              success=False,
                              error_code=-4,
                              error_message='The wallet already contains the private key for this address or script ("' + key.p2pkh_script + '")')

        # Address + Private key + watchonly
        self.log.info("Should import an address with private key and with watchonly")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": {"address": key.p2pkh_addr},
                               "timestamp": "now",
                               "keys": [key.privkey],
                               "watchonly": True},
                              success=True,
                              warnings=["All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=True,
                     timestamp=timestamp)

        # ScriptPubKey + Private key + internal
        self.log.info("Should import a scriptPubKey with internal and with private key")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": key.p2pkh_script,
                               "timestamp": "now",
                               "keys": [key.privkey],
                               "internal": True},
                              success=True)
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=True,
                     timestamp=timestamp)

        # Nonstandard scriptPubKey + Private key + !internal
        self.log.info("Should not import a nonstandard scriptPubKey without internal and with private key")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": nonstandardScriptPubKey,
                               "timestamp": "now",
                               "keys": [key.privkey]},
                              success=False,
                              error_code=-8,
                              error_message='Internal must be set to true for nonstandard scriptPubKey imports.')
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=False,
                     ismine=False,
                     timestamp=None)

        # P2SH address
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']

        self.log.info("Should import a p2sh")
        self.test_importmulti({"scriptPubKey": {"address": multisig.p2sh_addr},
                               "timestamp": "now"},
                              success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     isscript=True,
                     iswatchonly=True,
                     timestamp=timestamp)
        p2shunspent = self.nodes[1].listunspent(0, 999999, [multisig.p2sh_addr])[0]
        assert_equal(p2shunspent['spendable'], False)
        assert_equal(p2shunspent['solvable'], False)

        # P2SH + Redeem script
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']

        self.log.info("Should import a p2sh with respective redeem script")
        self.test_importmulti({"scriptPubKey": {"address": multisig.p2sh_addr},
                               "timestamp": "now",
                               "redeemscript": multisig.redeem_script},
                              success=True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     multisig.p2sh_addr, timestamp=timestamp, iswatchonly=True, ismine=False, solvable=True)

        p2shunspent = self.nodes[1].listunspent(0, 999999, [multisig.p2sh_addr])[0]
        assert_equal(p2shunspent['spendable'], False)
        assert_equal(p2shunspent['solvable'], True)

        # P2SH + Redeem script + Private Keys + !Watchonly
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']

        self.log.info("Should import a p2sh with respective redeem script and private keys")
        self.test_importmulti({"scriptPubKey": {"address": multisig.p2sh_addr},
                               "timestamp": "now",
                               "redeemscript": multisig.redeem_script,
                               "keys": multisig.privkeys[0:2]},
                              success=True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     timestamp=timestamp,
                     ismine=False,
                     iswatchonly=True,
                     solvable=True)

        p2shunspent = self.nodes[1].listunspent(0, 999999, [multisig.p2sh_addr])[0]
        assert_equal(p2shunspent['spendable'], False)
        assert_equal(p2shunspent['solvable'], True)

        # P2SH + Redeem script + Private Keys + Watchonly
        multisig = get_multisig(self.nodes[0])
        self.nodes[1].generate(100)
        self.nodes[1].sendtoaddress(multisig.p2sh_addr, 10.00)
        self.nodes[1].generate(1)
        timestamp = self.nodes[1].getblock(self.nodes[1].getbestblockhash())['mediantime']

        self.log.info("Should import a p2sh with respective redeem script and private keys")
        self.test_importmulti({"scriptPubKey": {"address": multisig.p2sh_addr},
                               "timestamp": "now",
                               "redeemscript": multisig.redeem_script,
                               "keys": multisig.privkeys[0:2],
                               "watchonly": True},
                              success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=True,
                     timestamp=timestamp)

        # Address + Public key + !Internal + Wrong pubkey
        self.log.info("Should not import an address with the wrong public key as non-solvable")
        key = get_key(self.nodes[0])
        wrong_key = get_key(self.nodes[0]).pubkey
        self.test_importmulti({"scriptPubKey": {"address": key.p2pkh_addr},
                               "timestamp": "now",
                               "pubkeys": [wrong_key]},
                              success=True,
                              warnings=["Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.", "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # ScriptPubKey + Public key + internal + Wrong pubkey
        self.log.info("Should import a scriptPubKey with internal and with a wrong public key as non-solvable")
        key = get_key(self.nodes[0])
        wrong_key = get_key(self.nodes[0]).pubkey
        self.test_importmulti({"scriptPubKey": key.p2pkh_script,
                               "timestamp": "now",
                               "pubkeys": [wrong_key],
                               "internal": True},
                              success=True,
                              warnings=["Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.", "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # Address + Private key + !watchonly + Wrong private key
        self.log.info("Should import an address with a wrong private key as non-solvable")
        key = get_key(self.nodes[0])
        wrong_privkey = get_key(self.nodes[0]).privkey
        self.test_importmulti({"scriptPubKey": {"address": key.p2pkh_addr},
                               "timestamp": "now",
                               "keys": [wrong_privkey]},
                               success=True,
                               warnings=["Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.", "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # ScriptPubKey + Private key + internal + Wrong private key
        self.log.info("Should import a scriptPubKey with internal and with a wrong private key as non-solvable")
        key = get_key(self.nodes[0])
        wrong_privkey = get_key(self.nodes[0]).privkey
        self.test_importmulti({"scriptPubKey": key.p2pkh_script,
                               "timestamp": "now",
                               "keys": [wrong_privkey],
                               "internal": True},
                              success=True,
                              warnings=["Importing as non-solvable: some required keys are missing. If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript.", "Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     iswatchonly=True,
                     ismine=False,
                     solvable=False,
                     timestamp=timestamp)

        # Importing existing watch only address with new timestamp should replace saved timestamp.
        assert_greater_than(timestamp, watchonly_timestamp)
        self.log.info("Should replace previously saved watch only timestamp.")
        self.test_importmulti({"scriptPubKey": {"address": watchonly_address},
                               "timestamp": "now"},
                              success=True)
        test_address(self.nodes[1],
                     watchonly_address,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=timestamp)
        watchonly_timestamp = timestamp

        # restart nodes to check for proper serialization/deserialization of watch only address
        self.stop_nodes()
        self.start_nodes()
        test_address(self.nodes[1],
                     watchonly_address,
                     iswatchonly=True,
                     ismine=False,
                     timestamp=watchonly_timestamp)

        # Bad or missing timestamps
        self.log.info("Should throw on invalid or missing timestamp values")
        assert_raises_rpc_error(-3, 'Missing required timestamp field for key',
                                self.nodes[1].importmulti, [{"scriptPubKey": key.p2pkh_script}])
        assert_raises_rpc_error(-3, 'Expected number or "now" timestamp value for key. got type string',
                                self.nodes[1].importmulti, [{
                                    "scriptPubKey": key.p2pkh_script,
                                    "timestamp": ""
                                }])

        # Import P2WPKH address as watch only
        self.log.info("Should import a P2WPKH address as watch only")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": {"address": key.p2wpkh_addr},
                               "timestamp": "now"},
                              success=True)
        test_address(self.nodes[1],
                     key.p2wpkh_addr,
                     iswatchonly=True,
                     solvable=False)

        # Import P2WPKH address with public key but no private key
        self.log.info("Should import a P2WPKH address and public key as solvable but not spendable")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": {"address": key.p2wpkh_addr},
                               "timestamp": "now",
                               "pubkeys": [key.pubkey]},
                              success=True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2wpkh_addr,
                     ismine=False,
                     solvable=True)

        # Import P2WPKH address with key and check it is spendable
        self.log.info("Should import a P2WPKH address with key")
        key = get_key(self.nodes[0])
        self.test_importmulti({"scriptPubKey": {"address": key.p2wpkh_addr},
                               "timestamp": "now",
                               "keys": [key.privkey]},
                              success=True)
        test_address(self.nodes[1],
                     key.p2wpkh_addr,
                     iswatchonly=False,
                     ismine=True)

        # P2WSH multisig address without scripts or keys
        multisig = get_multisig(self.nodes[0])
        self.log.info("Should import a p2wsh multisig as watch only without respective redeem script and private keys")
        self.test_importmulti({"scriptPubKey": {"address": multisig.p2wsh_addr},
                               "timestamp": "now"},
                              success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     solvable=False)

        # Same P2WSH multisig address as above, but now with witnessscript + private keys
        self.log.info("Should import a p2wsh with respective witness script and private keys")
        self.test_importmulti({"scriptPubKey": {"address": multisig.p2wsh_addr},
                               "timestamp": "now",
                               "witnessscript": multisig.redeem_script,
                               "keys": multisig.privkeys},
                              success=True)
        test_address(self.nodes[1],
                     multisig.p2sh_addr,
                     solvable=True,
                     ismine=True,
                     sigsrequired=2)

        # P2SH-P2WPKH address with no redeemscript or public or private key
        key = get_key(self.nodes[0])
        self.log.info("Should import a p2sh-p2wpkh without redeem script or keys")
        self.test_importmulti({"scriptPubKey": {"address": key.p2sh_p2wpkh_addr},
                               "timestamp": "now"},
                              success=True)
        test_address(self.nodes[1],
                     key.p2sh_p2wpkh_addr,
                     solvable=False,
                     ismine=False)

        # P2SH-P2WPKH address + redeemscript + public key with no private key
        self.log.info("Should import a p2sh-p2wpkh with respective redeem script and pubkey as solvable")
        self.test_importmulti({"scriptPubKey": {"address": key.p2sh_p2wpkh_addr},
                               "timestamp": "now",
                               "redeemscript": key.p2sh_p2wpkh_redeem_script,
                               "pubkeys": [key.pubkey]},
                              success=True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2sh_p2wpkh_addr,
                     solvable=True,
                     ismine=False)

        # P2SH-P2WPKH address + redeemscript + private key
        key = get_key(self.nodes[0])
        self.log.info("Should import a p2sh-p2wpkh with respective redeem script and private keys")
        self.test_importmulti({"scriptPubKey": {"address": key.p2sh_p2wpkh_addr},
                               "timestamp": "now",
                               "redeemscript": key.p2sh_p2wpkh_redeem_script,
                               "keys": [key.privkey]},
                              success=True)
        test_address(self.nodes[1],
                     key.p2sh_p2wpkh_addr,
                     solvable=True,
                     ismine=True)

        # P2SH-P2WSH multisig + redeemscript with no private key
        multisig = get_multisig(self.nodes[0])
        self.log.info("Should import a p2sh-p2wsh with respective redeem script but no private key")
        self.test_importmulti({"scriptPubKey": {"address": multisig.p2sh_p2wsh_addr},
                               "timestamp": "now",
                               "redeemscript": multisig.p2wsh_script,
                               "witnessscript": multisig.redeem_script},
                              success=True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     multisig.p2sh_p2wsh_addr,
                     solvable=True,
                     ismine=False)

        # Test importing of a P2SH-P2WPKH address via descriptor + private key
        key = get_key(self.nodes[0])
        self.log.info("Should not import a p2sh-p2wpkh address from descriptor without checksum and private key")
        self.test_importmulti({"desc": "sh(wpkh(" + key.pubkey + "))",
                               "timestamp": "now",
                               "label": "Descriptor import test",
                               "keys": [key.privkey]},
                              success=False,
                              error_code=-5,
                              error_message="Descriptor is invalid")

        # Test importing of a P2SH-P2WPKH address via descriptor + private key
        key = get_key(self.nodes[0])
        self.log.info("Should import a p2sh-p2wpkh address from descriptor and private key")
        self.test_importmulti({"desc": descsum_create("sh(wpkh(" + key.pubkey + "))"),
                               "timestamp": "now",
                               "label": "Descriptor import test",
                               "keys": [key.privkey]},
                              success=True)
        test_address(self.nodes[1],
                     key.p2sh_p2wpkh_addr,
                     solvable=True,
                     ismine=True,
                     label="Descriptor import test")

        # Test ranged descriptor fails if range is not specified
        xpriv = "tprv8ZgxMBicQKsPeuVhWwi6wuMQGfPKi9Li5GtX35jVNknACgqe3CY4g5xgkfDDJcmtF7o1QnxWDRYw4H5P26PXq7sbcUkEqeR4fg3Kxp2tigg"
        addresses = ["2N7yv4p8G8yEaPddJxY41kPihnWvs39qCMf", "2MsHxyb2JS3pAySeNUsJ7mNnurtpeenDzLA"] # hdkeypath=m/0'/0'/0' and 1'
        desc = "sh(wpkh(" + xpriv + "/0'/0'/*'" + "))"
        self.log.info("Ranged descriptor import should fail without a specified range")
        self.test_importmulti({"desc": descsum_create(desc),
                               "timestamp": "now"},
                              success=False,
                              error_code=-8,
                              error_message='Descriptor is ranged, please specify the range')

        # Test importing of a ranged descriptor without keys
        self.log.info("Should import the ranged descriptor with specified range as solvable")
        self.test_importmulti({"desc": descsum_create(desc),
                               "timestamp": "now",
                               "range": 1},
                              success=True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        for address in addresses:
            test_address(self.nodes[1],
                         key.p2sh_p2wpkh_addr,
                         solvable=True)

        # Test importing of a P2PKH address via descriptor
        key = get_key(self.nodes[0])
        self.log.info("Should import a p2pkh address from descriptor")
        self.test_importmulti({"desc": descsum_create("pkh(" + key.pubkey + ")"),
                               "timestamp": "now",
                               "label": "Descriptor import test"},
                              True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        test_address(self.nodes[1],
                     key.p2pkh_addr,
                     solvable=True,
                     ismine=False,
                     label="Descriptor import test")

        # Test import fails if both desc and scriptPubKey are provided
        key = get_key(self.nodes[0])
        self.log.info("Import should fail if both scriptPubKey and desc are provided")
        self.test_importmulti({"desc": descsum_create("pkh(" + key.pubkey + ")"),
                               "scriptPubKey": {"address": key.p2pkh_addr},
                               "timestamp": "now"},
                              success=False,
                              error_code=-8,
                              error_message='Both a descriptor and a scriptPubKey should not be provided.')

        # Test import fails if neither desc nor scriptPubKey are present
        key = get_key(self.nodes[0])
        self.log.info("Import should fail if neither a descriptor nor a scriptPubKey are provided")
        self.test_importmulti({"timestamp": "now"},
                              success=False,
                              error_code=-8,
                              error_message='Either a descriptor or scriptPubKey must be provided.')

        # Test importing of a multisig via descriptor
        key1 = get_key(self.nodes[0])
        key2 = get_key(self.nodes[0])
        self.log.info("Should import a 1-of-2 bare multisig from descriptor")
        self.test_importmulti({"desc": descsum_create("multi(1," + key1.pubkey + "," + key2.pubkey + ")"),
                               "timestamp": "now"},
                              success=True,
                              warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."])
        self.log.info("Should not treat individual keys from the imported bare multisig as watchonly")
        test_address(self.nodes[1],
                     key1.p2pkh_addr,
                     ismine=False,
                     iswatchonly=False)

        # Import pubkeys with key origin info
        self.log.info("Addresses should have hd keypath and master key id after import with key origin")
        pub_addr = self.nodes[1].getnewaddress()
        pub_addr = self.nodes[1].getnewaddress()
        info = self.nodes[1].getaddressinfo(pub_addr)
        pub = info['pubkey']
        pub_keypath = info['hdkeypath']
        pub_fpr = info['hdmasterfingerprint']
        result = self.nodes[0].importmulti(
            [{
                'desc' : descsum_create("wpkh([" + pub_fpr + pub_keypath[1:] +"]" + pub + ")"),
                "timestamp": "now",
            }]
        )
        assert result[0]['success']
        pub_import_info = self.nodes[0].getaddressinfo(pub_addr)
        assert_equal(pub_import_info['hdmasterfingerprint'], pub_fpr)
        assert_equal(pub_import_info['pubkey'], pub)
        assert_equal(pub_import_info['hdkeypath'], pub_keypath)

        # Import privkeys with key origin info
        priv_addr = self.nodes[1].getnewaddress()
        info = self.nodes[1].getaddressinfo(priv_addr)
        priv = self.nodes[1].dumpprivkey(priv_addr)
        priv_keypath = info['hdkeypath']
        priv_fpr = info['hdmasterfingerprint']
        result = self.nodes[0].importmulti(
            [{
                'desc' : descsum_create("wpkh([" + priv_fpr + priv_keypath[1:] + "]" + priv + ")"),
                "timestamp": "now",
            }]
        )
        assert result[0]['success']
        priv_import_info = self.nodes[0].getaddressinfo(priv_addr)
        assert_equal(priv_import_info['hdmasterfingerprint'], priv_fpr)
        assert_equal(priv_import_info['hdkeypath'], priv_keypath)

        # Make sure the key origin info are still there after a restart
        self.stop_nodes()
        self.start_nodes()
        import_info = self.nodes[0].getaddressinfo(pub_addr)
        assert_equal(import_info['hdmasterfingerprint'], pub_fpr)
        assert_equal(import_info['hdkeypath'], pub_keypath)
        import_info = self.nodes[0].getaddressinfo(priv_addr)
        assert_equal(import_info['hdmasterfingerprint'], priv_fpr)
        assert_equal(import_info['hdkeypath'], priv_keypath)

        # Check legacy import does not import key origin info
        self.log.info("Legacy imports don't have key origin info")
        pub_addr = self.nodes[1].getnewaddress()
        info = self.nodes[1].getaddressinfo(pub_addr)
        pub = info['pubkey']
        result = self.nodes[0].importmulti(
            [{
                'scriptPubKey': {'address': pub_addr},
                'pubkeys': [pub],
                "timestamp": "now",
            }]
        )
        assert result[0]['success']
        pub_import_info = self.nodes[0].getaddressinfo(pub_addr)
        assert_equal(pub_import_info['pubkey'], pub)
        assert 'hdmasterfingerprint' not in pub_import_info
        assert 'hdkeypath' not in pub_import_info

        # Import some public keys to the keypool of a no privkey wallet
        self.log.info("Adding pubkey to keypool of disableprivkey wallet")
        self.nodes[1].createwallet(wallet_name="noprivkeys", disable_private_keys=True)
        wrpc = self.nodes[1].get_wallet_rpc("noprivkeys")

        addr1 = self.nodes[0].getnewaddress()
        addr2 = self.nodes[0].getnewaddress()
        pub1 = self.nodes[0].getaddressinfo(addr1)['pubkey']
        pub2 = self.nodes[0].getaddressinfo(addr2)['pubkey']
        result = wrpc.importmulti(
            [{
                'desc': descsum_create('wpkh(' + pub1 + ')'),
                'keypool': True,
                "timestamp": "now",
            },
            {
                'desc': descsum_create('wpkh(' + pub2 + ')'),
                'keypool': True,
                "timestamp": "now",
            }]
        )
        assert result[0]['success']
        assert result[1]['success']
        assert_equal(wrpc.getwalletinfo()["keypoolsize"], 2)
        newaddr1 = wrpc.getnewaddress()
        assert_equal(addr1, newaddr1)
        newaddr2 = wrpc.getnewaddress()
        assert_equal(addr2, newaddr2)

        # Import some public keys to the internal keypool of a no privkey wallet
        self.log.info("Adding pubkey to internal keypool of disableprivkey wallet")
        addr1 = self.nodes[0].getnewaddress()
        addr2 = self.nodes[0].getnewaddress()
        pub1 = self.nodes[0].getaddressinfo(addr1)['pubkey']
        pub2 = self.nodes[0].getaddressinfo(addr2)['pubkey']
        result = wrpc.importmulti(
            [{
                'desc': descsum_create('wpkh(' + pub1 + ')'),
                'keypool': True,
                'internal': True,
                "timestamp": "now",
            },
            {
                'desc': descsum_create('wpkh(' + pub2 + ')'),
                'keypool': True,
                'internal': True,
                "timestamp": "now",
            }]
        )
        assert result[0]['success']
        assert result[1]['success']
        assert_equal(wrpc.getwalletinfo()["keypoolsize_hd_internal"], 2)
        newaddr1 = wrpc.getrawchangeaddress()
        assert_equal(addr1, newaddr1)
        newaddr2 = wrpc.getrawchangeaddress()
        assert_equal(addr2, newaddr2)

        # Import a multisig and make sure the keys don't go into the keypool
        self.log.info('Imported scripts with pubkeys should not have their pubkeys go into the keypool')
        addr1 = self.nodes[0].getnewaddress()
        addr2 = self.nodes[0].getnewaddress()
        pub1 = self.nodes[0].getaddressinfo(addr1)['pubkey']
        pub2 = self.nodes[0].getaddressinfo(addr2)['pubkey']
        result = wrpc.importmulti(
            [{
                'desc': descsum_create('wsh(multi(2,' + pub1 + ',' + pub2 + '))'),
                'keypool': True,
                "timestamp": "now",
            }]
        )
        assert result[0]['success']
        assert_equal(wrpc.getwalletinfo()["keypoolsize"], 0)

        # Cannot import those pubkeys to keypool of wallet with privkeys
        self.log.info("Pubkeys cannot be added to the keypool of a wallet with private keys")
        wrpc = self.nodes[1].get_wallet_rpc("")
        assert wrpc.getwalletinfo()['private_keys_enabled']
        result = wrpc.importmulti(
            [{
                'desc': descsum_create('wpkh(' + pub1 + ')'),
                'keypool': True,
                "timestamp": "now",
            }]
        )
        assert_equal(result[0]['error']['code'], -8)
        assert_equal(result[0]['error']['message'], "Keys can only be imported to the keypool when private keys are disabled")

        # Make sure ranged imports import keys in order
        self.log.info('Key ranges should be imported in order')
        wrpc = self.nodes[1].get_wallet_rpc("noprivkeys")
        assert_equal(wrpc.getwalletinfo()["keypoolsize"], 0)
        assert_equal(wrpc.getwalletinfo()["private_keys_enabled"], False)
        xpub = "tpubDAXcJ7s7ZwicqjprRaEWdPoHKrCS215qxGYxpusRLLmJuT69ZSicuGdSfyvyKpvUNYBW1s2U3NSrT6vrCYB9e6nZUEvrqnwXPF8ArTCRXMY"
        addresses = [
            'ncrt1qtmp74ayg7p24uslctssvjm06q5phz4yrvy646e', # m/0'/0'/0
            'ncrt1q8vprchan07gzagd5e6v9wd7azyucksq2vqu8lj', # m/0'/0'/1
            'ncrt1qtuqdtha7zmqgcrr26n2rqxztv5y8rafjtaapkf', # m/0'/0'/2
            'ncrt1qau64272ymawq26t90md6an0ps99qkrse7le8u6', # m/0'/0'/3
            'ncrt1qsg97266hrh6cpmutqen8s4s962aryy77ced5p6', # m/0'/0'/4
        ]
        result = wrpc.importmulti(
            [{
                'desc': descsum_create('wpkh([80002067/0h/0h]' + xpub + '/*)'),
                'keypool': True,
                'timestamp': 'now',
                'range' : [0, 4],
            }]
        )
        for i in range(0, 5):
            addr = wrpc.getnewaddress('', 'bech32')
            assert_equal(addr, addresses[i])
Beispiel #24
0
    def run_test(self):
        assert_raises_rpc_error(-5, "Invalid descriptor",
                                self.nodes[0].deriveaddresses, "a")

        descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)#t6wfjs64"
        address = "chirt1qjqmxmkpmxt80xz4y3746zgt0q3u3ferrqen86t"
        assert_equal(self.nodes[0].deriveaddresses(descriptor), [address])

        descriptor = descriptor[:-9]
        assert_raises_rpc_error(-5, "Invalid descriptor",
                                self.nodes[0].deriveaddresses, descriptor)

        descriptor_pubkey = "wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0)#s9ga3alw"
        address = "chirt1qjqmxmkpmxt80xz4y3746zgt0q3u3ferrqen86t"
        assert_equal(self.nodes[0].deriveaddresses(descriptor_pubkey),
                     [address])

        ranged_descriptor = "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)#kft60nuy"
        assert_equal(self.nodes[0].deriveaddresses(ranged_descriptor, [1, 2]),
                     [
                         "chirt1qhku5rq7jz8ulufe2y6fkcpnlvpsta7rqyem46m",
                         "chirt1qpgptk2gvshyl0s9lqshsmx932l9ccsv2tc9n2l"
                     ])
        assert_equal(self.nodes[0].deriveaddresses(ranged_descriptor, 2), [
            address, "chirt1qhku5rq7jz8ulufe2y6fkcpnlvpsta7rqyem46m",
            "chirt1qpgptk2gvshyl0s9lqshsmx932l9ccsv2tc9n2l"
        ])

        assert_raises_rpc_error(
            -8, "Range should not be specified for an un-ranged descriptor",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"
            ), [0, 2])

        assert_raises_rpc_error(
            -8, "Range must be specified for a ranged descriptor",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ))

        assert_raises_rpc_error(
            -8, "End of range is too high", self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), 10000000000)

        assert_raises_rpc_error(
            -8, "Range is too large", self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), [1000000000, 2000000000])

        assert_raises_rpc_error(
            -8, "Range specified as [begin,end] must not have begin after end",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), [2, 0])

        assert_raises_rpc_error(
            -8, "Range should be greater or equal than 0",
            self.nodes[0].deriveaddresses,
            descsum_create(
                "wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/*)"
            ), [-1, 0])

        combo_descriptor = descsum_create(
            "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/1/1/0)"
        )
        assert_equal(self.nodes[0].deriveaddresses(combo_descriptor), [
            "cdtc9yjKpBQkBYxSGHMUJPhRWCszYea4Pu",
            "cdtc9yjKpBQkBYxSGHMUJPhRWCszYea4Pu", address,
            "da6JZm5GyiBdz2ppDr5VqjftLGdp2EZyd7"
        ])

        hardened_without_privkey_descriptor = descsum_create(
            "wpkh(tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1'/1/0)"
        )
        assert_raises_rpc_error(-5,
                                "Cannot derive script without private keys",
                                self.nodes[0].deriveaddresses,
                                hardened_without_privkey_descriptor)

        bare_multisig_descriptor = descsum_create(
            "multi(1,tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/0,tpubD6NzVbkrYhZ4WaWSyoBvQwbpLkojyoTZPRsgXELWz3Popb3qkjcJyJUGLnL4qHHoQvao8ESaAstxYSnhyswJ76uZPStJRJCTKvosUCJZL5B/1/1/1)"
        )
        assert_raises_rpc_error(
            -5, "Descriptor does not have a corresponding address",
            self.nodes[0].deriveaddresses, bare_multisig_descriptor)