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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
225 changes: 205 additions & 20 deletions modules/sdk-coin-flrp/src/flrp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
AuditDecryptedKeyParams,
BaseCoin,
BitGoBase,
EcdsaUtils,
IWallet,
KeyPair,
MPCAlgorithm,
MultisigType,
Expand Down Expand Up @@ -36,7 +38,15 @@
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
Expand Down Expand Up @@ -136,7 +146,7 @@
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:
Expand Down Expand Up @@ -210,20 +220,21 @@

/**
* 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<void> {
const maxImportFee = (this._staticsCoin.network as FlareNetwork).maxImportFee;
const recipientAmount = new BigNumber(recipients[0].amount);
if (
Expand All @@ -238,12 +249,13 @@
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)) {
Expand All @@ -256,13 +268,186 @@
);
}
}
} 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);
Comment on lines 268 to +287

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 A compromised platform can again steal a whole P-to-C or C-to-P export by adding a second exported output. The base branch rejected this. The diff dropped the explainedTx.outputs.length !== 1 guard. Ownership (flrp.ts:287) and the C-to-P destination check (flrp.ts:264-265) still read only explainedTx.outputs[0]. Fix: check every exported output, or restore the exactly-one-output rule, and throw a clear error when outputs is empty. Same pattern at 3 sites (flrp.ts:249, flrp.ts:264, flrp.ts:287).

Why this was flagged

A malicious pvm.ExportTx prebuild reaches verifyTransaction (flrp.ts:149) and then validateExportTx. It has two outs: outs[0] pays 1 nFLR to the wallet owner set, and outs[1] pays almost all of recipients[0].amount to an attacker. Transaction.outputs (transaction.ts:479) maps every outs entry, and outputAmount (transaction.ts:602) sums them, so the amount window at flrp.ts:240-243 passes. requireWalletOwnedAddresses runs only on explainedTx.outputs[0].address (flrp.ts:287). validateExportOutputPolicy checks only locktime and threshold, and validateExportFee counts the attacker output as payout, so neither catches it. The user co-signs and the attacker imports the exported value. The C-to-P branch has the same hole: only outputs[0] is compared to the recipient destination (flrp.ts:264-265). On the base branch, if (recipients.length !== 1 || explainedTx.outputs.length !== 1) throw new Error('Export Tx requires one recipient') rejected any multi-output export. With zero outputs, explainedTx.outputs[0].address at flrp.ts:249 now throws a TypeError instead of that error.

Verification: Trigger: a compromised platform returns an export prebuild with two or more exported outputs. The base rejected this, and the diff deletes that guard from validateExportTx. P→C: the ownership check only reads the first output (flrp.ts:287). C→P: the destination check compares only explainedTx.outputs[0].address (flrp.ts:264-265).

for (const changeOutput of explainedTx.changeOutputs) {
this.requireWalletOwnedAddresses('Export change output', changeOutput.address, anchorOwners);
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
// 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<Set<string>> {
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();
}
Comment on lines +324 to +344

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 TSS FLRP wallets, the coin's default type, can no longer verify any P-to-C export after this change; the base branch verified them. Their keychains carry commonKeychain and no pub. So the typeof keychain.pub !== 'string' check at flrp.ts:273 returns an empty set, and validateExportTx throws 'Unable to verify P-chain export: could not derive the wallet owner set from keychains'. Fix: for TSS keychains, derive the single owner address from commonKeychain (as wallet.ts:2044-2048 does with EcdsaUtils.getPublicKeyFromCommonKeychain), and keep the per-key pub path for multisig. Add a test that uses a real TSS-shaped keychain.

Why this was flagged

Flrp.getDefaultMultisigType() returns multisigTypes.tss (flrp.ts:86-88), and getMPCAlgorithm() is 'ecdsa'. ECDSA MPCv2 keychains are created with only commonKeychain and no pub (ecdsaMPCv2.ts:462-471, keyType 'tss'). sdk-core wallet.ts:2042 says only one of pub/commonPub/commonKeychain is present. For a P-to-C export through verifyTransaction, validateExportTx calls deriveWalletOwnerSetFromKeychains (flrp.ts:236). That fetches the 3 TSS keychains, finds no string pub at flrp.ts:273 and returns an empty Set, and flrp.ts:237-238 then throws. On the base branch the same prebuild passed the amount-only check, so every TSS wallet's P-to-C export (the default wallet type) now fails before signing. The unit tests do not catch this because the keychainWallet mock (test/unit/flrp.ts:24-36) returns a synthesized pub per key, which real TSS keychains never have. The PR also notes that the MPC builder pays a single 1-of-1 owner address. Any fix therefore has to derive one address from the common key, not one address per keyId.

Verification: Trigger: any P-to-C export from an FLRP TSS/MPCv2 wallet. MPCv2 keychains are created with no pub (ecdsaMPCv2.ts:462-471), so flrp.ts:273 returns an empty set and validateExportTx throws. On the base branch, validateExportTx only checked the amount and passed. The new tests only use a keychainWallet mock that returns { pub } (test/unit/flrp.ts:25-36).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latest push brings this issue back at modules/sdk-coin-flrp/src/flrp.ts:279-283:

🔴 Real TSS FLRP wallets still cannot verify any P-to-C export; the new commonKeychain fallback throws 'Unsupported public key' instead of deriving an owner. A real ECDSA commonKeychain is the 33-byte public key followed by the 32-byte chaincode (130 hex chars). flrp.ts:283 passes that whole string to KeyPair({ pub }), which rejects it. Fix: take the public key from commonKeychain.slice(0, 66), as sdk-core's ecdsa base.ts:53 does. The derived address must match what the MPC builder actually pays. Also make the test mock use a real-shaped commonKeychain (pub plus chaincode).

Why this was flagged

Trigger: a P-to-C export verified through verifyTransaction for a TSS/MPCv2 wallet, the coin's default type. Its keychains carry only commonKeychain (ecdsaMPCv2.ts:462-466, keyType 'tss'). deriveWalletOwnerSetFromKeychains at flrp.ts:279 picks keychain.commonKeychain. Then flrp.ts:283 calls new FlrpLib.KeyPair({ pub }) on the 130-hex string. keyPair.ts recordKeysFromPublicKey gets 65 bytes from ECPair.fromPublicKey, which is not a valid point, and the cb58Decode fallback also fails, so it throws 'Unsupported public key'. Verification aborts and the user cannot sign the export. On the base branch, the amount-only check passed these exports. The new TSS unit test (test/unit/flrp.ts:27-36, 592-613) does not catch this. Its mock puts a bare 66-char compressed pub into commonKeychain, a shape real keychains never have. sdk-core reads only the first 66 chars of commonKeychain (utils/tss/ecdsa/base.ts:53).

Verification: flrp.ts:283 then passes that whole string to new FlrpLib.KeyPair({ pub: pub as string }). The code therefore throws 'Unsupported public key'. On the base branch, validateExportTx only checked the amount, so these exports verified; after this change every TSS P-to-C export fails before signing. The new test at test/unit/flrp.ts:592-612 hides the bug.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latest push brings this issue back at modules/sdk-coin-flrp/src/flrp.ts:333-346:

🔴 If FLRP TSS wallets hold funds at an HD-derived address, every legitimate P-to-C export from them is rejected. This includes 'm/0', the BitGo ECDSA TSS default. The base branch verified these exports. deriveWalletOwnerSetFromKeychains turns the root commonKeychain key straight into an address with KeyPair.getAddress and applies no HD derivation. sdk-core derives TSS addresses with deriveUnhardened at m/{index}, or {prefix}/{index} for SMC wallets. Fix: build the anchor from the commonKeychain derived at the wallet's real path (deriveMPCWalletAddress, including the derivedFromParentWithSeed prefix), not from the root key.

Why this was flagged

The condition, which this checkout cannot settle, is that FLRP TSS wallet UTXOs sit on an HD-derived address. That is the BitGo ECDSA TSS convention: deriveMPCWalletAddress (addressVerification.ts:87-91) derives m/${index} or ${prefix}/${index} via MPC.deriveUnhardened. For such an export, validateExportTx calls deriveWalletOwnerSetFromKeychains (flrp.ts:283). That function cuts the root 33-byte key out of commonKeychain (flrp.ts:338) and hashes it into an address (flrp.ts:346) without derivation. The export output and change are owned by the derived address, so requireWalletOwnedAddresses throws Export output pays non-wallet address ..., and the user cannot sign the export. On the base branch this path checked only the amount and verified. The unit tests do not catch it: the keychainWallet mock (test/unit/flrp.ts:29-36) builds commonKeychain as the raw pub plus a zero chain code, and the MPC builder fixture pays the root-key address directly.

Verification: Trigger: an FLRP TSS wallet whose P-chain UTXOs sit on an HD-derived address. deriveWalletOwnerSetFromKeychains (flrp.ts:333-338) takes the root compressed key, and flrp.ts:345 then does new FlrpLib.KeyPair({ pub }).getAddress(networkType) with no deriveUnhardened at any path. On the base branch, validateExportTx did no ownership check, so these exports verified.

const networkType = this._staticsCoin.network.type;
const ownerAddresses = publicKeys.map((pub) => new FlrpLib.KeyPair({ pub: pub as string }).getAddress(networkType));

Check failure on line 346 in modules/sdk-coin-flrp/src/flrp.ts

View check run for this annotation

Claude / Claude Code Review

If FLRP TSS wallets hold funds at an HD-derived address, every legitimate P-to-C export from them is rejected. This includes 'm/0', the BitGo ECDSA TSS default. The base branch verified these exports. deriveWalletOwnerSetFromKeychains turns the root commo

If FLRP TSS wallets hold funds at an HD-derived address, every legitimate P-to-C export from them is rejected. This includes 'm/0', the BitGo ECDSA TSS default. The base branch verified these exports. deriveWalletOwnerSetFromKeychains turns the root commonKeychain key straight into an address with KeyPair.getAddress and applies no HD derivation. sdk-core derives TSS addresses with deriveUnhardened at m/{index}, or {prefix}/{index} for SMC wallets. Fix: build the anchor from the commonKeychain de
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<string>} anchorOwners the wallet's normalized owner addresses
*/
private requireWalletOwnedAddresses(label: string, address: string, anchorOwners: Set<string>): 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.
}

/**
Expand Down
Loading
Loading