diff --git a/modules/sdk-coin-flrp/src/flrp.ts b/modules/sdk-coin-flrp/src/flrp.ts index 476ec3eb10..70602c1927 100644 --- a/modules/sdk-coin-flrp/src/flrp.ts +++ b/modules/sdk-coin-flrp/src/flrp.ts @@ -3,6 +3,8 @@ import { AuditDecryptedKeyParams, BaseCoin, BitGoBase, + EcdsaUtils, + IWallet, KeyPair, MPCAlgorithm, MultisigType, @@ -36,7 +38,15 @@ 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'; +import { pvm as FlarePvm, Common as FlareCommon, pvmSerial, UnsignedTx, TransferOutput } from '@flarenetwork/flarejs'; + +// P-chain dynamic-fee protocol constants (Flare fee weights, order: bandwidth, dbRead, +// dbWrite, compute) — the same weights the fixture feeState and flarejs use. +const PVM_FEE_WEIGHTS = { 0: 1, 1: 1000, 2: 1000, 3: 4 }; +// Ceiling on the dynamic-fee gas price used to bound export fees: ~4x the observed +// network price (251 on mainnet/testnet fee states, minPrice 250), leaving spike +// headroom while still bounding burned fees proportionally to the tx's own gas. +const GAS_PRICE_CEILING = 1_000n; /** * Normalize an address (or tilde-joined owner set) for comparison: case-insensitive @@ -136,7 +146,7 @@ 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, tx); + await this.validateExportTx(params.txParams.recipients, explainedTx, tx, params); } break; case TransactionType.Import: @@ -210,20 +220,21 @@ export class Flrp extends BaseCoin { /** * Check if export txn is valid, based on expected tx params. + * Besides the amount window, binds the exported outputs and change outputs to + * wallet-owned addresses (CECHO-2716): a malicious prebuild spending the wallet's + * UTXOs while paying an attacker-owned export output or change must fail. * * @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 + * @param {FlrpVerifyTransactionOptions} params verification params carrying the wallet */ - validateExportTx( + async 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'); - } - + tx: FlrpLib.Transaction, + params: FlrpVerifyTransactionOptions + ): Promise { const maxImportFee = (this._staticsCoin.network as FlareNetwork).maxImportFee; const recipientAmount = new BigNumber(recipients[0].amount); if ( @@ -238,12 +249,13 @@ 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. + // C→P export: the exported output pays the P-chain destination named by the + // recipient. Bind it when the caller carries the destination (CECHO-2716). + // RESIDUAL: an empty placeholder leaves the destination unbound — legitimate + // external destinations are held server-side, so wallet-binding here would + // false-reject cross-wallet exports. Tracked as CECHO-2867 (supply the + // destination client-side so it can be bound). const expectedExportDestination = recipients[0].address; if (expectedExportDestination) { if (!utils.isValidAddress(expectedExportDestination)) { @@ -256,13 +268,186 @@ export class Flrp extends BaseCoin { ); } } + } else { + // P→C export: the SDK builder pays the wallet's own addresses both for the + // exported output and for the P-chain change (baseTx.outputs) — the C destination + // is the wallet's paired C address. Require both to be wallet-owned so an + // attacker-owned export output or redirected change fails verification + // (CECHO-2716). + // + // The owner anchor is DERIVED FROM THE WALLET'S KEYCHAINS (client-verified key + // material, the same derivation isWalletAddress uses) — not from platform-served + // wallet fields: a compromised platform controls the prebuild AND + // rootAddress/receiveAddress, so those cannot anchor the ownership check. + // Fail closed when the keychain-derived owner set is unavailable. + const anchorOwners = await this.deriveWalletOwnerSetFromKeychains(params.wallet); + if (anchorOwners.size === 0) { + throw new Error('Unable to verify P-chain export: could not derive the wallet owner set from keychains'); + } + this.requireWalletOwnedAddresses('Export output', explainedTx.outputs[0].address, anchorOwners); + for (const changeOutput of explainedTx.changeOutputs) { + this.requireWalletOwnedAddresses('Export change output', changeOutput.address, anchorOwners); + } + // Locktime/threshold policy on the raw outputs (review hardening for + // CECHO-2716): a wallet-owned output with a far-future locktime or a malformed + // threshold would lock or strand the funds rather than steal them, but must + // still fail verification. + this.validateExportOutputPolicy(tx); + // Bound the implied burned fee (review hardening for CECHO-2716): the ceiling + // scales with the tx's own gas so many-input exports stay verifiable. + this.validateExportFee(explainedTx, tx); + } + } + + /** + * Derive the wallet's P-chain owner addresses from its keychain public keys — + * the same derivation isWalletAddress performs. Keychains are fetched by the + * wallet's key IDs; their public key material is the client-trusted source of + * wallet identity, unlike platform-served wallet fields (rootAddress/receiveAddress), + * which a compromised platform controls alongside the prebuild. + * TSS/MPC keychains carry the joint public key in `commonKeychain` (130 hex chars: + * 33-byte compressed public key + 32-byte chain code — the same field sdk-core's + * verifyMPCWalletAddress reads) and may not populate `pub`. The compressed public + * key is extracted from it exactly as sdk-core's EcdsaUtils does; a malformed + * commonKeychain throws and fails closed. The address is derived from the root + * public key — the same convention flrp's isWalletAddress MPC branch uses, which + * production createAddress verification already exercises. A keychain with neither + * field yields an incomplete owner set that fails closed in the caller. + * + * @param {IWallet} wallet the wallet whose keychains define the owner set + * @returns the wallet's normalized owner addresses; empty when no keychains resolve + */ + private async deriveWalletOwnerSetFromKeychains(wallet: IWallet | undefined): Promise> { + if (!wallet) { + return new Set(); + } + const keyIds = wallet.keyIds(); + if (keyIds.length === 0) { + return new Set(); + } + const keychains = await Promise.all(keyIds.map(async (keyId) => wallet.baseCoin.keychains().get({ id: keyId }))); + const publicKeys = keychains.map((keychain) => { + if (typeof keychain.pub === 'string') { + return keychain.pub; + } + if (typeof keychain.commonKeychain === 'string') { + // A TSS commonKeychain is the 33-byte compressed public key followed by the + // 32-byte chain code (130 hex chars) — NOT a bare public key. Extract the + // public key exactly as sdk-core's EcdsaUtils does; a malformed length throws + // and fails closed rather than feeding chain-code bytes to KeyPair. + return EcdsaUtils.getPublicKeyFromCommonKeychain(keychain.commonKeychain); + } + return undefined; + }); + if (publicKeys.some((pub) => typeof pub !== 'string')) { + return new Set(); + } + const networkType = this._staticsCoin.network.type; + const ownerAddresses = publicKeys.map((pub) => new FlrpLib.KeyPair({ pub: pub as string }).getAddress(networkType)); + return new Set(ownerAddresses.map((address) => address.toLowerCase())); + } + + /** + * Bind the P→C export's output spend policy (review hardening for CECHO-2716): + * every exported output and change output must be immediately spendable + * (locktime 0) and structurally sound (threshold between 1 and the owner count). + * A wallet-owned output with a far-future locktime freezes the funds; a threshold + * above the owner count strands them. The exact threshold is not bound to the + * wallet's configuration — no authoritative expected threshold reaches + * verifyTransaction (TSS wallets use 1, custodial m-of-n uses m), and the SDK's + * MPC builder legitimately produces single-key outputs, so neither threshold + * equality nor a minimum owner count can be enforced without false-rejecting + * legitimate exports. The keychain-derived wallet-ownership requirement in + * validateExportTx is what prevents platform-controlled theft; pinning the + * expected owner set / threshold by wallet type is tracked as CECHO-2868. + * + * @param {FlrpLib.Transaction} tx parsed P→C export carrying the raw outputs + * @throws Error when any output locktime is nonzero or its threshold is invalid + */ + private validateExportOutputPolicy(tx: FlrpLib.Transaction): void { + const pvmExportTx = (tx.getFlareTransaction() as UnsignedTx).getTx() as pvmSerial.ExportTx; + const outputs = [...pvmExportTx.outs, ...pvmExportTx.baseTx.outputs]; + for (const transferableOutput of outputs) { + const output = transferableOutput.output as TransferOutput; + const locktime = output.getLocktime(); + if (locktime !== 0n) { + throw new Error( + `Export output locktime ${locktime} must be 0 — a time-locked output would freeze the wallet's funds` + ); + } + const threshold = output.getThreshold(); + const ownerCount = output.getOwners().length; + if (threshold < 1 || threshold > ownerCount) { + throw new Error( + `Export output threshold ${threshold} is invalid for ${ownerCount} owner(s); refusing to verify` + ); + } + } + } + + /** + * Bound the fee burned by a P→C export (review hardening for CECHO-2716): the + * difference between the consumed input value and the exported amount plus change + * is burned as the export fee. Without this check, a prebuild with a tiny + * wallet-owned change output could burn the remainder of the spent UTXOs as fee + * and still verify. + * + * The ceiling scales with the tx's own gas (flarejs getTxComplexity × the P-chain + * fee weights, times a gas-price ceiling of ~4x the observed network price) — a + * flat cap would false-reject legitimate many-input exports, since the P-chain + * dynamic fee grows linearly with input count (~1M nFLR per 2-of-3 input at the + * observed price 251, so ≥10 inputs already exceed the flat maxImportFee). The + * flat maxImportFee remains the floor of the bound. Fails closed when any total + * is not a finite number. + * + * @param {FlrpLib.TransactionExplanation} explainedTx parsed export explanation + * @param {FlrpLib.Transaction} tx parsed export carrying the raw tx for gas computation + * @throws Error when the burned fee exceeds the complexity-scaled fee bound or + * totals are not finite + */ + private validateExportFee(explainedTx: FlrpLib.TransactionExplanation, tx: FlrpLib.Transaction): void { + const maxImportFee = (this._staticsCoin.network as FlareNetwork).maxImportFee; + // Input entries carry `value`; output and change entries carry `amount`. + const consumedTotal = (explainedTx.inputs as unknown as FlrpEntry[]).reduce( + (sum, input) => sum.plus(input.value), + new BigNumber(0) + ); + const payoutTotal = explainedTx.outputs + .concat(explainedTx.changeOutputs) + .reduce((sum, output) => sum.plus((output as unknown as FlrpEntry).value ?? output.amount), new BigNumber(0)); + if (!consumedTotal.isFinite() || !payoutTotal.isFinite()) { + throw new Error('Export fee bound: input/output totals are not finite numbers; refusing to verify'); + } + const burnedFee = consumedTotal.minus(payoutTotal); + // Ceiling = flat network fee bound + the tx's own gas at a spike-adjusted price. + const rawTx = (tx.getFlareTransaction() as UnsignedTx).getTx(); + const gas = FlareCommon.dimensionsToGas(FlarePvm.getTxComplexity(rawTx), PVM_FEE_WEIGHTS); + const feeCeiling = new BigNumber(maxImportFee).plus(new BigNumber((gas * GAS_PRICE_CEILING).toString())); + if (burnedFee.isGreaterThan(feeCeiling)) { + throw new Error( + `Export burns ${burnedFee.toString()} in fees, exceeding the complexity-scaled fee bound ${feeCeiling.toString()} (gas ${gas} at price ${GAS_PRICE_CEILING})` + ); + } + } + + /** + * Require every address in an (optionally tilde-joined) owner set to be one of the + * wallet's own addresses. Addresses are normalized (case-insensitive, sorted). + * + * @param {string} label which output is being checked, for the error message + * @param {string} address the output's tilde-joined owner-set address from the parsed tx + * @param {Set} anchorOwners the wallet's normalized owner addresses + */ + private requireWalletOwnedAddresses(label: string, address: string, anchorOwners: Set): void { + if (!utils.isValidAddress(address)) { + throw new Error(`Invalid ${label} address: ${address}`); + } + const foreignOwner = normalizeAddressSet(address) + .split(ADDRESS_SEPARATOR) + .find((owner) => !anchorOwners.has(owner)); + if (foreignOwner) { + throw new Error(`${label} pays non-wallet address ${foreignOwner}; refusing to verify`); } - // 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. } /** diff --git a/modules/sdk-coin-flrp/test/unit/flrp.ts b/modules/sdk-coin-flrp/test/unit/flrp.ts index 915a95fa56..f397979ba3 100644 --- a/modules/sdk-coin-flrp/test/unit/flrp.ts +++ b/modules/sdk-coin-flrp/test/unit/flrp.ts @@ -17,9 +17,33 @@ import { } from '../resources/transactionData/multisigDelegationTx'; import { HalfSignedAccountTransaction, TransactionType, MPCAlgorithm, common } from '@bitgo/sdk-core'; import { secp256k1, TypeSymbols } from '@flarenetwork/flarejs'; -import { FlrpContext } from '@bitgo/public-types'; +import { FlrpContext, FlrpFeeState } from '@bitgo/public-types'; import assert from 'assert'; import nock from 'nock'; +// Wallet mock whose owner set is derived from keychain public key material, +// mirroring the SDK's keychain-based ownership derivation in verifyTransaction +// (CECHO-2716). keyMaterial selects the keychain field: 'pub' (default) or +// 'commonKeychain'. The commonKeychain form stores the REAL TSS shape — the +// 66-char compressed public key followed by a 64-char chain code (130 chars), +// as sdk-core's EcdsaUtils.getPublicKeyFromCommonKeychain expects. +function keychainWallet(privKeys: string[], keyMaterial: 'pub' | 'commonKeychain' = 'pub') { + return { + keyIds: () => privKeys.map((_, i) => `${i}`), + baseCoin: { + keychains: () => ({ + get: async ({ id }: { id: string }) => { + const pub = new FlrpLib.KeyPair({ prv: privKeys[Number(id)] }).getKeys().pub; + return { [keyMaterial]: keyMaterial === 'commonKeychain' ? pub + '0'.repeat(64) : pub }; + }, + }), + }, + // Import-side verification reads wallet-anchored fields even when the recipient + // intent is present; the mock returns no rootAddress (undefined) so the + // recipients-only path is exercised. + coinSpecific: () => ({}), + receiveAddress: () => undefined, + }; +} import { CreatePairedWalletResponse } from '../../src/lib/iface'; describe('Flrp test cases', function () { @@ -381,8 +405,9 @@ describe('Flrp test cases', function () { type: 'Export', locktime: 0, }; + const wallet = keychainWallet(EXPORT_IN_P.privateKeys); - const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }); isVerified.should.equal(true); }); @@ -510,6 +535,321 @@ describe('Flrp test cases', function () { .should.be.rejectedWith('Expected 1 recipient in import transaction'); }); + it('should reject a P-to-C export whose exported output pays a foreign owner set (CECHO-2716)', async () => { + // Amount and shape match, but the exporting wallet's keychains (the trust + // anchor, derived client-side) do not own the fixture tx's outputs — exactly + // what a malicious prebuild paying an attacker looks like. + const txPrebuild = { + txHex: EXPORT_IN_P.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: EXPORT_IN_P.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + const wallet = keychainWallet([ON_CHAIN_TEST_WALLET.user.privateKey]); + + await basecoin + .verifyTransaction({ txParams, txPrebuild, wallet }) + .should.be.rejectedWith(/Export output pays non-wallet address/); + }); + + it('should reject a P-to-C export whose change output pays an attacker (CECHO-2716)', () => { + // The SDK builder computes change back to the wallet; a malicious prebuild can + // redirect it. Unit-test the owner binding directly with a crafted explanation. + const walletAnchor = EXPORT_IN_P.pAddresses.join('~'); + const anchorOwners = new Set( + walletAnchor + .split('~') + .map((a) => a.toLowerCase()) + .sort() + ); + const attackerChange = ON_CHAIN_TEST_WALLET.user.pChainAddress; + + assert.throws( + () => basecoin.requireWalletOwnedAddresses('Export change output', attackerChange, anchorOwners), + /Export change output pays non-wallet address/ + ); + }); + + it('should reject a P-to-C export with a mixed owner set (one wallet address, one attacker address)', () => { + // Subset containment must catch a single foreign owner hidden inside a + // wallet-majority owner set, not just fully-foreign destinations. + const walletAnchor = EXPORT_IN_P.pAddresses.join('~'); + const anchorOwners = new Set( + walletAnchor + .split('~') + .map((a) => a.toLowerCase()) + .sort() + ); + const mixedOwnerSet = `${EXPORT_IN_P.pAddresses[0]}~${ON_CHAIN_TEST_WALLET.user.pChainAddress}`; + + assert.throws( + () => basecoin.requireWalletOwnedAddresses('Export output', mixedOwnerSet, anchorOwners), + /Export output pays non-wallet address/ + ); + }); + + it('should fail closed on a P-to-C export with no wallet anchor', async () => { + const txPrebuild = { + txHex: EXPORT_IN_P.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: EXPORT_IN_P.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild }) + .should.be.rejectedWith( + 'Unable to verify P-chain export: could not derive the wallet owner set from keychains' + ); + }); + + it('should verify a P-to-C export anchored on keychains that carry only commonKeychain (TSS shape)', async () => { + // TSS/MPC keychains carry the joint public key in commonKeychain and may not + // populate pub — the derivation must accept both fields. + const txPrebuild = { + txHex: EXPORT_IN_P.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: EXPORT_IN_P.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + const wallet = keychainWallet(EXPORT_IN_P.privateKeys, 'commonKeychain'); + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }); + isVerified.should.equal(true); + }); + + it('should fail closed when a commonKeychain is not the real TSS shape (not 130 hex chars)', async () => { + // A bare 66-char public key stored in commonKeychain is not the real shape + // (33-byte compressed pubkey + 32-byte chain code); the extraction must throw + // rather than feed the field to KeyPair as-is. + const txPrebuild = { + txHex: EXPORT_IN_P.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: EXPORT_IN_P.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + const pub = new FlrpLib.KeyPair({ prv: ON_CHAIN_TEST_WALLET.user.privateKey }).getKeys().pub; + const wallet = { + keyIds: () => ['0'], + baseCoin: { + keychains: () => ({ + get: async () => ({ commonKeychain: pub }), + }), + }, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild, wallet }) + .should.be.rejectedWith(/Invalid commonKeychain length, expected 130/); + }); + + it('should fail closed when keychains carry neither pub nor commonKeychain', async () => { + const txPrebuild = { + txHex: EXPORT_IN_P.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: EXPORT_IN_P.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + const wallet = { + keyIds: () => ['0'], + baseCoin: { + keychains: () => ({ + get: async () => ({ ethAddress: '0xirrelevant' }), + }), + }, + }; + + await basecoin + .verifyTransaction({ txParams, txPrebuild, wallet }) + .should.be.rejectedWith( + 'Unable to verify P-chain export: could not derive the wallet owner set from keychains' + ); + }); + + it('should fail closed when a keychain fetch rejects', async () => { + const txPrebuild = { + txHex: EXPORT_IN_P.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: EXPORT_IN_P.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + const wallet = { + keyIds: () => ['0'], + baseCoin: { + keychains: () => ({ + get: async () => { + throw new Error('keychain not found'); + }, + }), + }, + }; + + await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }).should.be.rejectedWith('keychain not found'); + }); + + it('should reject a P-to-C export that burns more than the complexity-scaled fee bound', async () => { + // inputs 60M, exported 30M, change 0.5M — 29.5M burned exceeds the ceiling + // (flat 10M maxImportFee + the fixture tx's ~9.1k gas at price 1000 ≈ 19.1M). + // Gas is computed from the real fixture tx parsed below. + const factory = new FlrpLib.TransactionBuilderFactory(coins.get('tflrp')); + const tx = await factory.from(EXPORT_IN_P.fullSigntxHex).build(); + const maliciousExplanation = { + inputs: [{ address: '', value: '60000000' }], + outputs: [{ address: EXPORT_IN_P.pAddresses.join('~'), amount: '30000000' }], + changeOutputs: [{ address: EXPORT_IN_P.pAddresses.join('~'), amount: '500000' }], + }; + + assert.throws( + () => basecoin.validateExportFee(maliciousExplanation, tx), + /Export burns .* exceeding the complexity-scaled fee bound/ + ); + }); + + it('should accept a P-to-C export whose burned fee is within the complexity-scaled fee bound', async () => { + // Fixture shape: inputs 50M, exported 30M, change 18.69M — ~1.31M burned, + // well under the flat 10M floor alone. + const factory = new FlrpLib.TransactionBuilderFactory(coins.get('tflrp')); + const tx = await factory.from(EXPORT_IN_P.fullSigntxHex).build(); + const explanation = { + inputs: [{ address: '', value: '50000000' }], + outputs: [{ address: EXPORT_IN_P.pAddresses.join('~'), amount: '30000000' }], + changeOutputs: [{ address: EXPORT_IN_P.pAddresses.join('~'), amount: '18691035' }], + }; + + assert.doesNotThrow(() => basecoin.validateExportFee(explanation, tx)); + }); + + it('should accept a many-input export whose dynamic fee exceeds the flat maxImportFee', async () => { + // Models a 10-input consolidation export: the P-chain dynamic fee grows + // linearly with input count (~1M nFLR per 2-of-3 input at price 251), so + // 10 inputs legitimately burn ~11M — above the flat 10M cap but within the + // complexity-scaled ceiling. Without the gas-scaled bound this false-rejects. + const factory = new FlrpLib.TransactionBuilderFactory(coins.get('tflrp')); + const tx = await factory.from(EXPORT_IN_P.fullSigntxHex).build(); + const explanation = { + inputs: Array.from({ length: 10 }, () => ({ address: '', value: '5000000' })), + outputs: [{ address: EXPORT_IN_P.pAddresses.join('~'), amount: '30000000' }], + changeOutputs: [{ address: EXPORT_IN_P.pAddresses.join('~'), amount: '9000000' }], + }; + + assert.doesNotThrow(() => basecoin.validateExportFee(explanation, tx)); + }); + + it('should verify a P-to-C export whose outputs and change are wallet-owned', async () => { + // The fixture export pays the wallet owner set for both the exported output and + // the P-chain change; subset containment against the wallet anchor holds. + const txPrebuild = { + txHex: EXPORT_IN_P.fullSigntxHex, + txInfo: {}, + }; + const txParams = { + recipients: [ + { + address: '', + amount: EXPORT_IN_P.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + const wallet = keychainWallet(EXPORT_IN_P.privateKeys); + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }); + isVerified.should.equal(true); + }); + + it('should bind a C-to-P export to the named recipient destination (CECHO-2716)', async () => { + const txPrebuild = { + txHex: EXPORT_IN_C.signedHex, + txInfo: {}, + }; + const destination = + 'P-costwo1zt9n96hey4fsvnde35n3k4kt5pu7c784dzewzd~P-costwo1cwrdtrgf4xh80ncu7palrjw7gn4mpj0n4dxghh~P-costwo15msvr27szvhhpmah0c38gcml7vm29xjh7tcek8'; + const txParams = { + recipients: [ + { + address: destination, + amount: EXPORT_IN_C.amount, + }, + ], + type: 'Export', + locktime: 0, + }; + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + isVerified.should.equal(true); + }); + + it('should reject a C-to-P export whose destination differs from the named recipient', async () => { + const txPrebuild = { + txHex: EXPORT_IN_C.signedHex, + txInfo: {}, + }; + const attackerDestination = 'P-costwo1xv5mulgpe5lt4tnx2ntnylwe79azu9vpja6lut'; + const txParams = { + recipients: [ + { + address: attackerDestination, + 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 fail to verify import to C-chain with an attacker destination (CECHO-2717)', async () => { const txPrebuild = { txHex: IMPORT_IN_C.fullSigntxHex, @@ -811,8 +1151,9 @@ describe('Flrp test cases', function () { type: 'Export', locktime: 0, }; + const wallet = keychainWallet(EXPORT_IN_P.privateKeys); - const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }); isVerified.should.equal(true); }); @@ -1556,7 +1897,11 @@ describe('Flrp test cases', function () { } // Helper: build unsigned MPC ExportInP tx and return its hex - async function buildUnsignedExportInP(): Promise { + // Helper: build unsigned MPC ExportInP tx and return its hex. + // amount/locktime shape the exported output (a full-spend amount produces no + // change output; a future locktime produces a time-locked output). + async function buildUnsignedExportInP(opts?: { amount?: string; locktime?: number }): Promise { + const { amount = '30000000', locktime = 0 } = opts ?? {}; const mpcUtxo = { outputID: 7, amount: '50000000', @@ -1569,13 +1914,13 @@ describe('Flrp test cases', function () { const txBuilder = factory .getExportInPBuilder() .threshold(1) - .locktime(0) + .locktime(locktime) .fromPubKey([ON_CHAIN_TEST_WALLET.user.pChainAddress]) - .amount('30000000') + .amount(amount) .externalChainId(EXPORT_IN_P.sourceChainId) .decodedUtxos([mpcUtxo]) .context(EXPORT_IN_P.context as FlrpContext) - .feeState(EXPORT_IN_P.feeState as any); + .feeState(EXPORT_IN_P.feeState as unknown as FlrpFeeState); const tx = await txBuilder.build(); return tx.toBroadcastFormat(); @@ -1771,11 +2116,46 @@ describe('Flrp test cases', function () { type: 'Export', locktime: 0, }; + const wallet = keychainWallet([ON_CHAIN_TEST_WALLET.user.privateKey]); - const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }); + isVerified.should.equal(true); + }); + + it('should verify a P-to-C export with no change outputs (full-spend export)', async () => { + // Exporting the entire spendable amount leaves no P-chain change output; + // the empty change list must verify cleanly. + const txHex = await buildUnsignedExportInP({ amount: '48739000' }); + const txPrebuild = { txHex, txInfo: {} }; + const txParams = { + recipients: [{ address: ON_CHAIN_TEST_WALLET.user.pChainAddress, amount: '48739000' }], + type: 'Export', + locktime: 0, + }; + const wallet = keychainWallet([ON_CHAIN_TEST_WALLET.user.privateKey]); + + const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, wallet }); isVerified.should.equal(true); }); + it('should reject a P-to-C export whose output has a future locktime', async () => { + // Wallet-owned output, matching amount — but time-locked funds would be + // frozen until the locktime passes; verification must fail. + const futureLocktime = Math.floor(Date.now() / 1000) + 3600; + const txHex = await buildUnsignedExportInP({ locktime: futureLocktime }); + const txPrebuild = { txHex, txInfo: {} }; + const txParams = { + recipients: [{ address: ON_CHAIN_TEST_WALLET.user.pChainAddress, amount: '30000000' }], + type: 'Export', + locktime: 0, + }; + const wallet = keychainWallet([ON_CHAIN_TEST_WALLET.user.privateKey]); + + await basecoin + .verifyTransaction({ txParams, txPrebuild, wallet }) + .should.be.rejectedWith(/Export output locktime .* must be 0/); + }); + it('should verify MPC ImportInC transaction', async () => { const txHex = await buildUnsignedImportInC(); const txPrebuild = { txHex, txInfo: {} }; @@ -1988,10 +2368,12 @@ describe('Flrp test cases', function () { locktime: 0, }; + const wallet = keychainWallet([ON_CHAIN_TEST_WALLET.user.privateKey]); const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, walletType: 'tss', + wallet, }); isVerified.should.equal(true); }); @@ -2005,10 +2387,12 @@ describe('Flrp test cases', function () { locktime: 0, }; + const wallet = keychainWallet([ON_CHAIN_TEST_WALLET.user.privateKey]); const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, walletType: 'tss', + wallet, }); isVerified.should.equal(true); }); @@ -2022,10 +2406,12 @@ describe('Flrp test cases', function () { locktime: 0, }; + const wallet = keychainWallet([ON_CHAIN_TEST_WALLET.user.privateKey]); const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild, walletType: 'tss', + wallet, }); isVerified.should.equal(true); });