Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions modules/abstract-eth/src/lib/zamaUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
97 changes: 97 additions & 0 deletions modules/sdk-coin-eth/src/erc7984Token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
CoinNames,
DecryptionDelegationBuilder,
decodeTokenAddressesFromDelegationCalldata,
decodeDelegationCallsFromCalldata,
decodeConfidentialTransferData,
decodeDirectConfidentialTransferCalldata,
decodeFlushERC7984ForwarderTokenCalldata,
Expand Down Expand Up @@ -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
Comment thread
nvrakesh06 marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -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.
Comment thread
nvrakesh06 marked this conversation as resolved.
Resolved
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.
Expand Down
Loading
Loading