Skip to content

fix(sdk-coin-flrp): bind exported output owners and change outputs to the wallet - #10211

Open
prithvishet2503 wants to merge 1 commit into
masterfrom
prithvishet/cecho-2716-bitgojs-flrpvalidateexporttx-never
Open

prithvishet2503 wants to merge 1 commit into
masterfrom
prithvishet/cecho-2716-bitgojs-flrpvalidateexporttx-never

Conversation

@prithvishet2503

@prithvishet2503 prithvishet2503 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Description

Problem. Flrp.validateExportTx validated only the exported amount window — recipients[0].amount ≤ outputAmount ≤ recipients[0].amount + maxImportFee — and that outputs[0].address matches a
loose format regex. It never verified that the exported output is owned by the wallet, never inspected the P-chain export's change outputs (pvmSerial.ExportTx.baseTx.outputs, surfaced as
explainedTx.changeOutputs and read nowhere in the verification path), and never bounded the implied burned fee (CECHO-2716, duplicating the avaxp
avaxp-verifytransaction-export-destination-owners-not-bound gap in the Flare P-chain module).

Exploit. The user initiates an export of N FLR from their FLRP MPC wallet toward their paired C-chain wallet. A compromised platform returns a pvm.ExportTx prebuild that spends the wallet's
UTXOs but whose exported TransferOutput is owned by an attacker address (threshold 1), and/or whose baseTx change output pays the attacker, and/or which burns most of the spent UTXOs as
fee. verifyTransaction passes (amount matches, addresses well-formed); the MPC flow signs the digest computed over exactly these verified-but-malicious bytes; the attacker imports the
atomic UTXO to their own address — full theft of the exported amount plus redirected change or burned remainder. This coin-level gap is independent of the sdk-core pre-hashed-digest
finding: the verified serializedTxHex itself is never checked for destination ownership.

