From 9113b40745739bb0c7d7bb91da111694aca63ae2 Mon Sep 17 00:00:00 2001 From: Rakesh Reddy Date: Thu, 19 Nov 2026 17:35:09 +0530 Subject: [PATCH] fix(sdk-coin-eth): strictly verify the multisig enable-token sendMultiSig operation (CECHO-2815) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The multisig branch of Erc7984Token.verifyEnableTokenTransaction compared only txPrebuild.buildParams.recipients — client-attached echo data built by Wallet.buildTokenEnablements from the caller's own enableTokens — so the operation the user actually signs was never inspected. Onchain-multisig users sign the sendMultiSig operation hash over txPrebuild.recipients[0] (address, amount, data), never over txHex, and the MultiSigV3 contract enforces at execution that the broadcast args hash to that op: a compromised platform could serve any recipient (attacker contract with native value, ERC-20 approve theft, or a delegate substitution) and the user would first-sign it. Strict flow: bind the signed recipient in full — 1. sendMultiSig native value must be 0; 2. the recipient data must decode fail-closed as a delegation calldata (rejects approve/transfer and smuggled inner calls); 3. aclMulticall shape must target the ACL contract (the forwarder shape is bound on-chain by onlyParent plus the enforced callFromParent target/value); 4. verifyStrictEnableTokenCalldata binds delegate == pinned enterprise viewing key, future expiry, and an exact deduplicated match against the requested tokens (CECHO-2720 helper, unchanged); 5. when the prebuild carries a txHex, its sendMultiSig args must mirror the recipient — a diverging (decoy) txHex is rejected. Gate — non-breaking by construction: Flipt flag multisig-enable-token-strict-verification, delivered by the platform as the typed prebuild field multisigEnableTokenStrictVerification. The legacy flow is the default: absent or false keeps it; only an explicit true enables the strict flow. Bumping this SDK into any deployment before the platform stamps the field is therefore a no-op — behavior is byte-for-byte the pre-fix flow. Activation (stamping true by default) is the platform-side follow-up; flipping the Flipt flag to false is the runtime kill switch once active. Purpose-scoped: one declared field for this one check, no generic flag map on SDK types. Tests: 14 multisig strict-path cases — benign both delegation shapes (flag enabled by the platform), txHex mirror pass, value theft, approve theft, delegate substitution, smuggled inner call, wrong ACL target, callFromParent theft shape, decoy txHex, non-sendMultiSig txHex, missing recipient, and the legacy-default proofs: an absent flag and an explicit false both keep a fully hostile prebuild verifying on the legacy flow (bump-safety and kill-switch). The five legacy-path tests run with no flag on the prebuild — the exact shape the SDK sees before the platform-side change. sdk-coin-eth 592 passing, abstract-eth 188 passing. --- .../src/abstractEthLikeNewCoins.ts | 5 + modules/sdk-coin-eth/src/erc7984Token.ts | 363 +++++++++++++----- .../sdk-coin-eth/test/unit/erc7984Token.ts | 170 +++++++- 3 files changed, 431 insertions(+), 107 deletions(-) diff --git a/modules/abstract-eth/src/abstractEthLikeNewCoins.ts b/modules/abstract-eth/src/abstractEthLikeNewCoins.ts index b07629af0f..a7b910e4a9 100644 --- a/modules/abstract-eth/src/abstractEthLikeNewCoins.ts +++ b/modules/abstract-eth/src/abstractEthLikeNewCoins.ts @@ -166,6 +166,11 @@ export interface TransactionPrebuild extends BaseTransactionPrebuild { eip1559?: EIP1559; isBatch?: boolean; }; + /** + * Server-evaluated Flipt rollout state for the multisig enable-token verification: + * absent or false keeps the legacy flow; an explicit true enables the strict flow. + */ + multisigEnableTokenStrictVerification?: boolean; } export interface SignFinalOptions { diff --git a/modules/sdk-coin-eth/src/erc7984Token.ts b/modules/sdk-coin-eth/src/erc7984Token.ts index 499a10482e..2a09a7aef9 100644 --- a/modules/sdk-coin-eth/src/erc7984Token.ts +++ b/modules/sdk-coin-eth/src/erc7984Token.ts @@ -40,15 +40,24 @@ import { finalizeUnwrapMethodId, UINT64_MAX, decodeTransferData, + TransactionPrebuild, } from '@bitgo/abstract-eth'; import { bip32 } from '@bitgo/secp256k1'; import * as _ from 'lodash'; +import { BigNumber } from 'bignumber.js'; import { Eth } from './eth'; import { TransactionBuilder } from './lib'; export { Erc7984TokenConfig }; +/** The sendMultiSig operation an onchain-multisig user key signs; the operation-hash source. */ +interface MultisigSignedOperation { + address: string; + amount?: string | number; + data?: string; +} + export class Erc7984Token extends Eth { public readonly tokenConfig: Erc7984TokenConfig; protected readonly sendMethodName: 'sendMultiSig' | 'sendMultiSigToken'; @@ -738,135 +747,277 @@ export class Erc7984Token extends Eth { /** * Verifies a token enablement transaction for ERC-7984 decryption delegation. - * + * Routes by wallet type; on the multisig path the legacy flow is the default and + * the platform-delivered flag state (explicit true) enables the strict flow. + */ + private async verifyEnableTokenTransaction(params: VerifyEthTransactionOptions): Promise { + const { txPrebuild, walletType } = params; + if (walletType === 'tss') { + return this.verifyEnableTokenTransactionTss(params); + } + if (txPrebuild.multisigEnableTokenStrictVerification !== true) { + return this.verifyEnableTokenTransactionLegacyMultisig(params); + } + return this.verifyEnableTokenTransactionStrictMultisig(params); + } + + /** * TSS path: decodes the raw tx and verifies it calls the ACL contract with * calldata that covers all requested token contract addresses. - * - * Multisig path: verifies the buildParams recipients carry the correct tokenNames - * and zero amounts. */ - private async verifyEnableTokenTransaction(params: VerifyEthTransactionOptions): Promise { - const { txParams, txPrebuild, walletType } = params; + private async verifyEnableTokenTransactionTss(params: VerifyEthTransactionOptions): Promise { + const { txParams, txPrebuild } = params; + const enableTokens = txParams.enableTokens; + if (!enableTokens || enableTokens.length === 0) { + throw new Error('verifyEnableTokenTransaction: enableTokens must be non-empty for TSS path'); + } + if (!txPrebuild.txHex) { + throw new Error('verifyEnableTokenTransaction: missing txHex in txPrebuild'); + } - if (walletType === 'tss') { - // TSS path: full raw-tx decode - const enableTokens = txParams.enableTokens; - if (!enableTokens || enableTokens.length === 0) { - throw new Error('verifyEnableTokenTransaction: enableTokens must be non-empty for TSS path'); - } - if (!txPrebuild.txHex) { - throw new Error('verifyEnableTokenTransaction: missing txHex in txPrebuild'); - } + // Resolve requested token names → contract addresses + const requestedAddresses = enableTokens.map((t) => { + const tokenCoin = this.bitgo.coin(t.name) as Erc7984Token; + return tokenCoin.tokenContractAddress.toLowerCase(); + }); - // Resolve requested token names → contract addresses - const requestedAddresses = enableTokens.map((t) => { - const tokenCoin = this.bitgo.coin(t.name) as Erc7984Token; - return tokenCoin.tokenContractAddress.toLowerCase(); - }); - - // Parse the raw transaction - const txBuilder = this.getTransactionBuilder(); - txBuilder.from(txPrebuild.txHex); - const tx = await txBuilder.build(); - const txJson = tx.toJson(); - - // Verify transaction targets the correct contract based on calldata shape - const network = this.getNetwork() as EthereumNetwork; - const aclContractAddress = network?.zamaAclContractAddress; - if (!aclContractAddress) { - throw new Error('verifyEnableTokenTransaction: zamaAclContractAddress not configured for this network'); - } - if (!txJson.to) { - throw new Error('verifyEnableTokenTransaction: transaction is missing recipient address'); - } + // Parse the raw transaction + const txBuilder = this.getTransactionBuilder(); + txBuilder.from(txPrebuild.txHex); + const tx = await txBuilder.build(); + const txJson = tx.toJson(); - // Inspect calldata method ID to distinguish root wallet from forwarder wallet: - // aclMulticallMethodId → root wallet: to = ACL contract directly - // callFromParentMethodId → forwarder wallet: to = forwarder, ACL address is inside calldata - const calldataMethodId = txJson.data.slice(0, 10); - if (calldataMethodId === aclMulticallMethodId) { - // Root wallet (base address): tx calls the ACL contract directly - if (txJson.to.toLowerCase() !== aclContractAddress.toLowerCase()) { - throw new Error( - `verifyEnableTokenTransaction: transaction target ${txJson.to} does not match ACL contract ${aclContractAddress}` - ); - } - } else if (calldataMethodId === callFromParentMethodId) { - // Forwarder wallet: tx calls the forwarder, which calls the ACL via callFromParent. - // The forwarder address is wallet-specific and cannot be statically verified here; - // token address correctness is still verified below via calldata decoding. - } else { + // Verify transaction targets the correct contract based on calldata shape + const network = this.getNetwork() as EthereumNetwork; + const aclContractAddress = network?.zamaAclContractAddress; + if (!aclContractAddress) { + throw new Error('verifyEnableTokenTransaction: zamaAclContractAddress not configured for this network'); + } + if (!txJson.to) { + throw new Error('verifyEnableTokenTransaction: transaction is missing recipient address'); + } + + // Inspect calldata method ID to distinguish root wallet from forwarder wallet: + // aclMulticallMethodId → root wallet: to = ACL contract directly + // callFromParentMethodId → forwarder wallet: to = forwarder, ACL address is inside calldata + const calldataMethodId = txJson.data.slice(0, 10); + if (calldataMethodId === aclMulticallMethodId) { + // Root wallet (base address): tx calls the ACL contract directly + if (txJson.to.toLowerCase() !== aclContractAddress.toLowerCase()) { throw new Error( - `verifyEnableTokenTransaction: unrecognised calldata method ID ${calldataMethodId}; expected multicall or callFromParent` + `verifyEnableTokenTransaction: transaction target ${txJson.to} does not match ACL contract ${aclContractAddress}` ); } + } else if (calldataMethodId === callFromParentMethodId) { + // Forwarder wallet: tx calls the forwarder, which calls the ACL via callFromParent. + // The forwarder address is wallet-specific and cannot be statically verified here; + // token address correctness is still verified below via calldata decoding. + } else { + throw new Error( + `verifyEnableTokenTransaction: unrecognised calldata method ID ${calldataMethodId}; expected multicall or callFromParent` + ); + } - // Verify value is 0 - if (txJson.value !== '0') { - throw new Error(`verifyEnableTokenTransaction: expected transaction value 0 but got ${txJson.value}`); - } + // Verify value is 0 + if (txJson.value !== '0') { + throw new Error(`verifyEnableTokenTransaction: expected transaction value 0 but got ${txJson.value}`); + } - // Decode token addresses from calldata and verify all requested tokens are present - const decodedAddresses = decodeTokenAddressesFromDelegationCalldata(txJson.data); - for (const requested of requestedAddresses) { - if (!decodedAddresses.includes(requested)) { - throw new Error( - `verifyEnableTokenTransaction: requested token ${requested} not found in delegation calldata` - ); - } + // Decode token addresses from calldata and verify all requested tokens are present + const decodedAddresses = decodeTokenAddressesFromDelegationCalldata(txJson.data); + for (const requested of requestedAddresses) { + if (!decodedAddresses.includes(requested)) { + throw new Error(`verifyEnableTokenTransaction: requested token ${requested} not found in delegation calldata`); } + } - // CECHO-2720 rollout gate: strict delegation verification is enforced on test and - // staging environments first; prod keeps the legacy checks above for one release - // cycle while staging/testnet validation proves there are no false positives. - // This gate must be removed (enforcing everywhere) in the next release. - if (this.bitgo.env === 'test' || this.bitgo.env === 'staging') { - this.verifyStrictEnableTokenCalldata(txJson, aclContractAddress, requestedAddresses); - } + // CECHO-2720 rollout gate: strict delegation verification is enforced on test and + // staging environments first; prod keeps the legacy checks above for one release + // cycle while staging/testnet validation proves there are no false positives. + // This gate must be removed (enforcing everywhere) in the next release. + if (this.bitgo.env === 'test' || this.bitgo.env === 'staging') { + this.verifyStrictEnableTokenCalldata(txJson, aclContractAddress, requestedAddresses); + } - return true; - } else { - // Multisig path: buildParams-level check - const recipients = txPrebuild.buildParams?.recipients as - | Array<{ tokenName?: string; amount?: string }> - | undefined; - if (!recipients || recipients.length === 0) { - throw new Error('verifyEnableTokenTransaction: missing buildParams.recipients for multisig path'); - } + return true; + } + + /** + * Requested token names: enableTokens when present (prebuildAndSignTransaction + * merges the original params over the buildParams), else the client-built + * recipients' tokenNames. Empty when the caller supplied neither. + */ + private resolveRequestedTokenNames(txParams: VerifyEthTransactionOptions['txParams']): string[] { + if (txParams.enableTokens && txParams.enableTokens.length > 0) { + return txParams.enableTokens.map((t) => t.name); + } + if (txParams.recipients && txParams.recipients.length > 0) { + return txParams.recipients.map((r) => r.tokenName).filter((name): name is string => Boolean(name)); + } + return []; + } + + private resolveRequestedTokenAddresses(txParams: VerifyEthTransactionOptions['txParams']): string[] { + const tokenNames = this.resolveRequestedTokenNames(txParams); + if (tokenNames.length === 0) { + throw new Error('verifyEnableTokenTransaction: requested tokens must be non-empty for the multisig strict path'); + } + return tokenNames.map((name) => (this.bitgo.coin(name) as Erc7984Token).tokenContractAddress.toLowerCase()); + } - // Determine requested token names from txParams - const requestedTokenNames: string[] = []; - if (txParams.enableTokens && txParams.enableTokens.length > 0) { - requestedTokenNames.push(...txParams.enableTokens.map((t) => t.name)); - } else if (txParams.recipients && txParams.recipients.length > 0) { - requestedTokenNames.push(...txParams.recipients.map((r: any) => r.tokenName).filter(Boolean)); + /** + * The sendMultiSig operation that the multisig user key signs, resolved exactly as + * the signer does (Eth.signTransaction: txPrebuild.recipients || txPrebuild.txInfo?.recipients): + * exactly one recipient, and its address must be present. + */ + private resolveSignedMultisigOperation(txPrebuild: TransactionPrebuild): MultisigSignedOperation { + const recipients = txPrebuild.recipients || txPrebuild.txInfo?.recipients; + const recipient = Array.isArray(recipients) && recipients.length === 1 ? recipients[0] : undefined; + if (!recipient?.address) { + throw new Error( + 'verifyEnableTokenTransaction: multisig prebuild must carry exactly one recipient with an address — the sendMultiSig operation that gets signed' + ); + } + const data = 'data' in recipient && typeof recipient.data === 'string' ? recipient.data : undefined; + return { address: recipient.address, amount: recipient.amount, data }; + } + + /** + * Legacy multisig enable-token verification, the default flow until the + * platform-delivered flag enables the strict flow. + * Checks only txPrebuild.buildParams.recipients, which Wallet.buildTokenEnablements + * attaches client-side from the caller's own enableTokens — it validates the client's + * own request, not the prebuild the platform returned, and so provides no protection + * against a compromised platform. Do not extend this path; new checks belong in the + * strict flow. + */ + private verifyEnableTokenTransactionLegacyMultisig(params: VerifyEthTransactionOptions): boolean { + const { txParams, txPrebuild } = params; + const recipients = txPrebuild.buildParams?.recipients as Array<{ tokenName?: string; amount?: string }> | undefined; + if (!recipients || recipients.length === 0) { + throw new Error('verifyEnableTokenTransaction: missing buildParams.recipients for multisig path'); + } + + for (const recipient of recipients) { + if (!recipient.tokenName) { + throw new Error('verifyEnableTokenTransaction: recipient is missing tokenName in buildParams'); + } + if (recipient.amount !== '0') { + throw new Error( + `verifyEnableTokenTransaction: expected amount 0 for token enablement but got ${recipient.amount}` + ); } + } - // Verify all recipients have tokenName and amount = '0' - for (const recipient of recipients) { - if (!recipient.tokenName) { - throw new Error('verifyEnableTokenTransaction: recipient is missing tokenName in buildParams'); - } - if (recipient.amount !== '0') { + const requestedTokenNames = this.resolveRequestedTokenNames(txParams); + if (requestedTokenNames.length > 0) { + const recipientTokenNames = recipients.map((r) => r.tokenName); + for (const requested of requestedTokenNames) { + if (!recipientTokenNames.includes(requested)) { throw new Error( - `verifyEnableTokenTransaction: expected amount 0 for token enablement but got ${recipient.amount}` + `verifyEnableTokenTransaction: requested token ${requested} not found in buildParams recipients` ); } } + } - // Verify requested token names are present in recipients - if (requestedTokenNames.length > 0) { - const recipientTokenNames = recipients.map((r) => r.tokenName); - for (const requested of requestedTokenNames) { - if (!recipientTokenNames.includes(requested)) { - throw new Error( - `verifyEnableTokenTransaction: requested token ${requested} not found in buildParams recipients` - ); - } - } - } + return true; + } - return true; + /** + * Strict multisig enable-token verification — enabled by the platform-delivered flag. + * + * Onchain-multisig users sign the sendMultiSig operation hash over + * txPrebuild.recipients[0] = (address, amount, data): Eth.signTransaction resolves the + * recipients from the prebuild (never from client params) and hashes the data verbatim, + * halfSigned carries no txHex, and the MultiSigV3 contract enforces at execution that + * the broadcast args hash to the op the user signed. recipients[0] is therefore the + * single authoritative binding, and it is verified here in full: + * 1. amount == 0 — a non-zero sendMultiSig value moves native funds directly. + * 2. the data decodes fail-closed as a delegation calldata — rejects any other + * selector (e.g. an ERC-20 approve theft prebuild) and smuggled inner calls. + * 3. aclMulticall shape: the target must be the ACL contract (root wallet). + * callFromParent shape: the forwarder address is wallet-specific and not + * statically verifiable (same decision as the TSS path); the on-chain + * onlyParent modifier plus the enforced callFromParent target/value close + * the fund-theft vector regardless of which forwarder is targeted. + * 4. verifyStrictEnableTokenCalldata binds the delegate to the pinned enterprise + * viewing key (fail closed when unpinned), a future expiry, an exact + * deduplicated match against the requested tokens, and — for the + * callFromParent shape — target == ACL contract with zero native value. + * 5. When the prebuild carries a txHex, its sendMultiSig args must mirror + * recipients[0] exactly: a diverging txHex (e.g. a decoy that passes + * verification while different args get signed) is rejected. + */ + private async verifyEnableTokenTransactionStrictMultisig(params: VerifyEthTransactionOptions): Promise { + const { txParams, txPrebuild } = params; + + const requestedAddresses = this.resolveRequestedTokenAddresses(txParams); + const aclContractAddress = (this.getNetwork() as EthereumNetwork)?.zamaAclContractAddress; + if (!aclContractAddress) { + throw new Error('verifyEnableTokenTransaction: zamaAclContractAddress not configured for this network'); + } + + const operation = this.resolveSignedMultisigOperation(txPrebuild); + if (new BigNumber(operation.amount ?? 0).comparedTo(0) !== 0) { + throw new Error(`verifyEnableTokenTransaction: expected sendMultiSig value 0 but got ${operation.amount}`); + } + if (!operation.data || operation.data === '0x') { + throw new Error('verifyEnableTokenTransaction: multisig prebuild recipient is missing delegation calldata'); + } + const delegation = decodeDelegationCallsFromCalldata(operation.data); + + if (delegation.shape === 'aclMulticall' && operation.address.toLowerCase() !== aclContractAddress.toLowerCase()) { + throw new Error( + `verifyEnableTokenTransaction: sendMultiSig target ${operation.address} does not match ACL contract ${aclContractAddress}` + ); + } + + this.verifyStrictEnableTokenCalldata( + { to: operation.address, data: operation.data, value: '0' }, + aclContractAddress, + requestedAddresses + ); + + if (txPrebuild.txHex) { + await this.assertTxHexMirrorsSignedOperation(txPrebuild.txHex, operation); + } + return true; + } + + /** + * The prebuild txHex, when present, must encode the same sendMultiSig operation that + * will be signed — a diverging txHex (e.g. a decoy that passes verification while + * different args get signed) is rejected. + */ + private async assertTxHexMirrorsSignedOperation(txHex: string, operation: MultisigSignedOperation): Promise { + const txBuilder = this.getTransactionBuilder(); + txBuilder.from(txHex); + const txData = (await txBuilder.build()).toJson().data || ''; + if (!txData.toLowerCase().startsWith(sendMultisigMethodId.toLowerCase())) { + throw new Error( + 'verifyEnableTokenTransaction: multisig prebuild txHex must be a sendMultiSig call to the wallet contract' + ); + } + const decoded = decodeTransferData(txData); + if (decoded.to.toLowerCase() !== operation.address.toLowerCase()) { + throw new Error( + `verifyEnableTokenTransaction: txHex sendMultiSig target ${decoded.to} does not match the recipient ${operation.address} that will be signed` + ); + } + if (!new BigNumber(decoded.amount).isEqualTo(operation.amount ?? 0)) { + throw new Error( + `verifyEnableTokenTransaction: txHex sendMultiSig value ${decoded.amount} does not match the recipient amount ${operation.amount} that will be signed` + ); + } + // TransferData.data is typed loosely (bytes); for a sendMultiSig envelope it is the + // hex-encoded calldata, matching the decode in verifyWrapTransaction. + const txHexCalldata = (decoded.data as string).replace(/^0x/, '').toLowerCase(); + const signedCalldata = (operation.data ?? '').replace(/^0x/, '').toLowerCase(); + if (txHexCalldata !== signedCalldata) { + throw new Error( + 'verifyEnableTokenTransaction: txHex sendMultiSig calldata does not match the recipient calldata that will be signed' + ); } } diff --git a/modules/sdk-coin-eth/test/unit/erc7984Token.ts b/modules/sdk-coin-eth/test/unit/erc7984Token.ts index 5b6c9516ed..5eb6e97ec2 100644 --- a/modules/sdk-coin-eth/test/unit/erc7984Token.ts +++ b/modules/sdk-coin-eth/test/unit/erc7984Token.ts @@ -29,6 +29,7 @@ import { TransferBuilderERC7984, confidentialTransferNoProofMethodId, approveMethodId, + TransactionPrebuild, } from '@bitgo/abstract-eth'; import EthereumAbi from 'ethereumjs-abi'; import { addHexPrefix } from 'ethereumjs-util'; @@ -711,7 +712,7 @@ describe('Erc7984Token', function () { }); // ------------------------------------------------------------------------- - describe('verifyTransaction – multisig path', function () { + describe('verifyTransaction – multisig path (default legacy flow)', function () { it('should verify valid buildParams recipients', async function () { const result = await coin.verifyTransaction({ txParams: { @@ -807,6 +808,173 @@ describe('Erc7984Token', function () { .should.be.rejectedWith(/missing buildParams.recipients/); }); }); + + // ------------------------------------------------------------------------- + describe('verifyTransaction – multisig strict path (Flipt flag enabled by the platform)', function () { + // Client-built recipients echo, as attached by Wallet.buildTokenEnablements. + const clientRecipients = [{ tokenName: 'hteth:ctest1', address: '0xabc', amount: '0' }]; + const enableTokenParams = { type: 'enabletoken', enableTokens: [{ name: 'hteth:ctest1' }] }; + const delegationData = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, [CTEST1_TOKEN_ADDRESS], EXPIRY); + const forwarderDelegationData = wrapInCallFromParent(ZAMA_ACL_ADDRESS, delegationData); + // ERC-20 approve theft calldata: the wallet contract would call token.approve(attacker, 1). + const approveTheftCalldata = + approveMethodId + EthereumAbi.rawEncode(['address', 'uint256'], [ATTACKER_CONTRACT_ADDRESS, 1]).toString('hex'); + const smuggledDelegationData = encodeRawMulticall([ + buildDelegationCalldata(DELEGATE_ADDRESS, CTEST1_TOKEN_ADDRESS, EXPIRY), + approveTheftCalldata, + ]); + const forwarderTheftData = encodeRawCallFromParent( + ATTACKER_CONTRACT_ADDRESS, + '1000000000000000000', + delegationData + ); + const walletContract = '0x8f977e912ef500548a0c3be6ddde9899f1199b81'; + const expireTime = Math.floor(Date.now() / 1000) + 3600; + + /** + * A realistic onchain-multisig enable-token prebuild: recipients[0] is the sendMultiSig + * operation that Eth.signTransaction hashes into the user's operation signature. + * One unchecked cast: the wire recipient carries a `data` field the + * TransactionRecipient type does not model. + */ + function buildStrictPrebuild(opts: { + recipient?: { address: string; amount: string; data: string }; + multisigEnableTokenStrictVerification?: boolean; + txHex?: string; + }): TransactionPrebuild { + return { + buildParams: { type: 'enabletoken', recipients: clientRecipients }, + ...(opts.recipient ? { recipients: [opts.recipient] } : {}), + coin: 'hteth', + gasPrice: 1, + gasLimit: 1, + isBatch: false, + nextContractSequenceId: 1, + multisigEnableTokenStrictVerification: opts.multisigEnableTokenStrictVerification ?? true, + ...(opts.txHex ? { txHex: opts.txHex } : {}), + } as unknown as TransactionPrebuild; + } + + async function verifyMultisigEnable(prebuild: TransactionPrebuild): Promise { + // Test seam: the multisig strict path never reads the wallet object. + return coin.verifyTransaction({ + txParams: enableTokenParams, + txPrebuild: prebuild, + wallet: {} as unknown as Wallet, + walletType: 'onchain', + }); + } + + it('should verify a benign base-wallet enable (aclMulticall shape) when the platform enables the flag', async function () { + const result = await verifyMultisigEnable( + buildStrictPrebuild({ recipient: { address: ZAMA_ACL_ADDRESS, amount: '0', data: delegationData } }) + ); + result.should.equal(true); + }); + + it('should verify a benign forwarder enable (callFromParent shape)', async function () { + const result = await verifyMultisigEnable( + buildStrictPrebuild({ + recipient: { address: FORWARDER_ADDRESS, amount: '0', data: forwarderDelegationData }, + }) + ); + result.should.equal(true); + }); + + it('should verify a benign enable when the txHex sendMultiSig envelope mirrors the signed recipient', async function () { + const txHex = await buildRawContractCallTxHex( + walletContract, + sendMultiSigData(ZAMA_ACL_ADDRESS, '0', delegationData, expireTime, 1, '0x' + '00'.repeat(65)) + ); + const result = await verifyMultisigEnable( + buildStrictPrebuild({ recipient: { address: ZAMA_ACL_ADDRESS, amount: '0', data: delegationData }, txHex }) + ); + result.should.equal(true); + }); + + it('should reject a non-zero sendMultiSig value (native fund theft)', async function () { + await verifyMultisigEnable( + buildStrictPrebuild({ recipient: { address: ZAMA_ACL_ADDRESS, amount: '12345', data: delegationData } }) + ).should.be.rejectedWith(/expected sendMultiSig value 0/); + }); + + it('should reject an ERC-20 approve theft prebuild (non-delegation calldata)', async function () { + await verifyMultisigEnable( + buildStrictPrebuild({ + recipient: { address: ATTACKER_CONTRACT_ADDRESS, amount: '0', data: approveTheftCalldata }, + }) + ).should.be.rejectedWith(/Not a valid delegation calldata/); + }); + + it('should reject delegate substitution to an attacker viewing key', async function () { + await verifyMultisigEnable( + buildStrictPrebuild({ + recipient: { + address: ZAMA_ACL_ADDRESS, + amount: '0', + data: buildMulticallDelegationCalldata(ATTACKER_DELEGATE_ADDRESS, [CTEST1_TOKEN_ADDRESS], EXPIRY), + }, + }) + ).should.be.rejectedWith(/does not match the expected enterprise viewing key/); + }); + + it('should reject a smuggled non-delegation inner call', async function () { + await verifyMultisigEnable( + buildStrictPrebuild({ recipient: { address: ZAMA_ACL_ADDRESS, amount: '0', data: smuggledDelegationData } }) + ).should.be.rejectedWith(/unrecognised method ID/); + }); + + it('should reject an aclMulticall-shaped op targeted away from the ACL contract', async function () { + await verifyMultisigEnable( + buildStrictPrebuild({ recipient: { address: WRONG_ACL_ADDRESS, amount: '0', data: delegationData } }) + ).should.be.rejectedWith(/does not match ACL contract/); + }); + + it('should reject the callFromParent theft shape (forwarder calling an attacker contract with funds)', async function () { + await verifyMultisigEnable( + buildStrictPrebuild({ recipient: { address: FORWARDER_ADDRESS, amount: '0', data: forwarderTheftData } }) + ).should.be.rejectedWith(/callFromParent target .* does not match ACL contract/); + }); + + it('should reject a decoy txHex whose sendMultiSig args differ from the signed recipient', async function () { + const txHex = await buildRawContractCallTxHex( + walletContract, + sendMultiSigData(ATTACKER_CONTRACT_ADDRESS, '12345', delegationData, expireTime, 1, '0x' + '00'.repeat(65)) + ); + await verifyMultisigEnable( + buildStrictPrebuild({ recipient: { address: ZAMA_ACL_ADDRESS, amount: '0', data: delegationData }, txHex }) + ).should.be.rejectedWith(/txHex sendMultiSig target .* does not match the recipient/); + }); + + it('should reject a txHex that is not a sendMultiSig envelope', async function () { + const txHex = await buildRawContractCallTxHex(walletContract, approveTheftCalldata); + await verifyMultisigEnable( + buildStrictPrebuild({ recipient: { address: ZAMA_ACL_ADDRESS, amount: '0', data: delegationData }, txHex }) + ).should.be.rejectedWith(/must be a sendMultiSig call/); + }); + + it('should reject a prebuild with no recipient to bind the signature to', async function () { + await verifyMultisigEnable(buildStrictPrebuild({})).should.be.rejectedWith(/exactly one recipient/); + }); + + it('should keep the legacy flow when the flag is absent (a hostile prebuild passes before the platform enables strict)', async function () { + const result = await verifyMultisigEnable({ + buildParams: { type: 'enabletoken', recipients: clientRecipients }, + recipients: [{ address: ATTACKER_CONTRACT_ADDRESS, amount: '12345', data: approveTheftCalldata }], + } as unknown as TransactionPrebuild); + result.should.equal(true); + }); + + it('should keep the legacy flow when the flag is explicitly false (kill-switch proof)', async function () { + const result = await verifyMultisigEnable( + buildStrictPrebuild({ + recipient: { address: ATTACKER_CONTRACT_ADDRESS, amount: '12345', data: approveTheftCalldata }, + multisigEnableTokenStrictVerification: false, + }) + ); + result.should.equal(true); + }); + }); }); // ---------------------------------------------------------------------------