diff --git a/modules/abstract-eth/src/abstractEthLikeNewCoins.ts b/modules/abstract-eth/src/abstractEthLikeNewCoins.ts index b07629af0f..431f9769e3 100644 --- a/modules/abstract-eth/src/abstractEthLikeNewCoins.ts +++ b/modules/abstract-eth/src/abstractEthLikeNewCoins.ts @@ -86,6 +86,8 @@ import { EthLikeToken } from './ethLikeToken'; import { calculateForwarderV1Address, coinFamiliesWithL1Fees, + confidentialTransferWithProofMethodId, + confidentialTransferWithProofTypes, approveMethodId, decodeApproveCalldata, decodeFinalizeUnwrapCalldata, @@ -94,6 +96,7 @@ import { decodeUnwrapCalldata, decodeWrapCalldata, ERC1155TransferBuilder, + EthTransactionData, ERC721TransferBuilder, getBufferedByteCode, getCommon, @@ -590,11 +593,18 @@ export const optionalDeps = { }; /** Intent types other than payments that verifyTssTransaction already verifies. */ -const TSS_DEDICATED_INTENT_TYPES = new Set(['defiApprove', 'defiDeposit', 'defiWithdraw', 'wrapApprove']); +const TSS_DEDICATED_INTENT_TYPES = new Set([ + 'defiApprove', + 'defiDeposit', + 'defiWithdraw', + 'wrapApprove', + 'tokenApproval', +]); type TssDecodedArg = ReturnType[number]; const TSS_ERC20_TRANSFER_TYPES = ['address', 'uint256']; +const TSS_ERC20_APPROVE_TYPES = ['address', 'uint256']; const TSS_NATIVE_BATCH_TYPES = ['address[]', 'uint256[]']; const TSS_TOKEN_BATCH_TYPES = ['address', 'address[]', 'uint256[]']; @@ -3636,11 +3646,37 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem return { isToken: true, reason: `token '${declared}' cannot be resolved to a contract on this network` }; } if (token instanceof Erc7984Coin) { - return { isToken: true, confidential: true, reason: `token '${declared}' is an ERC-7984 token` }; + return { + isToken: true, + contract: contract.toLowerCase(), + confidential: true, + reason: `token '${declared}' is an ERC-7984 token`, + }; } return { isToken: true, contract: contract.toLowerCase() }; } + /** + * Decode raw serialized EVM transaction bytes directly via `EthTransactionData.fromSerialized`, + * bypassing `TransactionBuilder.from()` / `.build()` reserialization so calldata bytes cannot be + * altered or normalized before verification. + */ + protected decodeRawTssTxFields(txHex: string | undefined): { to: string; value: string; data: string } { + if (!txHex) { + throw new Error('missing txHex in txPrebuild'); + } + const common = AbstractEthLikeNewCoins.getCustomChainCommon(this.getChainId()); + if (!this.staticsCoin?.features.includes(CoinFeature.EIP1559)) { + common.setHardfork(optionalDeps.EthCommon.Hardfork.Petersburg); + } + const txJson = EthTransactionData.fromSerialized(txHex, common).toJson(); + return { + to: (txJson.to ?? '').toLowerCase(), + value: txJson.value ?? '0', + data: (txJson.data || '0x').toLowerCase(), + }; + } + /** * Verify a single-recipient payment: explicit calldata must match exactly; otherwise the bytes * must be a plain native send or a canonical ERC-20 transfer of the declared token. @@ -3651,12 +3687,7 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem txHex: string | undefined, throwRecipientMismatch: (message: string, mismatchedRecipients: Recipient[]) => Promise ): Promise { - const txBuilder = this.getTransactionBuilder(); - txBuilder.from(txHex); - const txJson = (await txBuilder.build()).toJson(); - const to = (txJson.to ?? '').toLowerCase(); - const value = txJson.value ?? '0'; - const data = (txJson.data || '0x').toLowerCase(); + const { to, value, data } = this.decodeRawTssTxFields(txHex); const mismatch = (message: string, address = to, amount = value): Promise => throwRecipientMismatch(message, [{ address, amount }]); @@ -3677,6 +3708,46 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem const token = this.resolveTssToken(recipient.tokenName ?? txParams.tokenName); + if (token.confidential) { + // ERC-7984 confidential token payment: MUST call confidentialTransfer(address,bytes32,bytes) + // on the declared token contract with zero native value and matching recipient. + // Encrypted amount (handle + inputProof) cannot be decrypted client-side and stays a warning. + const expectedSelector = confidentialTransferWithProofMethodId.toLowerCase(); + if (!data.startsWith(expectedSelector)) { + await mismatch('ERC-7984 payment calldata must use confidentialTransfer(address,bytes32,bytes)'); + } + if (!isCanonicalTssCalldata(data, confidentialTransferWithProofTypes)) { + await mismatch('ERC-7984 confidentialTransfer calldata is not canonical'); + } + const [innerRecipient, encryptedHandle, inputProof] = decodeTssCalldataArgs( + data, + confidentialTransferWithProofTypes + ); + const decodedRecipient = addHexPrefix(innerRecipient as string).toLowerCase(); + if (!recipient.address || decodedRecipient !== recipient.address.toLowerCase()) { + await mismatch('destination address does not match with the recipient address', decodedRecipient, value); + } + if (!tssValuesEqual(value, '0')) { + await mismatch('ERC-7984 confidential transfer must not carry native value'); + } + if (!token.contract || to !== token.contract) { + await mismatch('transaction is not sent to the declared token contract'); + } + const handleBuf = encryptedHandle as Buffer; + const proofBuf = inputProof as Buffer; + if (!handleBuf || handleBuf.length !== 32 || handleBuf.every((b) => b === 0)) { + await mismatch('ERC-7984 confidentialTransfer encryptedHandle is missing or empty'); + } + if (!proofBuf || proofBuf.length === 0) { + await mismatch('ERC-7984 confidentialTransfer inputProof is missing or empty'); + } + this.warnTssVerificationIncomplete( + 'transfer', + `${token.reason}: encrypted amount cannot be verified against declared plaintext amount` + ); + return; + } + if (isEmptyTssCalldata(data)) { if (token.isToken) { await mismatch('token payment carries no ERC-20 transfer calldata'); @@ -3692,10 +3763,6 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem const transferMethodId = tssMethodId('transfer', TSS_ERC20_TRANSFER_TYPES); if (!data.startsWith(transferMethodId)) { - if (token.confidential) { - this.warnTssVerificationIncomplete('transfer', `${token.reason}: the payment calldata was not verified`); - return; - } await mismatch('payment calldata is not a native send or an ERC-20 transfer(address,uint256)'); } if (!isCanonicalTssCalldata(data, TSS_ERC20_TRANSFER_TYPES)) { @@ -3741,12 +3808,7 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem txHex: string | undefined, throwRecipientMismatch: (message: string, mismatchedRecipients: Recipient[]) => Promise ): Promise { - const txBuilder = this.getTransactionBuilder(); - txBuilder.from(txHex); - const txJson = (await txBuilder.build()).toJson(); - const to = (txJson.to ?? '').toLowerCase(); - const value = txJson.value ?? '0'; - const data = (txJson.data || '0x').toLowerCase(); + const { to, value, data } = this.decodeRawTssTxFields(txHex); const mismatch = (message: string, address = to, amount = value): Promise => throwRecipientMismatch(message, [{ address, amount }]); @@ -3804,6 +3866,10 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem } const tokenContract = addHexPrefix(decoded[0] as string).toLowerCase(); for (const token of tokens) { + if (token.confidential) { + // ERC-7984 confidential tokens have no batchTransferFrom surface; a batch intent naming one is a mismatch. + await mismatch('ERC-7984 confidential tokens cannot be paid through a batch', tokenContract); + } if (!token.contract) { this.warnTssVerificationIncomplete( 'transfer', @@ -3815,6 +3881,72 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem } } + /** + * Verify a `tokenApproval` TSS intent against raw transaction bytes (CECHO-2689). + * + * Expected shape (fail closed on any deviation): + * - `to` = contract address of the declared token on this network + * - `value` = 0 + * - `data` = canonical `approve(address,uint256)` (`0x095ea7b3`) + * - `spender` = this network's configured `batcherContractAddress` + * - `amount` = `MAX_UINT256` (`2^256 - 1`) + */ + private async verifyTssTokenApproval( + txParams: EthTransactionParams, + txHex: string | undefined, + throwRecipientMismatch: (message: string, mismatchedRecipients: Recipient[]) => Promise + ): Promise { + const { to, value, data } = this.decodeRawTssTxFields(txHex); + const mismatch = (message: string, address = to, amount = value): Promise => + throwRecipientMismatch(message, [{ address, amount }]); + + const token = this.resolveTssToken(txParams.tokenName); + if (!token.isToken || !token.contract) { + await mismatch( + token.reason + ? `tokenApproval: ${token.reason}` + : 'tokenApproval transaction requires a declared tokenName resolvable to a contract on this network' + ); + } + + const configuredBatcher = this.getNetwork()?.batcherContractAddress; + if (!configuredBatcher) { + await mismatch('tokenApproval: no batcher contract is configured for this network'); + } + // Unreachable when the mismatch above threw; an empty string can never equal a decoded address. + const batcherSpender = configuredBatcher ?? ''; + + if (to !== token.contract) { + await mismatch('tokenApproval transaction is not sent to the declared token contract'); + } + if (!tssValuesEqual(value, '0')) { + await mismatch('tokenApproval transaction must not carry native value'); + } + + const expectedSelector = approveMethodId.toLowerCase(); + if (!data.startsWith(expectedSelector)) { + await mismatch('tokenApproval transaction must use ERC-20 approve(address,uint256) calldata'); + } + if (!isCanonicalTssCalldata(data, TSS_ERC20_APPROVE_TYPES)) { + await mismatch('tokenApproval approve calldata is not canonical'); + } + + const [rawSpender, rawAmount] = decodeTssCalldataArgs(data, TSS_ERC20_APPROVE_TYPES); + const decodedSpender = addHexPrefix(rawSpender as string).toLowerCase(); + const decodedAmount = (rawAmount as BN).toString(10); + + if (decodedSpender !== batcherSpender.toLowerCase()) { + await mismatch( + 'tokenApproval transaction spender does not match the network batcher contract', + decodedSpender, + decodedAmount + ); + } + if (!tssValuesEqual(decodedAmount, MAX_UINT256.toString())) { + await mismatch('tokenApproval transaction amount must be MAX_UINT256', decodedSpender, decodedAmount); + } + } + /** * @param {VerifyEthTransactionOptions} params * @param {TransactionParams} params.txParams - params object passed to send @@ -3971,9 +4103,14 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem } else { // Declared as anything else: only an approve of a registered wrapper is rejected (see the method doc); // for every other tx this returns without parsing or after one best-effort parse. + // Runs BEFORE tokenApproval so a relabeled approve(wrapper, ...) fails with the wrapper-approve error. await this.assertWrapperApproveIsDeclared(params, throwRecipientMismatch); } + if (txParams.type === 'tokenApproval') { + await this.verifyTssTokenApproval(txParams, txPrebuild.txHex, throwRecipientMismatch); + } + // Verify consolidation transactions send to base address if (params.verification?.consolidationToBaseAddress) { const coinSpecific = wallet.coinSpecific(); diff --git a/modules/sdk-coin-eth/src/erc7984Token.ts b/modules/sdk-coin-eth/src/erc7984Token.ts index aff504de6b..d239691bb2 100644 --- a/modules/sdk-coin-eth/src/erc7984Token.ts +++ b/modules/sdk-coin-eth/src/erc7984Token.ts @@ -22,7 +22,10 @@ import { decodeFlushERC7984ForwarderTokenCalldata, decodeSendMultiSigFlushERC7984Data, sendMultisigMethodId, + sendMultiSigTypes, confidentialTransferWithProofMethodId, + confidentialTransferWithProofTypes, + getRawDecoded, buildConfidentialTransferByHandleCalldata, optionalDeps, RecoverOptions, @@ -65,6 +68,24 @@ import { TransactionBuilder } from './lib'; const STRICT_CONSOLIDATION_MAX_DERIVATION_INDEX = 10000; const STRICT_CONSOLIDATION_FORWARDER_VERSIONS = [1, 2, 4, 5] as const; +/** + * True when the calldata body after the 4-byte selector is exactly the canonical ABI encoding of + * `types`: no trailing bytes, no dirty address padding, no non-standard dynamic offsets. + * + * Mirrors the check the chain-level TSS payment verifier applies, so the token-coin path + * (`Erc7984Token`) enforces the same calldata shape as the base coin. + */ +function isCanonicalErc7984Calldata(data: string, types: string[]): boolean { + try { + const args = data.slice(10).toLowerCase(); + const decoded = getRawDecoded(types, Buffer.from(args, 'hex')); + const encodable = decoded.map((value) => (typeof value === 'string' ? addHexPrefix(value) : value)); + return optionalDeps.ethAbi.rawEncode(types, encodable).toString('hex') === args; + } catch { + return false; + } +} + export { Erc7984TokenConfig }; export class Erc7984Token extends Eth { @@ -882,6 +903,12 @@ export class Erc7984Token extends Eth { * 2. Decoded recipient matches txParams.recipients[0].address or buildParams.recipients[0].address. * 3. encryptedHandle and inputProof are structurally present (non-empty). * 4. txParams.recipients[0].amount is a positive integer and matches buildParams when both present. + * 5. The transaction carries zero native value and the calldata is canonical for its shape. + * + * Verification limit (CECHO-2689): the transferred amount is encrypted (`euint64` ciphertext plus + * an input proof), so the plaintext `recipients[0].amount` cannot be compared against it. The + * selector, token contract, recipient, native value and calldata shape are all enforced; the + * encrypted amount is verified only structurally (non-empty 32-byte handle, non-empty proof). * * Without txHex (first-signer / pre-signing path): * 1. Requires exactly one recipient in txParams. @@ -933,11 +960,9 @@ export class Erc7984Token extends Eth { return true; } - // Parse and decode the raw transaction - const txBuilder = this.getTransactionBuilder(); - txBuilder.from(txPrebuild.txHex); - const tx = await txBuilder.build(); - const txJson = tx.toJson(); + // Decode the original signed bytes. A TransactionBuilder round trip reserializes from the fields it + // models, so the checks below would inspect a rebuilt copy instead of what is signed. + const txJson = this.decodeRawTssTxFields(txPrebuild.txHex); let toAddress: string; let tokenContractAddress: string; @@ -973,6 +998,31 @@ export class Erc7984Token extends Eth { ); } + // 0. Native value must be zero. A confidentialTransfer moves an encrypted token amount; any + // nonzero `value` would additionally send the chain's native coin to the token contract. + if (txJson.value !== undefined && String(txJson.value) !== '0') { + throw new Error( + `verifyConfidentialTransfer: confidential transfer must not carry native value (got ${txJson.value})` + ); + } + + // 0b. Calldata must be the canonical ABI encoding for its shape. The EVM ignores trailing + // bytes; accepting them would sign more than the decoded intent describes. + const calldataTypes = txJson.data.startsWith(sendMultisigMethodId) + ? sendMultiSigTypes + : confidentialTransferWithProofTypes; + if (!isCanonicalErc7984Calldata(txJson.data, calldataTypes)) { + throw new Error('verifyConfidentialTransfer: confidential transfer calldata is not canonical'); + } + + // 0c. A confidential transfer carries exactly one recipient. A multi-recipient intent would + // silently ignore every entry after the first. + if (txParams?.recipients && txParams.recipients.length > 1) { + throw new Error( + `verifyConfidentialTransfer: confidential transfers support exactly 1 recipient, got ${txParams.recipients.length}` + ); + } + // 1. Token contract address must match this coin if (tokenContractAddress.toLowerCase() !== this.tokenContractAddress.toLowerCase()) { throw new Error( diff --git a/modules/sdk-coin-eth/test/unit/erc7984Token.ts b/modules/sdk-coin-eth/test/unit/erc7984Token.ts index ef6f40b965..7a9edf3c8a 100644 --- a/modules/sdk-coin-eth/test/unit/erc7984Token.ts +++ b/modules/sdk-coin-eth/test/unit/erc7984Token.ts @@ -30,7 +30,10 @@ import { TransferBuilderERC7984, confidentialTransferNoProofMethodId, approveMethodId, + AbstractEthLikeNewCoins, + EthTransactionData, } from '@bitgo/abstract-eth'; +import { FeeMarketEIP1559Transaction } from '@ethereumjs/tx'; import EthereumAbi from 'ethereumjs-abi'; import { addHexPrefix } from 'ethereumjs-util'; import { ethers } from 'ethers'; @@ -824,12 +827,15 @@ async function buildConfidentialTransferTxHex(opts: { recipientAddress: string; encryptedHandle: string; inputProof: string; + /** Native value carried by the outer sendMultiSig transaction (must be 0 for a real transfer). */ + value?: string; }): Promise { const key = testData.KEYPAIR_PRV.getKeys().prv as string; const txBuilder = getBuilder('hteth') as TransactionBuilder; txBuilder.fee({ fee: '1000000000', gasLimit: '12100000' }); txBuilder.counter(1); txBuilder.contract(opts.walletContractAddress); + txBuilder.value(opts.value ?? '0'); txBuilder.type(TransactionType.SendERC7984); const transferBuilder = txBuilder.transfer() as TransferBuilderERC7984; @@ -1158,6 +1164,61 @@ describe('verifyTransaction – confidential transfer (SendERC7984)', function ( }) .should.be.rejectedWith(/recipient address mismatch/); }); + + it('should throw when the sendMultiSig-wrapped confidential call carries native value', async function () { + const txHex = await buildConfidentialTransferTxHex({ + walletContractAddress: WALLET_CONTRACT, + tokenContractAddress: CTEST1_TOKEN_ADDRESS, + recipientAddress: RECIPIENT, + encryptedHandle: HANDLE, + inputProof: PROOF, + value: '1', + }); + + await coin + .verifyTransaction({ + txParams: { recipients: [{ address: RECIPIENT, amount: AMOUNT }] }, + txPrebuild: { txHex } as any, + wallet: {} as any, + }) + .should.be.rejectedWith(/must not carry native value/); + }); + + // The TransactionBuilder round trip re-encodes sendMultiSig calldata and drops trailing bytes, so the + // check must read the original signed bytes; a rebuilt copy would look canonical. + it('should throw when the signed sendMultiSig calldata carries trailing bytes', async function () { + const builtHex = await buildConfidentialTransferTxHex({ + walletContractAddress: WALLET_CONTRACT, + tokenContractAddress: CTEST1_TOKEN_ADDRESS, + recipientAddress: RECIPIENT, + encryptedHandle: HANDLE, + inputProof: PROOF, + }); + const common = AbstractEthLikeNewCoins.getCustomChainCommon(coin.getChainId()); + const built = EthTransactionData.fromSerialized(builtHex, common).toJson(); + const tampered = FeeMarketEIP1559Transaction.fromTxData( + { + nonce: 1, + maxPriorityFeePerGas: 10, + maxFeePerGas: 100, + gasLimit: Number(built.gasLimit), + to: built.to, + value: 0, + data: built.data + 'ff', + chainId: coin.getChainId(), + }, + { common } + ); + const txHex = '0x' + tampered.serialize().toString('hex'); + + await coin + .verifyTransaction({ + txParams: { recipients: [{ address: RECIPIENT, amount: AMOUNT }] }, + txPrebuild: { txHex } as never, + wallet: {} as never, + }) + .should.be.rejectedWith(/not canonical/); + }); }); // --------------------------------------------------------------------------- @@ -1173,6 +1234,10 @@ async function buildDirectConfidentialTransferTxHex(opts: { recipientAddress: string; encryptedHandle: string; inputProof: string; + /** Native value carried by the call (must be 0 for a real transfer). */ + value?: string; + /** Extra hex appended after the canonical calldata, to model trailing bytes an EVM would ignore. */ + appendCalldata?: string; }): Promise { const txBuilder = getBuilder('hteth') as TransactionBuilder; txBuilder.fee({ fee: '1000000000', gasLimit: '200000' }); @@ -1180,6 +1245,7 @@ async function buildDirectConfidentialTransferTxHex(opts: { txBuilder.type(TransactionType.ContractCall); // tx.to = token contract (EOA calls it directly) txBuilder.contract(opts.tokenContractAddress); + txBuilder.value(opts.value ?? '0'); // Inner calldata: confidentialTransfer(address, bytes32, bytes) — no sendMultiSig wrapper const calldata = new TransferBuilderERC7984() .to(opts.recipientAddress) @@ -1187,7 +1253,7 @@ async function buildDirectConfidentialTransferTxHex(opts: { .encryptedHandle(opts.encryptedHandle) .inputProof(opts.inputProof) .build(); - txBuilder.data(calldata); + txBuilder.data(calldata + (opts.appendCalldata ?? '')); const tx = await txBuilder.build(); return tx.toBroadcastFormat(); } @@ -1309,6 +1375,61 @@ describe('verifyTransaction – direct confidentialTransfer (hot/TSS EOA wallet) }) .should.be.rejectedWith(/amount mismatch/); }); + + it('should throw when the direct confidential call carries native value', async function () { + const txHex = await buildDirectConfidentialTransferTxHex({ + tokenContractAddress: CTEST1_TOKEN_ADDRESS, + recipientAddress: RECIPIENT, + encryptedHandle: HANDLE, + inputProof: PROOF, + value: '1', + }); + await coin + .verifyTransaction({ + txParams: { recipients: [{ address: RECIPIENT, amount: AMOUNT }] }, + txPrebuild: { txHex } as any, + wallet: {} as any, + }) + .should.be.rejectedWith(/must not carry native value/); + }); + + it('should throw when the direct confidential calldata has trailing bytes', async function () { + const txHex = await buildDirectConfidentialTransferTxHex({ + tokenContractAddress: CTEST1_TOKEN_ADDRESS, + recipientAddress: RECIPIENT, + encryptedHandle: HANDLE, + inputProof: PROOF, + appendCalldata: '00'.repeat(32), + }); + await coin + .verifyTransaction({ + txParams: { recipients: [{ address: RECIPIENT, amount: AMOUNT }] }, + txPrebuild: { txHex } as any, + wallet: {} as any, + }) + .should.be.rejectedWith(/not canonical/); + }); + + it('should throw when more than one recipient is declared', async function () { + const txHex = await buildDirectConfidentialTransferTxHex({ + tokenContractAddress: CTEST1_TOKEN_ADDRESS, + recipientAddress: RECIPIENT, + encryptedHandle: HANDLE, + inputProof: PROOF, + }); + await coin + .verifyTransaction({ + txParams: { + recipients: [ + { address: RECIPIENT, amount: AMOUNT }, + { address: WRONG_RECIPIENT, amount: AMOUNT }, + ], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + }) + .should.be.rejectedWith(/exactly 1 recipient/); + }); }); // --------------------------------------------------------------------------- diff --git a/modules/sdk-coin-eth/test/unit/eth.ts b/modules/sdk-coin-eth/test/unit/eth.ts index 9eeb9106d3..a0b0c76847 100644 --- a/modules/sdk-coin-eth/test/unit/eth.ts +++ b/modules/sdk-coin-eth/test/unit/eth.ts @@ -1626,7 +1626,7 @@ describe('ETH:', function () { }); }; - ['tokenApproval', 'customTx', 'defiApprove'].forEach((type) => { + ['tokenApproval', 'defiApprove'].forEach((type) => { it(`should reject approve(wrapper, amount) on the underlying relabelled as ${type}`, async function () { await expectDefiRejection( verifyAs(type, defiCalldata('approve(address,uint256)', [wrapper, amount])), @@ -1635,23 +1635,23 @@ describe('ETH:', function () { }); }); - it('should reject a mutated-amount wrapper approve relabelled as customTx', async function () { + it('should reject a mutated-amount wrapper approve relabelled as transferToken', async function () { await expectDefiRejection( - verifyAs('customTx', defiCalldata('approve(address,uint256)', [wrapper, '999999999999'])), + verifyAs('transferToken', defiCalldata('approve(address,uint256)', [wrapper, '999999999999'])), /must be declared as a wrapApprove intent/ ); }); it('should reject a wrapper approve with trailing bytes (an ERC-20 ignores them)', async function () { await expectDefiRejection( - verifyAs('customTx', defiCalldata('approve(address,uint256)', [wrapper, amount]) + '00'), + verifyAs('transferToken', defiCalldata('approve(address,uint256)', [wrapper, amount]) + '00'), /must be declared as a wrapApprove intent/ ); }); it('should not affect approvals of the underlying to other spenders', async function () { - (await verifyAs('customTx', defiCalldata('approve(address,uint256)', [address2, amount]))).should.equal(true); - (await verifyAs('tokenApproval', defiCalldata('approve(address,uint256)', [address2, amount]))).should.equal( + // tokenApproval and customTx have their own verifiers; an intent type with no verifier still passes untouched. + (await verifyAs('transferToken', defiCalldata('approve(address,uint256)', [address2, amount]))).should.equal( true ); }); @@ -1668,7 +1668,7 @@ describe('ETH:', function () { ); try { await coin.verifyTransaction({ - txParams: { type: 'customTx', wallet } as any, + txParams: { type: 'transferToken', wallet } as never, txPrebuild: { txHex, coin: 'hteth', walletId: 'w' } as any, wallet, verification: {}, @@ -1688,11 +1688,10 @@ describe('ETH:', function () { // Every type below skips the wrapApprove check and reaches the guard; none of these txs is an approve of a // wrapper, so all must verify exactly as they did before the guard existed. const benign: Array<[string, string, string]> = [ - ['customTx', defiCalldata('transfer(address,uint256)', [address2, amount]), underlying], - ['customTx', defiCalldata('approve(address,uint256)', [address2, amount]), underlying], - ['customTx', defiCalldata('approve(address,uint256)', [wrapper, amount]), address2], - ['tokenApproval', defiCalldata('approve(address,uint256)', [address2, amount]), underlying], - ['tokenApproval', defiCalldata('approve(address,uint256)', [wrapper, amount]), address2], + // tokenApproval and customTx are verified by their own handlers and are not part of this list. + ['transferToken', defiCalldata('transfer(address,uint256)', [address2, amount]), underlying], + ['transferToken', defiCalldata('approve(address,uint256)', [address2, amount]), underlying], + ['transferToken', defiCalldata('approve(address,uint256)', [wrapper, amount]), address2], ['acceleration', defiCalldata('transfer(address,uint256)', [address2, amount]), address2], ['fillNonce', '0x', address2], ['enabletoken', defiCalldata('transfer(address,uint256)', [address2, amount]), address2], @@ -1703,9 +1702,11 @@ describe('ETH:', function () { }); it('should not affect transfers to the underlying or approves of the wrapper on other contracts', async function () { - (await verifyAs('customTx', defiCalldata('transfer(address,uint256)', [wrapper, amount]))).should.equal(true); + (await verifyAs('transferToken', defiCalldata('transfer(address,uint256)', [wrapper, amount]))).should.equal( + true + ); ( - await verifyAs('customTx', defiCalldata('approve(address,uint256)', [wrapper, amount]), address2) + await verifyAs('transferToken', defiCalldata('approve(address,uint256)', [wrapper, amount]), address2) ).should.equal(true); }); diff --git a/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts b/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts index 9f0c05234d..526424a3b0 100644 --- a/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts +++ b/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts @@ -15,7 +15,7 @@ import { Wallet, } from '@bitgo/sdk-core'; import { AbstractEthLikeNewCoins, TransferBuilderERC7984 } from '@bitgo/abstract-eth'; -import { BaseCoin as StaticsBaseCoin, CoinFeature, coins, EthereumNetwork } from '@bitgo/statics'; +import { BaseCoin as StaticsBaseCoin, CoinFeature, coins, Erc7984Coin, EthereumNetwork } from '@bitgo/statics'; import { Hteth, TransactionBuilder } from '../../src'; import { getBuilder } from './getBuilder'; @@ -575,7 +575,7 @@ describe('TSS payment verification', function () { } for (const { route, useSerializedTxHex } of routes) { - it(`verifies a stored confidential payment from ${route}`, async function () { + it(`verifies a stored confidential payment from ${route} and warns only about the encrypted amount`, async function () { const request = storedPaymentRequest( confidentialRecipient, { value: confidentialSendAmount, symbol: confidentialToken }, @@ -583,7 +583,9 @@ describe('TSS payment verification', function () { ); const { error, boundary } = await runSigning(request, useSerializedTxHex); error.should.be.exactly(boundary); - warned(/ERC-7984 token: the payment calldata was not verified/).should.be.true(); + // The calldata is now verified; only the encrypted amount is unverifiable. + warned(/encrypted amount cannot be verified/).should.be.true(); + warned(/the payment calldata was not verified/).should.be.false(); }); it(`verifies a stored native payment from ${route} without warnings`, async function () { @@ -651,4 +653,285 @@ describe('TSS payment verification', function () { ); }); }); + + // CECHO-2689: tokenApproval must be verified, not merely warned about. Expected shape is + // approve(batcher, MAX_UINT256) on the declared token contract with zero native value. + describe('tokenApproval verification', function () { + const approveData = (spender: string, amount: string) => + calldata('approve', ['address', 'uint256'], [spender, amount]); + const maxUint256 = ((1n << 256n) - 1n).toString(); + const approvalIntent = (declaredToken: string | undefined) => ({ + type: 'tokenApproval', + ...(declaredToken === undefined ? {} : { tokenName: declaredToken }), + }); + + it('verifies approve(batcher, MAX_UINT256) on the declared token contract', async function () { + const txHex = await buildTx({ to: tokenContract, data: approveData(batcher, maxUint256) }); + (await verify(approvalIntent(tokenName), txHex)).should.be.true(); + warn.called.should.be.false(); + }); + + it('rejects an approval on a different token contract', async function () { + const txHex = await buildTx({ to: otherTokenContract, data: approveData(batcher, maxUint256) }); + await expectMismatch(verify(approvalIntent(tokenName), txHex), /not sent to the declared token contract/); + }); + + it('rejects approve() of an attacker spender', async function () { + const txHex = await buildTx({ to: tokenContract, data: approveData(otherRecipient, maxUint256) }); + await expectMismatch(verify(approvalIntent(tokenName), txHex), /spender does not match the network batcher/); + }); + + it('rejects a finite approval amount', async function () { + const txHex = await buildTx({ to: tokenContract, data: approveData(batcher, '1000') }); + await expectMismatch(verify(approvalIntent(tokenName), txHex), /must be MAX_UINT256/); + }); + + it('rejects native value on an approval', async function () { + const txHex = await buildTx({ to: tokenContract, value: '1', data: approveData(batcher, maxUint256) }); + await expectMismatch(verify(approvalIntent(tokenName), txHex), /must not carry native value/); + }); + + it('rejects a non-approve selector', async function () { + const txHex = await buildTx({ to: tokenContract, data: erc20Transfer(recipient, '1000') }); + await expectMismatch(verify(approvalIntent(tokenName), txHex), /must use ERC-20 approve/); + }); + + it('rejects trailing bytes after the approve arguments', async function () { + const txHex = await buildTx({ + to: tokenContract, + data: approveData(batcher, maxUint256) + '00'.repeat(32), + }); + await expectMismatch(verify(approvalIntent(tokenName), txHex), /not canonical/); + }); + + it('rejects a tokenApproval with no declared token', async function () { + const txHex = await buildTx({ to: tokenContract, data: approveData(batcher, maxUint256) }); + await expectMismatch(verify(approvalIntent(undefined), txHex), /requires a declared tokenName/); + }); + + it('rejects a token that cannot be resolved on this network', async function () { + const txHex = await buildTx({ to: tokenContract, data: approveData(batcher, maxUint256) }); + await expectMismatch( + verify(approvalIntent('hteth:notatoken'), txHex), + /cannot be resolved to a contract on this network/ + ); + }); + + it('still rejects approve(wrapper, MAX) relabelled as tokenApproval', async function () { + const pair = coins.get('hteth:cusdt') as Erc7984Coin; + const txHex = await buildTx({ + to: String(pair.underlyingErc20Address), + data: approveData(String(pair.contractAddress), maxUint256), + }); + await expectMismatch(verify(approvalIntent('hteth:cusdt'), txHex), /must be declared as a wrapApprove intent/); + }); + }); + + // CECHO-2689 (Nov 19): a payment of an ERC-7984 token must use confidentialTransfer and name the + // declared recipient, token contract and zero native value. The encrypted amount stays a warning. + describe('ERC-7984 confidential payment verification', function () { + const confidentialToken = 'hteth:ctest1'; + const confidentialContract = String((coins.get(confidentialToken) as Erc7984Coin).contractAddress); + const encryptedHandle = '0x' + 'ab'.repeat(32); + const inputProof = '0x' + 'cd'.repeat(50); + const confidentialIntent = (address: string) => ({ + type: 'payment', + recipients: [{ address, amount: '1000000', tokenName: confidentialToken }], + }); + const confidentialTransferTo = (to: string) => + new TransferBuilderERC7984() + .to(to) + .tokenContractAddress(confidentialContract) + .encryptedHandle(encryptedHandle) + .inputProof(inputProof) + .build(); + + it('verifies a confidentialTransfer to the declared recipient on the declared token', async function () { + const txHex = await buildTx({ to: confidentialContract, data: confidentialTransferTo(recipient) }); + (await verify(confidentialIntent(recipient), txHex)).should.be.true(); + warned(/encrypted amount cannot be verified/).should.be.true(); + }); + + it('rejects approve(attacker, MAX) relabelled as a confidential payment', async function () { + const attack = calldata( + 'approve', + ['address', 'uint256'], + [otherRecipient, '115792089237316195423570985008687907853269984665640564039457584007913129639935'] + ); + const txHex = await buildTx({ to: confidentialContract, data: attack }); + await expectMismatch(verify(confidentialIntent(recipient), txHex), /must use confidentialTransfer/); + }); + + it('rejects a confidentialTransfer to a different recipient', async function () { + const txHex = await buildTx({ to: confidentialContract, data: confidentialTransferTo(otherRecipient) }); + await expectMismatch(verify(confidentialIntent(recipient), txHex), /destination address does not match/); + }); + + it('rejects a confidentialTransfer sent to a different token contract', async function () { + const txHex = await buildTx({ to: otherTokenContract, data: confidentialTransferTo(recipient) }); + await expectMismatch(verify(confidentialIntent(recipient), txHex), /not sent to the declared token contract/); + }); + + it('rejects native value on a confidential payment', async function () { + const txHex = await buildTx({ to: confidentialContract, value: '1', data: confidentialTransferTo(recipient) }); + await expectMismatch(verify(confidentialIntent(recipient), txHex), /must not carry native value/); + }); + + it('rejects trailing bytes after the confidentialTransfer arguments', async function () { + const txHex = await buildTx({ + to: confidentialContract, + data: confidentialTransferTo(recipient) + '00'.repeat(32), + }); + await expectMismatch(verify(confidentialIntent(recipient), txHex), /not canonical/); + }); + + it('rejects a batch that names an ERC-7984 token', async function () { + const txHex = await buildTx({ + to: batcher, + data: tokenBatch(confidentialContract, [recipient, otherRecipient], ['100', '200']), + }); + const intent = { + type: 'transfer', + recipients: [ + { address: recipient, amount: '100', tokenName: confidentialToken }, + { address: otherRecipient, amount: '200', tokenName: confidentialToken }, + ], + }; + await expectMismatch(verify(intent, txHex), /cannot be paid through a batch/); + }); + }); + + // Stored-intent signing carries no caller txParams, so the token survives only in the persisted + // intent. Both MPC versions must still verify the approval (tokenName propagation). + describe('stored tokenApproval intent without caller txParams', function () { + const approvalToken = tokenName; + const approvalTokenContract = tokenContract; + const maxUint256 = ((1n << 256n) - 1n).toString(); + const signingBoundaryMessage = 'signing boundary reached after intent verification'; + const signingMaterial = JSON.stringify({ + pShare: { i: 1, n: 'stub-user-paillier-modulus' }, + backupNShare: { i: 3, n: 'stub-backup-paillier-modulus' }, + }); + + function approvalBytes(spender: string) { + const common = AbstractEthLikeNewCoins.getCustomChainCommon(coin.getChainId()); + const tx = FeeMarketEIP1559Transaction.fromTxData( + { + nonce: 1, + maxPriorityFeePerGas: 10, + maxFeePerGas: 100, + gasLimit: 200000, + to: approvalTokenContract, + value: 0, + data: calldata('approve', ['address', 'uint256'], [spender, maxUint256]), + chainId: coin.getChainId(), + }, + { common } + ); + return { + signableHex: tx.getMessageToSign(false).toString('hex'), + serializedTxHex: tx.serialize().toString('hex'), + }; + } + + function storedApprovalRequest(txBytes: { signableHex: string; serializedTxHex: string }): TxRequest { + return { + txRequestId: 'stored-token-approval', + apiVersion: 'full', + walletId: 'storedApprovalWallet', + intent: { intentType: 'tokenApproval', tokenName: approvalToken }, + transactions: [{ unsignedTx: { derivationPath: 'm/0', ...txBytes }, signatureShares: [] }], + } as unknown as TxRequest; + } + + async function runMpcv2( + txRequest: TxRequest, + useSerializedTxHex: boolean + ): Promise<{ error: Error; boundary: Error }> { + const signingWallet = new Wallet(bitgo, coin, { + id: 'storedApprovalWallet', + multisigType: 'tss', + multisigTypeVersion: 'MPCv2', + coinSpecific: { baseAddress }, + }); + const utils = new EcdsaMPCv2Utils(bitgo, coin, signingWallet); + sinon + .stub(utils as unknown as Record Promise>, 'pickBitgoPubGpgKeyForSigning') + .resolves('stubbed-gpg-key'); + + const baseConfig = coin.getConfig(); + const features = baseConfig.features.filter((f) => f !== CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX); + sinon.stub(coin, 'getConfig').returns({ + ...baseConfig, + features: useSerializedTxHex ? [...features, CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX] : features, + } as unknown as Readonly); + + const boundary = new Error(signingBoundaryMessage); + sinon.stub(coin, 'getHashFunction').returns({ + update: () => { + throw boundary; + }, + } as unknown as Hash); + + try { + await utils.signTxRequest({ txRequest, prv: '', reqId: new RequestTracer() }); + } catch (e) { + return { error: e as Error, boundary }; + } + throw new Error('expected signTxRequest to reject'); + } + + async function runMpcv1( + txRequest: TxRequest, + useSerializedTxHex: boolean + ): Promise<{ error: Error; boundary: Error }> { + const signingWallet = new Wallet(bitgo, coin, { + id: 'storedApprovalWallet', + multisigType: 'tss', + coinSpecific: { baseAddress }, + }); + const utils = new EcdsaUtils(bitgo, coin, signingWallet); + const baseConfig = coin.getConfig(); + const features = baseConfig.features.filter((f) => f !== CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX); + sinon.stub(coin, 'getConfig').returns({ + ...baseConfig, + features: useSerializedTxHex ? [...features, CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX] : features, + } as unknown as Readonly); + + const boundary = new Error(signingBoundaryMessage); + sinon.stub(utils, 'getOfflineSignerPaillierModulus').throws(boundary); + + try { + await utils.signTxRequest({ txRequest, prv: signingMaterial, reqId: new RequestTracer() }); + } catch (e) { + return { error: e as Error, boundary }; + } + throw new Error('expected signTxRequest to reject'); + } + + const routes = [ + { route: 'signableHex', useSerializedTxHex: false }, + { route: 'serializedTxHex', useSerializedTxHex: true }, + ]; + + for (const { route, useSerializedTxHex } of routes) { + it(`verifies a stored approval from ${route} (MPCv2)`, async function () { + const { error, boundary } = await runMpcv2(storedApprovalRequest(approvalBytes(batcher)), useSerializedTxHex); + error.should.be.exactly(boundary); + warn.called.should.be.false(); + }); + + it(`verifies a stored approval from ${route} (MPCv1)`, async function () { + const { error, boundary } = await runMpcv1(storedApprovalRequest(approvalBytes(batcher)), useSerializedTxHex); + error.should.be.exactly(boundary); + warn.called.should.be.false(); + }); + + it(`rejects a stored approval naming an attacker spender from ${route} (MPCv2)`, async function () { + const { error } = await runMpcv2(storedApprovalRequest(approvalBytes(otherRecipient)), useSerializedTxHex); + error.should.be.instanceOf(TxIntentMismatchRecipientError); + error.message.should.match(/spender does not match the network batcher/); + }); + } + }); }); diff --git a/modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts b/modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts index 5d18c248ad..733eaa6918 100644 --- a/modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts +++ b/modules/sdk-core/src/bitgo/baseCoin/iBaseCoin.ts @@ -294,6 +294,8 @@ export interface TransactionParams { executorPartyId?: string; /** Canton split (fanout): number of equal-value holdings the selected unspents are split into. */ numberOfSplits?: number; + /** Top-level token name for token-scoped intents (e.g. `tokenApproval`, `consolidate`). */ + tokenName?: string; } export interface AddressVerificationData { diff --git a/modules/sdk-core/src/bitgo/utils/tss/recipientUtils.ts b/modules/sdk-core/src/bitgo/utils/tss/recipientUtils.ts index a08a1d94b1..1c108b891e 100644 --- a/modules/sdk-core/src/bitgo/utils/tss/recipientUtils.ts +++ b/modules/sdk-core/src/bitgo/utils/tss/recipientUtils.ts @@ -207,6 +207,20 @@ export function resolveEffectiveTxParams( effectiveTxParams.wrapParams = { tokenName: intent.tokenName, amount: intent.amount }; } + // Propagate the persisted top-level tokenName for `tokenApproval` only: those intents store tokenName + // at the intent root with no recipients, and pendingApproval/stored-intent signing carries no caller + // txParams. Any other type must not inherit it, or a caller's native payment would be verified as a + // payment of the stored token. + if ( + !effectiveTxParams.tokenName && + effectiveTxParams.type === 'tokenApproval' && + intent?.intentType === 'tokenApproval' && + typeof intent.tokenName === 'string' && + intent.tokenName !== '' + ) { + effectiveTxParams.tokenName = intent.tokenName; + } + // Propagate the persisted tx-level memo from the intent. Signing paths that carry no txParams // (pendingApproval.approve() -> recreateTxRequest() -> signTxRequest()) would otherwise reach // the coin verifier with a memo-less txParams while the prebuilt transaction carries the memo diff --git a/modules/sdk-core/test/unit/bitgo/utils/tss/recipientUtils.ts b/modules/sdk-core/test/unit/bitgo/utils/tss/recipientUtils.ts index 8dd1a87547..e1d7bfba64 100644 --- a/modules/sdk-core/test/unit/bitgo/utils/tss/recipientUtils.ts +++ b/modules/sdk-core/test/unit/bitgo/utils/tss/recipientUtils.ts @@ -208,6 +208,46 @@ describe('recipientUtils', function () { }); }); + describe('tokenName propagation (tokenApproval)', function () { + const approvalTokenName = 'hteth:stgusd1'; + + it('derives tokenName from the intent when txParams is undefined (pendingApproval re-sign path)', function () { + const txRequest = makeTxRequest({ + intent: { intentType: 'tokenApproval', tokenName: approvalTokenName } as PopulatedIntent, + }); + const result = resolveEffectiveTxParams(txRequest, undefined); + assert.strictEqual(result.tokenName, approvalTokenName); + assert.strictEqual(result.type, 'tokenApproval'); + assert.strictEqual(result.recipients, undefined); + }); + + it('does not overwrite a caller-supplied tokenName', function () { + const txRequest = makeTxRequest({ + intent: { intentType: 'tokenApproval', tokenName: approvalTokenName } as PopulatedIntent, + }); + assert.strictEqual(resolveEffectiveTxParams(txRequest, { tokenName: 'hteth:usdc' }).tokenName, 'hteth:usdc'); + }); + + it('does not attach a stored tokenName to a caller-declared payment', function () { + const txRequest = makeTxRequest({ + intent: { intentType: 'payment', tokenName: approvalTokenName, recipients: [] } as unknown as PopulatedIntent, + }); + const result = resolveEffectiveTxParams( + txRequest, + { type: 'transfer', recipients: [{ address: '0xabc', amount: '1' }] }, + 'hteth' + ); + assert.strictEqual(result.tokenName, undefined); + }); + + it('does not attach a stored tokenApproval tokenName when the caller declared another type', function () { + const txRequest = makeTxRequest({ + intent: { intentType: 'tokenApproval', tokenName: approvalTokenName } as PopulatedIntent, + }); + assert.strictEqual(resolveEffectiveTxParams(txRequest, { type: 'transfer' }).tokenName, undefined); + }); + }); + describe('tx-level memo propagation', function () { it('derives memo from the intent when txParams is undefined (pendingApproval re-sign path)', function () { const txRequest = makeTxRequest({