From ca7f3594d7eb4ae59451b4d818c858f9ae6cf725 Mon Sep 17 00:00:00 2001 From: David Kaplan Date: Mon, 16 Nov 2026 23:29:42 -0500 Subject: [PATCH] feat: recognise bip44 wallet prefix when parsing psbts Add deriveWalletAccount and deriveWalletPrefix (44//

/

, 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 --- .../js/fixedScriptWallet/BitGoPsbt.ts | 27 +- .../js/fixedScriptWallet/RootWalletKeys.ts | 36 ++ .../wasm-utxo/js/fixedScriptWallet/index.ts | 5 + .../js/fixedScriptWallet/walletPrefix.ts | 70 ++++ packages/wasm-utxo/src/error.rs | 20 + .../bitgo_psbt/bip44_prefix_tests.rs | 346 ++++++++++++++++++ .../src/fixed_script_wallet/bitgo_psbt/mod.rs | 18 +- .../bitgo_psbt/psbt_wallet_input.rs | 3 +- .../bitgo_psbt/psbt_wallet_output.rs | 4 +- .../wasm-utxo/src/fixed_script_wallet/mod.rs | 1 + .../src/fixed_script_wallet/wallet_keys.rs | 246 ++++++++++--- .../src/fixed_script_wallet/wallet_prefix.rs | 231 ++++++++++++ .../fixed_script_wallet/wallet_scripts/mod.rs | 7 +- .../src/wasm/fixed_script_wallet/mod.rs | 49 ++- packages/wasm-utxo/src/wasm/wallet_keys.rs | 28 +- .../wasm-utxo/test/fixedScript/bip44Prefix.ts | 136 +++++++ 16 files changed, 1169 insertions(+), 58 deletions(-) create mode 100644 packages/wasm-utxo/js/fixedScriptWallet/walletPrefix.ts create mode 100644 packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/bip44_prefix_tests.rs create mode 100644 packages/wasm-utxo/src/fixed_script_wallet/wallet_prefix.rs create mode 100644 packages/wasm-utxo/test/fixedScript/bip44Prefix.ts diff --git a/packages/wasm-utxo/js/fixedScriptWallet/BitGoPsbt.ts b/packages/wasm-utxo/js/fixedScriptWallet/BitGoPsbt.ts index a0738051b05..9c589901a00 100644 --- a/packages/wasm-utxo/js/fixedScriptWallet/BitGoPsbt.ts +++ b/packages/wasm-utxo/js/fixedScriptWallet/BitGoPsbt.ts @@ -5,7 +5,7 @@ import { } from "../wasm/wasm_utxo.js"; import type { IPsbtWithAddress } from "../psbt.js"; import { PsbtBase } from "../psbtBase.js"; -import { type WalletKeysArg, RootWalletKeys } from "./RootWalletKeys.js"; +import { type WalletKeysArg, RootWalletKeys, assertCoinTypeU32 } from "./RootWalletKeys.js"; import { type ReplayProtectionArg, ReplayProtection } from "./ReplayProtection.js"; import { type BIP32Arg, BIP32, isBIP32Arg } from "../bip32.js"; import { type ECPairArg, ECPair } from "../ecpair.js"; @@ -40,7 +40,11 @@ export type ParsedInput = { scriptId: ScriptId | null; scriptType: InputScriptType; sequence: number; - /** Full BIP32 derivation path from the wallet xpub (e.g. "0/1"). Null for replay-protection inputs. */ + /** + * Full BIP32 derivation path recorded in the PSBT, from the wallet root key: the prefix followed + * by `[chain, index]` (e.g. "0/0/20/5" for legacy, "44/0/

/

/20/5" for BIP44-style). + * Null for replay-protection inputs. + */ derivationPath: string | null; }; @@ -51,7 +55,11 @@ export type ParsedOutput = { /** Set only when the derivation path is chain-standard (chain code encodes script type per BitGo convention). */ scriptId: ScriptId | null; paygo: boolean; - /** Full BIP32 derivation path from the wallet xpub (e.g. "0/1"). Null for external outputs. */ + /** + * Full BIP32 derivation path recorded in the PSBT, from the wallet root key: the prefix followed + * by `[chain, index]` (e.g. "0/0/20/5" for legacy, "44/0/

/

/20/5" for BIP44-style). + * Null for external outputs. + */ derivationPath: string | null; }; @@ -1098,14 +1106,25 @@ export class BitGoPsbt< * was built with derived keys (from coldDerivationSeed) but the caller only * has root xpubs. Prefer passing wallet keys explicitly wherever possible. * + * @param options.bip44CoinType - BIP44 coin type of the coin family. If set, inputs under the + * wallet's BIP44-style prefix `44//

/

` are resolved too, and the returned keys + * recognise that prefix (see {@link RootWalletKeys.withBip44CoinType}). * @returns Sorted [user, backup, bitgo] RootWalletKeys */ -export function getWalletKeysFromPsbt(psbt: BitGoPsbt, xpubs: BIP32[]): RootWalletKeys { +export function getWalletKeysFromPsbt( + psbt: BitGoPsbt, + xpubs: BIP32[], + options: { bip44CoinType?: number } = {}, +): RootWalletKeys { + if (options.bip44CoinType !== undefined) { + assertCoinTypeU32(options.bip44CoinType); + } const wasmKeys = FixedScriptWalletNamespace.to_wallet_keys( psbt.wasm, xpubs[0].wasm, xpubs[1].wasm, xpubs[2].wasm, + options.bip44CoinType, ); return RootWalletKeys.fromWasm(wasmKeys); } diff --git a/packages/wasm-utxo/js/fixedScriptWallet/RootWalletKeys.ts b/packages/wasm-utxo/js/fixedScriptWallet/RootWalletKeys.ts index b956597fd83..cacd661edef 100644 --- a/packages/wasm-utxo/js/fixedScriptWallet/RootWalletKeys.ts +++ b/packages/wasm-utxo/js/fixedScriptWallet/RootWalletKeys.ts @@ -3,6 +3,18 @@ import { BIP32 } from "../bip32.js"; import { Triple } from "../triple.js"; import { WasmRootWalletKeys, WasmBIP32 } from "../wasm/wasm_utxo.js"; +/** + * wasm-bindgen wraps numbers into u32, so reject what cannot be a u32 before it gets there. + * Values in `(2^31-1, 2^32-1]` are rejected by the Rust side with the typed + * `WalletPrefixError.CoinTypeOutOfRange`. + * @internal + */ +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}`); + } +} + /** * IWalletKeys represents the various forms that wallet keys can take * before being converted to a RootWalletKeys instance @@ -127,6 +139,30 @@ export class RootWalletKeys { return new RootWalletKeys(wasm); } + /** + * Return keys that also recognise the wallet's BIP44-style subtree `44//

/

` + * (`h1`, `h2` from `deriveWalletAccount`) when parsing and explaining PSBTs, in addition to + * these keys' own derivation prefixes. Inputs and outputs recorded under any other prefix are + * not recognised. Building (addresses, inputs, outputs) keeps using the keys' own prefixes. + * + * @param coinType - BIP44 coin type of the coin family, an integer in `0..=2^31-1`. wasm-utxo + * has no coin registry: the caller supplies it (e.g. `coin.bip44CoinType` from `@bitgo/statics`). + * @throws a `WasmUtxoError` with code `WalletPrefixError.CoinTypeOutOfRange` if `coinType` is + * larger than `2^31-1` + */ + withBip44CoinType(coinType: number): RootWalletKeys { + assertCoinTypeU32(coinType); + return new RootWalletKeys(this._wasm.with_bip44_coin_type(coinType)); + } + + /** + * The BIP44-style prefix `44//

/

` these keys recognise, set by + * {@link withBip44CoinType}; `undefined` otherwise. + */ + bip44Prefix(): string | undefined { + return this._wasm.bip44_prefix() ?? undefined; + } + /** * Get the user key (first xpub) * @returns The user key as a BIP32 instance diff --git a/packages/wasm-utxo/js/fixedScriptWallet/index.ts b/packages/wasm-utxo/js/fixedScriptWallet/index.ts index 0c4e15180fc..e8d41bd5511 100644 --- a/packages/wasm-utxo/js/fixedScriptWallet/index.ts +++ b/packages/wasm-utxo/js/fixedScriptWallet/index.ts @@ -4,6 +4,11 @@ import type { CoinName } from "../coinName.js"; export { RootWalletKeys, type WalletKeysArg, type IWalletKeys } from "./RootWalletKeys.js"; export { ReplayProtection, type ReplayProtectionArg } from "./ReplayProtection.js"; export { outputScript, address } from "./address.js"; +export { + deriveWalletAccount, + deriveWalletPrefix, + type WalletPrefixKeysArg, +} from "./walletPrefix.js"; export { Dimensions } from "./Dimensions.js"; export { outputScriptTypes, diff --git a/packages/wasm-utxo/js/fixedScriptWallet/walletPrefix.ts b/packages/wasm-utxo/js/fixedScriptWallet/walletPrefix.ts new file mode 100644 index 00000000000..9a92aa4e558 --- /dev/null +++ b/packages/wasm-utxo/js/fixedScriptWallet/walletPrefix.ts @@ -0,0 +1,70 @@ +import { BIP32, type BIP32Arg } from "../bip32.js"; +import type { Triple } from "../triple.js"; +import { FixedScriptWalletNamespace } from "../wasm/wasm_utxo.js"; +import { RootWalletKeys, assertCoinTypeU32, type WalletKeysArg } from "./RootWalletKeys.js"; + +/** + * The three wallet root keys in `[user, backup, bitgo]` order. + * + * Accepts everything {@link RootWalletKeys.from} accepts, plus a triple of any {@link BIP32Arg} + * (xpub/xprv strings, `BIP32` instances, `BIP32Interface` objects). Private keys are neutered + * before use: the result is the same for an xprv and the matching xpub. + */ +export type WalletPrefixKeysArg = WalletKeysArg | Triple; + +function toBIP32Triple(keys: WalletPrefixKeysArg): Triple { + if (keys instanceof RootWalletKeys) { + return [keys.userKey(), keys.backupKey(), keys.bitgoKey()]; + } + if (Array.isArray(keys)) { + return (keys as Triple).map((key) => BIP32.from(key)) as Triple; + } + return keys.triple.map((key) => BIP32.from(key)) as Triple; +} + +/** + * Compute the `[h1, h2]` account indices of a wallet from its three root keys. + * + * ``` + * d = sha256("BitGo/utxo/wallet-prefix/v1" || K_user || K_backup || K_bitgo) + * K = compressed public key (33 bytes) || chain code (32 bytes) (of the neutered root key) + * h1 = u32be(d[0..4]) & 0x7fffffff + * h2 = u32be(d[4..8]) & 0x7fffffff + * ``` + * + * Both are valid non-hardened BIP32 indices (`0..=2^31-1`). The result depends on the key order + * `[user, backup, bitgo]`. These are indices, not amounts, hence `number`. + * + * @param keys - The three wallet root keys `[user, backup, bitgo]` + */ +export function deriveWalletAccount(keys: WalletPrefixKeysArg): [number, number] { + const [user, backup, bitgo] = toBIP32Triple(keys); + const account = FixedScriptWalletNamespace.derive_wallet_account( + user.wasm, + backup.wasm, + bitgo.wasm, + ); + return [account[0], account[1]]; +} + +/** + * Compute the relative per-wallet derivation prefix `44//

/

` (no leading `/` or + * `m/`), see {@link deriveWalletAccount}. Addresses of a wallet using this prefix derive at + * `//` from each of the three root keys. + * + * @param keys - The three wallet root keys `[user, backup, bitgo]` + * @param coinType - BIP44 coin type of the coin family, an integer in `0..=2^31-1`. wasm-utxo has + * no coin registry: the caller supplies it (e.g. `coin.bip44CoinType` from `@bitgo/statics`). + * @throws a `WasmUtxoError` with code `WalletPrefixError.CoinTypeOutOfRange` if `coinType` is + * larger than `2^31-1` + */ +export function deriveWalletPrefix(keys: WalletPrefixKeysArg, coinType: number): string { + assertCoinTypeU32(coinType); + const [user, backup, bitgo] = toBIP32Triple(keys); + return FixedScriptWalletNamespace.derive_wallet_prefix( + user.wasm, + backup.wasm, + bitgo.wasm, + coinType, + ); +} diff --git a/packages/wasm-utxo/src/error.rs b/packages/wasm-utxo/src/error.rs index 90214e15dd3..e71cc7681c8 100644 --- a/packages/wasm-utxo/src/error.rs +++ b/packages/wasm-utxo/src/error.rs @@ -2,6 +2,8 @@ use core::fmt; use crate::fixed_script_wallet::bitgo_psbt::zcash_psbt::VerifyV6SignatureError; use crate::fixed_script_wallet::bitgo_psbt::ParseTransactionError; +use crate::fixed_script_wallet::wallet_prefix::WalletPrefixError; +use crate::fixed_script_wallet::WalletKeysError; pub trait WasmErrorCode { fn code(&self) -> String; @@ -32,6 +34,8 @@ pub enum WasmUtxoError { VerifyIronwood(crate::zcash::ironwood_build::IronwoodVerifyError), IronwoodPsbt(crate::fixed_script_wallet::bitgo_psbt::zcash::error::IronwoodPsbtError), VerifyV6Signature(VerifyV6SignatureError), + WalletKeys(WalletKeysError), + WalletPrefix(WalletPrefixError), } impl std::error::Error for WasmUtxoError {} @@ -49,6 +53,8 @@ impl fmt::Display for WasmUtxoError { WasmUtxoError::VerifyIronwood(e) => write!(f, "{}", e), WasmUtxoError::IronwoodPsbt(e) => write!(f, "{}", e), WasmUtxoError::VerifyV6Signature(e) => write!(f, "{}", e), + WasmUtxoError::WalletKeys(e) => write!(f, "{}", e), + WasmUtxoError::WalletPrefix(e) => write!(f, "{}", e), } } } @@ -76,6 +82,8 @@ impl WasmErrorCode for WasmUtxoError { WasmUtxoError::VerifyIronwood(e) => e.code(), WasmUtxoError::IronwoodPsbt(e) => e.code(), WasmUtxoError::VerifyV6Signature(e) => e.code(), + WasmUtxoError::WalletKeys(e) => e.code(), + WasmUtxoError::WalletPrefix(e) => e.code(), } } } @@ -159,6 +167,18 @@ impl From for WasmUtxoError { } } +impl From for WasmUtxoError { + fn from(err: WalletKeysError) -> Self { + WasmUtxoError::WalletKeys(err) + } +} + +impl From for WasmUtxoError { + fn from(err: WalletPrefixError) -> Self { + WasmUtxoError::WalletPrefix(err) + } +} + impl WasmUtxoError { pub fn new(s: &str) -> WasmUtxoError { WasmUtxoError::StringError(s.to_string()) diff --git a/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/bip44_prefix_tests.rs b/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/bip44_prefix_tests.rs new file mode 100644 index 00000000000..073000b1833 --- /dev/null +++ b/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/bip44_prefix_tests.rs @@ -0,0 +1,346 @@ +//! Classification of PSBT inputs and outputs recorded under the wallet's BIP44-style prefix +//! `44//

/

` (see `RootWalletKeys::with_bip44_coin_type`). + +use std::str::FromStr; + +use miniscript::bitcoin::bip32::{DerivationPath, Xpriv, Xpub}; +use miniscript::bitcoin::hashes::Hash; +use miniscript::bitcoin::secp256k1::Secp256k1; +use miniscript::bitcoin::Txid; + +use super::psbt_wallet_input::{SignPath, SignerKey}; +use super::{BitGoPsbt, ParsedTransaction, ScriptId, WalletInputOptions}; +use crate::fixed_script_wallet::test_utils::get_test_wallet_keys; +use crate::fixed_script_wallet::wallet_keys::tests::get_test_wallet_xprvs; +use crate::fixed_script_wallet::wallet_prefix::derive_wallet_prefix_path; +use crate::fixed_script_wallet::{ReplayProtection, RootWalletKeys, XpubTriple}; +use crate::Network; + +const BTC_COIN_TYPE: u32 = 0; +const SEED: &str = "bip44_prefix_tests"; + +fn xpubs() -> XpubTriple { + get_test_wallet_keys(SEED) +} + +fn prefix(s: &str) -> DerivationPath { + DerivationPath::from_str(s).unwrap() +} + +/// Keys that build under `prefix` on all three keys. +fn keys_with_prefix(xpubs: XpubTriple, prefix: DerivationPath) -> RootWalletKeys { + RootWalletKeys::new_with_derivation_prefixes(xpubs, [prefix.clone(), prefix.clone(), prefix]) + .unwrap() +} + +/// Keys that build under the wallet's canonical BIP44-style prefix. +fn bip44_build_keys(xpubs: XpubTriple, coin_type: u32) -> RootWalletKeys { + keys_with_prefix(xpubs, derive_wallet_prefix_path(&xpubs, coin_type).unwrap()) +} + +/// Default (`0/0`) keys that also recognise the BIP44-style subtree: what a verifier holds. +fn verifier_keys(xpubs: XpubTriple) -> RootWalletKeys { + RootWalletKeys::new(xpubs) + .with_bip44_coin_type(BTC_COIN_TYPE) + .unwrap() +} + +fn sign_path_for(chain: u32) -> Option { + (30..=41).contains(&chain).then_some(SignPath { + signer: SignerKey::User, + cosigner: SignerKey::Bitgo, + }) +} + +fn add_input(psbt: &mut BitGoPsbt, keys: &RootWalletKeys, vout: u32, chain: u32) { + psbt.add_wallet_input( + Txid::all_zeros(), + vout, + 100_000, + keys, + ScriptId { chain, index: vout }, + WalletInputOptions { + sign_path: sign_path_for(chain), + ..Default::default() + }, + ) + .unwrap(); +} + +fn parse(psbt: &BitGoPsbt, keys: &RootWalletKeys) -> Result { + psbt.parse_transaction_with_wallet_keys(keys, &ReplayProtection::new(vec![]), &[]) + .map_err(|e| e.to_string()) +} + +/// Chains of every script type BTC supports (external chain of each). +const BTC_CHAINS: [u32; 5] = [0, 10, 20, 30, 40]; + +#[test] +fn bip44_inputs_and_outputs_parse_with_default_keys_that_know_the_coin_type() { + let xpubs = xpubs(); + let build = bip44_build_keys(xpubs, BTC_COIN_TYPE); + let mut psbt = BitGoPsbt::new(Network::Bitcoin, &build, Some(2), Some(0)); + for (vout, chain) in BTC_CHAINS.iter().enumerate() { + add_input(&mut psbt, &build, vout as u32, *chain); + psbt.add_wallet_output(chain + 1, vout as u32, 1_000, &build) + .unwrap(); + } + + let parsed = parse(&psbt, &verifier_keys(xpubs)).unwrap(); + let bip44 = derive_wallet_prefix_path(&xpubs, BTC_COIN_TYPE).unwrap(); + for (i, input) in parsed.inputs.iter().enumerate() { + let path = input.derivation_path.as_ref().unwrap(); + assert_eq!( + *path, + bip44 + .child(miniscript::bitcoin::bip32::ChildNumber::Normal { + index: BTC_CHAINS[i] + }) + .child(miniscript::bitcoin::bip32::ChildNumber::Normal { index: i as u32 }) + ); + } + assert!(parsed.outputs.iter().all(|o| !o.is_external())); + assert_eq!(parsed.spend_amount, 0); +} + +#[test] +fn bip44_inputs_fail_without_the_coin_type() { + // Without the coin type the keys only accept their own prefix, as before this change. + let xpubs = xpubs(); + let build = bip44_build_keys(xpubs, BTC_COIN_TYPE); + let mut psbt = BitGoPsbt::new(Network::Bitcoin, &build, Some(2), Some(0)); + add_input(&mut psbt, &build, 0, 20); + let err = parse(&psbt, &RootWalletKeys::new(xpubs)).unwrap_err(); + assert!(err.contains("wallet validation failed"), "{err}"); +} + +#[test] +fn mixed_legacy_and_bip44_inputs_and_outputs_parse_with_one_key_set() { + let xpubs = xpubs(); + let legacy = RootWalletKeys::new(xpubs); + let bip44 = bip44_build_keys(xpubs, BTC_COIN_TYPE); + // Built with two key sets on one PSBT: inputs and outputs carry their own prefix. + let mut psbt = BitGoPsbt::new(Network::Bitcoin, &legacy, Some(2), Some(0)); + for (vout, chain) in BTC_CHAINS.iter().enumerate() { + let keys = if vout % 2 == 0 { &legacy } else { &bip44 }; + add_input(&mut psbt, keys, vout as u32, *chain); + psbt.add_wallet_output(chain + 1, vout as u32, 1_000, keys) + .unwrap(); + } + + let parsed = parse(&psbt, &verifier_keys(xpubs)).unwrap(); + for (i, input) in parsed.inputs.iter().enumerate() { + let path = input.derivation_path.as_ref().unwrap().to_string(); + let expected_prefix = if i % 2 == 0 { "0/0/" } else { "44/0/" }; + assert!(path.starts_with(expected_prefix), "input {i}: {path}"); + } + assert!(parsed.outputs.iter().all(|o| !o.is_external())); +} + +#[test] +fn per_key_prefixes_still_parse_taproot_and_musig2_inputs() { + // Recovery builds keys as `[userKeyPath, 0/0, 0/0]`; taproot inputs record two key origins. + let xpubs = xpubs(); + let keys = RootWalletKeys::new_with_derivation_prefixes( + xpubs, + [prefix("m/1/2"), prefix("m/0/0"), prefix("m/0/0")], + ) + .unwrap(); + let mut psbt = BitGoPsbt::new(Network::Bitcoin, &keys, Some(2), Some(0)); + for (vout, chain) in [30u32, 40, 20].iter().enumerate() { + add_input(&mut psbt, &keys, vout as u32, *chain); + } + parse(&psbt, &keys).unwrap(); + parse( + &psbt, + &keys.clone().with_bip44_coin_type(BTC_COIN_TYPE).unwrap(), + ) + .unwrap(); +} + +#[test] +fn outputs_with_wallet_fingerprints_under_any_other_prefix_fail_the_parse() { + // An output whose key origins all carry this wallet's fingerprints but whose script is not + // derived under an accepted prefix is never wallet change: the parse fails closed. + let xpubs = xpubs(); + let legacy = RootWalletKeys::new(xpubs); + let (h1, h2) = crate::fixed_script_wallet::wallet_prefix::derive_wallet_account(&xpubs); + let other_prefixes = [ + prefix("m/7/7"), + // Right account, wrong coin type. + prefix(&format!("m/44/2/{h1}/{h2}")), + // Right coin type, wrong account. + prefix(&format!("m/44/0/{h1}/{}", h2 ^ 1)), + // Boundary accounts that are not this wallet's. + prefix("m/44/0/0/0"), + prefix("m/44/0/2147483647/2147483647"), + ]; + + for other in other_prefixes { + let rogue = keys_with_prefix(xpubs, other.clone()); + for chain in [1u32, 11, 21, 31, 41] { + let mut psbt = BitGoPsbt::new(Network::Bitcoin, &legacy, Some(2), Some(0)); + add_input(&mut psbt, &legacy, 0, 20); + psbt.add_wallet_output(chain, 5, 90_000, &rogue).unwrap(); + + let err = parse(&psbt, &verifier_keys(xpubs)).unwrap_err(); + assert!( + err.contains("Output 0") && err.contains("no script type matches"), + "prefix {other} chain {chain}: {err}" + ); + } + } +} + +#[test] +fn inputs_under_any_other_prefix_are_rejected() { + let xpubs = xpubs(); + let rogue = keys_with_prefix(xpubs, prefix("m/44/0/0/0")); + let mut psbt = BitGoPsbt::new(Network::Bitcoin, &rogue, Some(2), Some(0)); + add_input(&mut psbt, &rogue, 0, 30); + let err = parse(&psbt, &verifier_keys(xpubs)).unwrap_err(); + assert!(err.contains("wallet validation failed"), "{err}"); +} + +#[test] +fn sibling_wallet_bip44_output_is_external() { + // Shares user and backup keys, different bitgo key: a different (h1, h2) and bitgo leaf. + let xpubs = xpubs(); + let sibling: XpubTriple = [xpubs[0], xpubs[1], get_test_wallet_keys("sibling")[2]]; + let legacy = RootWalletKeys::new(xpubs); + let mut psbt = BitGoPsbt::new(Network::Bitcoin, &legacy, Some(2), Some(0)); + add_input(&mut psbt, &legacy, 0, 20); + let sibling_build = bip44_build_keys(sibling, BTC_COIN_TYPE); + for chain in [1u32, 21, 31, 41] { + psbt.add_wallet_output(chain, 0, 1_000, &sibling_build) + .unwrap(); + } + + let parsed = parse(&psbt, &verifier_keys(xpubs)).unwrap(); + assert!(parsed.outputs.iter().all(|o| o.is_external())); +} + +#[test] +fn get_wallet_keys_from_psbt_resolves_bip44_and_mixed_psbts() { + let xpubs = xpubs(); + let legacy = RootWalletKeys::new(xpubs); + let bip44 = bip44_build_keys(xpubs, BTC_COIN_TYPE); + let mut psbt = BitGoPsbt::new(Network::Bitcoin, &legacy, Some(2), Some(0)); + add_input(&mut psbt, &bip44, 0, 20); + add_input(&mut psbt, &legacy, 1, 40); + + let shuffled = [xpubs[2], xpubs[0], xpubs[1]]; + assert!(super::to_wallet_keys(&psbt, shuffled, None).is_err()); + let resolved = super::to_wallet_keys(&psbt, shuffled, Some(BTC_COIN_TYPE)).unwrap(); + assert_eq!(resolved.xpubs, xpubs); + assert_eq!( + resolved.bip44_prefix(), + Some(&derive_wallet_prefix_path(&xpubs, BTC_COIN_TYPE).unwrap()) + ); +} + +#[test] +fn bip44_inputs_sign_and_verify_ecdsa_and_musig2() { + let secp = Secp256k1::new(); + let xprvs = get_test_wallet_xprvs(SEED); + let xpubs = xprvs.map(|x| Xpub::from_priv(&secp, &x)); + let build = bip44_build_keys(xpubs, BTC_COIN_TYPE); + let mut psbt = BitGoPsbt::new(Network::Bitcoin, &build, Some(2), Some(0)); + for (vout, chain) in BTC_CHAINS.iter().enumerate() { + add_input(&mut psbt, &build, vout as u32, *chain); + } + + // MuSig2 (chain 40, input 4): nonce rounds for user and bitgo, then both sign. + let user: &Xpriv = &xprvs[0]; + let bitgo: &Xpriv = &xprvs[2]; + let musig2_input = 4; + let (user_first_round, user_nonce) = psbt + .generate_nonce_first_round(musig2_input, user, [1u8; 32]) + .unwrap(); + let (bitgo_first_round, bitgo_nonce) = psbt + .generate_nonce_first_round(musig2_input, bitgo, [2u8; 32]) + .unwrap(); + let _ = (user_nonce, bitgo_nonce); + psbt.sign_with_first_round(musig2_input, user_first_round, user) + .unwrap(); + psbt.sign_with_first_round(musig2_input, bitgo_first_round, bitgo) + .unwrap(); + + // ECDSA and taproot script path for the rest. + psbt.sign_all_with_xpriv(user).unwrap(); + psbt.sign_all_with_xpriv(bitgo).unwrap(); + + for input_index in 0..BTC_CHAINS.len() { + assert!( + psbt.verify_signature_with_xpub(&secp, input_index, &xpubs[0]) + .unwrap(), + "user signature on input {input_index}" + ); + assert!( + psbt.verify_signature_with_xpub(&secp, input_index, &xpubs[2]) + .unwrap(), + "bitgo signature on input {input_index}" + ); + } + parse(&psbt, &verifier_keys(xpubs)).unwrap(); +} + +#[test] +fn zcash_bip44_inputs_and_outputs_parse() { + use crate::zcash::NetworkUpgrade; + + let xpubs = xpubs(); + // zec coin type 133 + let build = bip44_build_keys(xpubs, 133); + let mut psbt = BitGoPsbt::new_zcash_at_height( + Network::ZcashTestnet, + &build, + NetworkUpgrade::Nu5.testnet_activation_height(), + None, + None, + None, + None, + ) + .unwrap(); + add_input(&mut psbt, &build, 0, 0); + psbt.add_wallet_output(1, 0, 1_000, &build).unwrap(); + + let verifier = RootWalletKeys::new(xpubs) + .with_bip44_coin_type(133) + .unwrap(); + let parsed = parse(&psbt, &verifier).unwrap(); + assert!(parsed.outputs.iter().all(|o| !o.is_external())); + // Wrong coin type: not recognised. + let err = parse( + &psbt, + &RootWalletKeys::new(xpubs) + .with_bip44_coin_type(BTC_COIN_TYPE) + .unwrap(), + ) + .unwrap_err(); + assert!(err.contains("wallet validation failed"), "{err}"); +} + +#[test] +fn with_bip44_coin_type_rejects_a_hardened_coin_type() { + let err = RootWalletKeys::new(xpubs()) + .with_bip44_coin_type(0x8000_0000) + .unwrap_err(); + assert_eq!( + crate::error::WasmErrorCode::code(&crate::error::WasmUtxoError::from(err)), + "WalletPrefixError.CoinTypeOutOfRange" + ); +} + +#[test] +fn hardened_derivation_prefix_is_an_error() { + let err = RootWalletKeys::new_with_derivation_prefixes( + xpubs(), + [prefix("m/44'/0"), prefix("m/0/0"), prefix("m/0/0")], + ) + .unwrap_err(); + assert_eq!( + crate::error::WasmErrorCode::code(&crate::error::WasmUtxoError::from(err)), + "WalletKeysError.HardenedDerivationPrefix" + ); +} diff --git a/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/mod.rs b/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/mod.rs index 45db627f8a0..e110592f943 100644 --- a/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/mod.rs +++ b/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/mod.rs @@ -3,6 +3,8 @@ //! This module provides PSBT deserialization that works across different //! bitcoin-like networks, including those with non-standard transaction formats. +#[cfg(test)] +mod bip44_prefix_tests; pub mod dash_psbt; mod legacy_txformat; pub mod p2tr_musig2_input; @@ -3389,9 +3391,14 @@ const XPUB_TRIPLE_PERMUTATIONS: [[usize; 3]; 6] = [ /// For each permutation, constructs `RootWalletKeys` and validates every non-replay-protection /// input against it. The first permutation where all inputs pass validation is returned. /// Works for all script types including p2tr. +/// +/// If `bip44_coin_type` is set, the candidate keys also recognise the wallet's BIP44-style +/// prefix (see [`RootWalletKeys::with_bip44_coin_type`]), so BIP44-style and mixed PSBTs +/// resolve too, and the returned keys carry it. pub fn to_wallet_keys( psbt: &BitGoPsbt, xpubs: crate::fixed_script_wallet::XpubTriple, + bip44_coin_type: Option, ) -> Result { use crate::fixed_script_wallet::RootWalletKeys; @@ -3415,7 +3422,12 @@ pub fn to_wallet_keys( for perm in &XPUB_TRIPLE_PERMUTATIONS { let permuted = [xpubs[perm[0]], xpubs[perm[1]], xpubs[perm[2]]]; - let wallet_keys = RootWalletKeys::new(permuted); + let wallet_keys = match bip44_coin_type { + Some(coin_type) => RootWalletKeys::new(permuted) + .with_bip44_coin_type(coin_type) + .map_err(|e| e.to_string())?, + None => RootWalletKeys::new(permuted), + }; let all_match = wallet_inputs.iter().all(|(tx_input, psbt_input)| { let output_script = psbt_wallet_input::get_output_script_and_value( @@ -5664,7 +5676,7 @@ mod tests { ) .expect("add_wallet_input"); - let result = to_wallet_keys(&psbt, xpubs).expect("should find correct order"); + let result = to_wallet_keys(&psbt, xpubs, None).expect("should find correct order"); assert_eq!(result.xpubs, xpubs); } @@ -5693,7 +5705,7 @@ mod tests { // Shuffle the xpubs: [bitgo, user, backup] instead of [user, backup, bitgo] let shuffled = [xpubs[2], xpubs[0], xpubs[1]]; - let result = to_wallet_keys(&psbt, shuffled).expect("should find correct order"); + let result = to_wallet_keys(&psbt, shuffled, None).expect("should find correct order"); // Result should be sorted back to [user, backup, bitgo] assert_eq!(result.xpubs, xpubs); } diff --git a/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/psbt_wallet_input.rs b/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/psbt_wallet_input.rs index ddb3058f83c..f1cdd1dd5d3 100644 --- a/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/psbt_wallet_input.rs +++ b/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/psbt_wallet_input.rs @@ -492,7 +492,8 @@ pub struct ParsedInput { pub script_id: Option, pub script_type: InputScriptType, pub sequence: u32, - /// Full BIP32 derivation path from the wallet xpub (e.g. `[chain, index]`). + /// Full BIP32 derivation path recorded in the PSBT, from the wallet root key: the prefix + /// followed by `[chain, index]` (e.g. `0/0/20/5` legacy, `44/0/

/

/20/5` BIP44-style). /// `None` for replay-protection inputs which have no wallet derivation. pub derivation_path: Option, } diff --git a/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/psbt_wallet_output.rs b/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/psbt_wallet_output.rs index f9db3c62edf..c6d542ea3f2 100644 --- a/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/psbt_wallet_output.rs +++ b/packages/wasm-utxo/src/fixed_script_wallet/bitgo_psbt/psbt_wallet_output.rs @@ -12,7 +12,9 @@ pub struct ParsedOutput { pub value: u64, pub script_id: Option, pub paygo: bool, - /// Full BIP32 derivation path from the wallet xpub (e.g. `[chain, index]`). + /// Full BIP32 derivation path recorded in the PSBT, from the wallet root key: the prefix + /// followed by `[chain, index]` (e.g. `0/0/20/5` legacy, `44/0/

/

/20/5` BIP44-style). + /// The prefix is everything except the last two components. /// `None` for outputs that do not belong to this wallet. pub derivation_path: Option, } diff --git a/packages/wasm-utxo/src/fixed_script_wallet/mod.rs b/packages/wasm-utxo/src/fixed_script_wallet/mod.rs index 1f7ed2d7420..82fcb3445b6 100644 --- a/packages/wasm-utxo/src/fixed_script_wallet/mod.rs +++ b/packages/wasm-utxo/src/fixed_script_wallet/mod.rs @@ -4,6 +4,7 @@ pub mod bitgo_psbt; pub mod replay_protection; pub mod script_id; mod wallet_keys; +pub mod wallet_prefix; pub mod wallet_scripts; #[cfg(test)] diff --git a/packages/wasm-utxo/src/fixed_script_wallet/wallet_keys.rs b/packages/wasm-utxo/src/fixed_script_wallet/wallet_keys.rs index 706133bf718..afb9433d3f7 100644 --- a/packages/wasm-utxo/src/fixed_script_wallet/wallet_keys.rs +++ b/packages/wasm-utxo/src/fixed_script_wallet/wallet_keys.rs @@ -29,43 +29,153 @@ pub fn derivation_path(prefix: &DerivationPath, chain: u32, index: u32) -> Deriv /// Maximum number of (chain, index) pairs to cache const DERIVATION_CACHE_MAX_SIZE: usize = 128; +type DerivationCache = RefCell>; + +/// The canonical BIP44-style subtree `44//

/

` of a wallet, shared by all three +/// keys (see [`crate::fixed_script_wallet::wallet_prefix`]). +#[derive(Debug)] +struct Bip44Subtree { + /// `44//

/

` + prefix: DerivationPath, + /// The three root keys derived to `prefix` + prefix_derived: XpubTriple, + derivation_cache: DerivationCache, +} + +impl Clone for Bip44Subtree { + fn clone(&self) -> Self { + Self { + prefix: self.prefix.clone(), + prefix_derived: self.prefix_derived, + derivation_cache: RefCell::new(self.derivation_cache.borrow().clone()), + } + } +} + pub struct RootWalletKeys { pub xpubs: XpubTriple, pub derivation_prefixes: [DerivationPath; 3], /// Keys derived to prefix level (computed once in constructor) prefix_derived: XpubTriple, /// Keys derived to (chain, index) level (cached on-demand, bounded size) - derivation_cache: RefCell>, + derivation_cache: DerivationCache, + /// The wallet's BIP44-style subtree, recognised in addition to `derivation_prefixes` when + /// classifying PSBT inputs and outputs. Set by [`RootWalletKeys::with_bip44_coin_type`]. + bip44: Option, /// Shared secp256k1 context (avoids repeated allocation) secp: Secp256k1, } +/// Names of the three wallet keys in `[user, backup, bitgo]` order, for error messages. +const KEY_NAMES: [&str; 3] = ["user", "backup", "bitgo"]; + +/// Errors while building a [`RootWalletKeys`]. +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] +pub enum WalletKeysError { + /// A derivation prefix contains a hardened component. Wallet keys are public (xpub) + /// keys, so only non-hardened (soft) derivation is possible. + HardenedDerivationPrefix { key: &'static str, prefix: String }, + /// Deriving a key along its prefix failed for a reason other than hardening. + PrefixDerivation { + key: &'static str, + prefix: String, + reason: String, + }, +} + +impl std::fmt::Display for WalletKeysError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::HardenedDerivationPrefix { key, prefix } => write!( + f, + "derivation prefix of the {key} key contains a hardened component \ + (only non-hardened derivation is possible from an xpub): {prefix}" + ), + Self::PrefixDerivation { + key, + prefix, + reason, + } => write!( + f, + "could not derive the {key} key along prefix {prefix}: {reason}" + ), + } + } +} + +impl std::error::Error for WalletKeysError {} +crate::impl_wasm_error_code!(WalletKeysError); + impl RootWalletKeys { + /// Build wallet keys with one derivation prefix per key. + /// + /// Returns an error if a prefix has a hardened component (an xpub cannot derive it). pub fn new_with_derivation_prefixes( xpubs: XpubTriple, derivation_prefixes: [DerivationPath; 3], - ) -> Self { + ) -> Result { let secp = Secp256k1::new(); // Pre-derive keys to prefix level (e.g., m/0/0) - let prefix_derived: XpubTriple = xpubs - .iter() - .zip(derivation_prefixes.iter()) - .map(|(xpub, prefix)| { - xpub.derive_pub(&secp, prefix) - .expect("valid prefix derivation") - }) - .collect::>() - .try_into() - .expect("3 keys"); + let prefix_derived: XpubTriple = { + let mut derived = Vec::with_capacity(3); + for (i, (xpub, prefix)) in xpubs.iter().zip(derivation_prefixes.iter()).enumerate() { + if prefix.into_iter().any(|c| c.is_hardened()) { + return Err(WalletKeysError::HardenedDerivationPrefix { + key: KEY_NAMES[i], + prefix: prefix.to_string(), + }); + } + derived.push(xpub.derive_pub(&secp, prefix).map_err(|e| { + WalletKeysError::PrefixDerivation { + key: KEY_NAMES[i], + prefix: prefix.to_string(), + reason: e.to_string(), + } + })?); + } + derived.try_into().expect("3 keys") + }; - Self { + Ok(Self { xpubs, derivation_prefixes, prefix_derived, derivation_cache: RefCell::new(HashMap::new()), + bip44: None, secp, - } + }) + } + + /// Also recognise the wallet's BIP44-style subtree `44//

/

` when + /// classifying PSBT inputs and outputs, with `(h1, h2)` computed from the three root keys. + /// + /// The derivation prefixes used to build addresses, inputs and outputs are unchanged. + /// `coin_type` is the BIP44 coin type of the coin family, supplied by the caller (wasm-utxo has + /// no coin registry); it must be a non-hardened index. + pub fn with_bip44_coin_type( + mut self, + coin_type: u32, + ) -> Result { + let prefix = crate::fixed_script_wallet::wallet_prefix::derive_wallet_prefix_path( + &self.xpubs, + coin_type, + )?; + let prefix_derived: XpubTriple = self.xpubs.map(|xpub| { + xpub.derive_pub(&self.secp, &prefix) + .expect("non-hardened prefix is derivable from an xpub") + }); + self.bip44 = Some(Bip44Subtree { + prefix, + prefix_derived, + derivation_cache: RefCell::new(HashMap::new()), + }); + Ok(self) + } + + /// The BIP44-style prefix `44//

/

` recognised by these keys, if any. + pub fn bip44_prefix(&self) -> Option<&DerivationPath> { + self.bip44.as_ref().map(|b| &b.prefix) } pub fn user_key(&self) -> &Xpub { @@ -80,6 +190,7 @@ impl RootWalletKeys { &self.xpubs[2] } + /// Wallet keys with the legacy `m/0/0` prefix on all three keys. pub fn new(xpubs: XpubTriple) -> Self { Self::new_with_derivation_prefixes( xpubs, @@ -89,46 +200,91 @@ impl RootWalletKeys { DerivationPath::from_str("m/0/0").unwrap(), ], ) + .expect("m/0/0 is a valid non-hardened prefix") } /// Derive keys from `self.prefix_derived` along `path`. /// Caches using the last two Normal path components as `(chain, index)`. pub fn derive_path(&self, path: &DerivationPath) -> Result { - let cache_key: Option<(u32, u32)> = { - let children: Vec<_> = path.into_iter().cloned().collect(); - let n = children.len(); - match (children.get(n.wrapping_sub(2)), children.last()) { - ( - Some(ChildNumber::Normal { index: c }), - Some(ChildNumber::Normal { index: i }), - ) => Some((*c, *i)), - _ => None, - } - }; - if let Some(key) = cache_key { - if let Some(cached) = self.derivation_cache.borrow().get(&key) { - return Ok(*cached); + derive_cached( + &self.secp, + &self.prefix_derived, + &self.derivation_cache, + path, + ) + } + + /// The three keys at `//` if the recorded prefix is one these + /// keys accept: the BIP44-style prefix (when set via [`Self::with_bip44_coin_type`]), else the + /// keys' own `derivation_prefixes`. + /// + /// `recorded_path` is a full path as recorded in a PSBT key origin. Any prefix other than the + /// BIP44-style one falls back to the keys' own prefixes, so a PSBT path under an unknown + /// prefix derives keys that do not match its script. + pub(crate) fn derive_for_recorded_path( + &self, + recorded_path: &DerivationPath, + chain: u32, + index: u32, + ) -> Result { + let tail = DerivationPath::from(vec![ + ChildNumber::Normal { index: chain }, + ChildNumber::Normal { index }, + ]); + 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::, _>>()? - .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) + } +} + +fn derive_cached( + secp: &Secp256k1, + prefix_derived: &XpubTriple, + derivation_cache: &DerivationCache, + path: &DerivationPath, +) -> Result { + let cache_key: Option<(u32, u32)> = { + let children: Vec<_> = path.into_iter().cloned().collect(); + let n = children.len(); + match (children.get(n.wrapping_sub(2)), children.last()) { + (Some(ChildNumber::Normal { index: c }), Some(ChildNumber::Normal { index: i })) => { + Some((*c, *i)) } - cache.insert(key, derived); + _ => None, + } + }; + if let Some(key) = cache_key { + if let Some(cached) = derivation_cache.borrow().get(&key) { + return Ok(*cached); + } + } + let derived: XpubTriple = prefix_derived + .iter() + .map(|xpub| { + xpub.derive_pub(secp, path) + .map_err(|e| WasmUtxoError::new(&format!("Error deriving xpub: {}", e))) + }) + .collect::, _>>()? + .try_into() + .map_err(|_| WasmUtxoError::new("Expected exactly 3 derived xpubs"))?; + if let Some(key) = cache_key { + let mut cache = derivation_cache.borrow_mut(); + if cache.len() >= DERIVATION_CACHE_MAX_SIZE { + cache.clear(); } - Ok(derived) + cache.insert(key, derived); } + Ok(derived) } impl Clone for RootWalletKeys { @@ -138,6 +294,7 @@ impl Clone for RootWalletKeys { derivation_prefixes: self.derivation_prefixes.clone(), prefix_derived: self.prefix_derived, derivation_cache: RefCell::new(self.derivation_cache.borrow().clone()), + bip44: self.bip44.clone(), secp: Secp256k1::new(), } } @@ -153,6 +310,7 @@ impl std::fmt::Debug for RootWalletKeys { "derivation_cache_size", &self.derivation_cache.borrow().len(), ) + .field("bip44_prefix", &self.bip44_prefix()) .finish() } } diff --git a/packages/wasm-utxo/src/fixed_script_wallet/wallet_prefix.rs b/packages/wasm-utxo/src/fixed_script_wallet/wallet_prefix.rs new file mode 100644 index 00000000000..75f40a278e4 --- /dev/null +++ b/packages/wasm-utxo/src/fixed_script_wallet/wallet_prefix.rs @@ -0,0 +1,231 @@ +//! Per-wallet derivation prefix for BitGo fixed-script wallets. +//! +//! Besides the legacy layout `/0/0//`, a wallet may derive its addresses +//! below a BIP44-style prefix `/44//

/

//`. All levels are +//! non-hardened, so everything can be derived from xpubs alone. +//! +//! `h1` and `h2` are never stored: they are a pure function of the three wallet root keys, +//! +//! ```text +//! d = sha256("BitGo/utxo/wallet-prefix/v1" || K_user || K_backup || K_bitgo) +//! K = compressed public key (33 bytes) || chain code (32 bytes) (of the neutered root key) +//! h1 = u32be(d[0..4]) & 0x7fffffff +//! h2 = u32be(d[4..8]) & 0x7fffffff +//! ``` +//! +//! The result depends on the key order `[user, backup, bitgo]`. + +use crate::bitcoin::bip32::{ChildNumber, DerivationPath}; +use crate::bitcoin::hashes::{sha256, Hash}; + +use super::wallet_keys::XpubTriple; + +/// Domain-separation tag hashed in front of the three root keys. +const WALLET_PREFIX_TAG: &[u8] = b"BitGo/utxo/wallet-prefix/v1"; + +/// Largest value of a non-hardened BIP32 child index (`2^31 - 1`). +pub const MAX_SOFT_INDEX: u32 = 0x7fff_ffff; + +/// Errors while computing a wallet prefix. +#[derive(Debug, Clone, PartialEq, Eq, strum::IntoStaticStr)] +pub enum WalletPrefixError { + /// The coin type is not a valid non-hardened index (`> 2^31 - 1`). + CoinTypeOutOfRange { coin_type: u32 }, +} + +impl std::fmt::Display for WalletPrefixError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::CoinTypeOutOfRange { coin_type } => write!( + f, + "coin type {coin_type} is out of range: must be at most {MAX_SOFT_INDEX}" + ), + } + } +} + +impl std::error::Error for WalletPrefixError {} +crate::impl_wasm_error_code!(WalletPrefixError); + +/// Compute the `(h1, h2)` account indices of a wallet from its three root keys +/// `[user, backup, bitgo]`. +/// +/// Only the public key and chain code of each key enter the hash, so the result is the same +/// whether the keys were an xprv or the matching xpub, and on any network. +pub fn derive_wallet_account(xpubs: &XpubTriple) -> (u32, u32) { + let mut preimage = Vec::with_capacity(WALLET_PREFIX_TAG.len() + 3 * 65); + preimage.extend_from_slice(WALLET_PREFIX_TAG); + for xpub in xpubs { + preimage.extend_from_slice(&xpub.public_key.serialize()); + preimage.extend_from_slice(&xpub.chain_code.to_bytes()); + } + let digest = sha256::Hash::hash(&preimage).to_byte_array(); + + let word = |offset: usize| { + let bytes: [u8; 4] = [ + digest[offset], + digest[offset + 1], + digest[offset + 2], + digest[offset + 3], + ]; + u32::from_be_bytes(bytes) & MAX_SOFT_INDEX + }; + (word(0), word(4)) +} + +/// Compute the relative derivation prefix `44//

/

` of a wallet (no leading +/// `/` or `m/`). +/// +/// `coin_type` is the BIP44 coin type of the coin family (supplied by the caller: wasm-utxo has +/// no coin registry). It must be a valid non-hardened index. +pub fn derive_wallet_prefix( + xpubs: &XpubTriple, + coin_type: u32, +) -> Result { + if coin_type > MAX_SOFT_INDEX { + return Err(WalletPrefixError::CoinTypeOutOfRange { coin_type }); + } + let (h1, h2) = derive_wallet_account(xpubs); + Ok(format!("44/{coin_type}/{h1}/{h2}")) +} + +/// [`derive_wallet_prefix`] as a [`DerivationPath`] of four non-hardened components. +pub fn derive_wallet_prefix_path( + xpubs: &XpubTriple, + coin_type: u32, +) -> Result { + if coin_type > MAX_SOFT_INDEX { + return Err(WalletPrefixError::CoinTypeOutOfRange { coin_type }); + } + let (h1, h2) = derive_wallet_account(xpubs); + Ok(DerivationPath::from( + [44, coin_type, h1, h2] + .map(|index| ChildNumber::Normal { index }) + .to_vec(), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitcoin::bip32::Xpub; + use crate::error::WasmErrorCode; + use crate::fixed_script_wallet::wallet_keys::tests::get_xpriv_from_seed; + use crate::fixed_script_wallet::RootWalletKeys; + + fn xpub_from_seed(seed: &str) -> Xpub { + let secp = crate::bitcoin::secp256k1::Secp256k1::new(); + Xpub::from_priv(&secp, &get_xpriv_from_seed(seed)) + } + + fn triple(bitgo_seed: &str) -> XpubTriple { + [ + xpub_from_seed("bip44-prefix-user"), + xpub_from_seed("bip44-prefix-backup"), + xpub_from_seed(bitgo_seed), + ] + } + + /// Known (bitgo seed, h1, h2) vectors for the `bip44-prefix-*` seeds below. + const VECTORS: [(&str, u32, u32); 3] = [ + ("bip44-prefix-bitgo1", 150281926, 1196201100), + ("bip44-prefix-bitgo2", 1154090906, 1226953368), + ("bip44-prefix-bitgo", 1419038811, 446779176), + ]; + + #[test] + fn derive_wallet_account_matches_the_known_vectors() { + for (bitgo_seed, h1, h2) in VECTORS { + assert_eq!( + derive_wallet_account(&triple(bitgo_seed)), + (h1, h2), + "bitgo seed {bitgo_seed}" + ); + } + } + + /// The project's published vectors: user `wcn3907-u`, backup `wcn3907-b`, keys from + /// `BIP32.fromSeedSha256(seed)` (sha256 of the seed string as the BIP32 master seed). + #[test] + fn derive_wallet_account_matches_the_project_spec_vectors() { + let spec_triple = |bitgo_seed: &str| -> XpubTriple { + [ + xpub_from_seed("wcn3907-u"), + xpub_from_seed("wcn3907-b"), + xpub_from_seed(bitgo_seed), + ] + }; + for (bitgo_seed, h1, h2) in [ + ("wcn3907-g1", 1528449227, 506574854), + ("wcn3907-g2", 1401193521, 285195054), + ("wcn3907-g", 1639221447, 1133889609), + ] { + assert_eq!( + derive_wallet_account(&spec_triple(bitgo_seed)), + (h1, h2), + "bitgo seed {bitgo_seed}" + ); + } + assert_eq!( + derive_wallet_prefix(&spec_triple("wcn3907-g"), 0).unwrap(), + "44/0/1639221447/1133889609" + ); + } + + #[test] + fn derive_wallet_prefix_formats_the_relative_prefix() { + assert_eq!( + derive_wallet_prefix(&triple("bip44-prefix-bitgo"), 0).unwrap(), + "44/0/1419038811/446779176" + ); + assert_eq!( + derive_wallet_prefix(&triple("bip44-prefix-bitgo1"), 145).unwrap(), + "44/145/150281926/1196201100" + ); + assert_eq!( + derive_wallet_prefix(&triple("bip44-prefix-bitgo2"), MAX_SOFT_INDEX).unwrap(), + "44/2147483647/1154090906/1226953368" + ); + } + + #[test] + fn derive_wallet_prefix_rejects_a_hardened_coin_type() { + let err = + derive_wallet_prefix(&triple("bip44-prefix-bitgo"), MAX_SOFT_INDEX + 1).unwrap_err(); + assert_eq!( + err, + WalletPrefixError::CoinTypeOutOfRange { + coin_type: MAX_SOFT_INDEX + 1 + } + ); + assert_eq!( + crate::error::WasmUtxoError::from(err).code(), + "WalletPrefixError.CoinTypeOutOfRange" + ); + assert!(derive_wallet_prefix(&triple("bip44-prefix-bitgo"), u32::MAX).is_err()); + } + + #[test] + fn derive_wallet_account_depends_on_key_order() { + let [user, backup, bitgo] = triple("bip44-prefix-bitgo"); + assert_ne!( + derive_wallet_account(&[user, backup, bitgo]), + derive_wallet_account(&[backup, user, bitgo]) + ); + assert_ne!( + derive_wallet_account(&[user, backup, bitgo]), + derive_wallet_account(&[user, bitgo, backup]) + ); + } + + #[test] + fn derive_wallet_account_ignores_derivation_prefixes_of_the_wallet_keys() { + // The account depends on the three root keys only, not on how a RootWalletKeys derives. + let xpubs = triple("bip44-prefix-bitgo"); + let keys = RootWalletKeys::new(xpubs); + assert_eq!( + derive_wallet_account(&keys.xpubs), + derive_wallet_account(&xpubs) + ); + } +} diff --git a/packages/wasm-utxo/src/fixed_script_wallet/wallet_scripts/mod.rs b/packages/wasm-utxo/src/fixed_script_wallet/wallet_scripts/mod.rs index 4974e4a184f..9e4f96b0222 100644 --- a/packages/wasm-utxo/src/fixed_script_wallet/wallet_scripts/mod.rs +++ b/packages/wasm-utxo/src/fixed_script_wallet/wallet_scripts/mod.rs @@ -218,6 +218,11 @@ impl OutputScriptType { /// Iterates all known script types; skips types unsupported by the network or /// incompatible with the script shape, then checks by derivation. /// Returns the first matching type, or `None` if none match. + /// + /// `(chain, index)` are the last two components of `path`. The keys are derived under the + /// wallet's BIP44-style prefix if `path` is `//` (see + /// [`RootWalletKeys::with_bip44_coin_type`]), and under the keys' own derivation prefixes + /// otherwise. No other prefix is accepted: a script derived under one does not match. pub fn check( wallet_keys: &RootWalletKeys, output_script: &ScriptBuf, @@ -227,7 +232,7 @@ impl OutputScriptType { ) -> Option { let (chain, index) = path_chain_index(path)?; let derived_keys = wallet_keys - .derive_path(&chain_index_path(chain, index)) + .derive_for_recorded_path(path, chain, index) .ok()?; let pub_triple = to_pub_triple(&derived_keys); for &script_type in Self::all() { diff --git a/packages/wasm-utxo/src/wasm/fixed_script_wallet/mod.rs b/packages/wasm-utxo/src/wasm/fixed_script_wallet/mod.rs index 90d4f36c56e..7d1476dd701 100644 --- a/packages/wasm-utxo/src/wasm/fixed_script_wallet/mod.rs +++ b/packages/wasm-utxo/src/wasm/fixed_script_wallet/mod.rs @@ -257,23 +257,68 @@ impl FixedScriptWalletNamespace { /// Sort an xpub triple into [user, backup, bitgo] order by validating /// against the PSBT's wallet inputs. Returns a RootWalletKeys with the /// correct ordering. + /// + /// If `bip44_coin_type` is set, inputs under the wallet's BIP44-style prefix + /// `44//

/

` are recognised as well, and the returned keys recognise it too. #[wasm_bindgen] pub fn to_wallet_keys( psbt: &BitGoPsbt, user_or_a: &WasmBIP32, backup_or_b: &WasmBIP32, bitgo_or_c: &WasmBIP32, + bip44_coin_type: Option, ) -> Result { let xpubs = [ user_or_a.to_xpub()?, backup_or_b.to_xpub()?, bitgo_or_c.to_xpub()?, ]; - let wallet_keys = crate::fixed_script_wallet::bitgo_psbt::to_wallet_keys(&psbt.psbt, xpubs) - .map_err(|e| WasmUtxoError::new(&e))?; + if let Some(coin_type) = bip44_coin_type { + // Fail on a bad coin type before trying permutations. + crate::fixed_script_wallet::wallet_prefix::derive_wallet_prefix(&xpubs, coin_type)?; + } + let wallet_keys = crate::fixed_script_wallet::bitgo_psbt::to_wallet_keys( + &psbt.psbt, + xpubs, + bip44_coin_type, + ) + .map_err(|e| WasmUtxoError::new(&e))?; Ok(WasmRootWalletKeys::from_inner(wallet_keys)) } + /// Compute the `[h1, h2]` account indices of a wallet from its three root keys + /// `[user, backup, bitgo]` (xpubs or xprvs; private keys are neutered first). + /// + /// `h1` and `h2` are non-hardened BIP32 indices (`0..=2^31-1`), derived as + /// `sha256("BitGo/utxo/wallet-prefix/v1" || K_user || K_backup || K_bitgo)` where + /// `K = compressed public key || chain code`. Returns a two-element array. + #[wasm_bindgen] + pub fn derive_wallet_account( + user: &WasmBIP32, + backup: &WasmBIP32, + bitgo: &WasmBIP32, + ) -> Result, WasmUtxoError> { + let xpubs = [user.to_xpub()?, backup.to_xpub()?, bitgo.to_xpub()?]; + let (h1, h2) = crate::fixed_script_wallet::wallet_prefix::derive_wallet_account(&xpubs); + Ok(vec![h1, h2]) + } + + /// Compute the relative derivation prefix `44//

/

` of a wallet from its + /// three root keys `[user, backup, bitgo]` (no leading `/` or `m/`). + /// + /// `coin_type` must be a non-hardened index (`<= 2^31-1`), otherwise this fails with + /// `WalletPrefixError.CoinTypeOutOfRange`. + #[wasm_bindgen] + pub fn derive_wallet_prefix( + user: &WasmBIP32, + backup: &WasmBIP32, + bitgo: &WasmBIP32, + coin_type: u32, + ) -> Result { + let xpubs = [user.to_xpub()?, backup.to_xpub()?, bitgo.to_xpub()?]; + Ok(crate::fixed_script_wallet::wallet_prefix::derive_wallet_prefix(&xpubs, coin_type)?) + } + /// Returns an object mapping BitGo proprietary key subtype names to their `u8` values. /// Values are loaded directly from the Rust enum at build time — no duplication in TypeScript. #[wasm_bindgen] diff --git a/packages/wasm-utxo/src/wasm/wallet_keys.rs b/packages/wasm-utxo/src/wasm/wallet_keys.rs index aa552ab0752..c14f48a247d 100644 --- a/packages/wasm-utxo/src/wasm/wallet_keys.rs +++ b/packages/wasm-utxo/src/wasm/wallet_keys.rs @@ -49,12 +49,15 @@ impl WasmRootWalletKeys { DerivationPath::from_str("m/0/0").unwrap(), DerivationPath::from_str("m/0/0").unwrap(), ], - ); + )?; Ok(WasmRootWalletKeys { inner }) } /// Create a RootWalletKeys from three BIP32 keys with custom derivation prefixes /// + /// Prefixes must be non-hardened: an xpub cannot derive a hardened child, so a hardened + /// component (`'` or `h`) is rejected with `WalletKeysError.HardenedDerivationPrefix`. + /// /// # Arguments /// - `user`: User key (first xpub) /// - `backup`: Backup key (second xpub) @@ -93,10 +96,31 @@ impl WasmRootWalletKeys { .try_into() .map_err(|_| WasmUtxoError::new("Failed to convert derivation paths"))?; - let inner = RootWalletKeys::new_with_derivation_prefixes(xpubs, derivation_paths); + let inner = RootWalletKeys::new_with_derivation_prefixes(xpubs, derivation_paths)?; + Ok(WasmRootWalletKeys { inner }) + } + + /// Return a copy of these keys that also recognises the wallet's BIP44-style subtree + /// `44//

/

` when parsing PSBTs (`(h1, h2)` computed from the three root + /// keys). Building is unaffected: the keys' own derivation prefixes are still used. + /// + /// `coin_type` is the BIP44 coin type of the coin family, supplied by the caller. Fails with + /// `WalletPrefixError.CoinTypeOutOfRange` if it is larger than `2^31-1`. + #[wasm_bindgen] + pub fn with_bip44_coin_type( + &self, + coin_type: u32, + ) -> Result { + let inner = self.inner.clone().with_bip44_coin_type(coin_type)?; Ok(WasmRootWalletKeys { inner }) } + /// The BIP44-style prefix `44//

/

` these keys recognise, if set. + #[wasm_bindgen] + pub fn bip44_prefix(&self) -> Option { + self.inner.bip44_prefix().map(|p| p.to_string()) + } + /// Get the user key (first xpub) #[wasm_bindgen] pub fn user_key(&self) -> WasmBIP32 { diff --git a/packages/wasm-utxo/test/fixedScript/bip44Prefix.ts b/packages/wasm-utxo/test/fixedScript/bip44Prefix.ts new file mode 100644 index 00000000000..7323b55e501 --- /dev/null +++ b/packages/wasm-utxo/test/fixedScript/bip44Prefix.ts @@ -0,0 +1,136 @@ +import assert from "node:assert"; + +import { BIP32 } from "../../js/bip32.js"; +import { isWasmUtxoError } from "../../js/index.js"; +import { + BitGoPsbt, + RootWalletKeys, + deriveWalletAccount, + deriveWalletPrefix, + getWalletKeysFromPsbt, +} from "../../js/fixedScriptWallet/index.js"; +import type { Triple } from "../../js/triple.js"; + +const specTriple = (bitgoSeed: string): Triple => [ + BIP32.fromSeedSha256("wcn3907-u"), + BIP32.fromSeedSha256("wcn3907-b"), + BIP32.fromSeedSha256(bitgoSeed), +]; + +describe("BIP44-style wallet prefix", function () { + describe("deriveWalletAccount / deriveWalletPrefix", function () { + const vectors = [ + ["wcn3907-g1", 1528449227, 506574854], + ["wcn3907-g2", 1401193521, 285195054], + ["wcn3907-g", 1639221447, 1133889609], + ] as const; + + for (const [bitgoSeed, h1, h2] of vectors) { + it(`matches the spec vector for ${bitgoSeed}`, function () { + assert.deepStrictEqual(deriveWalletAccount(specTriple(bitgoSeed)), [h1, h2]); + }); + } + + it("is the same for xprvs and xpubs", function () { + const xprvs = specTriple("wcn3907-g"); + const xpubs = xprvs.map((k) => k.neutered().toBase58()) as Triple; + assert.deepStrictEqual(deriveWalletAccount(xprvs), deriveWalletAccount(xpubs)); + }); + + it("formats the prefix", function () { + assert.strictEqual( + deriveWalletPrefix(specTriple("wcn3907-g"), 0), + "44/0/1639221447/1133889609", + ); + }); + + it("rejects a hardened coin type with a typed error", function () { + assert.throws( + () => deriveWalletPrefix(specTriple("wcn3907-g"), 0x80000000), + (e: unknown) => isWasmUtxoError(e) && e.code === "WalletPrefixError.CoinTypeOutOfRange", + ); + assert.throws(() => deriveWalletPrefix(specTriple("wcn3907-g"), -1), RangeError); + }); + }); + + describe("RootWalletKeys", function () { + it("rejects a hardened derivation prefix with a typed error", function () { + assert.throws( + () => + RootWalletKeys.from({ + triple: specTriple("wcn3907-g"), + derivationPrefixes: ["44'/0", "0/0", "0/0"], + }), + (e: unknown) => isWasmUtxoError(e) && e.code === "WalletKeysError.HardenedDerivationPrefix", + ); + }); + + it("withBip44CoinType exposes the canonical prefix", function () { + const keys = RootWalletKeys.fromXpubs( + specTriple("wcn3907-g").map((k) => k.neutered().toBase58()) as Triple, + ); + assert.strictEqual(keys.bip44Prefix(), undefined); + assert.strictEqual(keys.withBip44CoinType(0).bip44Prefix(), "44/0/1639221447/1133889609"); + }); + }); + + describe("parse", function () { + const triple = specTriple("wcn3907-g"); + const xpubs = triple.map((k) => k.neutered().toBase58()) as Triple; + const bip44Prefix = deriveWalletPrefix(triple, 0); + const legacyKeys = RootWalletKeys.fromXpubs(xpubs); + const bip44BuildKeys = RootWalletKeys.from({ + triple: triple.map((k) => k.neutered()) as Triple, + derivationPrefixes: [bip44Prefix, bip44Prefix, bip44Prefix], + }); + + function mixedPsbt(): BitGoPsbt { + const psbt = BitGoPsbt.createEmpty("btc", legacyKeys, { version: 2, lockTime: 0 }); + const txid = "00".repeat(32); + psbt.addWalletInput({ txid, vout: 0, value: 100_000n }, legacyKeys, { + scriptId: { chain: 20, index: 0 }, + }); + psbt.addWalletInput({ txid, vout: 1, value: 100_000n }, bip44BuildKeys, { + scriptId: { chain: 40, index: 0 }, + signPath: { signer: "user", cosigner: "bitgo" }, + }); + psbt.addWalletOutput(bip44BuildKeys, { chain: 41, index: 0, value: 90_000n }); + psbt.addWalletOutput(legacyKeys, { chain: 21, index: 3, value: 1_000n }); + return psbt; + } + + it("parses mixed legacy and bip44 PSBTs with fromXpubs keys that know the coin type", function () { + const parsed = mixedPsbt().parseTransactionWithWalletKeys(legacyKeys.withBip44CoinType(0), { + replayProtection: { publicKeys: [] }, + }); + assert.deepStrictEqual( + parsed.inputs.map((i) => i.derivationPath), + ["0/0/20/0", `${bip44Prefix}/40/0`], + ); + assert.deepStrictEqual( + parsed.outputs.map((o) => o.derivationPath), + [`${bip44Prefix}/41/0`, "0/0/21/3"], + ); + assert.strictEqual(parsed.spendAmount, 0n); + }); + + it("rejects bip44 inputs without the coin type", function () { + assert.throws( + () => + mixedPsbt().parseTransactionWithWalletKeys(legacyKeys, { + replayProtection: { publicKeys: [] }, + }), + (e: unknown) => + isWasmUtxoError(e) && + e.code === "ParseTransactionError.Input/ParseInputError.WalletValidation", + ); + }); + + it("getWalletKeysFromPsbt resolves a mixed PSBT when given the coin type", function () { + const shuffled = [triple[2], triple[0], triple[1]].map((k) => k.neutered()); + const keys = getWalletKeysFromPsbt(mixedPsbt(), shuffled, { bip44CoinType: 0 }); + assert.strictEqual(keys.userKey().toBase58(), xpubs[0]); + assert.strictEqual(keys.bip44Prefix(), bip44Prefix); + }); + }); +});