Fix (modules/sdk-coin-flrp/src/flrp.ts):

  1. P→C export (pvm.ExportTx) — the ticket's exploit path. Three bindings on every verification:
  • Ownership, anchored on client-trusted key material. The exported output and every P-chain change output must be wallet-owned: deriveWalletOwnerSetFromKeychains fetches the wallet's
    keychains via wallet.keyIds() and derives the owner addresses from the keychain public keys — the exact derivation isWalletAddress performs. It accepts keychain.pub ??
    keychain.commonKeychain (TSS/MPC keychains carry the joint public key in commonKeychain — the same field sdk-core's verifyMPCWalletAddress reads — and may not populate pub).
    Platform-served wallet fields (rootAddress/receiveAddress) are deliberately not trusted as anchors: a compromised platform controls the prebuild and those fields. Each on-chain owner
    address must be one of the keychain-derived addresses (case- and order-insensitive over the tilde-joined owner set); a foreign owner — even a single attacker address hidden inside a
    wallet-majority mixed set — throws (… pays non-wallet address …). Fails closed when the owner set can't be derived (no wallet, no key IDs, fetch rejection, or a keychain with neither
    pub nor commonKeychain).
  • Spend policy. validateExportOutputPolicy reads the raw tx outputs (exported outs + change baseTx.outputs): every output must be immediately spendable (locktime 0 — a far-future locktime
    would freeze wallet-owned funds) and structurally sound (1 ≤ threshold ≤ owner count).
  • Burned-fee bound. validateExportFee requires sum(inputs) − exported − change ≤ maxImportFee — the same network fee bound the amount window uses. Without it, a prebuild with a tiny
    wallet-owned change output could burn the remainder of the spent UTXOs as fee and still verify. Builder fee-state fees are ~1.3M vs the 10M ceiling, so builder-produced exports pass;
    non-finite totals fail closed.
  1. C→P export (evm.ExportTx). The exported P-chain destination owner set is bound to recipients[0].address when supplied (normalized comparison); a substituted destination throws. An empty
    recipient intentionally leaves the destination unbound: the fixture proves C→P destinations can be legitimate external P owner sets held server-side, so wallet-binding would false-reject
    cross-wallet exports. Tracked as CECHO-2867 — linked from the in-code comment.
  2. No false-rejects from the new bindings. The SDK's own P→C builder (ExportInPTxBuilder) pays the wallet's _fromAddresses for both the exported output and the change — verified against the
    real fixture (output and change are both the wallet's 3-address owner set) — produces locktime-0 outputs, and burns ~1.3M in fees, so none of the three bindings can reject
    builder-produced transactions (all 380 tests confirm, including MPC single-key exports). validateExportTx became async (it fetches keychains); repo grep confirmed its only caller is
    verifyTransaction, which awaits it.

Documented residual: the ownership check uses subset containment, so an output owned by a single wallet key at threshold 1 passes — the legitimate MPC builder shape. Theft to a foreign
address is prevented; pinning the expected owner set/threshold by wallet type requires wallet-platform metadata and is tracked as CECHO-2868 (linked from the validateExportOutputPolicy
JSDoc).

Known related gaps (not this PR): the avaxp export-side mirror (own ticket; import side is CECHO-2808), the C→P empty-recipient destination (CECHO-2867), and wallet-type-pinned owner
sets/thresholds (CECHO-2868).

Issue Number

Ticket: CECHO-2716
Follow-ups: CECHO-2867, CECHO-2868, CECHO-2808

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Ground truth established first via real parse-path probes and builder experiments: EXPORT_IN_P (P→C) pays the wallet's 3-address owner set for both the exported output and the change;
EXPORT_IN_C (C→P) pays an external 3-address P owner set with no change outputs; the full-spend amount (48,739,000 of a 50M UTXO) produces an empty change list; a future-dated locktime
builds; the MPC builder produces single-key 1-of-1 outputs; and builder fee-state exports burn ~1.3M — each fact drove the test design and the documented residuals.

14 new tests + P→C test wallets rebuilt as keychain-backed mocks, in modules/sdk-coin-flrp/test/unit/flrp.ts:

P→C ownership (keychain-derived anchor):

  1. Export output owned by a foreign owner set (wallet's keychains don't own the tx outputs) → throws (the CECHO-2716 scenario; passed before the fix)
  2. Attacker-owned change output → throws
  3. Mixed owner set — one wallet address + one attacker address → throws
  4. No wallet / no derivable owner set → throws (fail closed)
  5. Keychains carrying only commonKeychain (the TSS/MPC shape) → verifies
  6. Keychains with neither pub nor commonKeychain → fail closed
  7. Keychain fetch rejection → fail closed
  8. Wallet-owned output + change → true (fixture, anchor derived from the fixture's own keys)
  9. MPC export → true (single-key anchor from the signing key)

P→C spend policy:
10. Future-locktime output (real builder, future-dated locktime) → throws Export output locktime … must be 0
11. Full-spend export with no change outputs → verifies cleanly

P→C burned-fee bound:
12. 15M burned vs 10M network fee bound → throws Export burns … exceeding the network fee bound
13. Fixture-shaped ~1.31M fee → passes

C→P destination:
14. Recipient names the correct external destination (different address order) → true; attacker destination → throws

Reproduce:

cd modules/sdk-coin-flrp
BITGOJS_TEST_PASSWORD=testpassword yarn unit-test
# 380 passing, 0 failing

Also verified: module tsc build clean, eslint --quiet clean, prettier --check clean. All C→P fixture tests (empty-recipient convention) pass unchanged.

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • My code compiles correctly for both Node and Browser environments
  • I have commented my code, particularly in hard-to-understand areas
  • My commits follow Conventional Commits and I have properly described any BREAKING CHANGES
  • The ticket or github issue was included in the commit message as a reference (Ticket: CECHO-2716)
  • I have made corresponding changes to the documentation and on any new/updated functions and/or methods (JSDoc on validateExportTx, deriveWalletOwnerSetFromKeychains,
    requireWalletOwnedAddresses, validateExportOutputPolicy, and validateExportFee; in-code comments on both direction-specific bindings, the CECHO-2867/2868 residual links, and the threshold
    residual)
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes (380 passing)

@linear-code

linear-code Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

CECHO-2716

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility checks are failing on Node.js 27-nightly (experimental, non-blocking). This does not block merge, but it signals an incompatibility to fix before this release becomes supported.

View run

@prithvishet2503
prithvishet2503 marked this pull request as ready for review November 20, 2026 08:08
@prithvishet2503
prithvishet2503 requested a review from a team as a code owner November 20, 2026 08:08

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@prithvishet2503

Copy link
Copy Markdown
Contributor Author

@claude review this PR and Score it

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @prithvishet2503's task in 21s —— View job


Review of PR #10211: bind exported output owners and change outputs to the wallet

Score: 8/10. Approve with minor suggestions. I read the diff and did not run the test suite.

What the PR does

  • P→C export: the exported output and every changeOutputs entry must be a subset of the wallet's owner set. The owner set is anchored on rootAddress, falling back to receiveAddress(). The check runs after normalization (case- and order-insensitive). It fails closed when there is no anchor.
  • C→P export: when recipients[0].address is supplied, it must match the exported P-chain owner set.
  • Tests: attacker output, attacker change, no anchor, happy path, and C→P match and mismatch are all covered.

The fix addresses the stated exploit directly. It is small, well commented, and the fail-closed default is correct.

Findings

  1. Locktime and threshold are not checked (low to medium). Ownership is checked only on addresses. An exported output that is wallet-owned but has a far-future locktime, or a threshold above what the wallet can sign, would pass verification. That would lock or strand the funds rather than steal them. If explainedTx exposes locktime or threshold, a cheap extra assertion would close this. Otherwise, note it as a residual.

  2. C→P empty-recipient residual (acknowledged). With an empty recipients[0].address, the destination stays unbound, so a compromised platform can still redirect C→P exports. The PR documents this, and the reason (legitimate external owner sets) is reasonable. I'd still open a follow-up ticket. Possible options are requiring a destination for the new flows, or checking against a server-independent source. Please link that ticket from the code comment.

  3. Subset containment passes degenerate sets (low). An output paying only one wallet address is accepted. This is safe from a theft standpoint, but it may not match what the builder produces. Consider also asserting the owner count or threshold against the wallet's configuration, if the parsed tx exposes it.

  4. Anchor format assumption (low). The check assumes rootAddress is the full tilde-joined owner set, as in the fixture. For wallets whose rootAddress is a single address, a legitimate 3-owner export output would be rejected. The fixture shows this works for the standard FLRP MPC wallet. It's worth confirming against real wallet data, or adding a test with a single-address root.

  5. Style nit. normalizeAddressSet is followed directly by export class Flrp with no blank line (flrp.ts around line 51).

  6. API change. validateExportTx now requires tx and params. It is a public method, so check for external callers. A repo grep would settle this.

  7. Missing test. There's no case for an empty changeOutputs list on a P→C export, or for a mixed owner set (one wallet address plus one attacker address). The mixed case is the most valuable one, since it exercises the subset logic.

Positives

  • The CECHO-2716 scenario is covered by a failing-before, passing-after test.
  • Normalization is shared between the two directions.
  • The error messages name the offending address.

Verdict

The change is correct for the described threat and safe to merge once the nit and the mixed-owner test are addressed. The locktime and threshold gap and the C→P residual should be tracked as follow-ups.

@prithvishet2503
prithvishet2503 force-pushed the prithvishet/cecho-2716-bitgojs-flrpvalidateexporttx-never branch from e010916 to 947bce4 Compare November 20, 2026 08:14

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment thread modules/sdk-coin-flrp/src/flrp.ts Resolved
Comment thread modules/sdk-coin-flrp/src/flrp.ts Outdated
Comment on lines +234 to +238
const anchorOwners = new Set(normalizeAddressSet(walletAnchor).split(ADDRESS_SEPARATOR));
this.requireWalletOwnedAddresses('Export output', explainedTx.outputs[0].address, anchorOwners);
for (const changeOutput of explainedTx.changeOutputs) {
this.requireWalletOwnedAddresses('Export change output', changeOutput.address, anchorOwners);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟣 pre-existing, not blocking: A compromised platform can still take a P-to-C export or its change, because the new ownership check compares only owner addresses. Threshold and locktime are never checked. A prebuild whose exported output or change is owned by just the BitGo address with threshold 1 passes as wallet-owned (subset containment, flrp.ts:256). So does a far-future locktime. Fix: for the export output and every change output, also require threshold equal to the wallet's threshold and locktime 0 or the expected value, read from the parsed TransferOutput. ExportInPTxBuilder sets both from _threshold and _locktime.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

The trigger is a malicious P-to-C pvm.ExportTx prebuild verified through verifyTransaction, then validateExportTx (flrp.ts:221-239). Its TransferOutput owners are a strict subset of the wallet owner set, e.g. only the BitGo key's P address, with threshold 1. The amount still matches. requireWalletOwnedAddresses (flrp.ts:250-260) only checks that each owner in explainedTx.outputs[0].address is in the anchor set. The address string comes from utils.mapOutputToEntry (utils.ts:265-281), which drops threshold and locktime. So the check passes, the user co-signs, and the single platform-held key controls the exported atomic UTXO and any redirected change, the same theft the PR targets. A far-future locktime on either output would likewise lock the user's funds. The PR calls subset containment a deliberate design choice. But the SDK's own builder (ExportInPTxBuilder.ts:160-166, 194-200) always writes the full _fromAddresses with the wallet _threshold and _locktime, so checking those fields would not reject builder output.

Verification: Trigger: a P-to-C pvm.ExportTx prebuild whose exported or change output is owned by a subset of the wallet's keys with threshold 1. utils.mapOutputToEntry (utils.ts:265-281) builds each output Entry from just output.amount() and getOwners(). The output's own threshold and locktime are dropped. The base already accepted any owner set by this route.

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 new validateExportOutputPolicy fixes the locktime half: any nonzero locktime on the export or change outputs is now rejected. The theft case is still open. The threshold check only requires 1 <= threshold <= ownerCount, and requireWalletOwnedAddresses still accepts any subset of the anchor owners. So an output owned by just the BitGo key's P address with threshold 1 still passes, and that single platform key controls the exported UTXO or the redirected change. To close it, require the output's owner set to equal the full wallet owner set, not a subset. For multi-owner anchors, also require a threshold above 1, or the wallet's m-of-n threshold if the wallet object provides it.

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 new validateExportOutputPolicy handles the locktime half: any nonzero locktime is now rejected. The threshold half is still open. The check only requires 1 <= threshold <= ownerCount, and requireWalletOwnedAddresses still accepts any subset of the keychain-derived owners. So a P-to-C export or change output owned only by the BitGo key's address with threshold 1 still passes, and that one platform-held key controls the funds. To close it, require each output's owner set to equal the full keychain-derived anchor set instead of a subset. For TSS this is a single address, so the MPC builder's single-key outputs still pass. When there are several owners, also require threshold >= 2, or the wallet's m if you can get it.

@prithvishet2503

Copy link
Copy Markdown
Contributor Author

@claude review this PR and Score it

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @prithvishet2503's task in 18s —— View job


Review of PR #10211: bind exported output owners and change outputs to the wallet

Score: 7.5/10. Good fix for the stated threat, with one trust-anchor gap to consider. I read flrp.ts and the diff. I did not run the test suite.

What it does

  • P→C export: the exported output and every change output must have owners that are a subset of the wallet's owner set. The anchor is rootAddress, falling back to receiveAddress(). It fails closed when there's no anchor.
  • Spend policy: validateExportOutputPolicy requires locktime 0 and 1 ≤ threshold ≤ owners on the exported outputs and the change outputs.
  • C→P export: when recipients[0].address is given, it must match the exported owner set. An empty recipient leaves the destination unbound (CECHO-2867).
  • Tests: attacker output, attacker change, mixed owner set, no anchor, single-address anchor, future locktime, full-spend with no change, and C→P match and mismatch.

This closes the CECHO-2716 path where an attacker-owned output passes the amount check. The code is small and commented, it fails closed, and the tests cover the earlier review's gaps (mixed owners, locktime, empty change).

Findings

  1. The anchor comes from platform-served data (medium, and the main residual). walletAnchor is read from coinSpecific().rootAddress or receiveAddress() at flrp.ts:229. Under the PR's threat model (compromised platform), that same platform supplies the wallet object. A prebuild whose output and change pay P-attacker, paired with a wallet whose rootAddress is P-attacker, would pass. The check only validates address format (flrp.ts:235). If the wallet's keychains are available in verifyTransaction, derive or check the anchor against them, as isWalletAddress does. If that isn't feasible, the PR description and JSDoc should say the check protects only when the wallet metadata is trusted. The comment on line 224 currently implies stronger protection.

  2. The threshold is not pinned (low to medium, documented). Subset containment accepts an output owned only by the BitGo address with threshold 1. The JSDoc acknowledges that no authoritative expected threshold reaches verifyTransaction. If a TSS wallet always uses threshold 1 and the full owner set, a stricter check might be possible later. I'd keep a follow-up ticket for it, as you did for CECHO-2867.

  3. Subset containment is weaker than equality (low). This is deliberate, because signing flows can produce outputs over a subset of keys. Combined with finding 2, a subset that is only the platform-held key is accepted. Consider requiring that the output owner set includes the user's own key address, if that can be derived.

  4. Anchor format assumption (low). The check assumes rootAddress is the full owner set. The single-address MPC test covers one shape. A wallet whose rootAddress is a single address but whose builder output uses 3 owners would be rejected. The PR says the fixture confirms the builder pays the 3-address set, so this is probably fine for the real shape. Please confirm it against a real wallet.

  5. C→P empty-recipient residual (acknowledged). CECHO-2867 is linked in the code comment, as asked in the earlier review.

  6. Style nit. A blank line sits between the C→P comment block and const expectedExportDestination (flrp.ts:210). Remove it so the comment attaches to the code.

Positives

  • The exploit scenario is a fail-before, pass-after test.
  • Normalization is shared between the two directions.
  • Error messages name the offending address.
  • The validateExportTx signature change has no other callers in the repo, per the PR description.

Verdict

Merge-worthy for the stated scenario after the nit. I'd resolve finding 1 first, either by anchoring to the keychains or by documenting the trust assumption. Findings 2, 3 and 5 are reasonable follow-ups.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Still open from earlier reviews (2):

  • Unresolved: 2 minor or pre-existing.

Comment thread modules/sdk-coin-flrp/src/flrp.ts Resolved
@prithvishet2503
prithvishet2503 force-pushed the prithvishet/cecho-2716-bitgojs-flrpvalidateexporttx-never branch from 947bce4 to b5d5aa8 Compare November 20, 2026 08:25
@prithvishet2503

Copy link
Copy Markdown
Contributor Author

@claude review this PR and score it

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @prithvishet2503's task in 26s —— View job


Review of PR #10211: bind exported output owners and change outputs to the wallet

Score: 8/10. Approve, with one thing to confirm before merge. I read the diff and the surrounding flrp.ts and keyPair.ts. I did not run the test suite.

What changed since the earlier reviews

  • The trust anchor is now derived from the wallet's keychain pubs via wallet.keyIds() and keychains().get(). It no longer comes from platform-served rootAddress or receiveAddress. This fixes the main finding from the previous round.
  • validateExportOutputPolicy requires locktime 0 and 1 ≤ threshold ≤ owners on the exported outputs and the change outputs.
  • Ownership is checked per owner address, so a single foreign owner hidden in a mixed set is rejected.
  • The C→P recipient binding is kept, and CECHO-2867 is linked in the code comment.

Findings

  1. Possible false-reject for real TSS wallets (medium, please confirm). deriveWalletOwnerSetFromKeychains (flrp.ts:262-281) reads keychain.pub and returns an empty set if any keychain lacks one. That makes validateExportTx throw. For MPC wallets, BitGo keychains normally carry commonKeychain, and pub may be absent. isWalletAddress in flrp.ts:418 also reads keychains[0].pub, so the pattern isn't new. But if real TSS keychains have no pub, every legitimate MPC P→C export fails closed. The unit tests use mocks that set pub. Please check against a real TSS wallet's keychain shape. The PR says the MPC test derives its anchor "from the signing key's pub", so this is worth a second look. If the field can differ, handle commonKeychain explicitly or document it.

  2. Subset containment still lets a single-key output through (medium, documented residual). An output owned only by the BitGo key's P address with threshold 1 passes. The new JSDoc explains why equality or a minimum owner count would false-reject the MPC builder's 1-of-1 outputs. That reasoning is fair. The keychain anchor keeps this from being an attacker-address theft. It does mean the platform-held key alone can own the exported UTXO. A follow-up that pins the expected owner set from wallet type (multisig vs TSS) would close it. Please file one, as you did for CECHO-2867.

  3. No bound on the implied fee (medium, pre-existing). Nothing checks inputs − outputAmount − changeAmount. A prebuild with a tiny wallet-owned change output would burn the remainder as fee and still verify. The base had the same gap, so it is not a regression. It is worth a ticket, because this PR now says change is "bound".

  4. Derived addresses (low). The anchor covers only the root keychain-derived addresses. If any wallet type pays change to per-index derived addresses, those would be rejected. The fixture suggests this doesn't happen for FLRP.

  5. Network consistency (low). getAddress(networkType) returns the HRP address. requireWalletOwnedAddresses compares it with lowercased owner strings, so a mixed P-flare / P-costwo pair would fail closed. That is the safe direction.

  6. Nit. flrp.ts:211 has a blank line between the C→P comment block and const expectedExportDestination. Removing it keeps the comment attached to the code.

  7. Nit. Pass { id: keyId } through a small typed helper, or at least confirm keychains().get throws on a missing key. A rejected promise already fails closed, so this is fine as is.

Positives

  • The anchor is anchored on client-trusted key material. The comments explain why.
  • Fail-closed paths cover a missing wallet, no key IDs, a fetch error and a missing pub.
  • Tests cover the CECHO-2716 scenario, attacker change, mixed owner sets, a future locktime, a full spend with no change, and C→P match and mismatch.
  • validateExportTx has no other callers in the repo, and the PR's grep says the same.

Verdict

This closes the stated exploit. I'd confirm finding 1 against a real MPC wallet before merging. Findings 2 and 3 should be follow-up tickets.

@prithvishet2503
prithvishet2503 force-pushed the prithvishet/cecho-2716-bitgojs-flrpvalidateexporttx-never branch from b5d5aa8 to a325314 Compare November 20, 2026 08:46

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Still open from earlier reviews (2):

  • Unresolved: 2 minor or pre-existing.

Comment on lines +266 to +275
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 })));
// A keychain without a pub makes the derived owner set incomplete — fail closed
// (the caller rejects when the set is empty) rather than verify against partial keys.
if (keychains.some((keychain) => typeof keychain.pub !== 'string')) {
return new Set();
}

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.

