From 70c2773d0a0b3717ff2fb101a9d83631dd0ea602 Mon Sep 17 00:00:00 2001 From: prithvishet2503 Date: Mon, 23 Nov 2026 11:57:49 +0530 Subject: [PATCH] fix(sdk-coin-flrp): gas-aware import fee bound and wallet-threshold binding Two review follow-ups for the CECHO-2717 import verification hardening: - validateImportFee capped every import at the flat statics maxImportFee (10,000,000 nFLR), rejecting correctly built large imports: flarejs charges per serialized byte and per signature slot, so 400 one-signature inputs at the 25 nFLR/gas fixture base fee legitimately burn >= 11,070,000 nFLR. The bound is now gas-aware: the burned fee must stay under max(maxImportFee, gasCost x 1000 nFLR/gas), where gasCost mirrors flarejs's own import gas model (bytes + 1000 gas per signature + 10000 base gas) computed from the parsed transaction under verification. Protection against excessive fees is retained: a prebuild burning above its own gas cost at the ceiling rate still fails. - validateImportOutputPolicy only checked the output threshold's range, so a prebuild weakening the spend policy over the wallet's own addresses (e.g. a 1-of-3 output for a 2-of-3 wallet) passed verification. The output threshold must now equal the wallet record's spend threshold - the same independently established value wallet-platform passes to the import builder - and a missing wallet threshold fails closed. Ticket: CECHO-2717 --- modules/sdk-coin-flrp/src/flrp.ts | 104 ++++++++++++--- modules/sdk-coin-flrp/test/unit/flrp.ts | 165 +++++++++++++++++++++--- 2 files changed, 231 insertions(+), 38 deletions(-) diff --git a/modules/sdk-coin-flrp/src/flrp.ts b/modules/sdk-coin-flrp/src/flrp.ts index a54a99342c..3faf945c77 100644 --- a/modules/sdk-coin-flrp/src/flrp.ts +++ b/modules/sdk-coin-flrp/src/flrp.ts @@ -38,6 +38,24 @@ import BigNumber from 'bignumber.js'; import { isValidAddress as isValidEthAddress } from 'ethereumjs-util'; import { pvmSerial, TransferOutput, UnsignedTx } from '@flarenetwork/flarejs'; +/** + * FlareJS import gas model, mirroring the gas-cost function flarejs applies in + * newImportTxFromBaseFee: one gas per serialized unsigned-tx byte, gas per signature + * slot, plus the fixed AtomicTxBaseCost. + */ +const IMPORT_GAS_PER_SIGNATURE = 1000n; +const IMPORT_TX_BASE_GAS = 10000n; + +/** + * Verification-time ceiling on the per-gas fee rate (nFLR per gas unit) an import may + * burn (CECHO-2717 review follow-up). Flare C-chain base fees are historically in the + * tens of nFLR per gas (the CECHO-2717 fixtures use 25); 1000 nFLR/gas is ~40x that, + * absorbing base-fee volatility and P-chain fee-state spikes while still bounding a + * compromised prebuild: the burned fee can never exceed gasCost x 1000, however many + * UTXOs the import consumes. + */ +const MAX_IMPORT_FEE_RATE_PER_GAS = 1000n; + /** * 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 @@ -173,7 +191,7 @@ export class Flrp extends BaseCoin { ); } this.validateImportTx(explainedTx.inputs, params.txParams); - this.validateImportFee(explainedTx); + this.validateImportFee(explainedTx, tx); } else { // 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). @@ -182,8 +200,8 @@ export class Flrp extends BaseCoin { } this.validateImportTx(explainedTx.inputs, params.txParams); this.validateImportDestination(explainedTx.outputs[0].address, params); - this.validateImportOutputPolicy(tx); - this.validateImportFee(explainedTx); + this.validateImportOutputPolicy(tx, params); + this.validateImportFee(explainedTx, tx); } break; case TransactionType.AddPermissionlessDelegator: @@ -338,23 +356,27 @@ export class Flrp extends BaseCoin { /** * 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). + * be structurally sound (threshold between 1 and the owner count), and — the binding + * that matters — spend with the wallet's own spend policy: the output threshold must + * equal the threshold on the wallet record (1 for TSS wallets, 2 for 2-of-3 multisig), + * the same independently established value wallet-platform passes to the import + * builder. A prebuild weakening the spend policy over the wallet's own addresses + * (for example a 1-of-3 output for a 2-of-3 wallet) must fail verification, and a + * missing wallet threshold fails closed rather than falling back to the loose range + * check. * * 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. + * into a 2-of-3 output is valid. * * @param {FlrpLib.Transaction} tx the parsed transaction carrying the raw outputs + * @param {FlrpVerifyTransactionOptions} params verification params carrying the wallet record * @throws Error when the output locktime is nonzero, the import consumes no UTXOs, - * or the output threshold is structurally invalid + * the output threshold is structurally invalid, or the output threshold does not + * match the wallet's spend threshold */ - validateImportOutputPolicy(tx: FlrpLib.Transaction): void { + validateImportOutputPolicy(tx: FlrpLib.Transaction, params: FlrpVerifyTransactionOptions): void { const pvmImportTx = (tx.getFlareTransaction() as UnsignedTx).getTx() as pvmSerial.ImportTx; const output = pvmImportTx.baseTx.outputs[0].output as TransferOutput; @@ -374,19 +396,43 @@ export class Flrp extends BaseCoin { if (threshold < 1 || threshold > ownerCount) { throw new Error(`Import output threshold ${threshold} is invalid for ${ownerCount} owner(s); refusing to verify`); } + + // The wallet record is platform wallet data, not the prebuild under verification — + // the threshold it carries is the independently established wallet spend policy. + // Cast: the flrp wallet subdocument serializes its P-chain spend threshold into + // coinSpecific (wallet-platform flrp.schema), which sdk-core's WalletCoinSpecific + // does not model; the typeof guard below validates the value before use. + const coinSpecific = params.wallet?.coinSpecific() as { threshold?: unknown } | undefined; + const walletThreshold = coinSpecific?.threshold; + if (typeof walletThreshold !== 'number' || !Number.isInteger(walletThreshold) || walletThreshold < 1) { + throw new Error( + 'Import output threshold cannot be verified: the wallet spend threshold is unavailable; refusing to verify' + ); + } + if (threshold !== walletThreshold) { + throw new Error( + `Import output threshold ${threshold} does not match the wallet's spend threshold ${walletThreshold}; 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. + * import fee. The bound is gas-aware because flarejs charges per serialized byte + * and per signature slot (plus the fixed AtomicTxBaseCost): a large import + * legitimately burns a fee that scales with its own size, so a flat cap alone would + * reject every such import. The burned fee must stay within the larger of the + * network's flat maxImportFee and this transaction's own gas cost priced at the + * MAX_IMPORT_FEE_RATE_PER_GAS ceiling — a prebuild paying the right destination a + * dust amount while burning the rest as fee still exceeds that bound and fails. * * @param {FlrpLib.TransactionExplanation} explainedTx parsed import explanation - * @throws Error when the burned fee exceeds the network's maxImportFee + * @param {FlrpLib.Transaction} tx the parsed transaction whose gas cost bounds the fee + * @throws Error when the burned fee exceeds the gas-aware import fee bound */ - validateImportFee(explainedTx: FlrpLib.TransactionExplanation): void { - const maxImportFee = (this._staticsCoin.network as FlareNetwork).maxImportFee; + validateImportFee(explainedTx: FlrpLib.TransactionExplanation, tx: FlrpLib.Transaction): void { + const maxImportFee = new BigNumber((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. @@ -399,13 +445,33 @@ export class Flrp extends BaseCoin { 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)) { + const feeBound = BigNumber.max(maxImportFee, this.importGasCost(tx).times(MAX_IMPORT_FEE_RATE_PER_GAS.toString())); + if (burnedFee.isGreaterThan(feeBound)) { throw new Error( - `Import burns ${burnedFee.toString()} in fees, exceeding the network maxImportFee ${maxImportFee}` + `Import burns ${burnedFee.toString()} in fees, exceeding the gas-aware import fee bound ${feeBound.toString()} (network maxImportFee ${maxImportFee.toString()})` ); } } + /** + * Gas this import charges under FlareJS's import gas model: one gas per serialized + * unsigned-tx byte, IMPORT_GAS_PER_SIGNATURE per signature slot, plus the fixed + * IMPORT_TX_BASE_GAS (AtomicTxBaseCost). Mirrors the gas-cost function flarejs + * applies in newImportTxFromBaseFee, computed from the parsed transaction under + * verification so the fee bound tracks the transaction's real cost. + * + * @param {FlrpLib.Transaction} tx the parsed import transaction + * @returns {BigNumber} the import's gas cost in gas units + */ + importGasCost(tx: FlrpLib.Transaction): BigNumber { + const unsignedTx = tx.getFlareTransaction() as UnsignedTx; + const sigIndices = unsignedTx.getSigIndices() as number[][]; + const signatureCount = sigIndices.reduce((total, indices) => total + indices.length, 0); + const gasUnits = + BigInt(unsignedTx.toBytes().length) + IMPORT_GAS_PER_SIGNATURE * BigInt(signatureCount) + IMPORT_TX_BASE_GAS; + return new BigNumber(gasUnits.toString()); + } + /** * Validate AddPermissionlessDelegator transaction parameters. * Validates both expected txParams and the parsed explainedTx for consistency. diff --git a/modules/sdk-coin-flrp/test/unit/flrp.ts b/modules/sdk-coin-flrp/test/unit/flrp.ts index 9029c832f4..164cb8a3c0 100644 --- a/modules/sdk-coin-flrp/test/unit/flrp.ts +++ b/modules/sdk-coin-flrp/test/unit/flrp.ts @@ -417,7 +417,11 @@ describe('Flrp test cases', function () { locktime: 0, }; - const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + const isVerified = await basecoin.verifyTransaction({ + txParams, + txPrebuild, + wallet: { coinSpecific: () => ({ threshold: 2 }), receiveAddress: () => undefined }, + }); isVerified.should.equal(true); }); @@ -581,7 +585,7 @@ describe('Flrp test cases', function () { locktime: 0, }; const wallet = { - coinSpecific: () => ({ rootAddress: IMPORT_IN_P.pAddresses.join('~') }), + coinSpecific: () => ({ rootAddress: IMPORT_IN_P.pAddresses.join('~'), threshold: 2 }), receiveAddress: () => undefined, }; @@ -743,7 +747,7 @@ describe('Flrp test cases', function () { locktime: 0, }; const wallet = { - coinSpecific: () => ({ rootAddress: IMPORT_IN_P.pAddresses.slice().reverse().join('~') }), + coinSpecific: () => ({ rootAddress: IMPORT_IN_P.pAddresses.slice().reverse().join('~'), threshold: 2 }), receiveAddress: () => undefined, }; @@ -827,7 +831,7 @@ describe('Flrp test cases', function () { locktime: 0, }; const wallet = { - coinSpecific: () => ({}), + coinSpecific: () => ({ threshold: 2 }), receiveAddress: () => IMPORT_IN_P.pAddresses.join('~'), }; @@ -835,9 +839,11 @@ describe('Flrp test cases', function () { 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. + it('should reject an import whose burned fee exceeds the gas-aware fee bound', async () => { + // inputs 20M, output 5M — 15M burned exceeds both the network maxImportFee (10M) + // and the fixture tx's gas-aware bound (gasCost x 1000). Real explanations map + // outputs to { address, amount }, inputs carry value. + const tx = await basecoin.getBuilder().from(IMPORT_IN_P.signedHex).build(); const maliciousExplanation = { inputs: [ { address: '', value: '10000000' }, @@ -847,27 +853,64 @@ describe('Flrp test cases', function () { }; assert.throws( - () => basecoin.validateImportFee(maliciousExplanation), - /Import burns .* exceeding the network maxImportFee/ + () => basecoin.validateImportFee(maliciousExplanation, tx), + /Import burns .* exceeding the gas-aware import fee bound/ ); }); - it('should accept an import whose burned fee is within maxImportFee', () => { + it('should accept an import whose burned fee is within the flat maxImportFee', async () => { + const tx = await basecoin.getBuilder().from(IMPORT_IN_P.signedHex).build(); const explanation = { inputs: [{ address: '', value: '50000000' }], outputs: [{ address: IMPORT_IN_P.pAddresses.join('~'), amount: '48739000' }], }; - assert.doesNotThrow(() => basecoin.validateImportFee(explanation)); + assert.doesNotThrow(() => basecoin.validateImportFee(explanation, tx)); + }); + + it('should accept a large import whose gas-scaled fee exceeds the flat maxImportFee (CECHO-2717 review)', async () => { + // flarejs charges per serialized byte and per signature, so a large import's + // legitimate fee scales with its own gas cost and can exceed the flat 10M + // maxImportFee. The burned fee must be accepted whenever it stays under the + // transaction's gas-aware bound (gasCost x MAX_IMPORT_FEE_RATE_PER_GAS). + const tx = await basecoin.getBuilder().from(IMPORT_IN_P.signedHex).build(); + const gasAwareBound = basecoin.importGasCost(tx).times(1000).toNumber(); + const maxImportFee = 10000000; + gasAwareBound.should.be.greaterThan(maxImportFee); + + // burned fee above the flat cap but below the gas-aware bound must pass + const burned = maxImportFee + 1; + const explanation = { + inputs: [{ address: '', value: (50000000 + burned).toString() }], + outputs: [{ address: IMPORT_IN_P.pAddresses.join('~'), amount: '50000000' }], + }; + + assert.doesNotThrow(() => basecoin.validateImportFee(explanation, tx)); + }); + + it('should reject an import whose burned fee exceeds the gas-aware bound even when inputs are many', async () => { + const tx = await basecoin.getBuilder().from(IMPORT_IN_P.signedHex).build(); + const gasAwareBound = basecoin.importGasCost(tx).times(1000).toNumber(); + + // burned fee one unit above the gas-aware bound must fail — the bound retains + // protection against excessive fees no matter how the prebuild is shaped + const burned = gasAwareBound + 1; + const explanation = { + inputs: [{ address: '', value: (50000000 + burned).toString() }], + outputs: [{ address: IMPORT_IN_P.pAddresses.join('~'), amount: '50000000' }], + }; + + assert.throws(() => basecoin.validateImportFee(explanation, tx), /exceeding the gas-aware import fee bound/); }); - it('should fail closed when import output entries lack the amount field', () => { + it('should fail closed when import output entries lack the amount field', async () => { + const tx = await basecoin.getBuilder().from(IMPORT_IN_P.signedHex).build(); const malformedExplanation = { inputs: [{ address: '', value: '50000000' }], outputs: [{ address: IMPORT_IN_P.pAddresses.join('~') }], }; - assert.throws(() => basecoin.validateImportFee(malformedExplanation), /not finite numbers/); + assert.throws(() => basecoin.validateImportFee(malformedExplanation, tx), /not finite numbers/); }); }); @@ -1494,7 +1537,11 @@ describe('Flrp test cases', function () { locktime: 0, }; - const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + const isVerified = await basecoin.verifyTransaction({ + txParams, + txPrebuild, + wallet: { coinSpecific: () => ({ threshold: 1 }), receiveAddress: () => undefined }, + }); isVerified.should.equal(true); }); @@ -1507,7 +1554,11 @@ describe('Flrp test cases', function () { locktime: 0, }; - const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + const isVerified = await basecoin.verifyTransaction({ + txParams, + txPrebuild, + wallet: { coinSpecific: () => ({ threshold: 1 }), receiveAddress: () => undefined }, + }); isVerified.should.equal(true); }); @@ -1598,7 +1649,78 @@ describe('Flrp test cases', function () { }), }; - assert.doesNotThrow(() => basecoin.validateImportOutputPolicy(mixedThresholdTx)); + assert.doesNotThrow(() => + basecoin.validateImportOutputPolicy(mixedThresholdTx, { + wallet: { coinSpecific: () => ({ threshold: 2 }) }, + }) + ); + }); + + it('should reject an import-to-P output whose threshold does not match the wallet spend threshold', () => { + // The output threshold must bind to the wallet record's independently established + // spend policy — a prebuild weakening the policy over the wallet's own addresses + // (here a 1-of-3 output for a 2-of-3 wallet) must fail verification. + const weakenedThresholdTx = { + getFlareTransaction: () => ({ + getTx: () => ({ + baseTx: { + outputs: [ + { + output: { + getLocktime: () => 0n, + getThreshold: () => 1, + getOwners: () => [Buffer.alloc(20, 1), Buffer.alloc(20, 2), Buffer.alloc(20, 3)], + }, + }, + ], + }, + ins: [{ input: { sigIndicies: () => [0] } }], + }), + }), + }; + + assert.throws( + () => + basecoin.validateImportOutputPolicy(weakenedThresholdTx, { + wallet: { coinSpecific: () => ({ threshold: 2 }) }, + }), + /Import output threshold 1 does not match the wallet's spend threshold 2/ + ); + }); + + it('should fail closed when the wallet spend threshold is unavailable', () => { + // No wallet (or a wallet record without a threshold) must not silently fall back + // to the loose structural range check. + const thresholdTx = { + 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] } }], + }), + }), + }; + + assert.throws( + () => basecoin.validateImportOutputPolicy(thresholdTx, {}), + /the wallet spend threshold is unavailable/ + ); + assert.throws( + () => + basecoin.validateImportOutputPolicy(thresholdTx, { + wallet: { coinSpecific: () => ({}) }, + }), + /the wallet spend threshold is unavailable/ + ); }); it('should reject an import-to-P output whose threshold is structurally invalid', () => { @@ -1615,7 +1737,7 @@ describe('Flrp test cases', function () { }), }), }; - assert.throws(() => basecoin.validateImportOutputPolicy(zeroThresholdTx), /threshold 0 is invalid/); + assert.throws(() => basecoin.validateImportOutputPolicy(zeroThresholdTx, {}), /threshold 0 is invalid/); const overThresholdTx = { getFlareTransaction: () => ({ @@ -1635,7 +1757,7 @@ describe('Flrp test cases', function () { }), }), }; - assert.throws(() => basecoin.validateImportOutputPolicy(overThresholdTx), /threshold 3 is invalid/); + 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 () => { @@ -1671,7 +1793,11 @@ describe('Flrp test cases', function () { locktime: 0, }; - const isVerified = await basecoin.verifyTransaction({ txParams, txPrebuild }); + const isVerified = await basecoin.verifyTransaction({ + txParams, + txPrebuild, + wallet: { coinSpecific: () => ({ threshold: 2 }), receiveAddress: () => undefined }, + }); isVerified.should.equal(true); }); @@ -1743,6 +1869,7 @@ describe('Flrp test cases', function () { txParams, txPrebuild, walletType: 'tss', + wallet: { coinSpecific: () => ({ threshold: 1 }), receiveAddress: () => undefined }, }); isVerified.should.equal(true); });