Skip to content

WCN-3934 Recognise bip44 wallet prefix in PSBT parsing, wallet prefix helpers - #458

Open
davidkaplanbitgo wants to merge 1 commit into
masterfrom
davidkaplan/wcn-3934-bitgowasm-wasm-utxo-per-wallet-derivation-prefix-path
Open

davidkaplanbitgo wants to merge 1 commit into
masterfrom
davidkaplan/wcn-3934-bitgowasm-wasm-utxo-per-wallet-derivation-prefix-path

Conversation

@davidkaplanbitgo

@davidkaplanbitgo davidkaplanbitgo commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

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 legacy 0/0/<chain>/<index>. h1/h2 are recomputed from the three wallet root keys and never stored.

Changes

  • deriveWalletAccount(keys) → [h1, h2] and deriveWalletPrefix(keys, coinType) → "44/<ct>/<h1>/<h2>". Rust in wallet_prefix.rs, plus wasm exports and TS wrappers; the project test vectors are checked in Rust and mocha.
  • RootWalletKeys.withBip44CoinType(coinType) makes parse, explain and getWalletKeysFromPsbt recognise exactly one extra prefix, the wallet's own bip44 prefix, on top of the keys' own prefixes.
    • The caller supplies the coin type (bip44CoinType from statics); wasm-utxo has no coin registry.
    • Building addresses, inputs and outputs is unchanged.
  • A path under the bip44 prefix is classified under it. Every other path is classified exactly as before, against the keys' own prefixes, so per-key prefixes such as recovery's [userKeyPath, 0/0, 0/0] still work, including taproot and MuSig2 inputs.
  • An output whose key origins carry the wallet's fingerprints under any other prefix still fails the parse, as before. It is never counted as wallet change.
  • getWalletKeysFromPsbt(psbt, xpubs, { bip44CoinType }) resolves bip44 and mixed PSBTs, and the keys it returns carry the bip44 prefix.
  • A hardened derivation prefix now returns WalletKeysError.HardenedDerivationPrefix instead of trapping (Unreachable code).
  • ParsedInput/ParsedOutput.derivationPath is documented as the full recorded path, e.g. 0/0/20/5 or 44/0/<h1>/<h2>/20/5. The SDK takes the prefix as the path minus its last two components.

Not in this PR: hydrate_psbt still 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 no expectedScript on add-input: callers compare the unspent's script against outputScript(keys, chain, index, coin).

New public API

  • Rust:
    • RootWalletKeys::{with_bip44_coin_type, bip44_prefix}
    • wallet_prefix::{derive_wallet_account, derive_wallet_prefix, derive_wallet_prefix_path, WalletPrefixError}
    • WalletKeysError
    • to_wallet_keys(psbt, xpubs, bip44_coin_type: Option<u32>)
    • RootWalletKeys::new_with_derivation_prefixes now returns Result.
  • wasm:
    • WasmRootWalletKeys.{with_bip44_coin_type, bip44_prefix}
    • derive_wallet_account, derive_wallet_prefix
    • trailing optional bip44_coin_type on to_wallet_keys
  • TS:
    • RootWalletKeys.{withBip44CoinType, bip44Prefix}
    • deriveWalletAccount, deriveWalletPrefix
    • getWalletKeysFromPsbt(..., { 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 in bitgo_psbt/bip44_prefix_tests.rs, and the spec vectors are in wallet_prefix.rs. They cover:
    • bip44-only and mixed legacy+bip44 PSBTs across p2sh, p2shP2wsh, p2wsh, p2tr and p2trMusig2, built with two key sets and parsed with one
    • ECDSA and MuSig2 signing and verifying at bip44 paths
    • a Zcash PSBT
    • per-key prefixes with taproot and MuSig2 inputs
    • outputs and inputs under foreign prefixes: 7/7, wrong coin type, wrong account, 44/0/0/0, 44/0/2^31-1/2^31-1
    • a sibling wallet (same user and backup keys, different bitgo key)
    • to_wallet_keys with shuffled xpubs
    • hardened prefix and coin-type errors
  • mocha: 1659 passing, 10 pending. 11 of them are new in test/fixedScript/bip44Prefix.ts: the spec vectors, xprv/xpub equivalence, the typed errors, mixed parse, and getWalletKeysFromPsbt.
  • cargo clippy --all-targets --all-features -D warnings, rustfmt, prettier and eslint are clean.

@linear-code

linear-code Bot commented Oct 31, 2026

Copy link
Copy Markdown

WCN-3934

@davidkaplanbitgo
davidkaplanbitgo force-pushed the davidkaplan/wcn-3934-bitgowasm-wasm-utxo-per-wallet-derivation-prefix-path branch from 20c789d to 770c516 Compare October 31, 2026 12:03
@davidkaplanbitgo

Copy link
Copy Markdown
Contributor Author

@claude

@davidkaplanbitgo
davidkaplanbitgo force-pushed the davidkaplan/wcn-3934-bitgowasm-wasm-utxo-per-wallet-derivation-prefix-path branch 2 times, most recently from b083e50 to 13bc1f0 Compare November 9, 2026 16:23
@davidkaplanbitgo
davidkaplanbitgo marked this pull request as ready for review November 9, 2026 16:43
@davidkaplanbitgo
davidkaplanbitgo requested a review from a team as a code owner November 9, 2026 16:43

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@parasgarg-bitgo

Copy link
Copy Markdown

@claude review

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Findings marked 🟡 are optional suggestions and need no follow-up push.

@davidkaplanbitgo
davidkaplanbitgo marked this pull request as draft November 9, 2026 21:39
auto-merge was automatically disabled November 9, 2026 21:39

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
@davidkaplanbitgo
davidkaplanbitgo force-pushed the davidkaplan/wcn-3934-bitgowasm-wasm-utxo-per-wallet-derivation-prefix-path branch from 13bc1f0 to ca7f359 Compare November 17, 2026 04:29
@davidkaplanbitgo

Copy link
Copy Markdown
Contributor Author

@claude review - are all comments addressed?

@davidkaplanbitgo davidkaplanbitgo changed the title WCN-3934 Path-agnostic wallet PSBT parsing and wallet prefix helpers WCN-3934 Recognise bip44 wallet prefix in PSBT parsing, wallet prefix helpers Nov 17, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment on lines +12 to +14
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}`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

@davidkaplanbitgo
davidkaplanbitgo marked this pull request as ready for review November 17, 2026 04:43

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@davidkaplanbitgo

Copy link
Copy Markdown
Contributor Author

@claude review

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Still open from earlier reviews (1):

  • Unresolved: 1 minor or pre-existing.

Comment on lines +234 to +246
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants