Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions packages/wasm-utxo/js/fixedScriptWallet/BitGoPsbt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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/<h1>/<h2>/20/5" for BIP44-style).
* Null for replay-protection inputs.
*/
derivationPath: string | null;
};

Expand All @@ -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/<h1>/<h2>/20/5" for BIP44-style).
* Null for external outputs.
*/
derivationPath: string | null;
};

Expand Down Expand Up @@ -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/<coinType>/<h1>/<h2>` 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);
}
36 changes: 36 additions & 0 deletions packages/wasm-utxo/js/fixedScriptWallet/RootWalletKeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Comment on lines +12 to +14

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.

}
}

/**
* IWalletKeys represents the various forms that wallet keys can take
* before being converted to a RootWalletKeys instance
Expand Down Expand Up @@ -127,6 +139,30 @@ export class RootWalletKeys {
return new RootWalletKeys(wasm);
}

/**
* Return keys that also recognise the wallet's BIP44-style subtree `44/<coinType>/<h1>/<h2>`
* (`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/<coinType>/<h1>/<h2>` 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
Expand Down
5 changes: 5 additions & 0 deletions packages/wasm-utxo/js/fixedScriptWallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
70 changes: 70 additions & 0 deletions packages/wasm-utxo/js/fixedScriptWallet/walletPrefix.ts
Original file line number Diff line number Diff line change
@@ -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<BIP32Arg>;

function toBIP32Triple(keys: WalletPrefixKeysArg): Triple<BIP32> {
if (keys instanceof RootWalletKeys) {
return [keys.userKey(), keys.backupKey(), keys.bitgoKey()];
}
if (Array.isArray(keys)) {
return (keys as Triple<BIP32Arg>).map((key) => BIP32.from(key)) as Triple<BIP32>;
}
return keys.triple.map((key) => BIP32.from(key)) as Triple<BIP32>;
}

/**
* 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/<coinType>/<h1>/<h2>` (no leading `/` or
* `m/`), see {@link deriveWalletAccount}. Addresses of a wallet using this prefix derive at
* `<prefix>/<chain>/<index>` 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,
);
}
20 changes: 20 additions & 0 deletions packages/wasm-utxo/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {}
Expand All @@ -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),
}
}
}
Expand Down Expand Up @@ -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(),
}
}
}
Expand Down Expand Up @@ -159,6 +167,18 @@ impl From<VerifyV6SignatureError> for WasmUtxoError {
}
}

impl From<WalletKeysError> for WasmUtxoError {
fn from(err: WalletKeysError) -> Self {
WasmUtxoError::WalletKeys(err)
}
}

impl From<WalletPrefixError> for WasmUtxoError {
fn from(err: WalletPrefixError) -> Self {
WasmUtxoError::WalletPrefix(err)
}
}

impl WasmUtxoError {
pub fn new(s: &str) -> WasmUtxoError {
WasmUtxoError::StringError(s.to_string())
Expand Down
Loading
Loading