@prithvishet2503

Copy link
Copy Markdown
Contributor Author

@claude review this PR and Score it

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @prithvishet2503's task in 30s —— View job


Review of PR #10211: bind exported output owners and change outputs to the wallet

Score: 7.5/10. The design is sound and closes the stated exploit, but one blocker should be confirmed before merge. I read the full diff and keyPair.ts. I did not run the test suite.

What improved since earlier rounds

  • The trust anchor is now derived from the wallet's keychains, not from platform-served rootAddress or receiveAddress.
  • Ownership is checked per owner address, so one foreign owner hidden in a mixed set is rejected.
  • validateExportOutputPolicy requires locktime 0 and 1 ≤ threshold ≤ owners.
  • validateExportFee bounds the burned fee at maxImportFee. This closes the burn-the-remainder gap.
  • The CECHO-2867 and CECHO-2868 residuals are documented in the code.
  • keychain.pub ?? keychain.commonKeychain addresses the earlier TSS pub finding in form. See finding 1 for why it may not work in practice.

Findings

  1. Blocker to confirm: commonKeychain is probably not a valid input to KeyPair (flrp.ts:279-283).

    • The code passes commonKeychain straight to new FlrpLib.KeyPair({ pub }).
    • A real ECDSA TSS commonKeychain is the 33-byte compressed public key followed by the 32-byte chain code. That is 130 hex characters, not a bare 66-character public key.
    • recordKeysFromPublicKey (keyPair.ts:~64) would try ECPair.fromPublicKey on 65 bytes, which is invalid. It would then fall back to cb58 and throw Unsupported public key.
    • That promise rejection fails closed, so every legitimate TSS P→C export would be rejected. TSS is getDefaultMultisigType().
    • The new test hides this. keychainWallet(..., 'commonKeychain') in test/unit/flrp.ts:27-36 stores a bare 33-byte getKeys().pub in the commonKeychain field, which is not the real shape.
    • Fix: for commonKeychain, take the first 66 hex characters (or use EcdsaUtils.getPublicKeyFromCommonKeychain, as wallet.ts does). Then derive the address from that key. Change the test to use a real-shaped 130-character value, and add a test where the key isn't 33 bytes.
    • Please also confirm the derived address matches the on-chain owner address the MPC builder produces for a real TSS wallet. A root-pub address and a derived-path address would differ.
  2. Subset containment still accepts a single-key output (medium, documented, tracked as CECHO-2868). An output owned only by the BitGo key at threshold 1 passes. This is not theft to a foreign address, and the JSDoc explains why equality would false-reject MPC 1-of-1 outputs. Keep CECHO-2868 as a follow-up.

  3. validateExportFee relies on a cast (low). explainedTx.inputs as unknown as FlrpEntry[] and (output as unknown as FlrpEntry).value ?? output.amount work around typing. If the entry types ever change, this could silently compute NaN. That fails closed through the isFinite guard, so it is safe. Typing explainedTx.inputs properly would be cleaner, and the repo guidelines discourage as unknown.

  4. Per-keychain fetches have no timeout (low). Promise.all over keychains().get fails closed on rejection. The behavior is fine.

  5. C→P empty recipient (acknowledged). The destination stays unbound, tracked as CECHO-2867 and linked in the code.

  6. Nit. There is a blank line between the CECHO-2867 comment block and const expectedExportDestination, which detaches the comment from the code.

