Skip to content

Commit ff65b69

Browse files
committed
Merge bitcoin/bitcoin#22067: Test and document a basic M-of-N multisig using descriptor wallets and PSBTs
9de0d94 doc: add disclaimer highlighting shortcomings of the basic multisig example (Michael Dietz) f9479e4 test, doc: basic M-of-N multisig minor cleanup and clarifications (Michael Dietz) e05cd05 doc: add another signing flow for multisig with descriptor wallets and PSBTs (Michael Dietz) 17dd657 doc: M-of-N multisig using descriptor wallets and PSBTs, as well as a signing flow (Michael Dietz) 1f20501 test: add functional test for multisig flow with descriptor wallets and PSBTs (Michael Dietz) Pull request description: Aims to resolve issue bitcoin/bitcoin#21278. I try to follow the steps laanwj outlined there exactly, with the exception of using `combinepsbt` instead of `joinpsbts`. I wrote a functional test to make sure it works as expected before doing the docs, and figured it would also be a good source of documentation. So I kept the test as simple as possible and didn't go crazy with edge-cases and various checks. I do have a lot more test-cases I've written that I will follow up with (either in a separate PR or another commit - lmk if you have a preference), but I want to do it in a way that doesn't bloat this test so it remains useful as a quickstart (unless that's a bad idea)? ACKs for top commit: S3RK: Code review ACK 9de0d94. Rspigler's argument convinced me that we should leave the workflow with two wallets. I assume using multisig with external signers is a popular use-case and it's important to keep compatibility. laanwj: Code and documentation review ACK 9de0d94 Tree-SHA512: 6c76e787c21f09d8be5eaa11f3ca3eaa4868497824050562bdfb2095c73b90f5e8987a8775119891d6bfde586e3f31ad1b13e4b67b0802e1d23ef050227a1211
2 parents 2e82af4 + 9de0d94 commit ff65b69

File tree

4 files changed

+208
-0
lines changed

4 files changed

+208
-0
lines changed

doc/descriptors.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,47 @@ Key order does not matter for `sortedmulti()`. `sortedmulti()` behaves in the sa
139139
as `multi()` does but the keys are reordered in the resulting script such that they
140140
are lexicographically ordered as described in BIP67.
141141

142+
#### Basic multisig example
143+
144+
For a good example of a basic M-of-N multisig between multiple participants using descriptor
145+
wallets and PSBTs, as well as a signing flow, see [this functional test](/test/functional/wallet_multisig_descriptor_psbt.py).
146+
147+
Disclaimers: It is important to note that this example serves as a quick-start and is kept basic for readability. A downside of the approach
148+
outlined here is that each participant must maintain (and backup) two separate wallets: a signer and the corresponding multisig.
149+
It should also be noted that privacy best-practices are not "by default" here - participants should take care to only use the signer to sign
150+
transactions related to the multisig. Lastly, it is not recommended to use anything other than a Bitcoin Core descriptor wallet to serve as your
151+
signer(s). Other wallets, whether hardware or software, likely impose additional checks and safeguards to prevent users from signing transactions that
152+
could lead to loss of funds, or are deemed security hazards. Conforming to various 3rd-party checks and verifications is not in the scope of this example.
153+
154+
The basic steps are:
155+
156+
1. Every participant generates an xpub. The most straightforward way is to create a new descriptor wallet which we will refer to as
157+
the participant's signer wallet. Avoid reusing this wallet for any purpose other than signing transactions from the
158+
corresponding multisig we are about to create. Hint: extract the wallet's xpubs using `listdescriptors` and pick the one from the
159+
`pkh` descriptor since it's least likely to be accidentally reused (legacy addresses)
160+
2. Create a watch-only descriptor wallet (blank, private keys disabled). Now the multisig is created by importing the two descriptors:
161+
`wsh(sortedmulti(<M>,XPUB1/0/*,XPUB2/0/*,…,XPUBN/0/*))` and `wsh(sortedmulti(<M>,XPUB1/1/*,XPUB2/1/*,…,XPUBN/1/*))`
162+
(one descriptor w/ `0` for receiving addresses and another w/ `1` for change). Every participant does this
163+
3. A receiving address is generated for the multisig. As a check to ensure step 2 was done correctly, every participant
164+
should verify they get the same addresses
165+
4. Funds are sent to the resulting address
166+
5. A sending transaction from the multisig is created using `walletcreatefundedpsbt` (anyone can initiate this). It is simple to do
167+
this in the GUI by going to the `Send` tab in the multisig wallet and creating an unsigned transaction (PSBT)
168+
6. At least `M` participants check the PSBT with their multisig using `decodepsbt` to verify the transaction is OK before signing it.
169+
7. (If OK) the participant signs the PSBT with their signer wallet using `walletprocesspsbt`. It is simple to do this in the GUI by
170+
loading the PSBT from file and signing it
171+
8. The signed PSBTs are collected with `combinepsbt`, finalized w/ `finalizepsbt`, and then the resulting transaction is broadcasted
172+
to the network. Note that any wallet (eg one of the signers or multisig) is capable of doing this.
173+
9. Checks that balances are correct after the transaction has been included in a block
174+
175+
You may prefer a daisy chained signing flow where each participant signs the PSBT one after another until
176+
the PSBT has been signed `M` times and is "complete." For the most part, the steps above remain the same, except (6, 7)
177+
change slightly from signing the original PSBT in parallel to signing it in series. `combinepsbt` is not necessary with
178+
this signing flow and the last (`m`th) signer can just broadcast the PSBT after signing. Note that a parallel signing flow may be
179+
preferable in cases where there are more signers. This signing flow is also included in the test / Python example.
180+
[The test](/test/functional/wallet_multisig_descriptor_psbt.py) is meant to be documentation as much as it is a functional test, so
181+
it is kept as simple and readable as possible.
182+
142183
### BIP32 derived keys and chains
143184

144185
Most modern wallet software and hardware uses keys that are derived using

doc/psbt.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,9 @@ hardware implementations will typically implement multiple roles simultaneously.
9292

9393
#### Multisig with multiple Bitcoin Core instances
9494

95+
For a quick start see [Basic M-of-N multisig example using descriptor wallets and PSBTs](./descriptors.md#basic-multisig-example).
96+
If you are using legacy wallets feel free to continue with the example provided here.
97+
9598
Alice, Bob, and Carol want to create a 2-of-3 multisig address. They're all using
9699
Bitcoin Core. We assume their wallets only contain the multisig funds. In case
97100
they also have a personal wallet, this can be accomplished through the

test/functional/test_runner.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,7 @@
207207
'feature_assumevalid.py',
208208
'example_test.py',
209209
'wallet_txn_doublespend.py --legacy-wallet',
210+
'wallet_multisig_descriptor_psbt.py',
210211
'wallet_txn_doublespend.py --descriptors',
211212
'feature_backwards_compatibility.py --legacy-wallet',
212213
'feature_backwards_compatibility.py --descriptors',
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2021 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 a basic M-of-N multisig setup between multiple people using descriptor wallets and PSBTs, as well as a signing flow.
6+
7+
This is meant to be documentation as much as functional tests, so it is kept as simple and readable as possible.
8+
"""
9+
10+
from test_framework.address import base58_to_byte
11+
from test_framework.test_framework import BitcoinTestFramework
12+
from test_framework.util import (
13+
assert_approx,
14+
assert_equal,
15+
)
16+
17+
18+
class WalletMultisigDescriptorPSBTTest(BitcoinTestFramework):
19+
def set_test_params(self):
20+
self.num_nodes = 3
21+
self.setup_clean_chain = True
22+
self.wallet_names = []
23+
self.extra_args = [["-keypool=100"]] * self.num_nodes
24+
25+
def skip_test_if_missing_module(self):
26+
self.skip_if_no_wallet()
27+
self.skip_if_no_sqlite()
28+
29+
@staticmethod
30+
def _get_xpub(wallet):
31+
"""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)."""
32+
descriptor = next(filter(lambda d: d["desc"].startswith("pkh"), wallet.listdescriptors()["descriptors"]))
33+
return descriptor["desc"].split("]")[-1].split("/")[0]
34+
35+
@staticmethod
36+
def _check_psbt(psbt, to, value, multisig):
37+
"""Helper function for any of the N participants to check the psbt with decodepsbt and verify it is OK before signing."""
38+
tx = multisig.decodepsbt(psbt)["tx"]
39+
amount = 0
40+
for vout in tx["vout"]:
41+
address = vout["scriptPubKey"]["address"]
42+
assert_equal(multisig.getaddressinfo(address)["ischange"], address != to)
43+
if address == to:
44+
amount += vout["value"]
45+
assert_approx(amount, float(value), vspan=0.001)
46+
47+
def participants_create_multisigs(self, xpubs):
48+
"""The multisig is created by importing the following descriptors. The resulting wallet is watch-only and every participant can do this."""
49+
# some simple validation
50+
assert_equal(len(xpubs), self.N)
51+
# a sanity-check/assertion, this will throw if the base58 checksum of any of the provided xpubs are invalid
52+
for xpub in xpubs:
53+
base58_to_byte(xpub)
54+
55+
for i, node in enumerate(self.nodes):
56+
node.createwallet(wallet_name=f"{self.name}_{i}", blank=True, descriptors=True, disable_private_keys=True)
57+
multisig = node.get_wallet_rpc(f"{self.name}_{i}")
58+
external = multisig.getdescriptorinfo(f"wsh(sortedmulti({self.M},{f'/0/*,'.join(xpubs)}/0/*))")
59+
internal = multisig.getdescriptorinfo(f"wsh(sortedmulti({self.M},{f'/1/*,'.join(xpubs)}/1/*))")
60+
result = multisig.importdescriptors([
61+
{ # receiving addresses (internal: False)
62+
"desc": external["descriptor"],
63+
"active": True,
64+
"internal": False,
65+
"timestamp": "now",
66+
},
67+
{ # change addresses (internal: True)
68+
"desc": internal["descriptor"],
69+
"active": True,
70+
"internal": True,
71+
"timestamp": "now",
72+
},
73+
])
74+
assert all(r["success"] for r in result)
75+
yield multisig
76+
77+
def run_test(self):
78+
self.M = 2
79+
self.N = self.num_nodes
80+
self.name = f"{self.M}_of_{self.N}_multisig"
81+
self.log.info(f"Testing {self.name}...")
82+
83+
participants = {
84+
# Every participant generates an xpub. The most straightforward way is to create a new descriptor wallet.
85+
# This wallet will be the participant's `signer` for the resulting multisig. Avoid reusing this wallet for any other purpose (for privacy reasons).
86+
"signers": [node.get_wallet_rpc(node.createwallet(wallet_name=f"participant_{self.nodes.index(node)}", descriptors=True)["name"]) for node in self.nodes],
87+
# After participants generate and exchange their xpubs they will each create their own watch-only multisig.
88+
# Note: these multisigs are all the same, this justs highlights that each participant can independently verify everything on their own node.
89+
"multisigs": []
90+
}
91+
92+
self.log.info("Generate and exchange xpubs...")
93+
xpubs = [self._get_xpub(signer) for signer in participants["signers"]]
94+
95+
self.log.info("Every participant imports the following descriptors to create the watch-only multisig...")
96+
participants["multisigs"] = list(self.participants_create_multisigs(xpubs))
97+
98+
self.log.info("Check that every participant's multisig generates the same addresses...")
99+
for _ in range(10): # we check that the first 10 generated addresses are the same for all participant's multisigs
100+
receive_addresses = [multisig.getnewaddress() for multisig in participants["multisigs"]]
101+
all(address == receive_addresses[0] for address in receive_addresses)
102+
change_addresses = [multisig.getrawchangeaddress() for multisig in participants["multisigs"]]
103+
all(address == change_addresses[0] for address in change_addresses)
104+
105+
self.log.info("Get a mature utxo to send to the multisig...")
106+
coordinator_wallet = participants["signers"][0]
107+
coordinator_wallet.generatetoaddress(101, coordinator_wallet.getnewaddress())
108+
109+
deposit_amount = 6.15
110+
multisig_receiving_address = participants["multisigs"][0].getnewaddress()
111+
self.log.info("Send funds to the resulting multisig receiving address...")
112+
coordinator_wallet.sendtoaddress(multisig_receiving_address, deposit_amount)
113+
self.nodes[0].generate(1)
114+
self.sync_all()
115+
for participant in participants["multisigs"]:
116+
assert_approx(participant.getbalance(), deposit_amount, vspan=0.001)
117+
118+
self.log.info("Send a transaction from the multisig!")
119+
to = participants["signers"][self.N - 1].getnewaddress()
120+
value = 1
121+
self.log.info("First, make a sending transaction, created using `walletcreatefundedpsbt` (anyone can initiate this)...")
122+
psbt = participants["multisigs"][0].walletcreatefundedpsbt(inputs=[], outputs={to: value}, options={"feeRate": 0.00010})
123+
124+
psbts = []
125+
self.log.info("Now at least M users check the psbt with decodepsbt and (if OK) signs it with walletprocesspsbt...")
126+
for m in range(self.M):
127+
signers_multisig = participants["multisigs"][m]
128+
self._check_psbt(psbt["psbt"], to, value, signers_multisig)
129+
signing_wallet = participants["signers"][m]
130+
partially_signed_psbt = signing_wallet.walletprocesspsbt(psbt["psbt"])
131+
psbts.append(partially_signed_psbt["psbt"])
132+
133+
self.log.info("Finally, collect the signed PSBTs with combinepsbt, finalizepsbt, then broadcast the resulting transaction...")
134+
combined = coordinator_wallet.combinepsbt(psbts)
135+
finalized = coordinator_wallet.finalizepsbt(combined)
136+
coordinator_wallet.sendrawtransaction(finalized["hex"])
137+
138+
self.log.info("Check that balances are correct after the transaction has been included in a block.")
139+
self.nodes[0].generate(1)
140+
self.sync_all()
141+
assert_approx(participants["multisigs"][0].getbalance(), deposit_amount - value, vspan=0.001)
142+
assert_equal(participants["signers"][self.N - 1].getbalance(), value)
143+
144+
self.log.info("Send another transaction from the multisig, this time with a daisy chained signing flow (one after another in series)!")
145+
psbt = participants["multisigs"][0].walletcreatefundedpsbt(inputs=[], outputs={to: value}, options={"feeRate": 0.00010})
146+
for m in range(self.M):
147+
signers_multisig = participants["multisigs"][m]
148+
self._check_psbt(psbt["psbt"], to, value, signers_multisig)
149+
signing_wallet = participants["signers"][m]
150+
psbt = signing_wallet.walletprocesspsbt(psbt["psbt"])
151+
assert_equal(psbt["complete"], m == self.M - 1)
152+
finalized = coordinator_wallet.finalizepsbt(psbt["psbt"])
153+
coordinator_wallet.sendrawtransaction(finalized["hex"])
154+
155+
self.log.info("Check that balances are correct after the transaction has been included in a block.")
156+
self.nodes[0].generate(1)
157+
self.sync_all()
158+
assert_approx(participants["multisigs"][0].getbalance(), deposit_amount - (value * 2), vspan=0.001)
159+
assert_equal(participants["signers"][self.N - 1].getbalance(), value * 2)
160+
161+
162+
if __name__ == "__main__":
163+
WalletMultisigDescriptorPSBTTest().main()

0 commit comments

Comments
 (0)