wallet_listdescriptors.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2014-present The Bitcoin Core developers
   3  # Distributed under the MIT software license, see the accompanying
   4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  """Test the listdescriptors RPC."""
   6  
   7  from test_framework.blocktools import (
   8      TIME_GENESIS_BLOCK,
   9  )
  10  from test_framework.descriptors import (
  11      descsum_create,
  12  )
  13  from test_framework.extendedkey import ExtendedPrivateKey
  14  from test_framework.test_framework import BitcoinTestFramework
  15  from test_framework.util import (
  16      assert_not_equal,
  17      assert_equal,
  18      assert_raises_rpc_error,
  19  )
  20  from test_framework.wallet_util import generate_keypair
  21  
  22  
  23  class ListDescriptorsTest(BitcoinTestFramework):
  24      def set_test_params(self):
  25          self.num_nodes = 1
  26  
  27      def skip_test_if_missing_module(self):
  28          self.skip_if_no_wallet()
  29  
  30      # do not create any wallet by default
  31      def init_wallet(self, *, node):
  32          return
  33  
  34      def run_test(self):
  35          node = self.nodes[0]
  36          assert_raises_rpc_error(-18, 'No wallet is loaded.', node.listdescriptors)
  37  
  38          self.log.info('Test the command for empty descriptors wallet.')
  39          node.createwallet(wallet_name='w2', blank=True)
  40          assert_equal(0, len(node.get_wallet_rpc('w2').listdescriptors()['descriptors']))
  41  
  42          self.log.info('Test the command for a default descriptors wallet.')
  43          node.createwallet(wallet_name='w3')
  44          result = node.get_wallet_rpc('w3').listdescriptors()
  45          assert_equal("w3", result['wallet_name'])
  46          assert_equal(8, len(result['descriptors']))
  47          assert_equal(8, len([d for d in result['descriptors'] if d['active']]))
  48          assert_equal(4, len([d for d in result['descriptors'] if d['internal']]))
  49          for item in result['descriptors']:
  50              assert_not_equal(item['desc'], '')
  51              assert_equal(item['next_index'], 0)
  52              assert_equal(item['range'], [0, 0])
  53              assert item['timestamp'] is not None
  54  
  55          self.log.info('Test that descriptor strings are returned in lexicographically sorted order.')
  56          descriptor_strings = [descriptor['desc'] for descriptor in result['descriptors']]
  57          assert_equal(descriptor_strings, sorted(descriptor_strings))
  58  
  59          self.log.info('Test descriptors with hardened derivations are listed in importable form.')
  60          extended_key = ExtendedPrivateKey.generate()
  61          xprv = extended_key.to_string()
  62          xprv_fingerprint = extended_key._fingerprint().hex()
  63          hardened_path = '/84h/1h/0h'
  64          xpub_acc = extended_key.derive_path(f"m{hardened_path}").pubkey().to_string()
  65          wallet = node.get_wallet_rpc('w2')
  66          wallet.importdescriptors([{
  67              'desc': descsum_create('wpkh(' + xprv + hardened_path + '/0/*)'),
  68              'timestamp': TIME_GENESIS_BLOCK,
  69          }])
  70          expected = {
  71              'wallet_name': 'w2',
  72              'descriptors': [
  73                  {'desc': descsum_create('wpkh([' + xprv_fingerprint + hardened_path + ']' + xpub_acc + '/0/*)'),
  74                   'timestamp': TIME_GENESIS_BLOCK,
  75                   'active': False,
  76                   'range': [0, 0],
  77                   'next': 0,
  78                   'next_index': 0},
  79              ],
  80          }
  81          assert_equal(expected, wallet.listdescriptors())
  82          assert_equal(expected, wallet.listdescriptors(False))
  83  
  84          self.log.info('Test list private descriptors')
  85          expected_private = {
  86              'wallet_name': 'w2',
  87              'descriptors': [
  88                  {'desc': descsum_create('wpkh(' + xprv + hardened_path + '/0/*)'),
  89                   'timestamp': TIME_GENESIS_BLOCK,
  90                   'active': False,
  91                   'range': [0, 0],
  92                   'next': 0,
  93                   'next_index': 0},
  94              ],
  95          }
  96          assert_equal(expected_private, wallet.listdescriptors(True))
  97  
  98          self.log.info("Test listdescriptors with encrypted wallet")
  99          wallet.encryptwallet("pass")
 100          assert_equal(expected, wallet.listdescriptors())
 101  
 102          self.log.info('Test list private descriptors with encrypted wallet')
 103          assert_raises_rpc_error(-13, 'Please enter the wallet passphrase with walletpassphrase first.', wallet.listdescriptors, True)
 104          wallet.walletpassphrase(passphrase="pass", timeout=1000000)
 105          assert_equal(expected_private, wallet.listdescriptors(True))
 106  
 107          self.log.info('Test list private descriptors with watch-only wallet')
 108          node.createwallet(wallet_name='watch-only', disable_private_keys=True)
 109          watch_only_wallet = node.get_wallet_rpc('watch-only')
 110          watch_only_wallet.importdescriptors([{
 111              'desc': descsum_create('wpkh(' + xpub_acc + ')'),
 112              'timestamp': TIME_GENESIS_BLOCK,
 113          }])
 114          assert_raises_rpc_error(-4, 'Can\'t get private descriptor string for watch-only wallets', watch_only_wallet.listdescriptors, True)
 115  
 116          self.log.info('Test non-active non-range combo descriptor')
 117          node.createwallet(wallet_name='w4', blank=True)
 118          wallet = node.get_wallet_rpc('w4')
 119          wallet.importdescriptors([{
 120              'desc': descsum_create('combo(' + node.get_deterministic_priv_key().key + ')'),
 121              'timestamp': TIME_GENESIS_BLOCK,
 122          }])
 123          expected = {
 124              'wallet_name': 'w4',
 125              'descriptors': [
 126                  {'active': False,
 127                   'desc': 'combo(0227d85ba011276cf25b51df6a188b75e604b38770a462b2d0e9fb2fc839ef5d3f)#np574htj',
 128                   'timestamp': TIME_GENESIS_BLOCK},
 129              ],
 130          }
 131          assert_equal(expected, wallet.listdescriptors())
 132  
 133          self.log.info('Test taproot descriptor do not have mixed hardened derivation marker')
 134          node.createwallet(wallet_name='w5', descriptors=True, disable_private_keys=True)
 135          wallet = node.get_wallet_rpc('w5')
 136          derivation_path = "/48'/1'/0'/2'"
 137          xprvs = [ExtendedPrivateKey.generate() for _ in range(0, 2)]
 138          xprv_fingerprints = [xprv._fingerprint().hex() for xprv in xprvs]
 139          desc_xpubs = [xprv.derive_path(f"m{derivation_path}").pubkey().to_string() for xprv in xprvs]
 140          wallet.importdescriptors([{
 141              'desc': descsum_create(f"tr([{xprv_fingerprints[0]}{derivation_path}]{desc_xpubs[0]}/0/*,and_v(v:pk([{xprv_fingerprints[1]}{derivation_path}]{desc_xpubs[1]}/0/*),older(65535)))"),
 142              'timestamp': TIME_GENESIS_BLOCK,
 143          }])
 144          derivation_path_alternate = "/48h/1h/0h/2h"
 145          expected = {
 146              'wallet_name': 'w5',
 147              'descriptors': [
 148                  {'active': False,
 149                   'desc': descsum_create(f'tr([{xprv_fingerprints[0]}{derivation_path_alternate}]{desc_xpubs[0]}/0/*,and_v(v:pk([{xprv_fingerprints[1]}{derivation_path_alternate}]{desc_xpubs[1]}/0/*),older(65535)))'),
 150                   'timestamp': TIME_GENESIS_BLOCK,
 151                   'range': [0, 0],
 152                   'next': 0,
 153                   'next_index': 0},
 154              ]
 155          }
 156          assert_equal(expected, wallet.listdescriptors())
 157  
 158          self.log.info('Test descriptor with missing private keys')
 159          node.createwallet(wallet_name='w6', blank=True)
 160          wallet = node.get_wallet_rpc('w6')
 161  
 162          xprvs = []
 163          xpubs = []
 164          for _ in range(0, 8):
 165              xprvs.append(ExtendedPrivateKey.generate().to_string())
 166              xpubs.append(ExtendedPrivateKey.generate().pubkey().to_string())
 167  
 168          _, pubkey_bytes = generate_keypair()
 169          pubkey = pubkey_bytes.hex()
 170  
 171          expected_descs = {
 172              descsum_create(f'tr({node.get_deterministic_priv_key().key},{{pk({pubkey}),pk([d34db33f/44h/0h/0h]{xpubs[0]}/0)}})'),
 173              descsum_create(f'wsh(and_v(v:ripemd160(095ff41131e5946f3c85f79e44adbcf8e27e080e),multi(1,{node.get_deterministic_priv_key().key},{xpubs[1]}/0)))'),
 174              descsum_create(f'tr({pubkey},pk(musig({xprvs[0]},{xpubs[2]})/7/8/*))'),
 175              descsum_create(f'tr({pubkey},pk(musig({xprvs[1]}/10,{xpubs[3]}/11)/*))'),
 176              descsum_create(f'tr({pubkey},{{pk(musig({xpubs[4]},{xprvs[2]})/12/*),pk(musig({xprvs[3]},{xpubs[4]})/13/*)}})'),
 177              descsum_create(f'tr({pubkey},{{pk(musig({xpubs[5]},{xpubs[6]})/12/*),pk(musig({xprvs[4]},{xpubs[7]})/13/*)}})')
 178          }
 179  
 180          descs_to_import = []
 181          for desc in expected_descs:
 182              descs_to_import.append({'desc': desc, 'timestamp': TIME_GENESIS_BLOCK})
 183  
 184          wallet.importdescriptors(descs_to_import)
 185          result = wallet.listdescriptors(True)
 186          actual_descs = [d['desc'] for d in result['descriptors']]
 187  
 188          assert_equal(len(actual_descs), len(expected_descs))
 189          for desc in actual_descs:
 190              if desc not in expected_descs:
 191                  raise AssertionError(f"{desc} missing")
 192  
 193  
 194  
 195  if __name__ == '__main__':
 196      ListDescriptorsTest(__file__).main()
 197