Repository navigation
fix(sdk-coin-flrp): bind exported output owners and change outputs to the wallet - #10211
prithvishet2503 wants to merge 1 commit into
Conversation
|
|
There was a problem hiding this comment.
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.
|
@claude review this PR and Score it |
|
Claude finished @prithvishet2503's task in 21s —— View job Review of PR #10211: bind exported output owners and change outputs to the walletScore: 8/10. Approve with minor suggestions. I read the diff and did not run the test suite. What the PR does
The fix addresses the stated exploit directly. It is small, well commented, and the fail-closed default is correct. Findings
Positives
VerdictThe 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. |
e010916 to
947bce4
Compare
| 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); | ||
| } |
There was a problem hiding this comment.
🟣 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
@claude review this PR and Score it |
|
Claude finished @prithvishet2503's task in 18s —— View job Review of PR #10211: bind exported output owners and change outputs to the walletScore: 7.5/10. Good fix for the stated threat, with one trust-anchor gap to consider. I read What it does
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
Positives
VerdictMerge-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. |
947bce4 to
b5d5aa8
Compare
|
@claude review this PR and score it |
|
Claude finished @prithvishet2503's task in 26s —— View job Review of PR #10211: bind exported output owners and change outputs to the walletScore: 8/10. Approve, with one thing to confirm before merge. I read the diff and the surrounding What changed since the earlier reviews
Findings
Positives
VerdictThis 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. |
b5d5aa8 to
a325314
Compare
| 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(); | ||
| } |
There was a problem hiding this comment.
🔴 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).
There was a problem hiding this comment.
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.
|
@claude review this PR and Score it |
|
Claude finished @prithvishet2503's task in 30s —— View job Review of PR #10211: bind exported output owners and change outputs to the walletScore: 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 What improved since earlier rounds
Findings
Tests
VerdictFix finding 1 and give it a realistic test, and this is ready to merge. Everything else is a reasonable follow-up. |
There was a problem hiding this comment.
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.
| 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)) { |
There was a problem hiding this comment.
🔴 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
a325314 to
4ec11f5
Compare
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):
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).
would freeze wallet-owned funds) and structurally sound (1 ≤ threshold ≤ owner count).
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.
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.
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
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):
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:
Also verified: module tsc build clean, eslint --quiet clean, prettier --check clean. All C→P fixture tests (empty-recipient convention) pass unchanged.
Checklist
requireWalletOwnedAddresses, validateExportOutputPolicy, and validateExportFee; in-code comments on both direction-specific bindings, the CECHO-2867/2868 residual links, and the threshold
residual)