diff --git a/modules/sdk-coin-flrp/src/flrp.ts b/modules/sdk-coin-flrp/src/flrp.ts index 870249eb5ea..a54a99342c8 100644 --- a/modules/sdk-coin-flrp/src/flrp.ts +++ b/modules/sdk-coin-flrp/src/flrp.ts @@ -24,6 +24,7 @@ import { } from '@bitgo/sdk-core'; import * as FlrpLib from './lib'; import { + ADDRESS_SEPARATOR, CreatePairedWalletParams, CreatePairedWalletResponse, FlrpEntry, @@ -35,6 +36,20 @@ import { import utils from './lib/utils'; import BigNumber from 'bignumber.js'; import { isValidAddress as isValidEthAddress } from 'ethereumjs-util'; +import { pvmSerial, TransferOutput, UnsignedTx } from '@flarenetwork/flarejs'; + +/** + * Normalize an address (or tilde-joined owner set) for comparison: case-insensitive + * and order-insensitive over the sorted owner set. Handles both single addresses and + * multisig owner sets for P-chain destinations. + */ +function normalizeAddressSet(address: string): string { + return address + .split(ADDRESS_SEPARATOR) + .map((a) => a.trim().toLowerCase()) + .sort() + .join(ADDRESS_SEPARATOR); +} export class Flrp extends BaseCoin { protected readonly _staticsCoin: Readonly; @@ -97,20 +112,22 @@ export class Flrp extends BaseCoin { const type = params.txParams.type; // WP intentType aliases (lowercase) must map to TransactionType enum keys. + // 'ImportToC' aliases to 'Import' (TransactionType has no ImportToC key — the previous + // gate exemption for it was masking that gap and skipped the type check entirely). const normalizedType = type === 'stake' ? 'AddPermissionlessDelegator' - : type === 'import' + : type === 'export' + ? 'Export' + : type === 'import' || type === 'importtoc' || type === 'ImportToC' ? 'Import' - : type === 'importtoc' - ? 'ImportToC' : type; // When type is provided, verify it matches the parsed transaction. // When type is not provided (MPC/TSS intent flow where buildParams are unavailable), - // skip the type match check and rely on explainedTx.type from the parsed hex — - // the transaction was built by wallet-platform and the hex is the source of truth. - if (normalizedType && normalizedType !== 'ImportToC' && explainedTx.type !== TransactionType[normalizedType]) { + // rely on explainedTx.type from the parsed hex — but every branch below still + // validates the destination/value fields it can bind to intent. + if (normalizedType && explainedTx.type !== TransactionType[normalizedType]) { throw new Error('Tx type does not match with expected txParams type'); } @@ -119,29 +136,60 @@ export class Flrp extends BaseCoin { if (!params.txParams.recipients || params.txParams.recipients?.length !== 1) { throw new Error('Export Tx requires a recipient'); } else { - this.validateExportTx(params.txParams.recipients, explainedTx); + this.validateExportTx(params.txParams.recipients, explainedTx, tx); } break; case TransactionType.Import: if (tx.isTransactionForCChain) { - // Import to C-chain + // Import to C-chain: the single output pays all imported value to a C-chain + // address, which must equal the expected recipient (CECHO-2717) — a prebuild + // paying the wallet's in-flight UTXOs to any other address must fail. if (explainedTx.outputs.length !== 1) { throw new Error('Expected 1 output in import transaction'); } if (!params.txParams.recipients || params.txParams.recipients.length !== 1) { throw new Error('Expected 1 recipient in import transaction'); } + const importDestination = explainedTx.outputs[0].address; + const expectedCDestination = params.txParams.recipients[0].address; + if (!isValidEthAddress(importDestination)) { + throw new Error(`Invalid C-chain import destination: ${importDestination}`); + } + // The expected recipient must come from the caller's request — the TSS signing + // flow resolves recipients from the persisted intent, and prebuild flows carry + // the caller's request params. RESIDUAL TRUST ASSUMPTION: on the TSS path the + // intent itself is stored server-side, so a platform that controls both the + // intent and the prebuild is not caught by this comparison; there is no + // wallet-side C-chain anchor to cross-check against either (the paired C + // address is keccak(pubkey)[12:], which cannot be derived from the P-chain + // rootAddress — bech32 carries only ripemd160(pubkey)). Defense against a + // fully compromised platform rests on the sdk-core digest-binding work, not here. + if (typeof expectedCDestination !== 'string' || !isValidEthAddress(expectedCDestination)) { + throw new Error(`Invalid expected C-chain import recipient: ${expectedCDestination}`); + } + if (importDestination.toLowerCase() !== expectedCDestination.toLowerCase()) { + throw new Error( + `Import destination ${importDestination} does not match the expected recipient ${expectedCDestination}` + ); + } + this.validateImportTx(explainedTx.inputs, params.txParams); + this.validateImportFee(explainedTx); } else { - // Import to P-chain + // Import to P-chain: the output owner set receiving the imported value must be + // the wallet's own address, with its spend policy preserved (CECHO-2717). if (explainedTx.outputs.length !== 1) { throw new Error('Expected 1 output in import transaction'); } this.validateImportTx(explainedTx.inputs, params.txParams); + this.validateImportDestination(explainedTx.outputs[0].address, params); + this.validateImportOutputPolicy(tx); + this.validateImportFee(explainedTx); } break; case TransactionType.AddPermissionlessDelegator: if (params.txParams.stakingOptions) { this.validateDelegationTx(params.txParams, explainedTx); + this.validateDelegationOwners(tx, params); } break; default: @@ -155,8 +203,13 @@ export class Flrp extends BaseCoin { * * @param {ITransactionRecipient[]} recipients expected recipients and info * @param {FlrpLib.TransactionExplanation} explainedTx explained export transaction + * @param {FlrpLib.Transaction} tx parsed transaction, used to distinguish the export direction */ - validateExportTx(recipients: ITransactionRecipient[], explainedTx: FlrpLib.TransactionExplanation): void { + validateExportTx( + recipients: ITransactionRecipient[], + explainedTx: FlrpLib.TransactionExplanation, + tx: FlrpLib.Transaction + ): void { if (recipients.length !== 1 || explainedTx.outputs.length !== 1) { throw new Error('Export Tx requires one recipient'); } @@ -175,6 +228,31 @@ export class Flrp extends BaseCoin { if (explainedTx.outputs && !utils.isValidAddress(explainedTx.outputs[0].address)) { throw new Error(`Invalid P-chain address ${explainedTx.outputs[0].address}`); } + + if (tx.isTransactionForCChain) { + // C→P export: the outputs are the P-chain owner set the recipient names. Bind the + // destination when the caller carries a non-empty address (review hardening for + // CECHO-2717); an empty placeholder (destination supplied by the later import) is + // not comparable. + const expectedExportDestination = recipients[0].address; + if (expectedExportDestination) { + if (!utils.isValidAddress(expectedExportDestination)) { + throw new Error(`Invalid expected export destination: ${expectedExportDestination}`); + } + const exportDestination = explainedTx.outputs[0].address; + if (normalizeAddressSet(exportDestination) !== normalizeAddressSet(expectedExportDestination)) { + throw new Error( + `Export destination ${exportDestination} does not match the expected recipient ${expectedExportDestination}` + ); + } + } + } + // P→C export: the exported outputs are owned by the wallet's own addresses + // (ExportInPTxBuilder pays the wallet's fromAddresses — the C destination is the + // wallet's paired C address, supplied by the later import). A non-empty recipient + // here is the C-chain destination, which is not comparable to the P-form output + // owner set, so it is deliberately not bound — binding it would reject flows that + // pass the C destination. } /** @@ -199,6 +277,135 @@ export class Flrp extends BaseCoin { } } + /** + * Check that an import to P-chain pays the wallet's own address (CECHO-2717). + * The expected destination comes from txParams recipients when supplied, else from + * the wallet's rootAddress. Addresses are tilde-joined owner sets; comparison is + * order- and case-insensitive over the sorted owner set. + * + * @param {string} outputAddress P-chain destination of the import output (from the parsed prebuild) + * @param {FlrpVerifyTransactionOptions} params verification params carrying intent and wallet + * @throws Error when no expected destination is available or the destination does not match + */ + validateImportDestination(outputAddress: string, params: FlrpVerifyTransactionOptions): void { + const recipientAddress = + params.txParams.recipients && params.txParams.recipients.length > 0 + ? params.txParams.recipients[0].address + : undefined; + const walletRootAddress = params.wallet?.coinSpecific()?.rootAddress; + + // When both intent sources are present they must agree — an import pays the wallet + // itself, so a recipient that disagrees with the wallet's rootAddress is ambiguous + // and fails closed instead of one source silently overriding the other (review + // hardening for CECHO-2717). + if (recipientAddress && walletRootAddress) { + if (!utils.isValidAddress(recipientAddress) || !utils.isValidAddress(walletRootAddress)) { + throw new Error(`Invalid import destination intent: ${recipientAddress} / ${walletRootAddress}`); + } + if (normalizeAddressSet(recipientAddress) !== normalizeAddressSet(walletRootAddress)) { + throw new Error( + `Import destination intent conflict: txParams recipient ${recipientAddress} does not match wallet rootAddress ${walletRootAddress}` + ); + } + } + + // receiveAddress is a second wallet-anchored source (platform wallet data, not the + // prebuild under verification) — used as a last-resort anchor so wallets whose + // coinSpecific lacks a P-form rootAddress still verify instead of failing closed. + const walletReceiveAddress = params.wallet?.receiveAddress(); + const expectedDestination = recipientAddress || walletRootAddress || walletReceiveAddress; + + if (!expectedDestination) { + throw new Error( + 'Unable to verify import destination: no expected address provided in txParams.recipients or wallet rootAddress' + ); + } + + if (!utils.isValidAddress(outputAddress)) { + throw new Error(`Invalid P-chain import destination: ${outputAddress}`); + } + if (!utils.isValidAddress(expectedDestination)) { + throw new Error(`Invalid expected import destination: ${expectedDestination}`); + } + + if (normalizeAddressSet(outputAddress) !== normalizeAddressSet(expectedDestination)) { + throw new Error( + `Import destination ${outputAddress} does not match the expected wallet destination ${expectedDestination}` + ); + } + } + + /** + * Bind the import-to-P output's spend policy (review hardening for CECHO-2717): + * the output must be immediately spendable (locktime 0), consume at least one UTXO, + * and be structurally sound (threshold between 1 and the owner count). + * + * The output threshold is deliberately NOT bound to the consumed UTXOs' thresholds: + * those are set by whoever created the atomic UTXO (the earlier export) and may + * legitimately differ from the wallet's output threshold — importing a 1-of-N UTXO + * into a 2-of-3 output is valid, and equality here would reject flows the base branch + * verified. No client-side authoritative expected threshold exists either (TSS + * wallets use 1, custodial m-of-n uses m, and neither reaches verifyTransaction), + * so threshold weakening within the wallet's own owner set is not verifiable here — + * the owner-set binding in validateImportDestination is what keeps the funds on + * wallet-controlled addresses. + * + * @param {FlrpLib.Transaction} tx the parsed transaction carrying the raw outputs + * @throws Error when the output locktime is nonzero, the import consumes no UTXOs, + * or the output threshold is structurally invalid + */ + validateImportOutputPolicy(tx: FlrpLib.Transaction): void { + const pvmImportTx = (tx.getFlareTransaction() as UnsignedTx).getTx() as pvmSerial.ImportTx; + const output = pvmImportTx.baseTx.outputs[0].output as TransferOutput; + + const locktime = output.getLocktime(); + if (locktime !== 0n) { + throw new Error( + `Import output locktime ${locktime} must be 0 — a time-locked output would freeze the wallet's funds` + ); + } + + if (pvmImportTx.ins.length === 0) { + throw new Error('Import transaction consumes no UTXOs; refusing to verify'); + } + + const threshold = output.getThreshold(); + const ownerCount = output.getOwners().length; + if (threshold < 1 || threshold > ownerCount) { + throw new Error(`Import output threshold ${threshold} is invalid for ${ownerCount} owner(s); refusing to verify`); + } + } + + /** + * Bound the fee burned by an import (review hardening for CECHO-2717): the + * difference between consumed input value and the output value is burned as the + * import fee. Without this check, a prebuild paying the right destination a dust + * amount while burning the rest as fee would pass verification. + * + * @param {FlrpLib.TransactionExplanation} explainedTx parsed import explanation + * @throws Error when the burned fee exceeds the network's maxImportFee + */ + validateImportFee(explainedTx: FlrpLib.TransactionExplanation): void { + const maxImportFee = (this._staticsCoin.network as FlareNetwork).maxImportFee; + // Input entries carry `value`; output entries carry `amount` (explainTransaction + // maps outputs to { address, amount }). Fail closed when either total is not a + // finite number — a field mismatch must never silently disable the cap. + const consumedTotal = (explainedTx.inputs as unknown as FlrpEntry[]).reduce( + (sum, input) => sum.plus(input.value), + new BigNumber(0) + ); + const importedTotal = new BigNumber(explainedTx.outputs[0].amount); + if (!consumedTotal.isFinite() || !importedTotal.isFinite()) { + throw new Error('Import fee cap: input/output totals are not finite numbers; refusing to verify'); + } + const burnedFee = consumedTotal.minus(importedTotal); + if (burnedFee.isGreaterThan(maxImportFee)) { + throw new Error( + `Import burns ${burnedFee.toString()} in fees, exceeding the network maxImportFee ${maxImportFee}` + ); + } + } + /** * Validate AddPermissionlessDelegator transaction parameters. * Validates both expected txParams and the parsed explainedTx for consistency. @@ -233,6 +440,17 @@ export class Flrp extends BaseCoin { if (!utils.isValidNodeID(nodeID)) { throw new Error(`Invalid nodeID format: ${nodeID}`); } + // Bind the staked node: the parsed transaction's validator nodeId (exposed as the + // delegation output address) must equal the requested nodeID — a prebuild staking + // to a different node than the user chose must fail (review hardening for CECHO-2717). + // Fail closed when the parsed tx exposes no nodeId: there is nothing to compare. + const txNodeId = explainedTx.outputs.length > 0 ? explainedTx.outputs[0].address : undefined; + if (!txNodeId) { + throw new Error('Delegation transaction does not expose the validator nodeId; refusing to verify'); + } + if (txNodeId !== nodeID) { + throw new Error(`Delegation nodeID mismatch: expected ${nodeID}, transaction delegates to ${txNodeId}`); + } // Validate that the parsed transaction's output amount matches the expected staking amount // The outputAmount in explainedTx represents the total stake amount in the transaction @@ -245,6 +463,76 @@ export class Flrp extends BaseCoin { } } + /** + * Bind the delegation's stake and reward ownership (review hardening for CECHO-2717): + * a compromised platform can serve a delegation to the right node for the right + * amount while returning the stake to an attacker owner set or paying rewards to an + * attacker address. The stake owner set is bound to the wallet's own addresses when + * an anchor is available, and the delegator rewards owner must equal the requested + * stakingOptions.rewardAddress (P-/C- prefix-insensitive). Fails closed when the + * parsed transaction exposes no stake outputs or no rewards owner. + * + * @param {FlrpLib.Transaction} tx parsed delegation transaction + * @param {FlrpVerifyTransactionOptions} params verification params carrying intent and wallet + */ + validateDelegationOwners(tx: FlrpLib.Transaction, params: FlrpVerifyTransactionOptions): void { + const rewardAddress = params.txParams.stakingOptions?.rewardAddress; + if (!rewardAddress) { + throw new Error('Delegation transaction requires stakingOptions.rewardAddress'); + } + const network = this._staticsCoin.network as FlareNetwork; + const pvmDelegatorTx = (tx.getFlareTransaction() as UnsignedTx).getTx() as pvmSerial.AddPermissionlessDelegatorTx; + + if (pvmDelegatorTx.stake.length === 0) { + throw new Error('Delegation transaction exposes no stake outputs; refusing to verify'); + } + const stakeOwners = (pvmDelegatorTx.stake[0].output as TransferOutput) + .getOwners() + .map((owner) => utils.addressToString(network.hrp, 'P', Buffer.from(owner))) + .sort() + .join(ADDRESS_SEPARATOR); + + // Stake outputs are built from the signing keys (user+bitgo, or backup+bitgo in + // recovery), which are a SUBSET of the wallet's full owner set — exact-set equality + // against the wallet anchor would reject every multisig delegation. Require the + // stake owners to be contained in the wallet's owner set instead. + const walletAnchor = params.wallet?.coinSpecific()?.rootAddress || params.wallet?.receiveAddress(); + if (walletAnchor) { + const anchorOwners = new Set(normalizeAddressSet(walletAnchor).split(ADDRESS_SEPARATOR)); + const stakeOwnerList = normalizeAddressSet(stakeOwners).split(ADDRESS_SEPARATOR); + const foreignOwner = stakeOwnerList.find((owner) => !anchorOwners.has(owner)); + if (foreignOwner) { + throw new Error( + `Delegation stake owner ${foreignOwner} is not one of the wallet's own addresses ${walletAnchor}` + ); + } + } + + // Compare rewards owners by decoded address bytes so every accepted form of + // stakingOptions.rewardAddress matches: bech32 P-/C- prefixed forms and 0x-prefixed + // or raw hex (parseAddress decodes all of them). + const rewardsOwner = pvmDelegatorTx.getDelegatorRewardsOwner(); + if (rewardsOwner.addrs.length !== 1) { + throw new Error( + `Delegation rewards owner must be a single address, transaction has ${rewardsOwner.addrs.length} owner(s)` + ); + } + const onChainRewardBytes = Buffer.from(rewardsOwner.addrs[0].toBytes()); + let expectedRewardBytes: Buffer; + try { + expectedRewardBytes = utils.parseAddress(rewardAddress); + } catch (error) { + throw new Error(`Invalid stakingOptions.rewardAddress '${rewardAddress}': ${(error as Error).message}`); + } + if (!onChainRewardBytes.equals(expectedRewardBytes)) { + throw new Error( + `Delegation rewards owner 0x${onChainRewardBytes.toString( + 'hex' + )} does not match the requested rewardAddress ${rewardAddress}` + ); + } + } + private getBuilder(): FlrpLib.TransactionBuilderFactory { return new FlrpLib.TransactionBuilderFactory(coins.get(this.getChain())); } diff --git a/modules/sdk-coin-flrp/test/unit/flrp.ts b/modules/sdk-coin-flrp/test/unit/flrp.ts index 132084c09ae..9029c832f45 100644 --- a/modules/sdk-coin-flrp/test/unit/flrp.ts +++ b/modules/sdk-coin-flrp/test/unit/flrp.ts @@ -1,3 +1,4 @@ +import utils from '../../src/lib/utils'; import * as FlrpLib from '../../src/lib'; import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test'; import { Flrp, TflrP } from '../../src/'; @@ -343,6 +344,28 @@ describe('Flrp test cases', function () { isVerified.should.equal(true); }); + it('should verify an export when txParams.type is the lowercase "export" intent alias', async () => { + // WP issues lowercase intentTypes; TransactionType['export'] is undefined, so the + // alias must normalize to 'Export' or the type gate rejects every such export. + const txPrebuild = { + txHex: EXPORT_IN_C.signedHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: EXPORT_IN_C.amount, + }, + ], + type: 'export', + locktime: 0, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + isVerified.should.equal(true); + }); + it('should verify an export from P-chain transaction', async () => { const txPrebuild = { txHex: EXPORT_IN_P.fullSigntxHex, @@ -389,7 +412,7 @@ describe('Flrp test cases', function () { txInfo: {}, }; const txParams = { - recipients: [], + recipients: [{ address: IMPORT_IN_P.pAddresses.join('~'), amount: IMPORT_IN_P.amount }], type: 'Import', locktime: 0, }; @@ -486,6 +509,366 @@ describe('Flrp test cases', function () { .verifyTransaction({ txParams, txPrebuild }) .should.be.rejectedWith('Expected 1 recipient in import transaction'); }); + + it('should fail to verify import to C-chain with an attacker destination (CECHO-2717)', async () => { + const txPrebuild = { + txHex: IMPORT_IN_C.fullSigntxHex, + txInfo: {}, + }; + const attackerAddress = '0x0000000000000000000000000000000000000001'; + const txParams = { + recipients: [ + { + address: attackerAddress, + amount: '1', + }, + ], + type: 'ImportToC', + locktime: 0, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild }) + .should.be.rejectedWith(/Import destination .* does not match the expected recipient/); + }); + + it('should verify import to C-chain with a lowercase recipient address (case-insensitive compare)', async () => { + // checksummed vs lowercase forms must compare equal + const txPrebuild = { + txHex: IMPORT_IN_C.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: IMPORT_IN_C.to.toLowerCase(), + amount: '1', + }, + ], + type: 'ImportToC', + locktime: 0, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + isVerified.should.equal(true); + }); + + it('should fail to verify import to P-chain with an attacker owner set (CECHO-2717)', async () => { + const txPrebuild = { + txHex: IMPORT_IN_P.signedHex, + txInfo: {}, + }; + const attackerAddress = 'P-costwo1xv5mulgpe5lt4tnx2ntnylwe79azu9vpja6lut'; + const txParams = { + recipients: [{ address: attackerAddress, amount: IMPORT_IN_P.amount }], + type: 'Import', + locktime: 0, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild }) + .should.be.rejectedWith(/Import destination .* does not match the expected wallet destination/); + }); + + it('should verify import to P-chain against the wallet rootAddress when no recipients are given', async () => { + const txPrebuild = { + txHex: IMPORT_IN_P.signedHex, + txInfo: {}, + }; + const txParams = { + recipients: [], + type: 'Import', + locktime: 0, + }; + const wallet = { + coinSpecific: () => ({ rootAddress: IMPORT_IN_P.pAddresses.join('~') }), + receiveAddress: () => undefined, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }); + isVerified.should.equal(true); + }); + + it('should fail to verify import to P-chain when the wallet rootAddress does not match the output', async () => { + const txPrebuild = { + txHex: IMPORT_IN_P.signedHex, + txInfo: {}, + }; + const txParams = { + recipients: [], + type: 'Import', + locktime: 0, + }; + const wallet = { + coinSpecific: () => ({ rootAddress: ON_CHAIN_TEST_WALLET.user.pChainAddress }), + receiveAddress: () => undefined, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild, wallet }) + .should.be.rejectedWith(/Import destination .* does not match the expected wallet destination/); + }); + + it('should fail closed when import to P-chain has no destination intent at all', async () => { + const txPrebuild = { + txHex: IMPORT_IN_P.signedHex, + txInfo: {}, + }; + const txParams = { + recipients: [], + type: 'Import', + locktime: 0, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild }) + .should.be.rejectedWith( + 'Unable to verify import destination: no expected address provided in txParams.recipients or wallet rootAddress' + ); + }); + + it('should enforce the type gate for ImportToC instead of skipping it', async () => { + // Previously 'ImportToC' was exempt from the type-match gate, so a prebuild of + // any other type (here an Export) slipped past the gate when the caller asked + // for an import. It must now throw. + const txPrebuild = { + txHex: EXPORT_IN_C.signedHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: EXPORT_IN_C.amount, + }, + ], + type: 'ImportToC', + locktime: 0, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild }) + .should.be.rejectedWith('Tx type does not match with expected txParams type'); + }); + + it('should accept the lowercase importtoc intent alias for import transactions', async () => { + const txPrebuild = { + txHex: IMPORT_IN_C.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: IMPORT_IN_C.to, + amount: '1', + }, + ], + type: 'importtoc', + locktime: 0, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + isVerified.should.equal(true); + }); + + it('should throw a clean error when the import-to-C recipient address is empty', async () => { + // Runtime guard: a missing/empty expected address must fail with a clear + // validation error, not a TypeError from calling toLowerCase on undefined. + const txPrebuild = { + txHex: IMPORT_IN_C.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: '1', + }, + ], + type: 'ImportToC', + locktime: 0, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild }) + .should.be.rejectedWith('Invalid expected C-chain import recipient: '); + }); + + it('should throw a clean error when the import-to-C recipient address is undefined', async () => { + const txPrebuild = { + txHex: IMPORT_IN_C.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [{ amount: '1' }] as unknown as { address: string; amount: string }[], + type: 'ImportToC', + locktime: 0, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild }) + .should.be.rejectedWith('Invalid expected C-chain import recipient: undefined'); + }); + + it('should reject import to P-chain when recipients conflict with the wallet rootAddress', async () => { + // Both intent sources present but disagreeing must fail closed rather than + // silently preferring one. + const txPrebuild = { + txHex: IMPORT_IN_P.signedHex, + txInfo: {}, + }; + const txParams = { + recipients: [{ address: ON_CHAIN_TEST_WALLET.user.pChainAddress, amount: IMPORT_IN_P.amount }], + type: 'Import', + locktime: 0, + }; + const wallet = { + coinSpecific: () => ({ rootAddress: IMPORT_IN_P.pAddresses.join('~') }), + receiveAddress: () => undefined, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild, wallet }) + .should.be.rejectedWith(/Import destination intent conflict/); + }); + + it('should verify import to P-chain when recipients and wallet rootAddress agree', async () => { + const txPrebuild = { + txHex: IMPORT_IN_P.signedHex, + txInfo: {}, + }; + const txParams = { + recipients: [{ address: IMPORT_IN_P.pAddresses.join('~'), amount: IMPORT_IN_P.amount }], + type: 'Import', + locktime: 0, + }; + const wallet = { + coinSpecific: () => ({ rootAddress: IMPORT_IN_P.pAddresses.slice().reverse().join('~') }), + receiveAddress: () => undefined, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }); + isVerified.should.equal(true); + }); + + it('should verify an export when the recipient carries the matching destination', async () => { + const txPrebuild = { + txHex: EXPORT_IN_C.signedHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: + 'P-costwo1zt9n96hey4fsvnde35n3k4kt5pu7c784dzewzd~P-costwo1cwrdtrgf4xh80ncu7palrjw7gn4mpj0n4dxghh~P-costwo15msvr27szvhhpmah0c38gcml7vm29xjh7tcek8', + amount: EXPORT_IN_C.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + isVerified.should.equal(true); + }); + + it('should reject an export whose destination differs from the supplied recipient', async () => { + const txPrebuild = { + txHex: EXPORT_IN_C.signedHex, + txInfo: {}, + }; + const attackerAddress = 'P-costwo1xv5mulgpe5lt4tnx2ntnylwe79azu9vpja6lut'; + const txParams = { + recipients: [ + { + address: attackerAddress, + amount: EXPORT_IN_C.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild }) + .should.be.rejectedWith(/Export destination .* does not match the expected recipient/); + }); + + it('should verify a P-to-C export whose recipient carries the C-chain destination (not comparable to the P-form output)', async () => { + // P→C exports pay the wallet's own addresses; a caller-supplied C-chain + // destination recipient must not be bound against the P-form output owner set. + const txPrebuild = { + txHex: EXPORT_IN_P.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: EXPORT_IN_C.cHexAddress, + amount: EXPORT_IN_P.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + isVerified.should.equal(true); + }); + + it('should verify import to P-chain via wallet receiveAddress when rootAddress is absent', async () => { + const txPrebuild = { + txHex: IMPORT_IN_P.signedHex, + txInfo: {}, + }; + const txParams = { + recipients: [], + type: 'Import', + locktime: 0, + }; + const wallet = { + coinSpecific: () => ({}), + receiveAddress: () => IMPORT_IN_P.pAddresses.join('~'), + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }); + isVerified.should.equal(true); + }); + + it('should reject an import whose burned fee exceeds maxImportFee', () => { + // inputs 20M, output 5M — 15M burned exceeds the network maxImportFee of 10M. + // Real explanations map outputs to { address, amount }, inputs carry value. + const maliciousExplanation = { + inputs: [ + { address: '', value: '10000000' }, + { address: '', value: '10000000' }, + ], + outputs: [{ address: IMPORT_IN_P.pAddresses.join('~'), amount: '5000000' }], + }; + + assert.throws( + () => basecoin.validateImportFee(maliciousExplanation), + /Import burns .* exceeding the network maxImportFee/ + ); + }); + + it('should accept an import whose burned fee is within maxImportFee', () => { + const explanation = { + inputs: [{ address: '', value: '50000000' }], + outputs: [{ address: IMPORT_IN_P.pAddresses.join('~'), amount: '48739000' }], + }; + + assert.doesNotThrow(() => basecoin.validateImportFee(explanation)); + }); + + it('should fail closed when import output entries lack the amount field', () => { + const malformedExplanation = { + inputs: [{ address: '', value: '50000000' }], + outputs: [{ address: IMPORT_IN_P.pAddresses.join('~') }], + }; + + assert.throws(() => basecoin.validateImportFee(malformedExplanation), /not finite numbers/); + }); }); describe('Address Validation', () => { @@ -527,8 +910,7 @@ describe('Flrp test cases', function () { }); it('should fail to validate array with invalid address', function () { - const addresses = [...EXPORT_IN_C.pAddresses, 'invalid']; - basecoin.isValidAddress(addresses).should.be.false(); + basecoin.isValidAddress([...EXPORT_IN_C.pAddresses, 'invalid']).should.be.false(); }); }); @@ -647,7 +1029,7 @@ describe('Flrp test cases', function () { outputAmount: '50000000000000', type: TransactionType.AddPermissionlessDelegator, inputs: [], - outputs: [], + outputs: [{ address: validStakingOptions.nodeID, value: '0' }], changeOutputs: [], changeAmount: '0', fee: { fee: '1000' }, @@ -702,6 +1084,114 @@ describe('Flrp test cases', function () { ); }); + it('should fail closed when the delegation transaction exposes no stake outputs', () => { + const delegationTx = { + getFlareTransaction: () => ({ + getTx: () => ({ + stake: [], + getDelegatorRewardsOwner: () => ({ addrs: [] }), + }), + }), + }; + const params = { txParams: { stakingOptions: validStakingOptions } }; + + assert.throws(() => basecoin.validateDelegationOwners(delegationTx, params), /exposes no stake outputs/); + }); + + it('should reject a delegation whose rewards owner differs from stakingOptions.rewardAddress', () => { + const attackerOwnerBytes = Buffer.alloc(20, 2); + const delegationTx = { + getFlareTransaction: () => ({ + getTx: () => ({ + stake: [{ output: { getOwners: () => [Buffer.alloc(20, 1)] } }], + getDelegatorRewardsOwner: () => ({ addrs: [{ toBytes: () => attackerOwnerBytes }] }), + }), + }), + }; + const params = { txParams: { stakingOptions: validStakingOptions } }; + + assert.throws( + () => basecoin.validateDelegationOwners(delegationTx, params), + /does not match the requested rewardAddress/ + ); + }); + + it('should reject a delegation whose stake owner is outside the wallet anchor', () => { + const delegationTx = { + getFlareTransaction: () => ({ + getTx: () => ({ + stake: [{ output: { getOwners: () => [Buffer.alloc(20, 1)] } }], + getDelegatorRewardsOwner: () => ({ addrs: [{ toBytes: () => Buffer.alloc(20, 3) }] }), + }), + }), + }; + const params = { + txParams: { stakingOptions: validStakingOptions }, + wallet: { + coinSpecific: () => ({ rootAddress: ON_CHAIN_TEST_WALLET.user.pChainAddress }), + receiveAddress: () => undefined, + }, + }; + + assert.throws( + () => basecoin.validateDelegationOwners(delegationTx, params), + /is not one of the wallet's own addresses/ + ); + }); + + it('should accept a delegation whose stake owners are a signing-key subset of the wallet owner set', () => { + // Stake outputs are built from getSigningAddresses() — two of the wallet's three + // keys (user+bitgo, or backup+bitgo in recovery) — so the stake owners are a + // subset of the wallet's full owner set, not equal to it. + const walletOwners = [ + ON_CHAIN_TEST_WALLET.user.pChainAddress, + ON_CHAIN_TEST_WALLET.bitgo.pChainAddress, + ON_CHAIN_TEST_WALLET.backup.pChainAddress, + ].join('~'); + const signingOwnerBytes = [ + utils.parseAddress(ON_CHAIN_TEST_WALLET.user.pChainAddress), + utils.parseAddress(ON_CHAIN_TEST_WALLET.bitgo.pChainAddress), + ]; + const rewardBytes = utils.parseAddress(validStakingOptions.rewardAddress); + const delegationTx = { + getFlareTransaction: () => ({ + getTx: () => ({ + stake: [{ output: { getOwners: () => signingOwnerBytes } }], + getDelegatorRewardsOwner: () => ({ addrs: [{ toBytes: () => rewardBytes }] }), + }), + }), + }; + const params = { + txParams: { stakingOptions: validStakingOptions }, + wallet: { + coinSpecific: () => ({ rootAddress: walletOwners }), + receiveAddress: () => undefined, + }, + }; + + assert.doesNotThrow(() => basecoin.validateDelegationOwners(delegationTx, params)); + }); + + it('should accept a delegation whose rewardAddress is supplied in hex form', () => { + // The builder accepts 0x-prefixed reward addresses; the comparison is by decoded + // bytes so hex, raw-hex, and P-/C- bech32 forms of the same address all match. + const rewardBytes = utils.parseAddress(validStakingOptions.rewardAddress); + const hexRewardAddress = '0x' + rewardBytes.toString('hex'); + const delegationTx = { + getFlareTransaction: () => ({ + getTx: () => ({ + stake: [{ output: { getOwners: () => [rewardBytes] } }], + getDelegatorRewardsOwner: () => ({ addrs: [{ toBytes: () => rewardBytes }] }), + }), + }), + }; + const params = { + txParams: { stakingOptions: { ...validStakingOptions, rewardAddress: hexRewardAddress } }, + }; + + assert.doesNotThrow(() => basecoin.validateDelegationOwners(delegationTx, params)); + }); + it('should throw when rewardAddress is missing', () => { const txParams = { stakingOptions: { @@ -726,6 +1216,36 @@ describe('Flrp test cases', function () { /Delegation amount mismatch/ ); }); + + it('should pass when the transaction validator nodeId matches the requested nodeID', () => { + const txParams = { stakingOptions: validStakingOptions }; + const explainedTx = { + ...validExplainedTx, + outputs: [{ address: validStakingOptions.nodeID, value: '0' }], + }; + assert.doesNotThrow(() => basecoin.validateDelegationTx(txParams, explainedTx)); + }); + + it('should throw when the transaction delegates to a different node than requested', () => { + const txParams = { stakingOptions: validStakingOptions }; + const explainedTx = { + ...validExplainedTx, + outputs: [{ address: 'NodeID-AnotherNode1234567890abcdefghijklmnopqr', value: '0' }], + }; + assert.throws(() => basecoin.validateDelegationTx(txParams, explainedTx), /Delegation nodeID mismatch/); + }); + + it('should fail closed when the delegation transaction exposes no nodeId', () => { + const txParams = { stakingOptions: validStakingOptions }; + const explainedTx = { + ...validExplainedTx, + outputs: [], + }; + assert.throws( + () => basecoin.validateDelegationTx(txParams, explainedTx), + /does not expose the validator nodeId/ + ); + }); }); }); @@ -750,21 +1270,28 @@ describe('Flrp test cases', function () { return tx.toBroadcastFormat(); } - // Helper: build unsigned MPC ImportInP tx and return its hex - async function buildUnsignedImportInP(): Promise { + // Helper: build unsigned MPC ImportInP tx and return its hex. + // outputLocktime/outputThreshold shape the destination output; utxoThreshold is the + // threshold of the consumed UTXO (which determines the imported input's sig indices). + async function buildUnsignedImportInP(opts?: { + outputLocktime?: number; + outputThreshold?: number; + utxoThreshold?: number; + }): Promise { + const { outputLocktime = 0, outputThreshold = 1, utxoThreshold = 1 } = opts ?? {}; const mpcUtxo = { outputID: 7, amount: '50000000', txid: 'aLwVQequmbhhjfhL6SvfM6MGWAB8wHwQfJ67eowEbAEUpkueN', - threshold: 1, + threshold: utxoThreshold, addresses: [ON_CHAIN_TEST_WALLET.user.pChainAddress], outputidx: '0', locktime: '0', }; const txBuilder = factory .getImportInPBuilder() - .threshold(1) - .locktime(0) + .threshold(outputThreshold) + .locktime(outputLocktime) .fromPubKey([ON_CHAIN_TEST_WALLET.user.corethAddress]) .to([ON_CHAIN_TEST_WALLET.user.pChainAddress]) .externalChainId(IMPORT_IN_P.sourceChainId) @@ -962,7 +1489,7 @@ describe('Flrp test cases', function () { const txHex = await buildUnsignedImportInP(); const txPrebuild = { txHex, txInfo: {} }; const txParams = { - recipients: [], + recipients: [{ address: ON_CHAIN_TEST_WALLET.user.pChainAddress, amount: '1' }], type: 'Import', locktime: 0, }; @@ -975,7 +1502,7 @@ describe('Flrp test cases', function () { const txHex = await buildUnsignedImportInP(); const txPrebuild = { txHex, txInfo: {} }; const txParams = { - recipients: [], + recipients: [{ address: ON_CHAIN_TEST_WALLET.user.pChainAddress, amount: '1' }], type: 'import', locktime: 0, }; @@ -1010,6 +1537,144 @@ describe('Flrp test cases', function () { isVerified.should.equal(true); }); + it('should enforce the import-to-C destination check even without txParams.type (TSS intent flow pin)', async () => { + // The MPC signing flow can reach verifyTransaction with no txParams.type; the + // destination check must not depend on it. Correct destination passes: + const txHex = await buildUnsignedImportInC(); + const txPrebuild = { txHex, txInfo: {} }; + const okParams = { + recipients: [{ address: '0x96993BAEb6AaE2e06BF95F144e2775D4f8efbD35', amount: '1' }], + locktime: 0, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams: okParams, txPrebuild }); + isVerified.should.equal(true); + + // Attacker destination without a type still rejects: + const attackerParams = { + recipients: [{ address: '0x0000000000000000000000000000000000000001', amount: '1' }], + locktime: 0, + }; + await basecoin + .verifyTransaction({ txParams: attackerParams, txPrebuild }) + .should.be.rejectedWith(/Import destination .* does not match the expected recipient/); + }); + + it('should reject an import-to-P output with a future locktime', async () => { + const futureLocktime = Math.floor(Date.now() / 1000) + 3600; + const txHex = await buildUnsignedImportInP({ outputLocktime: futureLocktime }); + const txPrebuild = { txHex, txInfo: {} }; + const txParams = { + recipients: [{ address: ON_CHAIN_TEST_WALLET.user.pChainAddress, amount: '1' }], + type: 'Import', + locktime: 0, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild }) + .should.be.rejectedWith(/Import output locktime .* must be 0/); + }); + + it('should accept an import-to-P that consumes UTXOs whose thresholds differ from the output threshold', () => { + // Inputs may carry any threshold the network accepts — the consumed atomic UTXO's + // threshold is set by whoever created it (the earlier export), so importing a + // 1-of-N UTXO into a 2-of-3 output must not throw (regression pin). + const mixedThresholdTx = { + getFlareTransaction: () => ({ + getTx: () => ({ + baseTx: { + outputs: [ + { + output: { + getLocktime: () => 0n, + getThreshold: () => 2, + getOwners: () => [Buffer.alloc(20, 1), Buffer.alloc(20, 2), Buffer.alloc(20, 3)], + }, + }, + ], + }, + ins: [{ input: { sigIndicies: () => [0] } }, { input: { sigIndicies: () => [0, 1] } }], + }), + }), + }; + + assert.doesNotThrow(() => basecoin.validateImportOutputPolicy(mixedThresholdTx)); + }); + + it('should reject an import-to-P output whose threshold is structurally invalid', () => { + // threshold 0 and threshold > owner count are both invalid output policies + const zeroThresholdTx = { + getFlareTransaction: () => ({ + getTx: () => ({ + baseTx: { + outputs: [ + { output: { getLocktime: () => 0n, getThreshold: () => 0, getOwners: () => [Buffer.alloc(20, 1)] } }, + ], + }, + ins: [{ input: { sigIndicies: () => [0] } }], + }), + }), + }; + assert.throws(() => basecoin.validateImportOutputPolicy(zeroThresholdTx), /threshold 0 is invalid/); + + const overThresholdTx = { + getFlareTransaction: () => ({ + getTx: () => ({ + baseTx: { + outputs: [ + { + output: { + getLocktime: () => 0n, + getThreshold: () => 3, + getOwners: () => [Buffer.alloc(20, 1), Buffer.alloc(20, 2)], + }, + }, + ], + }, + ins: [{ input: { sigIndicies: () => [0] } }], + }), + }), + }; + assert.throws(() => basecoin.validateImportOutputPolicy(overThresholdTx), /threshold 3 is invalid/); + }); + + it('should verify an import-to-P output with a valid 2-of-2 owner set', async () => { + const mpcUtxo = { + outputID: 7, + amount: '50000000', + txid: 'aLwVQequmbhhjfhL6SvfM6MGWAB8wHwQfJ67eowEbAEUpkueN', + threshold: 2, + addresses: [ON_CHAIN_TEST_WALLET.user.pChainAddress, ON_CHAIN_TEST_WALLET.bitgo.pChainAddress], + outputidx: '0', + locktime: '0', + }; + const txBuilder = factory + .getImportInPBuilder() + .threshold(2) + .locktime(0) + .fromPubKey([ON_CHAIN_TEST_WALLET.user.corethAddress, ON_CHAIN_TEST_WALLET.bitgo.corethAddress]) + .to([ON_CHAIN_TEST_WALLET.user.pChainAddress, ON_CHAIN_TEST_WALLET.bitgo.pChainAddress]) + .externalChainId(IMPORT_IN_P.sourceChainId) + .decodedUtxos([mpcUtxo]) + .context(IMPORT_IN_P.context as FlrpContext) + .feeState(IMPORT_IN_P.feeState as any); + const txHex = (await (await txBuilder.build()).toBroadcastFormat()) as unknown as string; + const txPrebuild = { txHex, txInfo: {} }; + const txParams = { + recipients: [ + { + address: `${ON_CHAIN_TEST_WALLET.user.pChainAddress}~${ON_CHAIN_TEST_WALLET.bitgo.pChainAddress}`, + amount: '1', + }, + ], + type: 'Import', + locktime: 0, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + isVerified.should.equal(true); + }); + it('should verify delegation transaction when txParams.type is the "stake" intent alias', async () => { const txPrebuild = { txHex: MULTISIG_DELEGATION_FULLY_SIGNED_TX_HEX, txInfo: {} }; const txParams = {