From fe6c02f3f00d15e509ce1028d2a6e4718e03c60f Mon Sep 17 00:00:00 2001 From: Rakesh Reddy Date: Tue, 17 Nov 2026 17:01:37 +0530 Subject: [PATCH] fix(sdk-coin-eth): enforce strict ERC-7984 delegation verification on test/staging (CECHO-2720) Adds a fail-closed strict verification tier for ERC-7984 enable-token prebuilds, enforced when bitgo.env is test or staging; prod keeps legacy behavior for one release cycle (the env gate is removed in Release N+1, tracked in CECHO-2720). - abstract-eth: new decodeDelegationCallsFromCalldata surfaces the delegate and expiry of every inner delegateForUserDecryption call and the callFromParent target/value, and fails closed on any inner multicall entry that is not a well-formed delegation call (no smuggled calls). The legacy decoder is unchanged. - sdk-coin-eth: verifyEnableTokenTransaction strict mode requires an exact deduplicated token-set match, a single consistent delegate equal to the pinned enterprise viewing key (fail closed when no pin exists), a future expiry, and callFromParent target == ACL contract with zero native value (blocks forwarder fund exfiltration). - statics: optional EthereumNetwork.zamaViewingKeyAddress pins the BitGo enterprise viewing key per network; the real values for mainnet and Hoodi are a hard prerequisite for Release N. Addresses the Claude review findings on PR #10191: fail-closed without a pinned viewing key, and set-based token matching so duplicate requested tokens cannot smuggle unrequested tokens. The multisig enable-token path is a pre-existing gap tracked separately as CECHO-2815. --- modules/abstract-eth/src/lib/zamaUtils.ts | 100 +++++ modules/sdk-coin-eth/src/erc7984Token.ts | 97 +++++ .../sdk-coin-eth/test/unit/erc7984Token.ts | 405 +++++++++++++++++- modules/statics/src/networks.ts | 3 + 4 files changed, 601 insertions(+), 4 deletions(-) diff --git a/modules/abstract-eth/src/lib/zamaUtils.ts b/modules/abstract-eth/src/lib/zamaUtils.ts index d7c8271e8d6..7110dcabd97 100644 --- a/modules/abstract-eth/src/lib/zamaUtils.ts +++ b/modules/abstract-eth/src/lib/zamaUtils.ts @@ -534,6 +534,106 @@ export function decodeTokenAddressesFromDelegationCalldata(calldata: string): st return tokenAddresses; } +/** + * A single decoded ACL.delegateForUserDecryption(delegate, tokenAddress, expiry) call. + */ +export interface DecodedDelegationCall { + /** Address receiving decryption rights over the token contract (lowercase). */ + delegate: string; + /** Token contract address being delegated (lowercase). */ + tokenAddress: string; + /** Delegation expiry as a Unix timestamp (seconds). */ + expiry: bigint; +} + +/** + * Full, fail-closed decode of an ERC-7984 delegation calldata (CECHO-2720). + * + * Handles the same two calldata shapes as decodeTokenAddressesFromDelegationCalldata + * (direct ACL.multicall, or ForwarderV4.callFromParent wrapping a multicall) but + * surfaces every security-relevant field the legacy decoder discards: + * - the delegate and expiry of every inner delegateForUserDecryption call + * - the callFromParent target and native value in the forwarder shape + * + * Unlike the legacy decoder, this fails closed: any inner multicall entry that is + * not a well-formed delegateForUserDecryption call (unknown selector or trailing + * bytes) is rejected instead of silently skipped, so no additional calls can be + * smuggled into the verified transaction. + */ +export interface DecodedDelegation { + /** Calldata shape: direct ACL.multicall or ForwarderV4.callFromParent wrapping a multicall. */ + shape: 'aclMulticall' | 'callFromParent'; + /** Present when shape is 'callFromParent': the contract the forwarder is told to call (lowercase). */ + callFromParentTarget?: string; + /** Present when shape is 'callFromParent': the native value attached to the forwarder call. */ + callFromParentValue?: bigint; + /** Inner delegation calls, one per decoded delegateForUserDecryption entry. */ + calls: DecodedDelegationCall[]; +} + +/** + * Decodes an ERC-7984 delegation calldata, binding every security-relevant field. + * + * @param calldata ABI-encoded delegation calldata (0x-prefixed or raw hex) + * @returns the delegation shape, the callFromParent target/value when wrapped, + * and the full (delegate, tokenAddress, expiry) record of every inner call + * @throws {Error} if the calldata is not a recognised delegation shape, or if any + * inner multicall entry is not a well-formed delegateForUserDecryption call + */ +export function decodeDelegationCallsFromCalldata(calldata: string): DecodedDelegation { + const data = calldata.startsWith('0x') ? calldata : '0x' + calldata; + const methodId = data.slice(0, 10); + const abiCoder = new ethers.utils.AbiCoder(); + + const delegation: DecodedDelegation = { shape: 'aclMulticall', calls: [] }; + let multicallHex: string; + + if (methodId === callFromParentMethodId) { + // Decode callFromParent(address, uint256, bytes) — keep the target and value + // the legacy decoder discards; the inner bytes is the full multicall calldata. + const outerDecoded = abiCoder.decode([...callFromParentTypes], '0x' + data.slice(10)); + delegation.shape = 'callFromParent'; + delegation.callFromParentTarget = (outerDecoded[0] as string).toLowerCase(); + delegation.callFromParentValue = BigInt(outerDecoded[1].toString()); + multicallHex = ethers.utils.hexlify(outerDecoded[2]); + } else if (methodId === aclMulticallMethodId) { + multicallHex = data; + } else { + throw new Error('Not a valid delegation calldata'); + } + + if (multicallHex.slice(0, 10) !== aclMulticallMethodId) { + throw new Error('Not a valid delegation calldata'); + } + + // Decode multicall(bytes[]) — every element must be a well-formed + // delegateForUserDecryption call; anything else fails closed. + const outerDecoded = abiCoder.decode(['bytes[]'], '0x' + multicallHex.slice(10)); + const innerCalls: unknown[] = outerDecoded[0]; + + for (const innerCall of innerCalls) { + const innerHex = ethers.utils.hexlify(innerCall as ethers.utils.BytesLike).slice(2); // strip 0x + const innerMethodId = '0x' + innerHex.slice(0, 8); + if (innerMethodId !== delegateForUserDecryptionMethodId) { + throw new Error( + `Unexpected delegation calldata: inner multicall entry has unrecognised method ID ${innerMethodId}` + ); + } + // Fail closed: selector + exactly three 32-byte words; reject trailing bytes. + if (innerHex.length !== 8 + 3 * 64) { + throw new Error('Unexpected delegation calldata: malformed delegateForUserDecryption entry'); + } + const innerDecoded = abiCoder.decode([...delegateForUserDecryptionTypes], '0x' + innerHex.slice(8)); + delegation.calls.push({ + delegate: (innerDecoded[0] as string).toLowerCase(), + tokenAddress: (innerDecoded[1] as string).toLowerCase(), + expiry: BigInt(innerDecoded[2].toString()), + }); + } + + return delegation; +} + /** * Encodes confidentialTransfer(address to, bytes32 encryptedHandle) calldata. * Uses the no-proof variant (selector 0x5bebed7e) — valid when the caller (forwarder) diff --git a/modules/sdk-coin-eth/src/erc7984Token.ts b/modules/sdk-coin-eth/src/erc7984Token.ts index 52ecbc4c4de..499a10482ee 100644 --- a/modules/sdk-coin-eth/src/erc7984Token.ts +++ b/modules/sdk-coin-eth/src/erc7984Token.ts @@ -16,6 +16,7 @@ import { CoinNames, DecryptionDelegationBuilder, decodeTokenAddressesFromDelegationCalldata, + decodeDelegationCallsFromCalldata, decodeConfidentialTransferData, decodeDirectConfidentialTransferCalldata, decodeFlushERC7984ForwarderTokenCalldata, @@ -815,6 +816,14 @@ export class Erc7984Token extends Eth { } } + // 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 @@ -861,6 +870,94 @@ export class Erc7984Token extends Eth { } } + /** + * Strict CECHO-2720 checks on the delegation calldata, enforced on test/staging + * environments during the staged rollout. Binds every security-relevant field: + * 1. every inner multicall entry is a well-formed delegateForUserDecryption call + * (fail-closed decoding — no smuggled calls) + * 2. the decoded token set exactly matches the (deduplicated) requested token set + * 3. all delegations grant the same delegate, which must equal the pinned + * BitGo enterprise viewing key — fail closed when the network pins none + * 4. every delegation expiry is in the future + * 5. callFromParent shape: the forwarder must call the ACL contract with zero + * native value (blocks forwarder fund exfiltration to an attacker contract) + * + * The wallet-owned-forwarder (txJson.to) check of the callFromParent shape is not + * statically verifiable here; the on-chain onlyParent modifier plus the enforced + * target/value checks close the fund-theft vector regardless of which forwarder + * the transaction targets. + */ + private verifyStrictEnableTokenCalldata( + txJson: { to?: string; data: string; value: string }, + aclContractAddress: string, + requestedAddresses: string[] + ): void { + const delegation = decodeDelegationCallsFromCalldata(txJson.data); + + // Exact token-set match (CECHO-2720 review: compare as deduplicated sets): every + // requested token is delegated, nothing unrequested is, and no token twice. + const requestedTokens = [...new Set(requestedAddresses)]; + const decodedTokens = delegation.calls.map((call) => call.tokenAddress); + const decodedTokenSet = new Set(decodedTokens); + for (const requested of requestedTokens) { + if (!decodedTokenSet.has(requested)) { + throw new Error(`verifyEnableTokenTransaction: requested token ${requested} not found in delegation calldata`); + } + } + if (decodedTokens.length !== decodedTokenSet.size) { + throw new Error( + 'verifyEnableTokenTransaction: delegation calldata contains duplicate delegations for the same token' + ); + } + if (decodedTokenSet.size !== requestedTokens.length) { + throw new Error( + `verifyEnableTokenTransaction: delegation calldata must contain exactly ${requestedTokens.length} distinct token delegation(s) but found ${decodedTokenSet.size}` + ); + } + + // Delegate binding: all delegations must grant the same delegate, and it must be + // the pinned BitGo enterprise viewing key. Fail closed when the network pins + // nothing: without the pin, WHO receives decryption rights cannot be verified. + const delegates = new Set(delegation.calls.map((call) => call.delegate)); + if (delegates.size !== 1) { + throw new Error('verifyEnableTokenTransaction: delegation calldata grants inconsistent delegates'); + } + const expectedDelegate = (this.getNetwork() as EthereumNetwork)?.zamaViewingKeyAddress?.toLowerCase(); + if (expectedDelegate === undefined) { + throw new Error( + 'verifyEnableTokenTransaction: zamaViewingKeyAddress is not pinned for this network — cannot verify the delegation delegate (fail closed)' + ); + } + const [delegate] = [...delegates]; + if (delegate !== expectedDelegate) { + throw new Error( + `verifyEnableTokenTransaction: delegation delegate ${delegate} does not match the expected enterprise viewing key ${expectedDelegate}` + ); + } + + // Expiry sanity: a delegation that is already expired is never legitimate. + const nowSeconds = BigInt(Math.floor(Date.now() / 1000)); + for (const call of delegation.calls) { + if (call.expiry <= nowSeconds) { + throw new Error(`verifyEnableTokenTransaction: delegation for token ${call.tokenAddress} has already expired`); + } + } + + // Forwarder shape: the forwarder must call the ACL contract with no native value. + if (delegation.shape === 'callFromParent') { + if (delegation.callFromParentTarget !== aclContractAddress.toLowerCase()) { + throw new Error( + `verifyEnableTokenTransaction: callFromParent target ${delegation.callFromParentTarget} does not match ACL contract ${aclContractAddress}` + ); + } + if (delegation.callFromParentValue !== 0n) { + throw new Error( + `verifyEnableTokenTransaction: callFromParent must carry value 0 but got ${delegation.callFromParentValue}` + ); + } + } + } + /** * Override gas limit for ERC-7984 confidential token recovery. * Actual on-chain usage is ~506-530k gas based on testnet results. diff --git a/modules/sdk-coin-eth/test/unit/erc7984Token.ts b/modules/sdk-coin-eth/test/unit/erc7984Token.ts index 876a168debf..5b6c9516edc 100644 --- a/modules/sdk-coin-eth/test/unit/erc7984Token.ts +++ b/modules/sdk-coin-eth/test/unit/erc7984Token.ts @@ -14,8 +14,10 @@ import sinon from 'sinon'; import { BitGoAPI } from '@bitgo/sdk-api'; import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test'; import { RecoveryKeyMismatchError, TransactionType, Wallet } from '@bitgo/sdk-core'; +import { EthereumNetwork } from '@bitgo/statics'; import { buildMulticallDelegationCalldata, + buildDelegationCalldata, buildFlushERC7984ForwarderTokenCalldata, buildWrapCalldata, buildUnwrapCalldata, @@ -23,9 +25,14 @@ import { sendMultiSigData, wrapInCallFromParent, decodeTokenAddressesFromDelegationCalldata, + decodeDelegationCallsFromCalldata, TransferBuilderERC7984, confidentialTransferNoProofMethodId, + approveMethodId, } from '@bitgo/abstract-eth'; +import EthereumAbi from 'ethereumjs-abi'; +import { addHexPrefix } from 'ethereumjs-util'; +import { ethers } from 'ethers'; import { Erc7984Token } from '../../src/erc7984Token'; import { TransactionBuilder } from '../../src/lib'; import { getBuilder } from './getBuilder'; @@ -49,6 +56,10 @@ const WRONG_TOKEN_ADDRESS = '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef'; const WRONG_ACL_ADDRESS = '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; const FORWARDER_ADDRESS = '0x1234567890123456789012345678901234567890'; +// Hostile addresses for CECHO-2720 negative tests +const ATTACKER_DELEGATE_ADDRESS = '0x2222222222222222222222222222222222222222'; +const ATTACKER_CONTRACT_ADDRESS = '0x3333333333333333333333333333333333333333'; + const EXPIRY = Math.floor(Date.now() / 1000) + 365 * 86400; // --------------------------------------------------------------------------- @@ -58,13 +69,18 @@ const EXPIRY = Math.floor(Date.now() / 1000) + 365 * 86400; /** * Builds a root-wallet delegation tx hex (to = ACL, data = multicall). */ -async function buildDelegationTxHex(aclAddress: string, tokenAddresses: string[], value = '0'): Promise { +async function buildDelegationTxHex( + aclAddress: string, + tokenAddresses: string[], + value = '0', + delegateAddress = DELEGATE_ADDRESS +): Promise { const txBuilder = getBuilder('hteth') as TransactionBuilder; txBuilder.fee({ fee: '1000000000', gasLimit: '200000' }); txBuilder.counter(1); txBuilder.type(TransactionType.ContractCall); txBuilder.contract(aclAddress); - const calldata = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, tokenAddresses, EXPIRY); + const calldata = buildMulticallDelegationCalldata(delegateAddress, tokenAddresses, EXPIRY); txBuilder.data(calldata); if (value !== '0') { txBuilder.value(value); @@ -80,20 +96,62 @@ async function buildDelegationTxHex(aclAddress: string, tokenAddresses: string[] async function buildForwarderDelegationTxHex( forwarderAddress: string, aclAddress: string, - tokenAddresses: string[] + tokenAddresses: string[], + delegateAddress = DELEGATE_ADDRESS ): Promise { const txBuilder = getBuilder('hteth') as TransactionBuilder; txBuilder.fee({ fee: '1000000000', gasLimit: '200000' }); txBuilder.counter(1); txBuilder.type(TransactionType.ContractCall); txBuilder.contract(forwarderAddress); - const innerCalldata = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, tokenAddresses, EXPIRY); + const innerCalldata = buildMulticallDelegationCalldata(delegateAddress, tokenAddresses, EXPIRY); const outerCalldata = wrapInCallFromParent(aclAddress, innerCalldata); txBuilder.data(outerCalldata); const tx = await txBuilder.build(); return tx.toBroadcastFormat(); } +/** + * Encodes ACL.multicall(bytes[]) from raw inner call hex strings. + * Used to build hostile calldata (e.g. mixed inner selectors) for CECHO-2720 negative tests. + */ +function encodeRawMulticall(innerCallsHex: string[]): string { + const method = EthereumAbi.methodID('multicall', ['bytes[]']); + const args = Buffer.from(new ethers.utils.AbiCoder().encode(['bytes[]'], [innerCallsHex]).slice(2), 'hex'); + return addHexPrefix(Buffer.concat([method, args]).toString('hex')); +} + +/** + * Encodes ForwarderV4.callFromParent(target, value, data) with an arbitrary native value — + * unlike wrapInCallFromParent, which hardcodes value 0. + */ +function encodeRawCallFromParent(targetAddress: string, value: string | number, calldata: string): string { + const method = EthereumAbi.methodID('callFromParent', ['address', 'uint256', 'bytes']); + const args = EthereumAbi.rawEncode( + ['address', 'uint256', 'bytes'], + [targetAddress, value, Buffer.from(calldata.slice(2), 'hex')] + ); + return addHexPrefix(Buffer.concat([method, args]).toString('hex')); +} + +/** + * Builds a ContractCall tx with arbitrary calldata — the hostile-prebuild primitive + * for CECHO-2720 tests (attacker-controlled prebuild simulations). + */ +async function buildRawContractCallTxHex(contractAddress: string, calldata: string, value = '0'): Promise { + const txBuilder = getBuilder('hteth') as TransactionBuilder; + txBuilder.fee({ fee: '1000000000', gasLimit: '200000' }); + txBuilder.counter(1); + txBuilder.type(TransactionType.ContractCall); + txBuilder.contract(contractAddress); + txBuilder.data(calldata); + if (value !== '0') { + txBuilder.value(value); + } + const tx = await txBuilder.build(); + return tx.toBroadcastFormat(); +} + // --------------------------------------------------------------------------- // Tests // --------------------------------------------------------------------------- @@ -109,6 +167,21 @@ describe('Erc7984Token', function () { coin = bitgo.coin('hteth:ctest1') as Erc7984Token; }); + let getNetworkStub: sinon.SinonStub; + + beforeEach(function () { + // Test seam: statics network configs are frozen, so stub getNetwork to return a copy + // pinned with the enterprise viewing key; strict mode fails closed when no pin exists. + const originalNetwork = coin.getNetwork() as EthereumNetwork; + getNetworkStub = sinon + .stub(coin, 'getNetwork') + .returns({ ...originalNetwork, zamaViewingKeyAddress: DELEGATE_ADDRESS }); + }); + + afterEach(function () { + getNetworkStub.restore(); + }); + // ------------------------------------------------------------------------- describe('getTokenEnablementConfig', function () { it('should return requiresTokenEnablement: true', function () { @@ -313,6 +386,330 @@ describe('Erc7984Token', function () { }); }); + // ------------------------------------------------------------------------- + describe('verifyTransaction – strict delegation verification (CECHO-2720)', function () { + it('should reject a delegate substitution when the network pins an enterprise viewing key', async function () { + // The root beforeEach pins DELEGATE_ADDRESS as the enterprise viewing key. + const txHex = await buildDelegationTxHex( + ZAMA_ACL_ADDRESS, + [CTEST1_TOKEN_ADDRESS], + '0', + ATTACKER_DELEGATE_ADDRESS + ); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/does not match the expected enterprise viewing key/); + }); + + it('should verify a delegation whose delegate matches the pinned enterprise viewing key', async function () { + // The root beforeEach pins DELEGATE_ADDRESS as the enterprise viewing key. + const txHex = await buildDelegationTxHex(ZAMA_ACL_ADDRESS, [CTEST1_TOKEN_ADDRESS]); + const result = await coin.verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }); + result.should.equal(true); + }); + + it('should reject inconsistent delegates across inner delegation calls', async function () { + const innerCalls = [ + buildDelegationCalldata(DELEGATE_ADDRESS, CTEST1_TOKEN_ADDRESS, EXPIRY), + buildDelegationCalldata(ATTACKER_DELEGATE_ADDRESS, CUSDT_TOKEN_ADDRESS, EXPIRY), + ]; + const txHex = await buildRawContractCallTxHex(ZAMA_ACL_ADDRESS, encodeRawMulticall(innerCalls)); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }, { name: 'hteth:cusdt' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/inconsistent delegates/); + }); + + it('should reject smuggled non-delegation calls inside the multicall', async function () { + // Hostile inner entry: ACL.approve(attacker, 1) — a selector the legacy decoder silently skips. + const smuggledCall = + approveMethodId + EthereumAbi.rawEncode(['address', 'uint256'], [ATTACKER_CONTRACT_ADDRESS, 1]).toString('hex'); + const innerCalls = [buildDelegationCalldata(DELEGATE_ADDRESS, CTEST1_TOKEN_ADDRESS, EXPIRY), smuggledCall]; + const txHex = await buildRawContractCallTxHex(ZAMA_ACL_ADDRESS, encodeRawMulticall(innerCalls)); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/unrecognised method ID/); + }); + + it('should reject the forwarder theft prebuild (callFromParent to attacker contract with the forwarder balance)', async function () { + const inner = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, [CTEST1_TOKEN_ADDRESS], EXPIRY); + const calldata = encodeRawCallFromParent(ATTACKER_CONTRACT_ADDRESS, '1000000000000000000', inner); + const txHex = await buildRawContractCallTxHex(FORWARDER_ADDRESS, calldata); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/callFromParent target .* does not match ACL contract/); + }); + + it('should reject callFromParent with a non-zero native value', async function () { + const inner = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, [CTEST1_TOKEN_ADDRESS], EXPIRY); + const calldata = encodeRawCallFromParent(ZAMA_ACL_ADDRESS, '1000000000000000000', inner); + const txHex = await buildRawContractCallTxHex(FORWARDER_ADDRESS, calldata); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/callFromParent must carry value 0/); + }); + + it('should reject extra delegation calls for tokens that were not requested', async function () { + const txHex = await buildDelegationTxHex(ZAMA_ACL_ADDRESS, [CTEST1_TOKEN_ADDRESS, CUSDT_TOKEN_ADDRESS]); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/must contain exactly 1 distinct token delegation.s. but found 2/); + }); + + it('should reject duplicate delegations for the same token', async function () { + const innerCalls = [ + buildDelegationCalldata(DELEGATE_ADDRESS, CTEST1_TOKEN_ADDRESS, EXPIRY), + buildDelegationCalldata(DELEGATE_ADDRESS, CTEST1_TOKEN_ADDRESS, EXPIRY), + ]; + const txHex = await buildRawContractCallTxHex(ZAMA_ACL_ADDRESS, encodeRawMulticall(innerCalls)); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/duplicate delegations for the same token/); + }); + + it('should reject an unrequested token smuggled alongside a duplicate requested token', async function () { + // The pre-review length check let requested [A, A] with decoded [A, X] pass. + const txHex = await buildDelegationTxHex(ZAMA_ACL_ADDRESS, [CTEST1_TOKEN_ADDRESS, CUSDT_TOKEN_ADDRESS]); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }, { name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/must contain exactly 1 distinct token delegation.s. but found 2/); + }); + + it('should accept a deduplicated prebuild when the caller requests the same token twice', async function () { + const txHex = await buildDelegationTxHex(ZAMA_ACL_ADDRESS, [CTEST1_TOKEN_ADDRESS]); + const result = await coin.verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }, { name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }); + result.should.equal(true); + }); + + it('should reject already-expired delegations', async function () { + const expiredExpiry = Math.floor(Date.now() / 1000) - 3600; + const calldata = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, [CTEST1_TOKEN_ADDRESS], expiredExpiry); + const txHex = await buildRawContractCallTxHex(ZAMA_ACL_ADDRESS, calldata); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/has already expired/); + }); + + it('should enforce the strict checks on the staging environment as well', async function () { + // Test seam: flip the readonly env property to exercise the staging branch of the rollout gate. + const mutableBitgo = bitgo as { env: string }; + const originalEnv = mutableBitgo.env; + mutableBitgo.env = 'staging'; + try { + const inner = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, [CTEST1_TOKEN_ADDRESS], EXPIRY); + const calldata = encodeRawCallFromParent(ATTACKER_CONTRACT_ADDRESS, '1000000000000000000', inner); + const txHex = await buildRawContractCallTxHex(FORWARDER_ADDRESS, calldata); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/does not match ACL contract/); + } finally { + mutableBitgo.env = originalEnv; + } + }); + }); + + // ------------------------------------------------------------------------- + describe('verifyTransaction – strict mode fails closed without a pinned viewing key (CECHO-2720)', function () { + beforeEach(function () { + // Drop the root-level pin: strict mode must fail closed when nothing is pinned. + getNetworkStub.restore(); + }); + + it('should reject a valid delegation when the network pins no enterprise viewing key', async function () { + const txHex = await buildDelegationTxHex(ZAMA_ACL_ADDRESS, [CTEST1_TOKEN_ADDRESS]); + await coin + .verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }) + .should.be.rejectedWith(/zamaViewingKeyAddress is not pinned.*fail closed/); + }); + }); + + // ------------------------------------------------------------------------- + describe('verifyTransaction – CECHO-2720 rollout gate (prod keeps legacy behavior)', function () { + beforeEach(function () { + // Test seam: flip the readonly env property to simulate prod (legacy verification path). + const mutableBitgo = bitgo as { env: string }; + mutableBitgo.env = 'prod'; + }); + + afterEach(function () { + // Test seam: restore the test environment after each prod simulation. + const mutableBitgo = bitgo as { env: string }; + mutableBitgo.env = 'test'; + }); + + it('should still verify the forwarder theft prebuild on prod (strict checks not yet enforced there)', async function () { + const inner = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, [CTEST1_TOKEN_ADDRESS], EXPIRY); + const calldata = encodeRawCallFromParent(ATTACKER_CONTRACT_ADDRESS, '1000000000000000000', inner); + const txHex = await buildRawContractCallTxHex(FORWARDER_ADDRESS, calldata); + const result = await coin.verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }); + result.should.equal(true); + }); + + it('should still verify a smuggled-call prebuild on prod', async function () { + // Hostile inner entry: ACL.approve(attacker, 1). + const smuggledCall = + approveMethodId + EthereumAbi.rawEncode(['address', 'uint256'], [ATTACKER_CONTRACT_ADDRESS, 1]).toString('hex'); + const innerCalls = [buildDelegationCalldata(DELEGATE_ADDRESS, CTEST1_TOKEN_ADDRESS, EXPIRY), smuggledCall]; + const txHex = await buildRawContractCallTxHex(ZAMA_ACL_ADDRESS, encodeRawMulticall(innerCalls)); + const result = await coin.verifyTransaction({ + txParams: { + type: 'enabletoken', + enableTokens: [{ name: 'hteth:ctest1' }], + }, + txPrebuild: { txHex } as any, + wallet: {} as any, + walletType: 'tss', + }); + result.should.equal(true); + }); + }); + + // ------------------------------------------------------------------------- + describe('decodeDelegationCallsFromCalldata', function () { + it('should decode delegate, token, and expiry from multicall calldata', function () { + const calldata = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, [CTEST1_TOKEN_ADDRESS], EXPIRY); + const decoded = decodeDelegationCallsFromCalldata(calldata); + decoded.shape.should.equal('aclMulticall'); + decoded.calls.length.should.equal(1); + decoded.calls[0].delegate.should.equal(DELEGATE_ADDRESS.toLowerCase()); + decoded.calls[0].tokenAddress.should.equal(CTEST1_TOKEN_ADDRESS.toLowerCase()); + decoded.calls[0].expiry.should.equal(BigInt(EXPIRY)); + }); + + it('should decode the callFromParent target and native value', function () { + const inner = buildMulticallDelegationCalldata(DELEGATE_ADDRESS, [CTEST1_TOKEN_ADDRESS], EXPIRY); + const wrapped = encodeRawCallFromParent(ZAMA_ACL_ADDRESS, '123', inner); + const decoded = decodeDelegationCallsFromCalldata(wrapped); + decoded.shape.should.equal('callFromParent'); + (decoded.callFromParentTarget as string).should.equal(ZAMA_ACL_ADDRESS.toLowerCase()); + (decoded.callFromParentValue as bigint).should.equal(123n); + decoded.calls[0].delegate.should.equal(DELEGATE_ADDRESS.toLowerCase()); + }); + + it('should throw on a non-delegation inner call', function () { + const smuggledCall = + approveMethodId + EthereumAbi.rawEncode(['address', 'uint256'], [ATTACKER_CONTRACT_ADDRESS, 1]).toString('hex'); + const innerCalls = [buildDelegationCalldata(DELEGATE_ADDRESS, CTEST1_TOKEN_ADDRESS, EXPIRY), smuggledCall]; + should.throws(() => decodeDelegationCallsFromCalldata(encodeRawMulticall(innerCalls)), /unrecognised method ID/); + }); + + it('should throw on trailing bytes in an inner call', function () { + const paddedCall = buildDelegationCalldata(DELEGATE_ADDRESS, CTEST1_TOKEN_ADDRESS, EXPIRY) + 'ff'.repeat(32); + should.throws(() => decodeDelegationCallsFromCalldata(encodeRawMulticall([paddedCall])), /malformed/); + }); + }); + // ------------------------------------------------------------------------- describe('verifyTransaction – multisig path', function () { it('should verify valid buildParams recipients', async function () { diff --git a/modules/statics/src/networks.ts b/modules/statics/src/networks.ts index 3968f32f0d9..33a44d6cfcb 100644 --- a/modules/statics/src/networks.ts +++ b/modules/statics/src/networks.ts @@ -191,6 +191,9 @@ export interface EthereumNetwork extends AccountNetwork { readonly tokenOperationHashPrefix?: string; // Zama fhEVM ACL contract address — required for ERC-7984 confidential token delegation readonly zamaAclContractAddress?: string; + // BitGo enterprise viewing key address (the ERC-7984 decryption delegate). When pinned, + // enable-token verification binds every delegation's delegate to this address (CECHO-2720). + readonly zamaViewingKeyAddress?: string; } export interface TronNetwork extends AccountNetwork {