Repository navigation
WCN-3934 Recognise bip44 wallet prefix in PSBT parsing, wallet prefix helpers - #458
Conversation
20c789d to
770c516
Compare
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 |
Pull request was converted to draft
Add deriveWalletAccount and deriveWalletPrefix (44/<coin_type>/<h1>/<h2>, h1/h2 from sha256 of the three root keys) with the project test vectors. RootWalletKeys.withBip44CoinType(coinType) lets parse, explain and getWalletKeysFromPsbt recognise exactly one extra prefix, the wallet's canonical bip44 prefix, in addition to the keys' own prefixes. The coin type is supplied by the caller; wasm-utxo has no coin registry. Paths under any other prefix are classified as before, so outputs under an unknown prefix are never treated as wallet change. Hardened derivation prefixes now return WalletKeysError instead of trapping, and parsed derivationPath is documented as the full path. Ticket: WCN-3934
13bc1f0 to
ca7f359
Compare
|
@claude review - are all comments addressed? |
| export function assertCoinTypeU32(coinType: number): void { | ||
| if (!Number.isInteger(coinType) || coinType < 0 || coinType > 0xffffffff) { | ||
| throw new RangeError(`coinType must be an integer in 0..=2^31-1, got ${coinType}`); |
There was a problem hiding this comment.
🟡 nit (optional): Callers passing an out-of-range coin type get two different error types for the same mistake, which breaks the documented @ throws contract. assertCoinTypeU32 allows values up to 0xffffffff, so 2^31..2^32-1 reach Rust and fail with the typed WalletPrefixError.CoinTypeOutOfRange. Larger values (e.g. 2**32, 1e10) throw a plain RangeError instead. That message says "0..=2^31-1", a range the check itself does not apply. Fix: give every value above 0x7fffffff one error type and code, or document the RangeError case in the @ throws text of withBip44CoinType, deriveWalletPrefix and getWalletKeysFromPsbt.
Why this was flagged
The JSDoc of withBip44CoinType (RootWalletKeys.ts:150-151) and deriveWalletPrefix (walletPrefix.ts:59-60) says each throws "a WasmUtxoError with code WalletPrefixError.CoinTypeOutOfRange if coinType is larger than 2^31-1". Both first call assertCoinTypeU32 (RootWalletKeys.ts:12-16), which passes any integer up to 0xffffffff and throws RangeError for anything larger. So withBip44CoinType(0x80000000) throws a WasmUtxoError that passes isWasmUtxoError, while withBip44CoinType(2 ** 32) throws a RangeError with no code. A caller that branches on e.code === "WalletPrefixError.CoinTypeOutOfRange", as the docs and test/fixedScript/bip44Prefix.ts:50 suggest, misses the second case. The RangeError message "coinType must be an integer in 0..=2^31-1" also states a bound the check does not enforce. getWalletKeysFromPsbt (BitGoPsbt.ts:1119-1121) uses the same helper and has the same split. All of this is new API, so no base behaviour exists to compare against.
Verification: RootWalletKeys.ts:13-14 rejects only coinType > 0xffffffff, throwing a plain RangeError naming 0..=2^31-1. Values in 2^31..2^32-1 reach Rust, where wallet_prefix.rs:86 and :98 return WalletPrefixError::CoinTypeOutOfRange as a typed WasmUtxoError. The JSDoc at RootWalletKeys.ts:150-151 and walletPrefix.ts:58-59 promises that code for all values above 2^31-1, so withBip44CoinType(2**32) breaks it.
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 |
| if let Some(bip44) = &self.bip44 { | ||
| let recorded: &[ChildNumber] = recorded_path.as_ref(); | ||
| let prefix: &[ChildNumber] = bip44.prefix.as_ref(); | ||
| if recorded.len() == prefix.len() + 2 && recorded.starts_with(prefix) { | ||
| return derive_cached( | ||
| &self.secp, | ||
| &bip44.prefix_derived, | ||
| &bip44.derivation_cache, | ||
| &tail, | ||
| ); | ||
| } | ||
| } | ||
| let derived: XpubTriple = self | ||
| .prefix_derived | ||
| .iter() | ||
| .map(|xpub| { | ||
| xpub.derive_pub(&self.secp, path) | ||
| .map_err(|e| WasmUtxoError::new(&format!("Error deriving xpub: {}", e))) | ||
| }) | ||
| .collect::<Result<Vec<_>, _>>()? | ||
| .try_into() | ||
| .map_err(|_| WasmUtxoError::new("Expected exactly 3 derived xpubs"))?; | ||
| if let Some(key) = cache_key { | ||
| let mut cache = self.derivation_cache.borrow_mut(); | ||
| if cache.len() >= DERIVATION_CACHE_MAX_SIZE { | ||
| cache.clear(); | ||
| self.derive_path(&tail) |
There was a problem hiding this comment.
🟣 pre-existing, not blocking: SDK callers can get a wallet change output whose derivationPath names a prefix it was never derived under, so path minus last two gives a false prefix. When the recorded prefix is not the bip44 one, derive_for_recorded_path falls back to the keys' own prefixes and ignores the recorded one. from_psbt then reports the recorded path unchanged. Fix: make the reported path match the derivation that actually matched. Either return own prefix + chain/index, or reject a recorded prefix that differs from the key's own prefix (checked per key, so recovery's per-key prefixes keep working).
A small fix can ride a push you are already making; otherwise a short reply is enough.
Why this was flagged
Take a PSBT output whose script is the legacy wallet script at 0/0/1/5, with the wallet's fingerprints in bip32_derivation and recorded paths such as 44/1/<h1>/<h2>/1/5 (wrong coin type) or 7/7/1/5. WalletOutputScript::from_psbt (wallet_scripts/mod.rs:340-365) calls OutputScriptType::check, which calls derive_for_recorded_path (wallet_keys.rs:223-246). That prefix is not the bip44 one, so the code goes to self.derive_path(&tail), which ignores the recorded prefix and derives 0/0/1/5. The script matches, and derivation_path: path reports the forged path. The comments at wallet_keys.rs:220-222 and wallet_scripts/mod.rs:222-225 say other prefixes are "not matched". This diff newly documents derivationPath as prefix + chain/index, with "The prefix is everything except the last two components" (psbt_wallet_output.rs:15-17, BitGoPsbt.ts). So the SDK will now treat that prefix as meaningful and record or check the change under a wrong subtree. The base also echoed the recorded path, but nothing relied on its prefix.
Verification: Pre-existing. derive_for_recorded_path (wallet_keys.rs:223-246) compares the recorded path only with bip44.prefix. Any other path falls through to self.derive_path(&tail), which never looks at the recorded prefix. WalletOutputScript::from_psbt then returns derivation_path: path, the recorded path unchanged. The base check also ignored the recorded prefix completely.
Ticket: WCN-3934
Part of the BIP-0044 style wallet derivation project (spike WCN-3907). Wallets that share root xpubs get a second derivation scheme,
44/<coin_type>/<h1>/<h2>/<chain>/<index>, alongside legacy0/0/<chain>/<index>.h1/h2are recomputed from the three wallet root keys and never stored.Changes
deriveWalletAccount(keys)→[h1, h2]andderiveWalletPrefix(keys, coinType)→"44/<ct>/<h1>/<h2>". Rust inwallet_prefix.rs, plus wasm exports and TS wrappers; the project test vectors are checked in Rust and mocha.RootWalletKeys.withBip44CoinType(coinType)makes parse, explain andgetWalletKeysFromPsbtrecognise exactly one extra prefix, the wallet's own bip44 prefix, on top of the keys' own prefixes.bip44CoinTypefrom statics); wasm-utxo has no coin registry.[userKeyPath, 0/0, 0/0]still work, including taproot and MuSig2 inputs.getWalletKeysFromPsbt(psbt, xpubs, { bip44CoinType })resolves bip44 and mixed PSBTs, and the keys it returns carry the bip44 prefix.WalletKeysError.HardenedDerivationPrefixinstead of trapping (Unreachable code).ParsedInput/ParsedOutput.derivationPathis documented as the full recorded path, e.g.0/0/20/5or44/0/<h1>/<h2>/20/5. The SDK takes the prefix as the path minus its last two components.Not in this PR:
hydrate_psbtstill takes one key set. Wallets with bip44 addresses are PSBT-only, so legacy-tx hydration doesn't apply to them; IMS and wallet-platform enforce that. There is noexpectedScripton add-input: callers compare the unspent's script againstoutputScript(keys, chain, index, coin).New public API
RootWalletKeys::{with_bip44_coin_type, bip44_prefix}wallet_prefix::{derive_wallet_account, derive_wallet_prefix, derive_wallet_prefix_path, WalletPrefixError}WalletKeysErrorto_wallet_keys(psbt, xpubs, bip44_coin_type: Option<u32>)RootWalletKeys::new_with_derivation_prefixesnow returnsResult.WasmRootWalletKeys.{with_bip44_coin_type, bip44_prefix}derive_wallet_account,derive_wallet_prefixbip44_coin_typeonto_wallet_keysRootWalletKeys.{withBip44CoinType, bip44Prefix}deriveWalletAccount,deriveWalletPrefixgetWalletKeysFromPsbt(..., { bip44CoinType })Downstream
Parse, explain and signing-validation call sites in IMS, BitGoJS and wallet-platform must opt in with
.withBip44CoinType(ct). A site that doesn't fails closed on bip44 PSBTs (ParseInputError.WalletValidation); it never misclassifies them. Existing legacy-only callers behave the same as before.Test
cargo test --lib: 807 passed. New tests are inbitgo_psbt/bip44_prefix_tests.rs, and the spec vectors are inwallet_prefix.rs. They cover:7/7, wrong coin type, wrong account,44/0/0/0,44/0/2^31-1/2^31-1to_wallet_keyswith shuffled xpubstest/fixedScript/bip44Prefix.ts: the spec vectors, xprv/xpub equivalence, the typed errors, mixed parse, andgetWalletKeysFromPsbt.cargo clippy --all-targets --all-features -D warnings, rustfmt, prettier and eslint are clean.