Repository navigation
WCN-3934 Path-agnostic wallet PSBT parsing and wallet prefix helpers - #458
davidkaplanbitgo wants to merge 1 commit into
Conversation
20c789d to
770c516
Compare
770c516 to
b083e50
Compare
Add deriveWalletAccount and deriveWalletPrefix (44/<coin_type>/<h1>/<h2>) with the shared test vectors. Parse, explain and getWalletKeysFromPsbt now classify inputs and outputs by the full derivation path recorded in the PSBT, matching key origins by fingerprint and deriving a missing key (taproot and MuSig2 inputs) along a present entry's path; the script comparison still binds the result. A non-matching output returns None instead of aborting the parse. Hardened derivation prefixes return a typed error instead of panicking, and add-input accepts an optional expectedScript that fails with WalletInputScriptMismatch. Ticket: WCN-3934
b083e50 to
13bc1f0
Compare
There was a problem hiding this comment.
Claude Code Review
This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.
Tip: disable this comment in your organization's Code Review settings.
|
@claude review |
There was a problem hiding this comment.
🔴 Wallets whose three keys use different derivation prefixes can no longer parse their taproot or MuSig2 inputs; those inputs now fail as not belonging to the wallet. A key with no origin is derived along another key's full recorded path (reference_path), not its own prefix. Taproot inputs record only signer and cosigner, so the third key is always missing. Fix: derive a missing key along its own prefix plus (chain, index), as wallet_keys.derive_path did, and accept present origins with different prefixes when their (chain, index) agree.
Why this was flagged
This only matters if some caller builds keys with RootWalletKeys.withDerivationPrefixes (or IWalletKeys derivationPrefixes) using a different prefix per key; I could not list every such caller from this repo. Taproot and MuSig2 inputs carry only two tap_key_origins, written by create_tap_bip32_derivation(..., &[signer_idx, cosigner_idx], ...) (bitgo_psbt/mod.rs:1153/1167), and each records its own key's prefix. In derive_triple_from_origins, if the two present paths differ, !complete && ... *path != reference_path (wallet_scripts/mod.rs:631-637) returns Ok(None). If they agree, the missing key is derived along reference_path (mod.rs:643-646) and not along its own prefix, so OutputScriptType::check fails. ParsedInput::parse then errors with NO_WALLET_MATCH_MESSAGE, which aborts parseTransactionWithWalletKeys and signing validation. On the base branch, OutputScriptType::check derived all three keys via wallet_keys.derive_path(chain_index_path(chain, index)), which honours per-key prefixes, so these inputs parsed.
Verification: Taproot and MuSig2 inputs record origins only for &[signer_idx, cosigner_idx] (bitgo_psbt/mod.rs:1153, 1167). In derive_triple_from_origins (wallet_scripts/mod.rs:333-400), the missing key is derived along reference_path, and differing present prefixes return None. ParsedInput::parse (psbt_wallet_input.rs:576-587) turns that None into NO_WALLET_MATCH_MESSAGE. In the base, wallet_keys.derive_path applied each key's own prefix.
| for origin in origins.iter().filter(|o| o.fingerprint == fingerprint) { | ||
| // A path with hardened components cannot be derived from an xpub: it does not | ||
| // describe a key of this wallet. | ||
| let Ok(derived) = xpub.derive_pub(secp, origin.path) else { |
There was a problem hiding this comment.
🔴 Anyone verifying a PSBT will now see an output at any non-hardened path under the wallet's root keys counted as wallet change, not as an external spend. derive_triple_from_origins derives each key along whatever path the PSBT records, and the script check only ties the keys to the roots, not to a known prefix. Fix: accept only the prefixes the wallet uses, the wallet_keys prefix or 44/<ct>/<h1>/<h2> with h1/h2 from derive_wallet_account, while still parsing legacy 0/0 and BIP44 PSBTs. The base rejected such outputs.
Why this was flagged
A PSBT built by a third party has a change-looking output whose bip32_derivation has the wallet's three root fingerprints at a path like 7/7/1/5 or 44/0/1/1/1/5, with the pubkeys derived along that path. The output reaches ParsedOutput via WalletOutputScript::from_psbt (psbt_wallet_output.rs:32). derive_triple_from_origins (wallet_scripts/mod.rs:346) derives every key along origin.path from the root xpub, so OutputScriptType::check matches and the output gets a derivation_path and a script_id, so it counts as internal change. On the base, check derived at wallet_keys prefix + chain/index, failed, and from_psbt returned Err "wallet keys match but no script type matches", so parsing aborted. After merging, value can be moved to addresses the wallet does not index or monitor while verification reports no external spend. The script-equality check described as the binding check only proves the keys come from the roots. It does not prove the path is one the wallet tracks.
Verification: In derive_triple_from_origins (wallet_scripts/mod.rs), each root key is derived with xpub.derive_pub(secp, origin.path) along the full recorded path. Nothing compares the prefix to wallet_keys' prefix or to 44/<ct>/<h1>/<h2>. The base check used wallet_keys.derive_path(&chain_index_path(chain, index)), so such an output failed to match and from_psbt returned Err.
| actual: ScriptBuf, | ||
| }, | ||
| /// Any other failure (invalid chain, derivation, missing sign path, PSBT insertion, ...). | ||
| Invalid(String), |
There was a problem hiding this comment.
🟡 (optional) JS callers matching the error code of addWalletInput failures will now get AddWalletInputError.Invalid instead of WasmUtxoError.StringError. Invalid(String) is a catch-all string variant, which CONVENTIONS.md rule 10 rules out for new error enums. Every other failure flows into it through From<String>: bad chain, missing sign path, P2MR, Zcash rejection and insert errors. Fix: give each of these failures its own structured variant (e.g. MissingSignPath, UnsupportedP2mr, InvalidChain), or keep them on the previous code path, so only WalletInputScriptMismatch is new.
Why this was flagged
The wasm add_wallet_input_at_index (src/wasm/fixed_script_wallet/mod.rs) used to map every failure through WasmUtxoError::new, which gave code "WasmUtxoError.StringError". It now calls try_add_wallet_input_at_index and converts with ?. Every failure except a script mismatch becomes AddWalletInputError::Invalid through impl From<String> for AddWalletInputError, so its code is "AddWalletInputError.Invalid". Callers that branch on the old code for a missing sign path or an invalid chain now take a different branch. The new variant only wraps free-form messages, which is the stringly-typed error pattern rule 10 prohibits ("Do not return String ... errors").
Verification: The new public enum AddWalletInputError in psbt_wallet_input.rs has a catch-all variant at line 456, Invalid(String), fed by impl From<String> for AddWalletInputError. The wasm binding in src/wasm/fixed_script_wallet/mod.rs changed from .map_err(|e| WasmUtxoError::new(&e)) to Ok(self.psbt.try_add_wallet_input_at_index(...)?). So err.code visibly changes for every non-mismatch failure.
Pull request was converted to draft
Ticket: WCN-3934
Part of the BIP-0044 style wallet derivation project (spike WCN-3907): wallets that share root xpubs get a second, per-wallet derivation scheme
44/<coin_type>/<h1>/<h2>/<chain>/<index>.h1/h2are recomputed from the three wallet root keys, never stored.Changes
fixedScriptWallet.deriveWalletAccount(keys)andderiveWalletPrefix(keys, coinType)(Rustwallet_prefix.rs, wasm exports, TS wrappers) with the shared test vectors as a Rust test.getWalletKeysFromPsbtclassify wallet inputs/outputs by the full derivation path recorded in the PSBT, matching key origins by fingerprint. A key with no origin entry (taproot/MuSig2 inputs only carry signer+cosigner) is derived from its xpub along a present entry's path; script equality is still the binding check. A non-matching output returnsNoneinstead of aborting the whole parse; a non-matching input is an error.ParsedInput/ParsedOutput.derivationPathhold the full recorded path.RootWalletKeys::new_with_derivation_prefixesreturns a typed error on a hardened component instead of panicking.expectedScriptoption on add-wallet-input; mismatch fails with the typedWalletInputScriptMismatchand leaves the PSBT unchanged. Omitting it changes nothing.New public API
Rust:
wallet_prefix::{derive_wallet_account, derive_wallet_prefix, WalletPrefixError},WalletKeysError,AddWalletInputError,WalletInputOptions.expected_script,BitGoPsbt::try_add_wallet_input_at_index.RootWalletKeys::new_with_derivation_prefixesnow returnsResult;OutputScriptType::checktakes the three derived pubkeys. wasm:derive_wallet_account,derive_wallet_prefix, trailingexpected_scriptargument onadd_wallet_input/add_wallet_input_at_index. TS:deriveWalletAccount,deriveWalletPrefix,AddWalletInputOptions.expectedScript.Test
cargo check --all-targetspasses.cargo testand the mocha suite have NOT been run, and no mocha tests were added for the new behaviour yet; existing fixtures should be unaffected by inspection only.RootWalletKeysrelies on per-keys prefixes increate_bip32_derivationand is untested;hydrate_psbtstill takes one key set (no per-unspent prefix).Downstream (IMS, BitGoJS, wallet-platform) need the release of this change.