wallet_miniscript_decaying_multisig_descriptor_psbt.py raw
1 #!/usr/bin/env python3
2 # Copyright (c) 2024 The Limenka 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 a miniscript multisig that starts as 4-of-4 and "decays" to 3-of-4, 2-of-4, and finally 1-of-4 at each future halvening block height.
6 7 Spending policy: `thresh(4,pk(key_1),pk(key_2),pk(key_3),pk(key_4),after(t1),after(t2),after(t3))`
8 This is similar to `test/functional/wallet_multisig_descriptor_psbt.py`.
9 """
10 11 import random
12 from test_framework.test_framework import LimenkaTestFramework
13 from test_framework.util import (
14 assert_approx,
15 assert_equal,
16 assert_raises_rpc_error,
17 )
18 19 20 class WalletMiniscriptDecayingMultisigDescriptorPSBTTest(LimenkaTestFramework):
21 def add_options(self, parser):
22 self.add_wallet_options(parser, legacy=False)
23 24 def set_test_params(self):
25 self.num_nodes = 1
26 self.setup_clean_chain = True
27 self.wallet_names = []
28 self.extra_args = [["-keypool=100"]]
29 30 def skip_test_if_missing_module(self):
31 self.skip_if_no_wallet()
32 self.skip_if_no_sqlite()
33 34 @staticmethod
35 def _get_xpub(wallet, internal):
36 """Extract the wallet's xpubs using `listdescriptors` and pick the one from the `pkh` descriptor since it's least likely to be accidentally reused (legacy addresses)."""
37 pkh_descriptor = next(filter(lambda d: d["desc"].startswith("pkh(") and d["internal"] == internal, wallet.listdescriptors()["descriptors"]))
38 # keep all key origin information (master key fingerprint and all derivation steps) for proper support of hardware devices
39 # see section 'Key origin identification' in 'doc/descriptors.md' for more details...
40 return pkh_descriptor["desc"].split("pkh(")[1].split(")")[0]
41 42 def create_multisig(self, external_xpubs, internal_xpubs):
43 """The multisig is created by importing the following descriptors. The resulting wallet is watch-only and every signer can do this."""
44 self.node.createwallet(wallet_name=f"{self.name}", blank=True, descriptors=True, disable_private_keys=True)
45 multisig = self.node.get_wallet_rpc(f"{self.name}")
46 # spending policy: `thresh(4,pk(key_1),pk(key_2),pk(key_3),pk(key_4),after(t1),after(t2),after(t3))`
47 # IMPORTANT: when backing up your descriptor, the order of key_1...key_4 must be correct!
48 external = multisig.getdescriptorinfo(f"wsh(thresh({self.N},pk({'),s:pk('.join(external_xpubs)}),sln:after({'),sln:after('.join(map(str, self.locktimes))})))")
49 internal = multisig.getdescriptorinfo(f"wsh(thresh({self.N},pk({'),s:pk('.join(internal_xpubs)}),sln:after({'),sln:after('.join(map(str, self.locktimes))})))")
50 result = multisig.importdescriptors([
51 { # receiving addresses (internal: False)
52 "desc": external["descriptor"],
53 "active": True,
54 "internal": False,
55 "timestamp": "now",
56 },
57 { # change addresses (internal: True)
58 "desc": internal["descriptor"],
59 "active": True,
60 "internal": True,
61 "timestamp": "now",
62 },
63 ])
64 assert all(r["success"] for r in result)
65 return multisig
66 67 def run_test(self):
68 self.node = self.nodes[0]
69 self.M = 4 # starts as 4-of-4
70 self.N = 4
71 72 self.locktimes = [104, 106, 108]
73 assert_equal(len(self.locktimes), self.N - 1)
74 75 self.name = f"{self.M}_of_{self.N}_decaying_multisig"
76 self.log.info(f"Testing a miniscript multisig which starts as 4-of-4 and 'decays' to 3-of-4 at block height {self.locktimes[0]}, 2-of-4 at {self.locktimes[1]}, and finally 1-of-4 at {self.locktimes[2]}...")
77 78 self.log.info("Create the signer wallets and get their xpubs...")
79 signers = [self.node.get_wallet_rpc(self.node.createwallet(wallet_name=f"signer_{i}", descriptors=True)["name"]) for i in range(self.N)]
80 external_xpubs, internal_xpubs = [[self._get_xpub(signer, internal) for signer in signers] for internal in [False, True]]
81 82 self.log.info("Create the watch-only decaying multisig using signers' xpubs...")
83 multisig = self.create_multisig(external_xpubs, internal_xpubs)
84 85 self.log.info("Get a mature utxo to send to the multisig...")
86 coordinator_wallet = self.node.get_wallet_rpc(self.node.createwallet(wallet_name="coordinator", descriptors=True)["name"])
87 self.generatetoaddress(self.node, 101, coordinator_wallet.getnewaddress())
88 89 self.log.info("Send funds to the multisig's receiving address...")
90 deposit_amount = 6.15
91 coordinator_wallet.sendtoaddress(multisig.getnewaddress(), deposit_amount)
92 self.generate(self.node, 1)
93 assert_approx(multisig.getbalance(), deposit_amount, vspan=0.001)
94 95 self.log.info("Send transactions from the multisig as required signers decay...")
96 amount = 1.5
97 receiver = signers[0]
98 sent = 0
99 for locktime in [0] + self.locktimes:
100 self.log.info(f"At block height >= {locktime} this multisig is {self.M}-of-{self.N}")
101 current_height = self.node.getblock(self.node.getbestblockhash())['height']
102 103 # in this test each signer signs the same psbt "in series" one after the other.
104 # Another option is for each signer to sign the original psbt, and then combine
105 # and finalize these. In some cases this may be more optimal for coordination.
106 psbt = multisig.walletcreatefundedpsbt(inputs=[], outputs={receiver.getnewaddress(): amount}, feeRate=0.00010, locktime=locktime)
107 # the random sample asserts that any of the signing keys can sign for the 3-of-4,
108 # 2-of-4, and 1-of-4. While this is basic behavior of the miniscript thresh primitive,
109 # it is a critical property of this wallet.
110 for i, m in enumerate(random.sample(range(self.M), self.M)):
111 psbt = signers[m].walletprocesspsbt(psbt["psbt"])
112 assert_equal(psbt["complete"], i == self.M - 1)
113 114 if self.M < self.N:
115 self.log.info(f"Check that the time-locked transaction is too immature to spend with {self.M}-of-{self.N} at block height {current_height}...")
116 assert_equal(current_height >= locktime, False)
117 assert_raises_rpc_error(-26, "non-final", multisig.sendrawtransaction, psbt["hex"])
118 119 self.log.info(f"Generate blocks to reach the time-lock block height {locktime} and broadcast the transaction...")
120 self.generate(self.node, locktime - current_height)
121 else:
122 self.log.info("All the signers are required to spend before the first locktime")
123 124 multisig.sendrawtransaction(psbt["hex"])
125 sent += amount
126 127 self.log.info("Check that balances are correct after the transaction has been included in a block...")
128 self.generate(self.node, 1)
129 assert_approx(multisig.getbalance(), deposit_amount - sent, vspan=0.001)
130 assert_equal(receiver.getbalance(), sent)
131 132 self.M -= 1 # decay the number of required signers for the next locktime..
133 134 135 if __name__ == "__main__":
136 WalletMiniscriptDecayingMultisigDescriptorPSBTTest(__file__).main()
137