From 3513f7ad4f7d05dab4cb0d08d45532a976f05fbe Mon Sep 17 00:00:00 2001 From: Veetrag Jain Date: Mon, 23 Nov 2026 14:33:55 +0530 Subject: [PATCH] feat(abstract-utxo): add shielded zec tx verification Ticket: CSHLD-2297 --- modules/abstract-utxo/src/impl/zec/index.ts | 1 + .../src/impl/zec/shieldedVerify.ts | 337 +++++++++++++ modules/abstract-utxo/src/impl/zec/zec.ts | 80 +++- .../fixedScript/explainTransaction.ts | 17 +- .../zec/fixtures/ironwoodShieldedSpend.json | 95 ++++ .../test/unit/impl/zec/shieldedVerify.ts | 444 ++++++++++++++++++ modules/bitgo/test/v2/unit/pendingApproval.ts | 23 +- modules/bitgo/test/v2/unit/wallets.ts | 64 +++ .../bitgo/pendingApproval/pendingApproval.ts | 9 +- modules/sdk-core/src/bitgo/wallet/wallets.ts | 7 + 10 files changed, 1072 insertions(+), 5 deletions(-) create mode 100644 modules/abstract-utxo/src/impl/zec/shieldedVerify.ts create mode 100644 modules/abstract-utxo/test/unit/impl/zec/fixtures/ironwoodShieldedSpend.json create mode 100644 modules/abstract-utxo/test/unit/impl/zec/shieldedVerify.ts diff --git a/modules/abstract-utxo/src/impl/zec/index.ts b/modules/abstract-utxo/src/impl/zec/index.ts index 5707f7a4ee1..af990416bc2 100644 --- a/modules/abstract-utxo/src/impl/zec/index.ts +++ b/modules/abstract-utxo/src/impl/zec/index.ts @@ -4,3 +4,4 @@ export * from './shieldedAddress'; export * from './address'; export * from './recipients'; export * from './types'; +export * from './shieldedVerify'; diff --git a/modules/abstract-utxo/src/impl/zec/shieldedVerify.ts b/modules/abstract-utxo/src/impl/zec/shieldedVerify.ts new file mode 100644 index 00000000000..787236f3e65 --- /dev/null +++ b/modules/abstract-utxo/src/impl/zec/shieldedVerify.ts @@ -0,0 +1,337 @@ +/** + * Keyless verification of Zcash shielded (Ironwood v6) spend PSBTs built for custodial MPC + * (RedPallas) wallets. + * + * These wallets hold no viewing keys client-side, so nothing here can prove which addresses + * belong to the wallet. The only change a keyless client can recognize is the parser's + * `isChange`: an output paying back to the exact address of a note the transaction spends + * (wallet-platform/IMS always pay change to the first selected note's address). Every other + * output is a recipient and must match one the caller asked for. + * + * Every function here is pure (no wallet, no network), so the same checks run in the online + * `sendMany` path (`Zec.verifyTransaction`) and in the offline vault console. + */ +import { fixedScriptWallet } from '@bitgo/wasm-utxo'; + +import { stringToBufferTryFormats } from '../../transaction/decode'; +import type { Output } from '../../transaction/types'; +import type { TransactionExplanationShielded } from '../../transaction/fixedScript/explainTransaction'; + +export type { TransactionExplanationShielded }; + +import { ZecAddressCodec } from './address'; +import type { ZcashCoinName } from './types'; + +/** + * ZIP-317 marginal fee (zatoshi per logical action). IMS folds a changeless leftover into the + * fee only when it cannot pay for its own change output, so a shielded build's fee is at most + * one marginal fee above the conventional fee. Mirrors wallet-platform's build-time bound. + */ +export const ZIP317_MARGINAL_FEE = 5000n; + +export class ShieldedTransactionVerificationError extends Error { + constructor(message: string) { + super(message); + this.name = 'ShieldedTransactionVerificationError'; + } +} + +function fail(message: string): never { + throw new ShieldedTransactionVerificationError(message); +} + +function toHex(bytes: Uint8Array): string { + return Buffer.from(bytes).toString('hex'); +} + +function toBytes(value: string | Uint8Array): Uint8Array { + return typeof value === 'string' ? new Uint8Array(Buffer.from(value, 'hex')) : value; +} + +function errorMessage(e: unknown): string { + if (e instanceof Error) { + const code = 'code' in e && typeof e.code === 'string' ? ` (${e.code})` : ''; + return `${e.message}${code}`; + } + return String(e); +} + +export type ShieldedTxInput = string | Uint8Array; + +/** Decode a v6 (Ironwood) Zcash PSBT from hex, base64 or raw bytes. */ +export function decodeShieldedPsbt( + tx: ShieldedTxInput, + coinName: ZcashCoinName +): fixedScriptWallet.ZcashIronwoodBitGoPsbt { + const bytes = typeof tx === 'string' ? stringToBufferTryFormats(tx, ['hex', 'base64']) : tx; + try { + return fixedScriptWallet.ZcashIronwoodBitGoPsbt.fromBytes(new Uint8Array(bytes), coinName); + } catch (e) { + return fail(`not a Zcash Ironwood (v6) PSBT: ${errorMessage(e)}`); + } +} + +/** + * Whether `tx` decodes as a v6 (Ironwood) PSBT carrying shielded spends — the shape of every + * custodial MPC (RedPallas) shielded transaction. + */ +export function isShieldedSpendPsbt(tx: ShieldedTxInput, coinName: ZcashCoinName): boolean { + try { + parseShieldedSpendPsbt(decodeShieldedPsbt(tx, coinName)); + return true; + } catch { + return false; + } +} + +/** + * Keyless parse of a shielded spend PSBT. The parse runs the key-free bundle verifier first, + * so a tampered bundle (value balance, note commitments, anchor, ...) throws. + * + * @throws ShieldedTransactionVerificationError when the bundle fails verification or the PSBT + * spends no shielded notes (a RedPallas wallet never has transparent inputs). + */ +export function parseShieldedSpendPsbt( + psbt: fixedScriptWallet.ZcashIronwoodBitGoPsbt +): fixedScriptWallet.ZcashShieldedParsedTransaction { + let parsed: fixedScriptWallet.ZcashShieldedParsedTransaction; + try { + parsed = psbt.parseShieldedTransaction(); + } catch (e) { + return fail(`shielded transaction failed keyless verification: ${errorMessage(e)}`); + } + if (parsed.shieldedSpends.length === 0) { + fail('shielded transaction spends no shielded notes'); + } + return parsed; +} + +/** + * The fee MUST lie within [ZIP-317 conventional fee, conventional + one marginal fee] — the + * same bound wallet-platform enforces at build time. Without it a builder could shrink the + * change and burn the difference as fee while every output check still passes. + */ +export function assertShieldedFeeWithinZip317Bounds(psbt: fixedScriptWallet.ZcashIronwoodBitGoPsbt, fee: bigint): void { + const conventionalFee = psbt.zip317ConventionalFee(); + if (fee < conventionalFee || fee > conventionalFee + ZIP317_MARGINAL_FEE) { + fail( + `shielded transaction fee ${fee} is outside the ZIP-317 bounds [${conventionalFee}, ${ + conventionalFee + ZIP317_MARGINAL_FEE + }]` + ); + } +} + +export type ShieldedRecipient = { address: string; amount: string | number | bigint }; + +/** + * Every requested recipient must consume exactly one output paying its receiver its exact + * amount; every output left over must be parser-marked change. + * + * Recipients are matched first, against every output: a recipient paying back to a spent + * note's own address (a note split) is parser-marked change yet is still a requested + * recipient. + */ +export function assertShieldedOutputsMatchRecipients( + outputs: fixedScriptWallet.ZcashIronwoodParsedOutput[], + recipients: ShieldedRecipient[], + coinName: ZcashCoinName +): void { + const codec = new ZecAddressCodec(coinName, coinName); + const remaining = [...outputs]; + for (const recipient of recipients) { + if (!recipient.address) { + fail('recipient address is required to verify a shielded transaction'); + } + let value: bigint; + try { + value = BigInt(recipient.amount); + } catch { + return fail(`invalid recipient amount ${recipient.amount}`); + } + const index = remaining.findIndex( + (output) => + output.value === value && + codec.isMatchingScript({ address: recipient.address, script: output.script, isShielded: output.isShielded }) + ); + if (index === -1) { + fail(`expected output missing in shielded transaction: ${recipient.address} ${value}`); + } + remaining.splice(index, 1); + } + const external = remaining.filter((output) => !output.isChange); + if (external.length > 0) { + fail( + `shielded transaction pays unintended external recipients: ${external + .map((output) => `${output.address ?? toHex(output.script)} ${output.value}`) + .join(', ')}` + ); + } +} + +/** + * Full intent check of a shielded spend prebuild (the online `sendMany` path): keyless parse + + * bundle verification, recipients, change and fee. + */ +export function verifyShieldedSpendAgainstRecipients( + tx: ShieldedTxInput, + recipients: ShieldedRecipient[], + coinName: ZcashCoinName +): fixedScriptWallet.ZcashShieldedParsedTransaction { + const psbt = decodeShieldedPsbt(tx, coinName); + const parsed = parseShieldedSpendPsbt(psbt); + assertShieldedOutputsMatchRecipients(parsed.outputs, recipients, coinName); + assertShieldedFeeWithinZip317Bounds(psbt, parsed.fee); + return parsed; +} + +function outputAddress(output: fixedScriptWallet.ZcashIronwoodParsedOutput): string { + return output.address ?? `scriptPubKey:${toHex(output.script)}`; +} + +/** + * Explain a shielded spend PSBT without wallet keys: parser-marked change outputs go to + * `changeOutputs`, every other output to `outputs`. + */ +export function explainShieldedSpendPsbt( + psbt: fixedScriptWallet.ZcashIronwoodBitGoPsbt +): TransactionExplanationShielded { + const parsed = parseShieldedSpendPsbt(psbt); + const toOutput = (output: fixedScriptWallet.ZcashIronwoodParsedOutput, external: boolean): Output => ({ + address: outputAddress(output), + amount: output.value.toString(), + external, + }); + const outputs = parsed.outputs.filter((output) => !output.isChange).map((output) => toOutput(output, true)); + const changeOutputs = parsed.outputs.filter((output) => output.isChange).map((output) => toOutput(output, false)); + const sum = (values: bigint[]) => values.reduce((acc, v) => acc + v, 0n); + const inputAmount = sum(parsed.shieldedSpends.map((spend) => spend.value)); + let id = ''; + try { + id = psbt.getId(); + } catch { + // The txid is display-only; it may be unavailable before the proof is combined. + } + return { + id, + inputs: parsed.shieldedSpends.map((spend) => ({ address: spend.address, value: spend.value.toString() })), + inputAmount: inputAmount.toString(), + outputs, + changeOutputs, + outputAmount: sum(parsed.outputs.filter((o) => !o.isChange).map((o) => o.value)).toString(), + changeAmount: sum(parsed.outputs.filter((o) => o.isChange).map((o) => o.value)).toString(), + fee: parsed.fee.toString(), + shieldedSpends: parsed.shieldedSpends.map((spend) => ({ + actionIndex: spend.actionIndex, + address: spend.address, + value: spend.value.toString(), + nullifier: toHex(spend.nullifier), + })), + }; +} + +export type ShieldedRk = { actionIndex: number; rk: string | Uint8Array }; + +/** + * The spend sighash (hex) of `originalTx` once `rks` are installed — exactly what + * wallet-platform's post-rerand rebuild computes (`addSpendRks` + `spendSighash`). + */ +export function computeShieldedSpendSighash( + originalTx: ShieldedTxInput, + rks: ShieldedRk[], + coinName: ZcashCoinName +): string { + const psbt = decodeShieldedPsbt(originalTx, coinName); + try { + psbt.addSpendRks(rks.map(({ actionIndex, rk }) => ({ actionIndex, rk: toBytes(rk) }))); + return toHex(psbt.spendSighash()); + } catch (e) { + return fail(`failed to install rerandomized keys on the shielded transaction: ${errorMessage(e)}`); + } +} + +/** + * Resolve which action each of the signer's own rerandomized keys was installed at in the + * rebuilt PSBT, without trusting any server-side spend → action mapping: each rk must be + * installed at exactly one real spend, and every real spend must carry exactly one of them. + */ +export function resolveInstalledShieldedRks( + rebuiltPsbt: fixedScriptWallet.ZcashIronwoodBitGoPsbt, + rks: Array +): ShieldedRk[] { + const spendActionIndices = parseShieldedSpendPsbt(rebuiltPsbt).shieldedSpends.map((spend) => spend.actionIndex); + if (spendActionIndices.length !== rks.length) { + fail( + `rebuilt shielded transaction has ${spendActionIndices.length} spends but ${rks.length} rerandomized keys were produced` + ); + } + const unclaimed = new Set(spendActionIndices); + return rks.map((rk, spendIndex) => { + const rkBytes = toBytes(rk); + const matches = [...unclaimed].filter((actionIndex) => { + try { + rebuiltPsbt.verifyShieldedBundle({ rks: [{ actionIndex, rk: rkBytes }] }); + return true; + } catch { + return false; + } + }); + if (matches.length !== 1) { + fail(`rerandomized key for spend ${spendIndex} is not installed in the rebuilt shielded transaction`); + } + unclaimed.delete(matches[0]); + return { actionIndex: matches[0], rk: rkBytes }; + }); +} + +/** + * Offline check of wallet-platform's post-rerand rebuild. + * + * After rerand round 2 the platform installs the spends' rerandomized keys (rks) into the + * PSBT, then replaces `serializedTxHex` with the rk-bearing PSBT and `signableHex` with its + * spend sighash. Nothing else may change. The DSG signs `signableHex`, and the sighash commits + * every spend, output, memo, the fee and every rk — so if `signableHex` equals the sighash of + * the ORIGINAL (reviewed) PSBT with the signer's OWN rks installed, the signature can only + * authorize the transaction that was reviewed. + * + * @param originalTxHex the `serializedTxHex` reviewed before rerand (first trip) + * @param rebuiltTxHex the post-rerand `serializedTxHex`; the HSM derives its sighash from these + * bytes, so it must hash to `signableHex` as well + * @param signableHex the post-rerand `signableHex` the DSG will sign + * @param rks the signer's own rerand result `pk` per spend, in spend order + * @returns the rks with the action index each was installed at + */ +export function assertRebuiltShieldedSignable(params: { + coinName: ZcashCoinName; + originalTxHex: ShieldedTxInput; + rebuiltTxHex: ShieldedTxInput; + signableHex: string; + rks: Array; +}): ShieldedRk[] { + const { coinName, signableHex } = params; + const expectedSignableHex = signableHex.toLowerCase(); + + const original = decodeShieldedPsbt(params.originalTxHex, coinName); + const originalParsed = parseShieldedSpendPsbt(original); + const rebuilt = decodeShieldedPsbt(params.rebuiltTxHex, coinName); + const installedRks = resolveInstalledShieldedRks(rebuilt, params.rks); + + if (originalParsed.shieldedSpends.length !== installedRks.length) { + fail('rebuilt shielded transaction spends a different number of notes than the reviewed transaction'); + } + + if (computeShieldedSpendSighash(params.originalTxHex, installedRks, coinName) !== expectedSignableHex) { + fail('rebuilt signable does not commit to the reviewed shielded transaction'); + } + + let rebuiltSighash: string; + try { + rebuiltSighash = toHex(rebuilt.spendSighash()); + } catch (e) { + return fail(`rebuilt shielded transaction has no spend sighash: ${errorMessage(e)}`); + } + if (rebuiltSighash !== expectedSignableHex) { + fail('rebuilt serialized transaction does not match the rebuilt signable'); + } + return installedRks; +} diff --git a/modules/abstract-utxo/src/impl/zec/zec.ts b/modules/abstract-utxo/src/impl/zec/zec.ts index da51fe6126b..43a483de2c2 100644 --- a/modules/abstract-utxo/src/impl/zec/zec.ts +++ b/modules/abstract-utxo/src/impl/zec/zec.ts @@ -6,22 +6,27 @@ import { BitGoBase, ExtraPrebuildParamsOptions, HalfSignedUtxoTransaction, + IBaseCoin, IWallet, MPCAlgorithm, SignedTransaction, - Wallet, + TxIntentMismatchError, UnifiedRecipientPreference, + Wallet, } from '@bitgo/sdk-core'; import _ from 'lodash'; import { AbstractUtxoCoin, ParseTransactionOptions, + ExplainTransactionOptions, SignTransactionOptions, UtxoCoinSpecific, VerifyAddressOptions, + VerifyTransactionOptions, } from '../../abstractUtxoCoin'; import type { ParsedTransaction } from '../../transaction/types'; +import type { TransactionExplanation } from '../../transaction/fixedScript/explainTransaction'; import { stringToBufferTryFormats } from '../../transaction/decode'; import { UtxoCoinName, toWasmUtxoCoinName } from '../../names'; import { AddressCodec } from '../../transaction/recipient'; @@ -31,6 +36,7 @@ import { signIronwoodTransaction } from './signIronwoodTransaction'; import { resolvePsbtRecipients, PsbtRecipient } from './recipients'; import { assertShieldedWalletAddress } from './shieldedAddress'; import type { ZcashCoinName } from './types'; +import { explainShieldedSpendPsbt, verifyShieldedSpendAgainstRecipients } from './shieldedVerify'; export class Zec extends AbstractUtxoCoin { readonly name: UtxoCoinName = 'zec'; @@ -49,6 +55,12 @@ export class Zec extends AbstractUtxoCoin { return 'redpallas'; } + override supportsTss(): boolean { + // Shielded (Orchard/Ironwood) wallets are RedPallas TSS; without this the Wallet + // constructor never instantiates tssUtils and TSS sends crash on `prebuildTxWithIntent`. + return true; + } + static createInstance(bitgo: BitGoBase): Zec { return new Zec(bitgo); } @@ -112,6 +124,72 @@ export class Zec extends AbstractUtxoCoin { ); } + override async verifyTransaction( + params: VerifyTransactionOptions + ): Promise { + if (params.walletType === 'tss' || params.wallet?.multisigType() === 'tss') { + // TSS (RedPallas) wallets carry no xpub keychains, so the fixed-script verification + // path (which fetches `{ pub }`-shaped keychains to classify outputs) cannot run. + return this.verifyShieldedTransaction(params); + } + return super.verifyTransaction(params); + } + + /** + * Verify a prebuilt transaction for a TSS (RedPallas) shielded wallet against the requested + * recipients, without wallet keys or wallet data. + * + * The client holds no viewing keys, so it cannot prove which addresses are the wallet's. + * The only change it can recognize is the keyless parser's `isChange` (an output paying back + * to the exact address of a note the transaction spends — where wallet-platform always sends + * change). The prebuild must therefore: + * - pass the key-free bundle verifier, + * - contain every requested recipient with its exact amount, + * - pay every other output to parser-marked change, and + * - pay a fee within the ZIP-317 bounds wallet-platform enforces. + */ + async verifyShieldedTransaction( + params: VerifyTransactionOptions + ): Promise { + const { txParams, txPrebuild, reqId } = params; + const txExplanation = await TxIntentMismatchError.tryGetTxExplanation(this as unknown as IBaseCoin, txPrebuild); + const throwTxMismatch = (message: string): never => { + throw new TxIntentMismatchError(message, reqId, [txParams], txPrebuild.txHex, txExplanation); + }; + if (txPrebuild.txHex === undefined) { + return throwTxMismatch('missing required txPrebuild property txHex'); + } + try { + verifyShieldedSpendAgainstRecipients(txPrebuild.txHex, txParams.recipients ?? [], this.name as ZcashCoinName); + } catch (e) { + return throwTxMismatch(e instanceof Error ? e.message : String(e)); + } + return true; + } + + /** + * Shielded spend PSBTs of TSS (RedPallas) wallets carry no fixed-script keys, so they are + * explained keylessly; everything else keeps the fixed-script path. + */ + override async explainTransaction( + params: ExplainTransactionOptions, + wallet?: IWallet + ): Promise { + const isTssWallet = wallet?.multisigType() === 'tss'; + if (!params.pubs && (wallet === undefined || isTssWallet)) { + const tx = this.decodeTransactionFromPrebuild(params); + // A shielded-input v6 PSBT is a RedPallas spend bundle; a transparent-input one (a + // fixed-script shielding send) still needs the wallet's pubs. + if ( + tx instanceof fixedScriptWallet.ZcashIronwoodBitGoPsbt && + (isTssWallet || tx.shieldedStatus().inputKind === 'shielded') + ) { + return explainShieldedSpendPsbt(tx); + } + } + return super.explainTransaction(params, wallet); + } + override async getExtraPrebuildParams(buildParams: ExtraPrebuildParamsOptions & { wallet: Wallet }) { const extraParams = await super.getExtraPrebuildParams(buildParams); const { unifiedRecipientPreference } = buildParams; diff --git a/modules/abstract-utxo/src/transaction/fixedScript/explainTransaction.ts b/modules/abstract-utxo/src/transaction/fixedScript/explainTransaction.ts index 3e5738b7bb9..e9947d825f3 100644 --- a/modules/abstract-utxo/src/transaction/fixedScript/explainTransaction.ts +++ b/modules/abstract-utxo/src/transaction/fixedScript/explainTransaction.ts @@ -50,4 +50,19 @@ export type TransactionExplanationUtxolibPsbt = TransactionExplanationWithSignat export type TransactionExplanationDescriptor = TransactionExplanationWithSignatures; -export type TransactionExplanation = TransactionExplanationUtxolibPsbt | TransactionExplanationWasm; +/** + * Keyless explanation of a Zcash shielded (Ironwood v6) spend PSBT of a TSS (RedPallas) wallet. + * Change is only what the keyless parser can recognize (an output paying back to a spent + * note's own address), so change outputs carry no fixed-script chain/index. + */ +export type TransactionExplanationShielded = AbstractUtxoTransactionExplanation & { + inputs: Array<{ address: string; value: string }>; + inputAmount: string; + /** The spent notes, in action order. */ + shieldedSpends: Array<{ actionIndex: number; address: string; value: string; nullifier: string }>; +}; + +export type TransactionExplanation = + | TransactionExplanationUtxolibPsbt + | TransactionExplanationWasm + | TransactionExplanationShielded; diff --git a/modules/abstract-utxo/test/unit/impl/zec/fixtures/ironwoodShieldedSpend.json b/modules/abstract-utxo/test/unit/impl/zec/fixtures/ironwoodShieldedSpend.json new file mode 100644 index 00000000000..64d35c43c59 --- /dev/null +++ b/modules/abstract-utxo/test/unit/impl/zec/fixtures/ironwoodShieldedSpend.json @@ -0,0 +1,95 @@ +{ + "_source": "transferSigning: wallet-platform ironwood-transfer-signing golden (from BitGoWASM ironwood_spend_transfer, ciphertexts + anchor refresh applied, no rks). spendBuild: BitGoWASM ironwood_spend_deshield request spend note + ironwood_spend_transfer recipient receiver.", + "coin": "tzec", + "transferSigning": { + "psbtHex": "70736274ff01000a060000000000000000004f01043587cf0000000000000000000dcf63c0c58d60cd065b388fa2c34b876b86fd448293ef0d86a6c00707da642503156e00db8bdcf3dace5b90d2510ee3f3680386fc65cbb2561fc970240c5cc9ff04a9476a134f01043587cf000000000000000000cd8df2a8a1b4f067b569b0594208c238021d8cb0c8cfcef9696251eceaab32aa0327c60d0eb92140ca555ef37b4aa01fb48b9fdaf9f514ea017f2b766ee548e11e04922f3cf44f01043587cf000000000000000000b9ecb3635fe5f7d92c77652a36058bf7f5adb433a00eef8288148827888a75350379d23afd7f0dd37c3c95455e8e5a1928379442d4fb8f77773a4d24146eeae2d304bb97031e08fc05424954474f00045b16a5370ffc0c424954474f2f5a45432f563600045b16a5370ffc0c424954474f2f5a45432f563601fdc81002070102904e00972f2298bcd1f4a6e9736eb1ececac519917967e5bb8fbca80de395a6e7dc511000002b3adb77e7e9cb97aefc80ac7bfa4d175b797b7a8f1717a3930c0c6bc42408fb901afa7403387c236561d4cf309aa562ee4e0c16a6604745ed09974db8a3946672136784e21bf4ffd676c1906835206c5f6e399141a0905802a9b7a18486cf0b539c9f65548f6268302081796a70563141d16f53569dae4e9e9d463fabe5712218e00012b37f1c1f4c922ecb98f3cf2dbe6f12f65a73fc93316a1c0ad4a23a8a3b9b4eadbb7687b6e82161d031698bf0180e8922601c9000000000000000000000000000000000000000000000000000000000000000135353535353535353535353535353535353535353535353535353535353535350001012038fe5156c36c78da72290b6d81ccade9932a4a83500aa8962f04a6fd593bd30ccb4c336f095e14606787ca35145715c5acbc8970fd4e3d6a0450bc344bcfbd1902000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000103636d782033190bdef16c2df1b0f6d41903142f52660fde345f45b9c94d87e61a9f788516b3509d4b6f458ab08e2ddb24ba9bb188f43d4492167b727ca6322383de1d26060bfc1743d4556a9702277d2b3989446fff656b61830d1504f4f5ceafb0f0370dc404b5b066d80f695f611db079e1db68b2de1cf3148b18bc89bb00516c833ab30dff821e7e1af1eb5f1ce6741fbf3079761666540e025ccbb4f339352890a3b7f0858b3c4e3b3bf71e4591f77fb7731ca58a10ac880bf7acc776896c52160022be8fc72212b19ea7fe3ed1535b88ebb8e906f05564c66406c5f5c28257686a936ae54370f194772894a59dadd37283fd848b69b6b26ecb22a6b6c1f6d0c49bd782bb9ff467478643e73983af90d4620de3e2fc8447f3e251c42e3770d6ed9b57d51deac2810e648a5016a6ead566e49c1828a43167ce041b3a2719022336a947d1fa3eda81dfa75b3b8d753d031bbe04f929d7080d8f549830f3b616abea43d342b4f017528c68aef95278f18eda744cae46bb53553d0089e4030cea6158aebd1e31b6e7145f7b79fa704d7f556e0e1f6a9588208c376ed9ee8a193e79316f98977a2971b0dc0b6b175c6d567647bf9770703d6bee6714777f9542e8e31cac4b5c1b384a6af5b511291e606d7e8699e6114a2d953bcb5a4526e2b5942a108f9d10de854d33dbdbb87dc57fee8aae6f2362da808d004d1af99bef5177a9f3f9f3502c4764eba80deb3147a13c922d213003b388c49810aa7cc44f100f227161f6c76276d43e4ec861a1c2296e964df533c5821025e782e5484204eef0cc3dbfa36a58ba2ea8076e283af2d4adbaa7a5037f18ed796cb0d3412567a48b7ce201bdc475a543c9826d8a1bb25b666eef03d0c1fe822ace54b9e6d2a2dcad920e621685bb31280fff93f3fea83a674dc3d555d62a163ae4e908b1bd4f1459b1628812a95395bc9bf55021bf03ff6d04f84ed3f2ea3713f09dac4db712643e0b929315fc49711e79f880ec92fc3b002941cc0e10afc7f55f512a3d8041db69d5f7aaee6d5a8db962b7decff349190cb2dddac1e17f9598ab5f5f012bb22b122d2d03d30be6665844ac2fa20e5f177cef86a49ec93c195e6597af49d3b01b958617fce8170ce0a701f8edf42a014828e01738b0a8d784860040b6908a76ca6f17581c1788462a9195a48cc1e3ac0000000f864af500bca593d9b13fca0080029af59fb41a10987433c9996f208611b830015850d6cefdf244c13d203eef21973ea6f2e43411d8199e81447b91d89d43760c621c8910e2a41c7959bd4f2e685a9a917b94fb0ed734ba906c1af5ad75abfe0cc9f65548f6268302081796a70563141d16f53569dae4e9e9d463fabe5712218e00012b4559029c0b5dbf941c5ad181a5fe8f45b34630f29d0c8dd8dc1cc3573386f416cb324133156d723df5e62d0180c2d72f01c8000000000000000000000000000000000000000000000000000000000000000134343434343434343434343434343434343434343434343434343434343434340001002033190bdef16c2df1b0f6d41903142f52660fde345f45b9c94d87e61a9f788516cb4c336f095e14606787ca35145715c5acbc8970fd4e3d6a0450bc344bcfbd1902000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000103636d782038fe5156c36c78da72290b6d81ccade9932a4a83500aa8962f04a6fd593bd30c28ddec0af49be6052349934b32afa84b18d8031cc035e7550a120a4954016e3d43f7e27fb426b524fd48757e03768bfe237361641ab602101cd457d95799e492c404bb7e1484e4860594894a05906c1b17ff1e758d22d5a3ebdc96690703db34b977fef5255236ffb468c5036fbac83b15e4c0fe85152192a1b383be5c809b2c348c48488186e49264e3a0e89801d9dd943adb9ec36cacf795c1529ba164d5260224634e8744146ab9e49bb60d0222f17bddfa8aad8df1ac1ba608acc1f5247d4e33c28c17c1dcbd76d6e5101911da5dc7ae75ebfbc47ee71cbf440f156843d845deb788e4cc9d1913964f4cd4fc6a0a2c9e242a49d66d7bb6b387cea5ccb3727fca1aa6dd79153df930cf54f5513582d5c28fb9b312fd6ac6ea790679bedc2ecdf6b28970cff57ca59e18fe3ee397c686d184a42d8e0188a356d9791a99921b332ade2e6cbfb5fc838407d8727e6ab66acd83b9288d0f86744d008aac094cf2b98a0d2226c5c4938850f71dd960b356cd412a0189b2361ae4fc51980d9e4c930aa935addf265560d0a99d300b86a2219beef3938ab04466b9e26e9eba5946b4142721fb97f6b9fbdcc520700b85811464db19daa6c97e6c4b87a4664195d9a6e8a9b1fb0e420b817e324a4d05887e093705428c554b90caf3e45c1b8c1ac475c0c3ffb39667fa63d6fb6374e0310a1e30255295d6c492bb260042c520b6fbdeec4d6faec13bb23cfe7b521b59b829c0342db81c2f07cc5a2bf115baea84a60459af44d40cca78a3cad130fbe5468e8e9bb1a1b5a5787c3bf3fd07707260e174f57c41f2a8936578248313b5e29f632ba5345c5cc0c02ad281b179a9132dd4912a64b4c3464da95b4026a820295597842b0e5e0c597d4429d9c39062ddfbdc7fc46a7fef681b5074cb7768c899b2991a0659bd775eb2bf45954e98856cc3659f9ce39abe8dd329f67a088141c44451dd599692d9fda74ccada5a47fd66f49cb74122e756de6600a08c99810a747848b1d9cd1fea91c7a6012b38b8c9ef7b9ad7d18319bff63ee4eee248c43176fbb19364bb81c8b5e65789f900bc05ec219b4e6c1979ae01f8edf42a0139a31c3e6ad71544f767a20334a7ace90376584b10ed8328d939a6f4c825cc250000000ffc0c424954474f2f5a45432f5636020498b684d80ffc0c424954474f2f5a45432f56360304000000000ffc0c424954474f2f5a45432f563609010300", + "spends": [ + { + "spendIndex": 0, + "actionIndex": 1, + "value": "100000000", + "address": "utest1j6uf5arygvvnypvh7n9pgcmt70xapzx70t3nemk2yy6646ekn2d296wyc355pvjtwnftcaukuqv687wnecvs47h9w82z4v498c58d6w8" + }, + { + "spendIndex": 1, + "actionIndex": 0, + "value": "80000000", + "address": "utest1scuz7xf9wxep7xzuf5utvwclg649svw8wk2z90zdygpza0mkpe4070nleu5me07j8g7re27ed2y2qy5p5vtwgcf0vrr3ym33jve4eafm" + } + ], + "outputs": [ + { + "actionIndex": 0, + "address": "utest1csfxlvxzuvp0zcfvtdj42cmsmklgw72vsuwsqhwshfvte0s48rgh2dmeak7gqqwe29cemxhm8l6a2vvvy3cghcv8mqc4lvv2w5sgf99p", + "amount": "89995000", + "isShielded": true, + "isChange": false + }, + { + "actionIndex": 1, + "address": "utest1ffu0jn6q3wx09k74cpc7kwajv7zdkjty686q2nmchgg05f45ese46g5mreydhuwgpjzsju8t257teu4d0pqj5lqgjd2kl8ta8sf7ggfg", + "amount": "89995000", + "isShielded": true, + "isChange": false + } + ], + "rks": [ + "c1857f55b48efd7b6ee7ac7763607029bb21f5b91f4e47198dae7bb797cf4a97", + "94ee60820d9ae8b832f5bc9fd10bf413fd6cf772d24b1957c7d6a36f3e34842b" + ], + "sighash": "80ea17c39e7609c86b5bd67d28469c71e60f12aa3177d0675a3c9dd8974c3df3", + "ak": "6ebb833c1d2f8433080abceabe47906097f90678d603f577d0486c9111737b07" + }, + "spendBuild": { + "blockHeight": 4134000, + "anchor": "277302f645a4c6b7ea56fc199ba39f31721d42d2dd08813bddb57bcfeb5e2c2d", + "spends": [ + { + "cmx": "38fe5156c36c78da72290b6d81ccade9932a4a83500aa8962f04a6fd593bd30c", + "nullifier": "621c8910e2a41c7959bd4f2e685a9a917b94fb0ed734ba906c1af5ad75abfe0c", + "recipient": "4559029c0b5dbf941c5ad181a5fe8f45b34630f29d0c8dd8dc1cc3573386f416cb324133156d723df5e62d", + "rho": "c800000000000000000000000000000000000000000000000000000000000000", + "rseed": "3434343434343434343434343434343434343434343434343434343434343434", + "value": "100000000", + "witness": { + "authPath": [ + "33190bdef16c2df1b0f6d41903142f52660fde345f45b9c94d87e61a9f788516", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000", + "0200000000000000000000000000000000000000000000000000000000000000" + ], + "position": 0 + } + } + ], + "recipientReceiver": "38b8c9ef7b9ad7d18319bff63ee4eee248c43176fbb19364bb81c8b5e65789f900bc05ec219b4e6c1979ae" + } +} \ No newline at end of file diff --git a/modules/abstract-utxo/test/unit/impl/zec/shieldedVerify.ts b/modules/abstract-utxo/test/unit/impl/zec/shieldedVerify.ts new file mode 100644 index 00000000000..9bc86034ddc --- /dev/null +++ b/modules/abstract-utxo/test/unit/impl/zec/shieldedVerify.ts @@ -0,0 +1,444 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as path from 'path'; + +import { TxIntentMismatchError } from '@bitgo/sdk-core'; +import { fixedScriptWallet } from '@bitgo/wasm-utxo'; + +import { + assertRebuiltShieldedSignable, + computeShieldedSpendSighash, + decodeShieldedPsbt, + explainShieldedSpendPsbt, + isShieldedSpendPsbt, + resolveInstalledShieldedRks, + ShieldedTransactionVerificationError, + verifyShieldedSpendAgainstRecipients, +} from '../../../../src/impl/zec/shieldedVerify'; +import type { Zec } from '../../../../src/impl/zec'; +import { getUtxoCoin } from '../../util'; +import { getDefaultWasmWalletKeys } from '../../util/keychains'; + +type IronwoodShieldedSpendFixture = { + coin: 'tzec'; + /** Wallet-platform signing golden: IMS-built PSBT (ciphertexts + anchor applied, no rks). */ + transferSigning: { + psbtHex: string; + spends: { spendIndex: number; actionIndex: number; value: string; address: string }[]; + outputs: { actionIndex: number; address: string; amount: string; isShielded: boolean; isChange: boolean }[]; + /** Rerand round 2 rks, spend order. */ + rks: string[]; + sighash: string; + ak: string; + }; + /** A spendable note (with witness) to build keyless spend PSBTs from. */ + spendBuild: { + blockHeight: number; + anchor: string; + spends: { + cmx: string; + nullifier: string; + recipient: string; + rho: string; + rseed: string; + value: string; + witness: { position: number; authPath: string[] }; + }[]; + recipientReceiver: string; + }; +}; + +const fixture: IronwoodShieldedSpendFixture = JSON.parse( + fs.readFileSync(path.join(__dirname, 'fixtures', 'ironwoodShieldedSpend.json'), 'utf8') +); + +const COIN = 'tzec' as const; +const SPEND_VALUE = 100_000_000n; +/** ZIP-317 conventional fee for a 2-action bundle (1 spend, 2 outputs). */ +const FEE = 10_000n; + +const hex = (value: string): Uint8Array => new Uint8Array(Buffer.from(value, 'hex')); +const toHex = (bytes: Uint8Array): string => Buffer.from(bytes).toString('hex'); + +/** The fixture spend note, with its witness rebuilt (and re-validated) from the raw auth path. */ +function spendRequests(): fixedScriptWallet.ZcashShieldedSpendRequest[] { + const { spends, anchor } = fixture.spendBuild; + return spends.map((spend) => ({ + recipient: hex(spend.recipient), + value: BigInt(spend.value), + rho: hex(spend.rho), + rseed: hex(spend.rseed), + cmx: hex(spend.cmx), + witness: fixedScriptWallet.ZcashIronwoodWitness.build( + hex(spend.cmx), + spend.witness.position, + spend.witness.authPath.map(hex), + hex(anchor) + ), + nullifier: hex(spend.nullifier), + })); +} + +/** Build a keyless 1-spend shielded PSBT paying `outputs`, plus change back to the spent note. */ +function buildSpendPsbt(outputs: { receiver: Uint8Array; amount: bigint }[], change?: bigint): string { + const psbt = fixedScriptWallet.ZcashIronwoodBitGoPsbt.createEmptyKeyless(COIN, { + blockHeight: fixture.spendBuild.blockHeight, + }); + psbt.addShieldedSpends( + spendRequests(), + outputs.map(({ receiver, amount }) => ({ recipient: receiver, amount })), + { + anchor: hex(fixture.spendBuild.anchor), + ...(change !== undefined ? { change: { amount: change, spendIndex: 0 } } : {}), + } + ); + return toHex(psbt.serialize()); +} + +const recipientReceiver = hex(fixture.spendBuild.recipientReceiver); +const recipientAddress = fixedScriptWallet.ZcashUnifiedAddress.encodeOrchardReceiver(recipientReceiver, COIN); +const spentNoteReceiver = hex(fixture.spendBuild.spends[0].recipient); +const spentNoteAddress = fixedScriptWallet.ZcashUnifiedAddress.encodeOrchardReceiver(spentNoteReceiver, COIN); +// An unrelated shielded address (a recipient of the transfer golden). +const otherAddress = fixture.transferSigning.outputs[0].address; +const otherReceiver = fixedScriptWallet.ZcashUnifiedAddress.parse(otherAddress, COIN).orchardReceiver as Uint8Array; + +describe('Zec shielded (RedPallas TSS) keyless verification', function () { + describe('verifyShieldedSpendAgainstRecipients', function () { + it('accepts the requested recipient plus parser-marked change', function () { + const txHex = buildSpendPsbt([{ receiver: recipientReceiver, amount: 30_000_000n }], 69_990_000n); + const parsed = verifyShieldedSpendAgainstRecipients( + txHex, + [{ address: recipientAddress, amount: '30000000' }], + COIN + ); + assert.strictEqual(parsed.fee, FEE); + assert.deepStrictEqual( + parsed.outputs.map((o) => o.isChange), + parsed.outputs.map((o) => o.value === 69_990_000n) + ); + }); + + it('accepts duplicate recipients as separate outputs', function () { + const txHex = buildSpendPsbt( + [ + { receiver: recipientReceiver, amount: 10_000_000n }, + { receiver: recipientReceiver, amount: 10_000_000n }, + ], + SPEND_VALUE - 20_000_000n - 15_000n + ); + verifyShieldedSpendAgainstRecipients( + txHex, + [ + { address: recipientAddress, amount: 10_000_000 }, + { address: recipientAddress, amount: '10000000' }, + ], + COIN + ); + }); + + it('accepts a recipient paying a spent note address (note split)', function () { + // Both outputs are parser-marked change; the recipient still consumes one of them. + const txHex = buildSpendPsbt([{ receiver: spentNoteReceiver, amount: 30_000_000n }], 69_990_000n); + verifyShieldedSpendAgainstRecipients(txHex, [{ address: spentNoteAddress, amount: '30000000' }], COIN); + }); + + it('accepts the transfer golden paying both of its recipients', function () { + verifyShieldedSpendAgainstRecipients( + fixture.transferSigning.psbtHex, + fixture.transferSigning.outputs.map((o) => ({ address: o.address, amount: o.amount })), + COIN + ); + }); + + it('rejects a recipient amount that differs from the output', function () { + const txHex = buildSpendPsbt([{ receiver: recipientReceiver, amount: 30_000_000n }], 69_990_000n); + assert.throws( + () => verifyShieldedSpendAgainstRecipients(txHex, [{ address: recipientAddress, amount: '30000001' }], COIN), + (e: unknown) => e instanceof ShieldedTransactionVerificationError && /expected output missing/.test(e.message) + ); + }); + + it('rejects a requested recipient missing from the transaction', function () { + const txHex = buildSpendPsbt([{ receiver: recipientReceiver, amount: 30_000_000n }], 69_990_000n); + assert.throws( + () => + verifyShieldedSpendAgainstRecipients( + txHex, + [ + { address: recipientAddress, amount: '30000000' }, + { address: otherAddress, amount: '1000' }, + ], + COIN + ), + /expected output missing/ + ); + }); + + it('rejects an output to an unrequested external recipient', function () { + const txHex = buildSpendPsbt([ + { receiver: recipientReceiver, amount: 30_000_000n }, + { receiver: otherReceiver, amount: 69_990_000n }, + ]); + assert.throws( + () => verifyShieldedSpendAgainstRecipients(txHex, [{ address: recipientAddress, amount: '30000000' }], COIN), + /unintended external recipients/ + ); + }); + + it('rejects the transfer golden when only one of its recipients was requested', function () { + const [first] = fixture.transferSigning.outputs; + assert.throws( + () => + verifyShieldedSpendAgainstRecipients( + fixture.transferSigning.psbtHex, + [{ address: first.address, amount: first.amount }], + COIN + ), + /unintended external recipients/ + ); + }); + + it('rejects a fee above the ZIP-317 bounds (change burned as fee)', function () { + const txHex = buildSpendPsbt([{ receiver: recipientReceiver, amount: 30_000_000n }], 69_980_000n); + assert.throws( + () => verifyShieldedSpendAgainstRecipients(txHex, [{ address: recipientAddress, amount: '30000000' }], COIN), + /outside the ZIP-317 bounds/ + ); + }); + + it('rejects a transparent-input (non-RedPallas) v6 PSBT', function () { + const { walletKeys } = getDefaultWasmWalletKeys(); + const psbt = fixedScriptWallet.ZcashIronwoodBitGoPsbt.createEmpty(COIN, walletKeys, { blockHeight: 4200000 }); + psbt.addWalletInput({ txid: '11'.repeat(32), vout: 0, value: 100000n }, walletKeys, { + scriptId: { chain: 0, index: 0 }, + }); + psbt.addShieldedOutputs([{ recipient: recipientReceiver, amount: 90000n }], new Uint8Array(32)); + const txHex = toHex(psbt.serialize()); + assert.strictEqual(isShieldedSpendPsbt(txHex, COIN), false); + assert.throws( + () => verifyShieldedSpendAgainstRecipients(txHex, [{ address: recipientAddress, amount: '90000' }], COIN), + /spends no shielded notes/ + ); + }); + + it('rejects bytes that are not a v6 PSBT', function () { + assert.throws(() => verifyShieldedSpendAgainstRecipients('deadbeef', [], COIN), /not a Zcash Ironwood/); + }); + }); + + describe('explainShieldedSpendPsbt', function () { + it('splits parser-marked change from recipients and reports the fee and spends', function () { + const txHex = buildSpendPsbt([{ receiver: recipientReceiver, amount: 30_000_000n }], 69_990_000n); + const explanation = explainShieldedSpendPsbt(decodeShieldedPsbt(txHex, COIN)); + assert.deepStrictEqual(explanation.outputs, [{ address: recipientAddress, amount: '30000000', external: true }]); + assert.deepStrictEqual(explanation.changeOutputs, [ + { address: spentNoteAddress, amount: '69990000', external: false }, + ]); + assert.strictEqual(explanation.outputAmount, '30000000'); + assert.strictEqual(explanation.changeAmount, '69990000'); + assert.strictEqual(explanation.fee, FEE.toString()); + assert.strictEqual(explanation.inputAmount, SPEND_VALUE.toString()); + assert.deepStrictEqual(explanation.inputs, [{ address: spentNoteAddress, value: SPEND_VALUE.toString() }]); + assert.strictEqual(explanation.shieldedSpends.length, 1); + assert.strictEqual(explanation.shieldedSpends[0].nullifier, fixture.spendBuild.spends[0].nullifier); + }); + }); + + describe('Zec.verifyTransaction / explainTransaction (TSS wallet)', function () { + const zec = getUtxoCoin(COIN) as unknown as Zec; + const txHex = buildSpendPsbt([{ receiver: recipientReceiver, amount: 30_000_000n }], 69_990_000n); + // A TSS wallet stub: the shielded path must need nothing from the wallet but its type. + const tssWallet = { multisigType: () => 'tss' } as unknown as Parameters[0]['wallet']; + + it('verifies a shielded prebuild without wallet keys or a receive address', async function () { + const ok = await zec.verifyTransaction({ + txParams: { recipients: [{ address: recipientAddress, amount: '30000000' }] }, + txPrebuild: { txHex }, + wallet: tssWallet, + }); + assert.strictEqual(ok, true); + }); + + it('takes the shielded path from walletType alone', async function () { + const ok = await zec.verifyTransaction({ + txParams: { recipients: [{ address: recipientAddress, amount: '30000000' }] }, + txPrebuild: { txHex }, + wallet: undefined as unknown as typeof tssWallet, + walletType: 'tss', + }); + assert.strictEqual(ok, true); + }); + + it('throws TxIntentMismatchError (with an explanation) on a recipient mismatch', async function () { + await assert.rejects( + zec.verifyTransaction({ + txParams: { recipients: [{ address: recipientAddress, amount: '29000000' }] }, + txPrebuild: { txHex }, + wallet: tssWallet, + }), + (e: unknown) => { + assert.ok(e instanceof TxIntentMismatchError); + assert.match(e.message, /expected output missing/); + assert.strictEqual(JSON.parse(e.txExplanation as string).fee, FEE.toString()); + return true; + } + ); + }); + + it('throws TxIntentMismatchError when txHex is missing', async function () { + await assert.rejects( + zec.verifyTransaction({ txParams: { recipients: [] }, txPrebuild: {}, wallet: tssWallet }), + (e: unknown) => + e instanceof TxIntentMismatchError && /missing required txPrebuild property txHex/.test(e.message) + ); + }); + + it('explains a shielded spend PSBT without pubs or a wallet', async function () { + const explanation = await zec.explainTransaction({ txHex }); + assert.strictEqual(explanation.fee, FEE.toString()); + assert.deepStrictEqual( + explanation.outputs.map((o) => [o.address, o.amount]), + [[recipientAddress, '30000000']] + ); + assert.deepStrictEqual( + explanation.changeOutputs.map((o) => [o.address, o.amount]), + [[spentNoteAddress, '69990000']] + ); + }); + + it('explains a shielded spend PSBT for a TSS wallet', async function () { + const explanation = await zec.explainTransaction({ txHex }, tssWallet); + assert.strictEqual(explanation.changeOutputs.length, 1); + }); + }); + + describe('post-rerand rebuild (offline vault console)', function () { + const { psbtHex, spends, rks, sighash } = fixture.transferSigning; + + /** wallet-platform's rebuildShieldedSignableAfterRerand: install rks at each spend's action. */ + function rebuild(entries: { actionIndex: number; rk: string }[]): string { + const psbt = decodeShieldedPsbt(psbtHex, COIN); + psbt.addSpendRks(entries.map(({ actionIndex, rk }) => ({ actionIndex, rk: hex(rk) }))); + return toHex(psbt.serialize()); + } + const platformEntries = spends.map((spend) => ({ actionIndex: spend.actionIndex, rk: rks[spend.spendIndex] })); + const rebuiltTxHex = rebuild(platformEntries); + + it('computes the platform sighash from the original PSBT and the rks', function () { + assert.strictEqual(computeShieldedSpendSighash(psbtHex, platformEntries, COIN), sighash); + }); + + it('accepts the platform rebuild and resolves each rk to its action', function () { + const installed = assertRebuiltShieldedSignable({ + coinName: COIN, + originalTxHex: psbtHex, + rebuiltTxHex, + signableHex: sighash, + rks, + }); + assert.deepStrictEqual( + installed.map((entry) => entry.actionIndex), + spends.map((spend) => spend.actionIndex) + ); + }); + + it('accepts an upper-case signableHex', function () { + assertRebuiltShieldedSignable({ + coinName: COIN, + originalTxHex: psbtHex, + rebuiltTxHex, + signableHex: sighash.toUpperCase(), + rks: rks.map(hex), + }); + }); + + it('rejects a signableHex that does not commit to the reviewed transaction', function () { + assert.throws( + () => + assertRebuiltShieldedSignable({ + coinName: COIN, + originalTxHex: psbtHex, + rebuiltTxHex, + signableHex: 'ff'.repeat(32), + rks, + }), + /rebuilt signable does not commit to the reviewed shielded transaction/ + ); + }); + + it('rejects a rebuild of a different transaction than the one reviewed', function () { + const reviewed = buildSpendPsbt([{ receiver: recipientReceiver, amount: 30_000_000n }], 69_990_000n); + assert.throws( + () => + assertRebuiltShieldedSignable({ + coinName: COIN, + originalTxHex: reviewed, + rebuiltTxHex, + signableHex: sighash, + rks, + }), + /different number of notes|does not commit to the reviewed/ + ); + }); + + it('rejects a rebuild that installed an rk the signer did not produce', function () { + const foreign = rebuild([ + { actionIndex: spends[0].actionIndex, rk: fixture.transferSigning.ak }, + { actionIndex: spends[1].actionIndex, rk: rks[1] }, + ]); + assert.throws( + () => + assertRebuiltShieldedSignable({ + coinName: COIN, + originalTxHex: psbtHex, + rebuiltTxHex: foreign, + signableHex: sighash, + rks, + }), + /rerandomized key for spend 0 is not installed/ + ); + }); + + it('rejects a rebuilt serializedTxHex without the rks installed', function () { + assert.throws( + () => + assertRebuiltShieldedSignable({ + coinName: COIN, + originalTxHex: psbtHex, + rebuiltTxHex: psbtHex, + signableHex: sighash, + rks, + }), + /is not installed in the rebuilt shielded transaction/ + ); + }); + + it('rejects a serializedTxHex whose sighash differs from the signable', function () { + // The rks swapped between the two spends: the signer's own keys, but a different + // transaction (the sighash commits each action's rk). + const swapped = rebuild([ + { actionIndex: spends[0].actionIndex, rk: rks[1] }, + { actionIndex: spends[1].actionIndex, rk: rks[0] }, + ]); + assert.throws( + () => + assertRebuiltShieldedSignable({ + coinName: COIN, + originalTxHex: psbtHex, + rebuiltTxHex: swapped, + signableHex: sighash, + rks, + }), + /does not commit to the reviewed shielded transaction/ + ); + }); + + it('rejects a wrong number of rerandomized keys', function () { + assert.throws( + () => resolveInstalledShieldedRks(decodeShieldedPsbt(rebuiltTxHex, COIN), [rks[0]]), + /has 2 spends but 1 rerandomized keys/ + ); + }); + }); +}); diff --git a/modules/bitgo/test/v2/unit/pendingApproval.ts b/modules/bitgo/test/v2/unit/pendingApproval.ts index 985ee9002aa..953943ceea2 100644 --- a/modules/bitgo/test/v2/unit/pendingApproval.ts +++ b/modules/bitgo/test/v2/unit/pendingApproval.ts @@ -12,6 +12,7 @@ import { coins as staticsCoins } from '@bitgo/statics'; import { BaseCoin, ECDSAUtils, + EDDSAUtils, EddsaUtils, Environments, Keychain, @@ -19,6 +20,7 @@ import { PendingApproval, PendingApprovalData, PendingApprovalInfo, + RedpallasUtils, RequestTracer, SignatureShareType, SignedTransaction, @@ -90,7 +92,7 @@ describe('Pending Approvals:', () => { (pendingApprovalData as any).wallet = wallet; }); - ['tsol', 'teth', 'tbtc'].forEach((coinName) => { + ['tsol', 'teth', 'tbtc', 'tzec'].forEach((coinName) => { it(`should use correct tssUtils for ${coinName}`, () => { const coin = bitgo.coin(coinName); const pendingAproval = new PendingApproval(bitgo, coin, {} as unknown as PendingApprovalData); @@ -99,6 +101,8 @@ describe('Pending Approvals:', () => { pendingAproval['tssUtils'].should.be.instanceOf(ECDSAUtils.EcdsaUtils); } else if (coin.getMPCAlgorithm() === 'eddsa') { pendingAproval['tssUtils'].should.be.instanceOf(EddsaUtils); + } else if (coin.getMPCAlgorithm() === 'redpallas') { + pendingAproval['tssUtils'].should.be.instanceOf(RedpallasUtils.RedpallasMPCv2Utils); } } else { (pendingAproval['tssUtils'] === undefined).should.be.true(); @@ -106,6 +110,23 @@ describe('Pending Approvals:', () => { }); }); + ['MPCv2', undefined].forEach((multisigTypeVersion) => { + it(`should use RedpallasMPCv2Utils for tzec TSS wallet, multisigTypeVersion: ${multisigTypeVersion}`, () => { + const coin = bitgo.coin('tzec'); + const tzecTssWallet = new Wallet(bitgo, coin, { + ...walletData, + coin: 'tzec', + multisigType: 'tss', + multisigTypeVersion, + }); + + const pendingApproval = new PendingApproval(bitgo, coin, {} as unknown as PendingApprovalData, tzecTssWallet); + pendingApproval['tssUtils'].should.be.instanceOf(RedpallasUtils.RedpallasMPCv2Utils); + pendingApproval['tssUtils'].should.not.be.instanceOf(EddsaUtils); + pendingApproval['tssUtils'].should.not.be.instanceOf(EDDSAUtils.EddsaMPCv2Utils); + }); + }); + ['MPCv2', undefined].forEach((multisigTypeVersion) => { it(`should use correct tssUtils for multisigTypeVersion: ${multisigTypeVersion}`, () => { const coin = bitgo.coin('hteth'); diff --git a/modules/bitgo/test/v2/unit/wallets.ts b/modules/bitgo/test/v2/unit/wallets.ts index da8330b8084..67fda2601d1 100644 --- a/modules/bitgo/test/v2/unit/wallets.ts +++ b/modules/bitgo/test/v2/unit/wallets.ts @@ -14,6 +14,7 @@ import { Wallets, ECDSAUtils, EDDSAUtils, + Keychains, KeychainsTriplet, GenerateWalletOptions, Wallet, @@ -1057,6 +1058,69 @@ describe('V2 Wallets:', function () { await shieldedWallets.generateWallet(walletParams).should.be.rejectedWith('enterprise is required'); }); + + (['hot', 'custodial', 'cold'] as const).forEach((type) => { + [false, undefined].forEach((isShielded) => { + it(`should reject non-shielded ${type} TSS wallet (isShielded: ${isShielded})`, async function () { + const walletParams: GenerateWalletOptions = { + label: 'tss wallet', + multisigType: 'tss', + enterprise: 'enterprise', + passphrase: 'passphrase', + type, + isShielded, + ...(type === 'cold' && { bitgoKeyId: 'bitgoKeyId', commonKeychain: 'commonKeychain' }), + }; + const createMpcSpy = sinon.spy(Keychains.prototype, 'createMpc'); + const postSpy = sinon.spy(bitgo, 'post'); + try { + await new Wallets(bitgo, tzec) + .generateWallet(walletParams) + .should.be.rejectedWith('coin tzec only supports TSS for shielded wallets (set isShielded: true)'); + createMpcSpy.called.should.be.false(); + postSpy.called.should.be.false(); + } finally { + createMpcSpy.restore(); + postSpy.restore(); + } + }); + }); + }); + + it('should still create an onchain tzec wallet without isShielded', async function () { + const walletParams: GenerateWalletOptions = { + label: 'onchain wallet', + multisigType: 'onchain', + type: 'custodial', + enterprise: 'enterprise', + }; + + // Stub the request layer directly rather than nock, so interceptors left behind by other tests in + // this suite cannot answer the /wallet/add request. + const sentBodies: Record[] = []; + const postStub = sinon.stub(bitgo, 'post').callsFake((url: string) => { + url.should.endWith('/api/v2/tzec/wallet/add'); + return { + send: (body: Record) => { + sentBodies.push(body); + return { result: async () => ({ ...walletParams, id: 'onchain-wallet', keys: ['1', '2', '3'] }) }; + }, + } as unknown as ReturnType; + }); + const keychainGetStub = sinon + .stub(Keychains.prototype, 'get') + .callsFake(async ({ id }) => ({ id, pub: `pub${id}`, type: 'independent' })); + try { + await new Wallets(bitgo, tzec).generateWallet(walletParams); + sentBodies.should.have.length(1); + should(sentBodies[0].type).equal('custodial'); + should.not.exist(sentBodies[0].multisigType); + keychainGetStub.callCount.should.equal(3); + } finally { + postStub.restore(); + keychainGetStub.restore(); + } + }); }); describe('Generate TSS MPCv2 wallet:', async function () { diff --git a/modules/sdk-core/src/bitgo/pendingApproval/pendingApproval.ts b/modules/sdk-core/src/bitgo/pendingApproval/pendingApproval.ts index bb4db3daf7b..df8834907d0 100644 --- a/modules/sdk-core/src/bitgo/pendingApproval/pendingApproval.ts +++ b/modules/sdk-core/src/bitgo/pendingApproval/pendingApproval.ts @@ -27,6 +27,7 @@ import EddsaUtils, { EddsaMPCv2Utils } from '../utils/tss/eddsa'; import { EcdsaMPCv2Utils, EcdsaUtils } from '../utils/tss/ecdsa'; import { KeyShare as EcdsaKeyShare } from '../utils/tss/ecdsa/types'; import { KeyShare as EddsaKeyShare } from '../utils/tss/eddsa/types'; +import { RedpallasMPCv2Utils } from '../utils/tss/redpallas'; import { sendTxRequest } from '../tss/common'; import assert from 'assert'; @@ -45,7 +46,7 @@ type ApprovePendingApprovalRequestBody = { export class PendingApproval implements IPendingApproval { private readonly bitgo: BitGoBase; private readonly baseCoin: IBaseCoin; - private tssUtils?: BaseTssUtils; + private tssUtils?: BaseTssUtils | RedpallasMPCv2Utils; private wallet?: IWallet; private _pendingApproval: PendingApprovalData; @@ -55,12 +56,16 @@ export class PendingApproval implements IPendingApproval { this.wallet = wallet; if (this.baseCoin.supportsTss()) { - if (this.baseCoin.getMPCAlgorithm() === 'ecdsa') { + const mpcAlgorithm = this.baseCoin.getMPCAlgorithm(); + if (mpcAlgorithm === 'ecdsa') { if (this.wallet?.multisigTypeVersion() === 'MPCv2') { this.tssUtils = new EcdsaMPCv2Utils(this.bitgo, this.baseCoin, wallet); } else { this.tssUtils = new EcdsaUtils(this.bitgo, this.baseCoin, wallet); } + } else if (mpcAlgorithm === 'redpallas') { + // RedPallas (Zcash Orchard shielded pool) is MPCv2-only; there is no MPCv1 variant. + this.tssUtils = new RedpallasMPCv2Utils(this.bitgo, this.baseCoin, wallet); } else { if (this.wallet?.multisigTypeVersion() === 'MPCv2') { this.tssUtils = new EddsaMPCv2Utils(this.bitgo, this.baseCoin, wallet); diff --git a/modules/sdk-core/src/bitgo/wallet/wallets.ts b/modules/sdk-core/src/bitgo/wallet/wallets.ts index 772482dbf3f..df266743e2d 100644 --- a/modules/sdk-core/src/bitgo/wallet/wallets.ts +++ b/modules/sdk-core/src/bitgo/wallet/wallets.ts @@ -454,6 +454,13 @@ export class Wallets implements IWallets { }); } + // RedPallas (Zcash Orchard) keys exist only for shielded wallets, which returned above. Without this + // guard a non-shielded zec TSS request would fall through to the generic TSS paths below (e.g. an + // ECDSA key ceremony for hot wallets, or a custodial wallet without coinSpecific.isShielded). + if (isTss && this.baseCoin.getMPCAlgorithm() === 'redpallas') { + throw new Error(`coin ${this.baseCoin.getChain()} only supports TSS for shielded wallets (set isShielded: true)`); + } + if (isTss) { if (!this.baseCoin.supportsTss()) { throw new Error(`coin ${this.baseCoin.getFamily()} does not support TSS at this time`);