Tests

  • The coverage is good: foreign output, foreign change, mixed owners, no wallet, fetch rejection, future locktime, full spend, fee bound, and C→P match and mismatch.
  • The gap is the commonKeychain fixture shape from finding 1.

Verdict

Fix finding 1 and give it a realistic test, and this is ready to merge. Everything else is a reasonable follow-up.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Still open from earlier reviews (2):

  • 🔴 modules/sdk-coin-flrp/src/flrp.ts:275 — TSS FLRP wallets, the coin's default type, can no longer verify any P-to-C export after this change; the base branch ve…
  • Also unresolved: 1 minor or pre-existing.

If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.

Comment on lines +340 to +354
private validateExportFee(explainedTx: FlrpLib.TransactionExplanation): 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);
if (burnedFee.isGreaterThan(maxImportFee)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Legitimate P-to-C exports that spend about 10 or more UTXOs will now fail verification, even at the minimum gas price. The base branch verified them. validateExportFee caps the burned fee at the flat network maxImportFee (10,000,000 nFLR). The P-chain dynamic fee grows linearly with input count, and each 2-of-3 input adds roughly 965k nFLR at price 251. Fix: derive the ceiling from the tx's own complexity, for example the flarejs pvm complexity times a gas-price ceiling, or scale it per input and output. Builder-produced exports with many inputs must keep verifying.

Why this was flagged

Trigger: a P-to-C export from a wallet whose balance sits in many small UTXOs (deposits, staking rewards), so the builder (ExportInPTxBuilder.ts:170 pvm.e.newExportTx) consumes about 10+ inputs. It goes through verifyTransaction to validateExportTx, then validateExportFee (flrp.ts:251). The fixture shows how the fee grows with inputs at price 251 (test/resources/transactionData/exportInP.ts:44-55, weights dbRead/dbWrite 1000, compute 4). One 2-of-3 input with no change burns 1,261,000. Two inputs plus change burn 2,285,355 (unsignedHex: inputs 22885875+48739000, outputs 14339520+55000000). So each extra input adds about 0.75M-0.97M, and the fee passes maxImportFee = '10000000' (statics networks.ts:2462) at about 10 inputs, or fewer when the gas price rises above its 250 minimum. flrp.ts:354 then throws Export burns ... exceeding the network fee bound, and the user cannot export at all. The base branch had no fee check and verified these transactions. The PR's claim that builder exports pass (~1.3M vs 10M) was measured on 1-2 input fixtures only.

Verification: validateExportFee (flrp.ts) throws when burnedFee.isGreaterThan(maxImportFee), a flat '10000000' (statics networks.ts:2462/2498). The builder (ExportInPTxBuilder.ts:170-179) pays a dynamic fee that grows per input, so about 10 or more 2-of-3 inputs exceed it. On the base branch validateExportTx had no fee check, so these exports verified.

… the wallet

Flrp.validateExportTx checked only the exported amount window and a loose
address format — never that the exported output is owned by the wallet, and
never the P-chain export's change outputs. A compromised platform could
serve a prebuild spending the wallet's UTXOs whose exported TransferOutput
is owned by an attacker address and/or whose baseTx change output pays the
attacker; verification passed and the MPC flow signed the theft (CECHO-2716).

- P→C export (pvm.ExportTx): the exported output and every P-chain change
  output (baseTx.outputs) must be wallet-owned — each owner address must be
  one of the wallet's own addresses (rootAddress or receiveAddress anchor,
  subset containment). Fails closed when no wallet anchor is available.
- C→P export (evm.ExportTx): the exported P-chain destination owner set is
  bound to the recipient's named address when supplied (normalized, order-
  and case-insensitive). An empty placeholder leaves nothing client-side
  to compare, matching the destination-less flow.
- The SDK's own P→C builder pays the wallet's fromAddresses for both the
  export output and change, so the wallet-owned requirement cannot
  false-reject builder-produced transactions.

Ticket: CECHO-2716
@prithvishet2503
prithvishet2503 force-pushed the prithvishet/cecho-2716-bitgojs-flrpvalidateexporttx-never branch from a325314 to 4ec11f5 Compare November 20, 2026 09:09

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant