Repository navigation
wallet: fill PSBT_GLOBAL_XPUB - #36154
jeanpablojp wants to merge 2 commits into
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. |
b2ac7cd to
a586e55
Compare
|
🚧 At least one of the CI tasks failed. HintsTry to run the tests locally, according to the documentation. However, a CI failure may still
Leave a comment here, if you need help tracking down a confusing failure. |
a586e55 to
92bf732
Compare
|
@jeanpablojp in the RP description, can you point to the source code in Specter where it adds the global xpub? This might be useful for those who want to verify that it's still needed. Similarly, it's useful to provide a before and after example flow with HWI (and e.g. a Trezor / simulator). (It's also better to not to tag people in the PR description, because IIUC that text ends up in the merge commit, which then keeps triggering notifications as other projects backport it.) |
|
Both are in the description now. The Specter link points at On the flow: I ran the Trezor T simulator first, and it signs the same PSBT with or without the field, same signature, same prompts, same screens. What differs is only the data HWI hands it, since without the field I had written that the Trezor needed the field. That was wrong, and the description is corrected. Also dropped the tag, thanks for the note about the merge commit. |
|
Thanks. It's useful to know that Trezor doesn't seem to need this, but BitBox02 and perhaps other devices do. I suspect that once we support the new But providing global xpubs may still be useful for flows without HWI. |
|
Please shorten your description. We don't need to know the exact details about every single device that needs to know about the global xpub. Why is this restricted to only multisigs? Just because that is the described use case in the original issue does not mean that it is the only use case. PSBTs and Descriptors are generic objects, we should avoid doing things that are specific to one type of descriptor or psbt. |
| * of the key itself, in the form BIP 174's PSBT_GLOBAL_XPUB expects: the key at the | ||
| * deepest hardened derivation step, so that the unhardened children used in the | ||
| * transaction can be derived from it. */ | ||
| virtual void GetExtPubKeysWithOrigins(const SigningProvider& arg, const DescriptorCache* cache, std::map<KeyOriginInfo, std::set<CExtPubKey>>& out) const = 0; |
There was a problem hiding this comment.
In 92bf732 "wallet: fill PSBT_GLOBAL_XPUB for descriptors with more than one key"
This should return the map rather than taking it as an output parameter.
Do not provide SigningProvider, either the last hardened key is already cached, or it does not exist. There is no need to take a SigningProvider here, otherwise the wallet wouldn't function.
There was a problem hiding this comment.
Done, it returns the map and takes only the cache.
| // A hardened ranged key expression derives children the receiver cannot reach from | ||
| // any parent we could publish, so there is nothing useful to contribute. | ||
| if (m_derive == DeriveType::HARDENED_RANGED) return; |
There was a problem hiding this comment.
In 92bf732 "wallet: fill PSBT_GLOBAL_XPUB for descriptors with more than one key"
We should not make assumptions about what the caller is going to use the xpubs for. This should return the root and it's fingerprint for any key where we cannot do the normalized key thing.
There was a problem hiding this comment.
Done, it now returns the root and its fingerprint, /*h included.
|
|
||
| KeyOriginInfo origin; | ||
| CExtPubKey xpub; | ||
| const int last_hardened{LastHardenedIndex()}; |
There was a problem hiding this comment.
In 92bf732 "wallet: fill PSBT_GLOBAL_XPUB for descriptors with more than one key"
It is not necessary to determine what the last hardened index is, just ask the cache for it, and if the cache doesn't have that key, return the root.
There was a problem hiding this comment.
Done, it asks the cache and falls back to the root.
| // Derivation here is applied to the aggregate key, not to the participants, so a | ||
| // participant's extended key does not derive the key that ends up in the script. | ||
| // BIP 174 asks for keys the receiver can derive the transaction's keys from, so | ||
| // there is nothing here that fits. | ||
| void GetExtPubKeysWithOrigins(const SigningProvider&, const DescriptorCache*, std::map<KeyOriginInfo, std::set<CExtPubKey>>&) const override {} |
There was a problem hiding this comment.
In 92bf732 "wallet: fill PSBT_GLOBAL_XPUB for descriptors with more than one key"
This is incorrect. It should traverse the participants and get their xpubs.
There was a problem hiding this comment.
Right, done. It now merges whatever its participants return, and wallet_musig.py checks that every participant's xpub ends up in global_xpubs with the origin that leads to it.
|
@jeanpablojp, in case it saves you time: https://github.com/fametrano/bitcoin/tree/psbt-global-xpub-achow has achow101's points and the NetBSD thread-safety fix, rebased on master. Changes: the multisig-only restriction is gone. There are two commits. The wallet one is yours, with me as co-author. Take any of it or none. To use it as it is: Written with LLM, a computer and the Internet; the mistakes, as usual, are all mine. Suggested descriptionCloses #27583. BIP 174 lets a PSBT carry, in
So, by default, a PSBT from the wallet carries the account xpubs of the descriptors it uses, and whoever gets it can derive the wallet's addresses. With hardened ranged derivation ( |
92bf732 to
437936e
Compare
|
@achow101 thanks, shortened the description and dropped the multisig restriction. @fametrano thanks for the branch. The single-key test over the four address types follows yours. Unlike your branch, keys that derive none of the PSBT's keys stay out, like the root of a |
fametrano
left a comment
There was a problem hiding this comment.
Concept ACK
One issue should be fixed before merge: a watch-only wallet holding one xpub under two origins now gets a PSBT that decodepsbt refuses. With wpkh([A/84h/1h/0h]xpub/0/*) and wpkh([00000000/84h/1h/0h]xpub/1/*), walletcreatefundedpsbt and send, which has no bip32derivs to turn it off, both report success and return it. No funds are at risk, but the error only shows when the next tool reads the file. This is the first of Ralph's two Minors; both reproduce at 437936e without an edited file.
The suggestion in AddGlobalXpubs keeps the origin already present, as MergeGlobalXPubs does since #35665. With all the suggestions, both reproductions exit 0, and the affected unit tests and eight functional tests pass; each regression test fails without its fix. Scripts and output: https://gist.github.com/fametrano/1cb22c31d89e06cd722dadaec3dc7230/b7f27effa3b47cd36468d9ae24407e71cf9970ee
Not blocking: the root exclusion falls to two RPCs. A sender calls descriptorprocesspsbt with wpkh([root origin]key) on a stranger's key, then a /*h wallet that the PSBT pays adds its root in walletprocesspsbt. That root derives no key of the wallet's descriptor, so no address is exposed, but the description says /*h adds nothing. The other two suggestions derive the key instead of comparing its path, and test it.
| //! Whether a key at this origin derives one of the keys the PSBT gives a derivation path | ||
| //! for, through unhardened steps alone. | ||
| static bool DerivesKeyInPSBT(const PartiallySignedTransaction& psbtx, const KeyOriginInfo& origin) | ||
| { | ||
| const auto derives{[&](const KeyOriginInfo& info) { | ||
| if (info.fingerprint != origin.fingerprint || info.path.size() < origin.path.size()) return false; | ||
| const auto rest{info.path.begin() + origin.path.size()}; | ||
| return std::equal(info.path.begin(), rest, origin.path.begin()) && | ||
| std::none_of(rest, info.path.end(), [](uint32_t step) { return (step & BIP32_HARDENED_FLAG) != 0; }); | ||
| }}; | ||
| const auto lists_derived_key{[&](const auto& in_or_out) { | ||
| return std::ranges::any_of(in_or_out.hd_keypaths, [&](const auto& entry) { return derives(entry.second); }) || | ||
| std::ranges::any_of(in_or_out.m_tap_bip32_paths, [&](const auto& entry) { return derives(entry.second.second); }); | ||
| }}; | ||
| return std::ranges::any_of(psbtx.inputs, lists_derived_key) || std::ranges::any_of(psbtx.outputs, lists_derived_key); | ||
| } | ||
|
|
||
| void DescriptorScriptPubKeyMan::AddGlobalXpubs(PartiallySignedTransaction& psbtx) const | ||
| { | ||
| LOCK(cs_desc_man); | ||
| std::map<KeyOriginInfo, std::set<CExtPubKey>> xpubs{ | ||
| m_wallet_descriptor.descriptor->GetExtPubKeysWithOrigins(&m_wallet_descriptor.cache)}; | ||
|
|
||
| // BIP 174 wants the keys that the transaction's keys derive from, each with as many | ||
| // steps in its path as its depth. Where the cache lacks the key at the last hardened | ||
| // step, the descriptor hands out its root instead, and a root with hardened steps still | ||
| // below it derives none of them; a key written without its origin has a path too short | ||
| // for its depth. Neither can go in. | ||
| std::erase_if(xpubs, [&](const auto& entry) { | ||
| const auto& [origin, keys]{entry}; | ||
| return !DerivesKeyInPSBT(psbtx, origin) || |
There was a problem hiding this comment.
Not blocking: a path in the PSBT is only a claim, so this derives the key and compares it. It keeps the hardened check, since CPubKey::Derive asserts on a hardened step, and the regression test is the suggestion in the functional test. Only entries at this origin cost a derivation, and a PSBT's real key stops the search; a hostile 2 MB file of 510,000 steps took 6 to 7 s in walletprocesspsbt here, against 0.06 s on the head.
| //! Whether a key at this origin derives one of the keys the PSBT gives a derivation path | |
| //! for, through unhardened steps alone. | |
| static bool DerivesKeyInPSBT(const PartiallySignedTransaction& psbtx, const KeyOriginInfo& origin) | |
| { | |
| const auto derives{[&](const KeyOriginInfo& info) { | |
| if (info.fingerprint != origin.fingerprint || info.path.size() < origin.path.size()) return false; | |
| const auto rest{info.path.begin() + origin.path.size()}; | |
| return std::equal(info.path.begin(), rest, origin.path.begin()) && | |
| std::none_of(rest, info.path.end(), [](uint32_t step) { return (step & BIP32_HARDENED_FLAG) != 0; }); | |
| }}; | |
| const auto lists_derived_key{[&](const auto& in_or_out) { | |
| return std::ranges::any_of(in_or_out.hd_keypaths, [&](const auto& entry) { return derives(entry.second); }) || | |
| std::ranges::any_of(in_or_out.m_tap_bip32_paths, [&](const auto& entry) { return derives(entry.second.second); }); | |
| }}; | |
| return std::ranges::any_of(psbtx.inputs, lists_derived_key) || std::ranges::any_of(psbtx.outputs, lists_derived_key); | |
| } | |
| void DescriptorScriptPubKeyMan::AddGlobalXpubs(PartiallySignedTransaction& psbtx) const | |
| { | |
| LOCK(cs_desc_man); | |
| std::map<KeyOriginInfo, std::set<CExtPubKey>> xpubs{ | |
| m_wallet_descriptor.descriptor->GetExtPubKeysWithOrigins(&m_wallet_descriptor.cache)}; | |
| // BIP 174 wants the keys that the transaction's keys derive from, each with as many | |
| // steps in its path as its depth. Where the cache lacks the key at the last hardened | |
| // step, the descriptor hands out its root instead, and a root with hardened steps still | |
| // below it derives none of them; a key written without its origin has a path too short | |
| // for its depth. Neither can go in. | |
| std::erase_if(xpubs, [&](const auto& entry) { | |
| const auto& [origin, keys]{entry}; | |
| return !DerivesKeyInPSBT(psbtx, origin) || | |
| //! Whether one of these keys, at this origin, derives a key the PSBT gives a derivation | |
| //! path for, through unhardened steps alone. The key is derived rather than its path | |
| //! compared, since a path in the PSBT says whatever its sender wrote. | |
| static bool DerivesKeyInPSBT(const PartiallySignedTransaction& psbtx, const KeyOriginInfo& origin, const std::set<CExtPubKey>& keys) | |
| { | |
| const auto derives{[&](const XOnlyPubKey& pubkey, const KeyOriginInfo& info) { | |
| if (info.fingerprint != origin.fingerprint || info.path.size() < origin.path.size()) return false; | |
| const auto rest{info.path.begin() + origin.path.size()}; | |
| if (!std::equal(info.path.begin(), rest, origin.path.begin()) || | |
| std::any_of(rest, info.path.end(), [](uint32_t step) { return (step & BIP32_HARDENED_FLAG) != 0; })) return false; | |
| return std::ranges::any_of(keys, [&](CExtPubKey key) { | |
| for (auto step{rest}; step != info.path.end(); ++step) { | |
| CExtPubKey child; | |
| if (!key.Derive(child, *step)) return false; | |
| key = child; | |
| } | |
| return XOnlyPubKey{key.pubkey} == pubkey; | |
| }); | |
| }}; | |
| const auto lists_derived_key{[&](const auto& in_or_out) { | |
| return std::ranges::any_of(in_or_out.hd_keypaths, [&](const auto& entry) { return derives(XOnlyPubKey{entry.first}, entry.second); }) || | |
| std::ranges::any_of(in_or_out.m_tap_bip32_paths, [&](const auto& entry) { return derives(entry.first, entry.second.second); }); | |
| }}; | |
| return std::ranges::any_of(psbtx.inputs, lists_derived_key) || std::ranges::any_of(psbtx.outputs, lists_derived_key); | |
| } | |
| void DescriptorScriptPubKeyMan::AddGlobalXpubs(PartiallySignedTransaction& psbtx) const | |
| { | |
| LOCK(cs_desc_man); | |
| std::map<KeyOriginInfo, std::set<CExtPubKey>> xpubs{ | |
| m_wallet_descriptor.descriptor->GetExtPubKeysWithOrigins(&m_wallet_descriptor.cache)}; | |
| // BIP 174 wants the keys that the transaction's keys derive from, each with as many | |
| // steps in its path as its depth. Where the cache lacks the key at the last hardened | |
| // step, the descriptor hands out its root instead, and a root with hardened steps still | |
| // below it derives none of them; a key written without its origin has a path too short | |
| // for its depth. Neither can go in. | |
| std::erase_if(xpubs, [&](const auto& entry) { | |
| const auto& [origin, keys]{entry}; | |
| return !DerivesKeyInPSBT(psbtx, origin, keys) || |
There was a problem hiding this comment.
Taken, thanks, with non-taproot entries compared as full keys rather than x-only.
| for (const auto& [origin, keys] : xpubs) { | ||
| psbtx.m_xpubs[origin].insert(keys.begin(), keys.end()); | ||
| } |
There was a problem hiding this comment.
walletcreatefundedpsbt and send both returned a PSBT decodepsbt refuses, in a wallet holding one xpub under two origins. MergeGlobalXPubs already keeps the first origin it sees (#35665), so this uses it. With this they decode, with one record, and the PR's tests still pass. In that wallet the origin that stays follows the pointer order of GetAllScriptPubKeyMans, so it can change across a restart.
| for (const auto& [origin, keys] : xpubs) { | |
| psbtx.m_xpubs[origin].insert(keys.begin(), keys.end()); | |
| } | |
| PartiallySignedTransaction candidates{CMutableTransaction{}}; | |
| candidates.m_xpubs = std::move(xpubs); | |
| psbtx.MergeGlobalXPubs(candidates); |
There was a problem hiding this comment.
Taken, thanks. MergeGlobalXPubs now takes the map, so the wallet calls it without the throwaway PSBT.
| {"desc": descriptor(1), "active": True, "internal": True, "timestamp": "now"}, | ||
| ]) | ||
| assert all(r["success"] for r in result) | ||
| self._check_publishes_nothing(wallet, coordinator) |
There was a problem hiding this comment.
Not blocking: no edited bytes are needed, since two RPCs give the stranger's key the root's origin. This fails on the head because the root gets in, and passes with the derivation suggestion.
| self._check_publishes_nothing(wallet, coordinator) | |
| self._check_publishes_nothing(wallet, coordinator) | |
| # A path in a PSBT is only a claim: this one gives a stranger's key the root's origin. | |
| stranger = coordinator.getaddressinfo(coordinator.getnewaddress(address_type="bech32"))["pubkey"] | |
| forged_desc = descsum_create(f"wpkh({keys[0]['origin']}{stranger})") | |
| psbt = coordinator.walletcreatefundedpsbt( | |
| inputs=[], outputs={wallet.getnewaddress(): 0.1, self.node.deriveaddresses(forged_desc)[0]: 0.1}, | |
| feeRate=0.00010, bip32derivs=False)["psbt"] | |
| forged = self.node.descriptorprocesspsbt(psbt, [forged_desc], bip32derivs=True, finalize=False)["psbt"] | |
| processed = wallet.walletprocesspsbt(forged, sign=False)["psbt"] | |
| assert_equal(wallet.decodepsbt(processed)["global_xpubs"], []) |
There was a problem hiding this comment.
Added, with a second forged output through tr(), since the taproot comparison had no test otherwise, and a check that both claims reach the PSBT.
| assert funded["changepos"] != -1, "the case needs a change output" | ||
| # The receiving and change descriptors of an address type share their account key. | ||
| parent_desc = wallet.getaddressinfo(address)["parent_desc"] | ||
| self._check_global_xpubs(funded["psbt"], [parent_desc[parent_desc.index("["):]], wallet) |
There was a problem hiding this comment.
This fails on the head with Duplicate Key and passes with the suggestion in AddGlobalXpubs.
| self._check_global_xpubs(funded["psbt"], [parent_desc[parent_desc.index("["):]], wallet) | |
| self._check_global_xpubs(funded["psbt"], [parent_desc[parent_desc.index("["):]], wallet) | |
| # One xpub under two origins is one record: a repeated record makes the PSBT undecodable. | |
| account = wallet.derivehdkey("m/84h/1h/0h") | |
| two_origins = self.node.get_wallet_rpc(self.node.createwallet( | |
| wallet_name="two_origins", blank=True, disable_private_keys=True)["name"]) | |
| result = two_origins.importdescriptors([ | |
| {"desc": descsum_create(f"wpkh({account['origin']}{account['xpub']}/0/*)"), | |
| "active": True, "timestamp": "now"}, | |
| {"desc": descsum_create(f"wpkh([00000000/84h/1h/0h]{account['xpub']}/1/*)"), | |
| "active": True, "internal": True, "timestamp": "now"}, | |
| ]) | |
| assert all(r["success"] for r in result) | |
| coordinator.sendtoaddress(two_origins.getnewaddress(), 1) | |
| self.generate(self.node, 1) | |
| funded = two_origins.walletcreatefundedpsbt(inputs=[], outputs={coordinator.getnewaddress(): 0.5}, feeRate=0.00010) | |
| assert_equal(len(two_origins.decodepsbt(funded["psbt"])["global_xpubs"]), 1) |
There was a problem hiding this comment.
Added, with two more cases, the same xpub twice in one descriptor and a PSBT whose sender already lists the wallet's xpub under another origin. The second also made walletprocesspsbt return a PSBT that does not decode.
437936e to
1cc67cf
Compare
fametrano
left a comment
There was a problem hiding this comment.
tACK 1cc67cf
The four suggestions are in, and the new tests pin them. With each fix reverted on this head, wallet_multisig_descriptor_psbt.py fails: in test_one_record_per_xpub when the xpubs bypass MergeGlobalXPubs, and at the forged claims when DerivesKeyInPSBT stops comparing the derived key, even in the taproot map alone. Unmodified, the descriptor, PSBT, wallet and key_io unit suites and eight wallet and PSBT functional tests pass.
Not blocking: Ralph's first Minor here, the cost of deriving along unrelated paths, comes from my derivation suggestion. Beyond the 2 MB file I timed then, a 17 MB PSBT whose output lists 16,000 stranger keys at the root's origin, each 255 unhardened steps deep, kept walletprocesspsbt busy 73 to 96 s on a loaded 10-core machine. Ralph's fix would bound it, and I would take it here.
Give Descriptor a way to hand out the extended public keys it is built from, each keyed by its origin. Each BIP 32 key expression gives the key at its last hardened step when the descriptor cache holds that key, and its root key otherwise. The key at the last hardened step is the one the expression's unhardened children derive from. A key origin written in the descriptor takes the place of the root's fingerprint and is prepended to the path. A musig() expression hands out its participants' keys, and a plain public key has none to give. The keys carry the network's version bytes, since BIP 174 serializes those bytes as part of each PSBT_GLOBAL_XPUB key and a key parsed from a descriptor lacks them. The wallet starts using this in the next commit.
1cc67cf to
118c6d1
Compare
vicjuma
left a comment
There was a problem hiding this comment.
Concept ACK, global xpubs are optional, so including them is harmless, and wallets or signers that require them can use them
BIP 174 lets a PSBT carry the extended public keys that the keys in its inputs and outputs derive from, so that a signer holding no wallet state can rebuild the scripts from the PSBT alone. The PSBT code already serializes, deserializes and merges PSBT_GLOBAL_XPUB, but the wallet never writes it. Have DescriptorScriptPubKeyMan::FillPSBT add the extended keys of every descriptor that contributed an input or an output, unless bip32derivs is false. That covers walletcreatefundedpsbt, walletprocesspsbt, send, sendall, psbtbumpfee and the GUI, which all go through CWallet::FillPSBT. Only keys that BIP 174 allows go in. A key has to derive, through unhardened steps alone, one of the keys the descriptor produced that the PSBT gives a derivation path for, and its path has to have as many steps as its depth. The derivation is checked by deriving the key and comparing it with the listed one, since keys can share an origin. The first rule leaves out the root key a descriptor falls back to when its cache lacks the key at the last hardened step, which is always the case with /*h derivation. The second leaves out a non-master key written in the descriptor without its origin. A path in a PSBT is only what its sender claims, so a listed key counts only at the origin the descriptor gave it, and nothing is derived along any other path, however many the PSBT lists. A key the PSBT already carries keeps the origin it has there, since BIP 174 allows one record per key. MergeGlobalXPubs already does this when PSBTs are combined, and now takes the xpubs to merge rather than a whole PSBT, so that the wallet adds its own through it. A PSBT from the wallet now carries the extended keys of the descriptors it uses, and whoever holds it can derive their addresses. Setting bip32derivs to false in walletcreatefundedpsbt or walletprocesspsbt keeps the wallet from adding the extended keys, along with the derivation paths, and does not remove those a PSBT already carries. The BIP 174 updater test vector now carries the extended keys of its descriptors.
118c6d1 to
8ae5b94
Compare
|
Rebased, and took Ralph's two minor findings on |
Github-Pull: bitcoin#36154 Rebased-From: 92bf732 (partial)
Github-Pull: bitcoin#36154 Rebased-From: 92bf732 (partial)
Github-Pull: bitcoin#36154 Rebased-From: 92bf732 (partial)

Closes #27583.
PSBT_GLOBAL_XPUBalready serializes, deserializes and merges when PSBTs are combined. Nothing writes it, so a PSBT produced by the wallet never carries it, and a signer that only has the file cannot rebuild the multisig from it. Today Specter fills the field itself after getting the PSBT from Core.Before and after with the BitBox02 and Trezor simulators
A 2-of-3
wsh(sortedmulti(...))on regtest with the simulator as one co-signer, signed through HWI 3.2.0. The "before" file is the same PSBT with itsPSBT_GLOBAL_XPUBrecords removed, so nothing else differs.This BitBox02 is not one of the cosignersWhat
parse_multisighands the Trezor for the change output:A new
Descriptoraccessor returns the extended keys a descriptor is built from, andDescriptorScriptPubKeyMan::FillPSBTwrites those of every descriptor with an input or an output in the PSBT. That coverswalletcreatefundedpsbt,walletprocesspsbt,send,sendall,psbtbumpfeeand the GUI send dialog, which all go throughCWallet::FillPSBT.Only the keys BIP 174 allows are added, the ones that derive, through unhardened steps alone, a key their descriptor produced, listed in the PSBT at the origin the descriptor gave it. So a key expression ending in
/*hadds nothing.Whoever holds a PSBT from the wallet can now derive the addresses of the descriptors it uses. Setting
bip32derivsto false inwalletcreatefundedpsbtorwalletprocesspsbtstops the wallet from adding the field, along with the derivation paths, and does not remove what a PSBT already carries.descriptorprocesspsbtis left out, since it signs from the descriptors it is given without going through the wallet, and I intend to cover it as a follow-up.