diff --git a/modules/abstract-eth/src/lib/utils.ts b/modules/abstract-eth/src/lib/utils.ts index 95dc0ca69d..5319bcbffb 100644 --- a/modules/abstract-eth/src/lib/utils.ts +++ b/modules/abstract-eth/src/lib/utils.ts @@ -754,7 +754,11 @@ export function decodeConfidentialTransferData(data: string): ConfidentialTransf export interface SendMultiSigFlushERC7984Data { forwarderAddress: string; + /** Native value carried by the sendMultiSig call; must be '0' for a legitimate consolidation. */ + amount: string; tokenContractAddress: string; + /** Native value attached to the inner callFromParent call; must be 0n for a legitimate consolidation. */ + callFromParentValue: bigint; parentAddress: string; encryptedHandle: string; } @@ -765,6 +769,9 @@ export interface SendMultiSigFlushERC7984Data { * Multisig consolidation shape: * sendMultiSig(forwarder, 0, callFromParent(token, 0, confidentialTransferNoProof(parent, handle)), ...) * + * The sendMultiSig amount and the callFromParent native value are both surfaced so + * verifiers can enforce they are zero (CECHO-2719). + * * @param data The full calldata hex string starting with sendMultiSigMethodId */ export function decodeSendMultiSigFlushERC7984Data(data: string): SendMultiSigFlushERC7984Data { @@ -772,18 +779,20 @@ export function decodeSendMultiSigFlushERC7984Data(data: string): SendMultiSigFl throw new BuildTransactionError(`Invalid multisig flush bytecode: unexpected method ID ${data.slice(0, 10)}`); } - const [forwarderAddress, , internalData] = getRawDecoded( + const [forwarderAddress, amount, internalData] = getRawDecoded( sendMultiSigTypes, getBufferedByteCode(sendMultisigMethodId, data) ); const internalDataHex = bufferToHex(internalData as Buffer); - const { tokenContractAddress, parentAddress, encryptedHandle } = + const { tokenContractAddress, callFromParentValue, parentAddress, encryptedHandle } = decodeFlushERC7984ForwarderTokenCalldata(internalDataHex); return { forwarderAddress: addHexPrefix(forwarderAddress as string), + amount: new BigNumber(bufferToHex(amount as Buffer)).toFixed(), tokenContractAddress, + callFromParentValue, parentAddress, encryptedHandle, }; diff --git a/modules/abstract-eth/src/lib/zamaUtils.ts b/modules/abstract-eth/src/lib/zamaUtils.ts index 7110dcabd9..8f3d695750 100644 --- a/modules/abstract-eth/src/lib/zamaUtils.ts +++ b/modules/abstract-eth/src/lib/zamaUtils.ts @@ -672,13 +672,18 @@ export function buildFlushERC7984ForwarderTokenCalldata( /** * Decodes a FlushERC7984ForwarderToken calldata. * Strips the outer callFromParent wrapper and the inner confidentialTransfer. - * Returns { tokenContractAddress, parentAddress, encryptedHandle }. + * Returns { tokenContractAddress, callFromParentValue, parentAddress, encryptedHandle }. + * + * The callFromParent native value is surfaced so verifiers can enforce that it is 0 + * (a legitimate flush moves confidential balances via calldata only; a non-zero value + * lets the forwarder forward native funds to an arbitrary target — CECHO-2719). * * @param data ABI-encoded flush calldata (0x-prefixed) - * @returns Decoded fields + * @returns Decoded fields, including the native value attached to the callFromParent call */ export function decodeFlushERC7984ForwarderTokenCalldata(data: string): { tokenContractAddress: string; + callFromParentValue: bigint; parentAddress: string; encryptedHandle: string; } { @@ -691,6 +696,7 @@ export function decodeFlushERC7984ForwarderTokenCalldata(data: string): { const abiCoder = new ethers.utils.AbiCoder(); const outerDecoded = abiCoder.decode([...callFromParentTypes], '0x' + data.slice(10)); const tokenContractAddress: string = outerDecoded[0]; + const callFromParentValue = BigInt(outerDecoded[1].toString()); const innerCalldata: string = ethers.utils.hexlify(outerDecoded[2]); if (!innerCalldata.startsWith(confidentialTransferNoProofMethodId)) { @@ -708,6 +714,7 @@ export function decodeFlushERC7984ForwarderTokenCalldata(data: string): { return { tokenContractAddress, + callFromParentValue, parentAddress, encryptedHandle, }; diff --git a/modules/abstract-eth/test/unit/zamaUtils.ts b/modules/abstract-eth/test/unit/zamaUtils.ts index a36d34d2bc..f8820d0262 100644 --- a/modules/abstract-eth/test/unit/zamaUtils.ts +++ b/modules/abstract-eth/test/unit/zamaUtils.ts @@ -25,6 +25,8 @@ import { callFromParentMethodId, } from '../../src/lib/zamaUtils'; import { confidentialTransferNoProofMethodId } from '../../src/lib/walletUtil'; +import { decodeSendMultiSigFlushERC7984Data, sendMultiSigData } from '../../src/lib/utils'; +import { addHexPrefix } from 'ethereumjs-util'; describe('Zama Utils', () => { const ACL_ADDRESS = '0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D'; @@ -778,5 +780,65 @@ describe('Zama Utils', () => { should.exist(decoded.tokenContractAddress); decoded.tokenContractAddress.should.be.a.String(); }); + + it('should surface the callFromParent native value as 0n for builder output', () => { + const encoded = buildFlushERC7984ForwarderTokenCalldata(TOKEN_ADDRESS, PARENT_ADDRESS, HANDLE); + const decoded = decodeFlushERC7984ForwarderTokenCalldata(encoded); + decoded.callFromParentValue.should.equal(0n); + }); + + it('should surface a non-zero callFromParent native value', () => { + // Hand-encode callFromParent with a non-zero value, unlike wrapInCallFromParent + // which hardcodes 0 — the exact hostile shape from CECHO-2719. + const inner = buildConfidentialTransferByHandleCalldata(PARENT_ADDRESS, HANDLE); + const method = EthereumAbi.methodID('callFromParent', ['address', 'uint256', 'bytes']); + const args = EthereumAbi.rawEncode( + ['address', 'uint256', 'bytes'], + [TOKEN_ADDRESS, 123, Buffer.from(inner.slice(2), 'hex')] + ); + const encoded = addHexPrefix(Buffer.concat([method, args]).toString('hex')); + const decoded = decodeFlushERC7984ForwarderTokenCalldata(encoded); + decoded.callFromParentValue.should.equal(123n); + decoded.tokenContractAddress.toLowerCase().should.equal(TOKEN_ADDRESS.toLowerCase()); + decoded.parentAddress.toLowerCase().should.equal(PARENT_ADDRESS.toLowerCase()); + }); + }); + // ------------------------------------------------------------------------- + describe('decodeSendMultiSigFlushERC7984Data (CECHO-2719 value surfacing)', () => { + const FORWARDER = '0xAbC1234567890123456789012345678901234567'; + const PARENT = '0x2222222222222222222222222222222222222222'; + const HANDLE = '0x' + 'ef'.repeat(32); + const SEQUENCE_ID = 14; + const EXPIRE_TIME = Math.floor(Date.now() / 1000) + 3600; + const SIGNATURE = '0x' + '00'.repeat(65); + + it('should surface the sendMultiSig amount and callFromParent value as zero for a standard flush', () => { + const flushCalldata = buildFlushERC7984ForwarderTokenCalldata(TOKEN_ADDRESS, PARENT, HANDLE); + const sendData = sendMultiSigData(FORWARDER, '0', flushCalldata, EXPIRE_TIME, SEQUENCE_ID, SIGNATURE); + const decoded = decodeSendMultiSigFlushERC7984Data(sendData); + decoded.forwarderAddress.toLowerCase().should.equal(FORWARDER.toLowerCase()); + decoded.amount.should.equal('0'); + decoded.callFromParentValue.should.equal(0n); + decoded.tokenContractAddress.toLowerCase().should.equal(TOKEN_ADDRESS.toLowerCase()); + decoded.parentAddress.toLowerCase().should.equal(PARENT.toLowerCase()); + decoded.encryptedHandle.should.equal(HANDLE); + }); + + it('should surface a non-zero sendMultiSig amount', () => { + // sendMultiSig(attacker, balance, flush) — the multisig theft prebuild from + // CECHO-2719: the amount word was previously dropped and never checked. + const flushCalldata = buildFlushERC7984ForwarderTokenCalldata(TOKEN_ADDRESS, PARENT, HANDLE); + const sendData = sendMultiSigData( + FORWARDER, + '1000000000000000000', + flushCalldata, + EXPIRE_TIME, + SEQUENCE_ID, + SIGNATURE + ); + const decoded = decodeSendMultiSigFlushERC7984Data(sendData); + decoded.amount.should.equal('1000000000000000000'); + decoded.callFromParentValue.should.equal(0n); + }); }); }); diff --git a/modules/sdk-coin-eth/src/erc7984Token.ts b/modules/sdk-coin-eth/src/erc7984Token.ts index 499a10482e..af0c3c5880 100644 --- a/modules/sdk-coin-eth/src/erc7984Token.ts +++ b/modules/sdk-coin-eth/src/erc7984Token.ts @@ -42,11 +42,28 @@ import { decodeTransferData, } from '@bitgo/abstract-eth'; import { bip32 } from '@bitgo/secp256k1'; +import { ethers } from 'ethers'; +import { addHexPrefix } from 'ethereumjs-util'; import * as _ from 'lodash'; import { Eth } from './eth'; import { TransactionBuilder } from './lib'; +// CECHO-2719 strict consolidation verification: upper bound on the CREATE2 derivation +// indices scanned when checking whether a consolidation destination is a wallet-owned +// forwarder. BitGo EVM forwarders use the derivation index as the CREATE2 salt, so every +// wallet-owned forwarder is reproducible from (baseAddress, index). The scan early-exits +// on the first match, so legitimate (low-index) forwarders verify cheaply; only +// rejections and very-high-index matches pay the full bound. Measured cost is ~15µs per +// derivation, so a full miss across all three derivable version layouts (~30k +// derivations) costs well under a second; recoverConsolidations caps its own address +// scan at 10 * DEFAULT_SCAN_FACTOR = 200, and 10000 covers exchange-scale deposit +// wallets. A destination derived beyond this bound is rejected with an error naming +// the scanned range — diagnosable during the staging validation window, which exists +// to de-risk exactly this class of false positive. +const STRICT_CONSOLIDATION_MAX_DERIVATION_INDEX = 10000; +const STRICT_CONSOLIDATION_FORWARDER_VERSIONS = [1, 2, 4, 5] as const; + export { Erc7984TokenConfig }; export class Erc7984Token extends Eth { @@ -495,6 +512,15 @@ export class Erc7984Token extends Eth { const { txParams, txPrebuild, wallet } = params; if (!txPrebuild?.txHex) { + // CECHO-2719 rollout gate: strict consolidation verification requires inspecting the + // material that will be signed — a consolidateId alone proves nothing about the + // transaction, so a txHex-less prebuild is rejected outright on test/staging. + // This gate must be removed (enforcing everywhere) in the next release. + if (this.bitgo.env === 'test' || this.bitgo.env === 'staging') { + throw new Error( + 'verifyConfidentialConsolidation: txPrebuild.txHex is required to verify a consolidation on test/staging' + ); + } if (!txPrebuild?.consolidateId && !txParams?.prebuildTx?.consolidateId) { throw new Error('verifyConfidentialConsolidation: missing consolidateId'); } @@ -533,6 +559,11 @@ export class Erc7984Token extends Eth { ); } + // Note: in strict mode the checks below run first on this builder round-trip + // decode, and verifyStrictConsolidationCalldata then re-verifies every field from + // the original signed bytes; both must pass, so if the two decodes disagree, the + // legacy error surfaces first and the strict tier never runs. + if (tokenContractAddress.toLowerCase() !== this.tokenContractAddress.toLowerCase()) { throw new Error( `verifyConfidentialConsolidation: token contract address mismatch — ` + @@ -567,9 +598,269 @@ export class Erc7984Token extends Eth { } } + // CECHO-2719 rollout gate: strict consolidation 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. + // Release N+1 removes this gate everywhere. + if (this.bitgo.env === 'test' || this.bitgo.env === 'staging') { + this.verifyStrictConsolidationCalldata(wallet, baseAddress, txPrebuild.txHex); + } + return true; } + /** + * Strict CECHO-2719 checks on a consolidation (flush) prebuild, enforced on test and + * staging environments during the staged rollout. + * + * Every bound field — outer value, outer `to`, token contract, parent, handle, + * sendMultiSig amount, callFromParent value, and the flushed forwarder — is decoded + * from the ORIGINAL signed bytes (ethers parseTransaction), never from the + * TransactionBuilder from()/build() round trip: the round trip re-encodes + * FlushERC7984ForwarderToken calldata through buildFlushERC7984ForwarderTokenCalldata, + * which hardcodes value 0 and would silently normalize a hostile non-zero value word + * out of the inspected transaction — while the wallet signs the original bytes. + * Verifying the original bytes closes that whole class of builder-normalization + * blind spots, not just the value word. + * + * Checks: + * 1. the calldata decodes as one of the two consolidation shapes with the expected + * token contract, the wallet base address as parent, and a non-empty handle + * 2. the outer transaction value is 0 (every sibling verifier — + * verifyWrapTransaction / verifyUnwrapTransaction / verifyFinalizeUnwrapTransaction — + * already enforces this on the round-tripped form) + * 3. the sendMultiSig amount (multisig shape) and the callFromParent value (both + * shapes) are 0 + * 4. multisig shape: the outer call targets the wallet contract (base address) + * 5. the flushed forwarder is a wallet-owned address derived locally from wallet + * data — never from txPrebuild.recipients, which comes from the same untrusted + * server response as txHex. Unlike the enable-token verifier (CECHO-2720) there + * is no structural backstop: `to = attacker` with a zero value still executes an + * arbitrary call as the wallet, so the destination binding cannot be skipped. + * Fails closed when no wallet-owned forwarder can be derived. + * + * These checks depend only on the decoded transaction content and local wallet data, + * so they apply identically no matter which (server-controlled) flag routed the + * prebuild into this verifier. + */ + private verifyStrictConsolidationCalldata( + wallet: VerifyEthTransactionOptions['wallet'], + baseAddress: string, + originalTxHex: string + ): void { + let originalTo: string | undefined; + let originalValue: ethers.BigNumber; + let tokenContractAddress: string; + let parentAddress: string; + let encryptedHandle: string; + let forwarderAddress: string; + let sendMultiSigAmount: string | undefined; + let callFromParentValue: bigint | undefined; + + try { + // addHexPrefix: TransactionBuilder.from() accepts unprefixed serialized txHex + // (RAW_TX_HEX_REGEX), so a producer (e.g. a TSS serializedTxHex) may send it; + // ethers v5 parseTransaction requires the 0x prefix. addHexPrefix is idempotent. + const originalTx: { to?: string; value: ethers.BigNumber; data?: string } = ethers.utils.parseTransaction( + addHexPrefix(originalTxHex) + ); + originalTo = originalTx.to; + originalValue = originalTx.value; + const originalData: string = originalTx.data ?? '0x'; + if (originalData.startsWith(sendMultisigMethodId)) { + const decoded = decodeSendMultiSigFlushERC7984Data(originalData); + forwarderAddress = decoded.forwarderAddress; + sendMultiSigAmount = decoded.amount; + callFromParentValue = decoded.callFromParentValue; + tokenContractAddress = decoded.tokenContractAddress; + parentAddress = decoded.parentAddress; + encryptedHandle = decoded.encryptedHandle; + } else if (originalData.startsWith(callFromParentMethodId)) { + if (!originalTo) { + throw new Error('consolidation transaction has no destination'); + } + const decoded = decodeFlushERC7984ForwarderTokenCalldata(originalData); + tokenContractAddress = decoded.tokenContractAddress; + callFromParentValue = decoded.callFromParentValue; + parentAddress = decoded.parentAddress; + encryptedHandle = decoded.encryptedHandle; + forwarderAddress = originalTo; + } else { + throw new Error(`unexpected method ID ${originalData.slice(0, 10)}`); + } + } catch (e) { + throw new Error( + `verifyConfidentialConsolidation: failed to decode original consolidation calldata — ${(e as Error).message}` + ); + } + const isMultisigShape = sendMultiSigAmount !== undefined; + + // 1. Bind the calldata to the token contract, the wallet base address, and a handle. + if (tokenContractAddress.toLowerCase() !== this.tokenContractAddress.toLowerCase()) { + throw new Error( + `verifyConfidentialConsolidation: token contract address mismatch — ` + + `expected ${this.tokenContractAddress}, got ${tokenContractAddress}` + ); + } + if (parentAddress.toLowerCase() !== baseAddress.toLowerCase()) { + throw new Error( + `verifyConfidentialConsolidation: parent address mismatch — expected ${baseAddress}, got ${parentAddress}` + ); + } + if (!encryptedHandle || encryptedHandle === '0x') { + throw new Error('verifyConfidentialConsolidation: encryptedHandle is missing or empty in transaction calldata'); + } + + // 2. A consolidation moves confidential balances via calldata only; a non-zero outer + // value sends native funds to whatever address the transaction targets. + if (!originalValue.isZero()) { + throw new Error( + `verifyConfidentialConsolidation: expected transaction value 0 but got ${originalValue.toString()}` + ); + } + + // 3. Inner value words must both be zero. + if (isMultisigShape && sendMultiSigAmount !== '0') { + throw new Error(`verifyConfidentialConsolidation: sendMultiSig amount must be 0 but got ${sendMultiSigAmount}`); + } + if (callFromParentValue !== undefined && callFromParentValue !== 0n) { + throw new Error( + `verifyConfidentialConsolidation: callFromParent must carry value 0 but got ${callFromParentValue}` + ); + } + + // The remaining sendMultiSig parameters (expireTime, sequenceId, signature) are + // deliberately not bound here: they are enforced by the on-chain wallet contract + // and the platform co-signature, and are not client-verifiable. + + // 4. Multisig shape: the outer call targets the wallet contract itself, not any + // other contract the platform picked. + if (isMultisigShape) { + if (!originalTo || originalTo.toLowerCase() !== baseAddress.toLowerCase()) { + throw new Error( + `verifyConfidentialConsolidation: multisig consolidation must call the wallet contract ` + + `(${baseAddress}) but got ${originalTo}` + ); + } + } + + // 5. The flushed forwarder must be a wallet-owned address derived locally from the + // wallet's own data (fails closed when it cannot be derived). Any wallet-owned + // forwarder is acceptable by design: which forwarder to flush is the platform's + // choice (consolidations sweep whichever forwarder holds balances), and safety + // comes from the parent binding — the flush returns funds to this wallet's base + // address (checked above), never elsewhere. + if (!this.isWalletOwnedForwarderAddress(forwarderAddress, baseAddress, wallet)) { + throw new Error( + `verifyConfidentialConsolidation: consolidation destination ${forwarderAddress} is not a ` + + `wallet-owned forwarder address (verified CREATE2 derivation indices ` + + `0..${STRICT_CONSOLIDATION_MAX_DERIVATION_INDEX - 1} across forwarder versions ` + + `${STRICT_CONSOLIDATION_FORWARDER_VERSIONS.join('/')})` + ); + } + } + + /** + * Whether an address is a wallet-owned destination for a consolidation (flush): a + * forwarder the wallet owns, derived locally from wallet data only — never from the + * prebuild response (CECHO-2719). + * + * BitGo EVM forwarders are deployed via CREATE2 from the wallet's base address with + * the derivation index as the salt, so every wallet-owned forwarder is reproducible + * locally from (baseAddress, index) plus the network factory/implementation constants + * — the same math AbstractEthLikeNewCoins.deriveAddress and isWalletAddress use. All + * known forwarder versions are scanned (v4 only when the wallet carries its fee + * address, because the fee is part of the v4 CREATE2 salt — see + * getCreateForwarderParamsAndTypes / verifyForwarderAddress), so the result does not + * depend on wallet version metadata; an attacker-chosen address can never verify + * without controlling the wallet's own base address. + * + * The wallet's base address is deliberately NOT accepted as a flush destination: a + * legitimate consolidation always targets a forwarder contract holding confidential + * balances, never the wallet's own contract or EOA (which has no callFromParent and + * holds no balances to flush). The multisig shape's outer `to == base` requirement + * is enforced separately in verifyStrictConsolidationCalldata. + * + * The scan starts at index 0 and returns on the first match, so legitimate + * (low-index) forwarders verify cheaply; only rejections pay the full scan. Indices + * are bounded by STRICT_CONSOLIDATION_MAX_DERIVATION_INDEX (see its comment). + * Throws (fails closed) when the network configures no forwarder factory at all, or — + * naming the missing fee address — when v4 derivations were impossible and the + * destination matched nothing. + */ + private isWalletOwnedForwarderAddress( + destination: string, + baseAddress: string, + wallet: VerifyEthTransactionOptions['wallet'] + ): boolean { + const destinationLower = destination.toLowerCase(); + + const coinSpecific = typeof wallet?.coinSpecific === 'function' ? wallet.coinSpecific() : wallet?.coinSpecific; + const feeAddress = (coinSpecific as { feeAddress?: string } | undefined)?.feeAddress; + let anyFactoryConfigured = false; + let v4SkippedForMissingFee = false; + + for (const forwarderVersion of STRICT_CONSOLIDATION_FORWARDER_VERSIONS) { + let factoryAddresses: { forwarderFactoryAddress: string; forwarderImplementationAddress: string }; + try { + factoryAddresses = this.getForwarderFactoryAddressesAndForwarderImplementationAddress(forwarderVersion); + } catch { + // This network does not configure the factory for this forwarder version; skip it. + continue; + } + anyFactoryConfigured = true; + // Only the v4 CREATE2 salt layout includes the enterprise fee address; every + // other version derives with an empty fee address, and v4 cannot be derived + // without one. + const versionFeeAddress: string = forwarderVersion === 4 ? feeAddress ?? '' : ''; + if (forwarderVersion === 4 && !versionFeeAddress) { + // Not silently: without the wallet's fee address the v4 salt layout is not + // reproducible offline; the rejection after the scan names the missing data. + v4SkippedForMissingFee = true; + continue; + } + for (let index = 0; index < STRICT_CONSOLIDATION_MAX_DERIVATION_INDEX; index++) { + let forwarder: string; + try { + forwarder = this.generateForwarderAddress( + baseAddress, + versionFeeAddress, + factoryAddresses.forwarderFactoryAddress, + factoryAddresses.forwarderImplementationAddress, + index + ); + } catch { + // Derivation for this index failed; keep scanning the remaining indices. + // Fee-less v4 is already skipped before the loop, so a catch here can only be + // a malformed derivation input (e.g. an invalid base address), and the + // destination comparison below fails closed on it regardless. + continue; + } + if (forwarder.toLowerCase() === destinationLower) { + return true; + } + } + } + + if (!anyFactoryConfigured) { + throw new Error( + 'verifyConfidentialConsolidation: unable to derive any wallet-owned forwarder address — ' + + 'no forwarder factory addresses are configured for this network' + ); + } + if (v4SkippedForMissingFee) { + throw new Error( + `verifyConfidentialConsolidation: consolidation destination ${destination} is not a wallet-owned ` + + `forwarder address (verified CREATE2 derivation indices ` + + `0..${STRICT_CONSOLIDATION_MAX_DERIVATION_INDEX - 1} across forwarder versions 1/2/5). ` + + 'v4-salted forwarders were NOT verifiable because the wallet record carries no feeAddress, ' + + 'and the fee address is part of the v4 CREATE2 salt — if the flush targets a v4/v5-wallet ' + + 'forwarder, the wallet data must carry its feeAddress' + ); + } + return false; + } + /** * Verifies a confidential token transfer (SendERC7984) transaction. * diff --git a/modules/sdk-coin-eth/test/unit/erc7984Token.ts b/modules/sdk-coin-eth/test/unit/erc7984Token.ts index 5b6c9516ed..ef6f40b965 100644 --- a/modules/sdk-coin-eth/test/unit/erc7984Token.ts +++ b/modules/sdk-coin-eth/test/unit/erc7984Token.ts @@ -18,6 +18,7 @@ import { EthereumNetwork } from '@bitgo/statics'; import { buildMulticallDelegationCalldata, buildDelegationCalldata, + buildConfidentialTransferByHandleCalldata, buildFlushERC7984ForwarderTokenCalldata, buildWrapCalldata, buildUnwrapCalldata, @@ -1369,20 +1370,37 @@ describe('decodeTokenAddressesFromDelegationCalldata', function () { // --------------------------------------------------------------------------- const MULTISIG_WALLET_CONTRACT = '0x3b58684525564b38a381e46a731703ed03f32122'; -const CONSOLIDATION_FORWARDER = '0xf4bcb366bb5e34ebbee51fae5de98cc876c0146f'; +// Wallet-owned flush forwarder for the fixture wallet, derived rather than arbitrary: +// the strict consolidation verifier (CECHO-2719) only accepts destinations that are +// locally derivable from the wallet's base address, so the fixture uses the real +// CREATE2 forwarder of CONSOLIDATION_BASE_ADDRESS (assigned in before() below). +let CONSOLIDATION_FORWARDER = ''; const CONSOLIDATION_BASE_ADDRESS = '0x3b58684525564b38a381e46a731703ed03f32122'; const CONSOLIDATION_HANDLE = '0x65df136b609ab395c1a99ae46f7939c7f8b20dff4bff0000000088bb0050'; const DUMMY_MULTISIG_SIGNATURE = '0x' + '00'.repeat(65); +// Hoodi enterprise fee address used in v4 forwarder CREATE2 salts (from the v5-wallet +// address fixture in test/unit/eth.ts) — for the v4-salted forwarder regression tests. +const V4_WALLET_FEE_ADDRESS = '0xb1e725186990b86ca8efed08a3ccda9c9f400f09'; -async function buildMultisigConsolidationTxHex(): Promise { +/** + * Builds a multisig consolidation tx: to = wallet contract, data = sendMultiSig + * wrapping callFromParent flush calldata. Parameters allow hostile prebuild variants + * (attacker forwarder, non-zero amount, wrong outer contract) for CECHO-2719 tests. + */ +async function buildMultisigConsolidationTxHex( + forwarderAddress: string = CONSOLIDATION_FORWARDER, + amount = '0', + contractAddress: string = MULTISIG_WALLET_CONTRACT, + outerValue = '0' +): Promise { const flushCalldata = buildFlushERC7984ForwarderTokenCalldata( CTEST1_TOKEN_ADDRESS, CONSOLIDATION_BASE_ADDRESS, CONSOLIDATION_HANDLE ); const sendData = sendMultiSigData( - CONSOLIDATION_FORWARDER, - '0', + forwarderAddress, + amount, flushCalldata, Math.floor(Date.now() / 1000) + 3600, 14, @@ -1393,8 +1411,11 @@ async function buildMultisigConsolidationTxHex(): Promise { txBuilder.fee({ fee: '1000000000', gasLimit: '12100000' }); txBuilder.counter(1); txBuilder.type(TransactionType.ContractCall); - txBuilder.contract(MULTISIG_WALLET_CONTRACT); + txBuilder.contract(contractAddress); txBuilder.data(sendData); + if (outerValue !== '0') { + txBuilder.value(outerValue); + } const tx = await txBuilder.build(); return tx.toBroadcastFormat(); } @@ -1422,6 +1443,16 @@ describe('verifyTransaction – confidential consolidation (FlushERC7984Forwarde bitgo.initializeTestVars(); register(bitgo); coin = bitgo.coin('hteth:ctest1') as Erc7984Token; + // CECHO-2719: derive the fixture forwarder locally (Hoodi v1 forwarder factory, + // index 1) so it is a genuinely wallet-owned destination for strict verification. + const hoodiNetwork = coin.getNetwork() as EthereumNetwork; + CONSOLIDATION_FORWARDER = coin.generateForwarderAddress( + CONSOLIDATION_BASE_ADDRESS, + '', + hoodiNetwork.forwarderFactoryAddress as string, + hoodiNetwork.forwarderImplementationAddress as string, + 1 + ); }); it('should verify a valid multisig consolidation tx (sendMultiSig → callFromParent → confidentialTransferNoProof)', async function () { @@ -1550,6 +1581,497 @@ describe('verifyTransaction – confidential consolidation (FlushERC7984Forwarde }) .should.be.rejectedWith(/parent address mismatch/); }); + // ------------------------------------------------------------------------- + describe('strict consolidation verification (CECHO-2719)', function () { + it('should reject a TSS direct theft prebuild (to = attacker, value = wallet balance)', async function () { + const flushCalldata = buildFlushERC7984ForwarderTokenCalldata( + CTEST1_TOKEN_ADDRESS, + CONSOLIDATION_BASE_ADDRESS, + CONSOLIDATION_HANDLE + ); + const txHex = await buildRawContractCallTxHex(ATTACKER_CONTRACT_ADDRESS, flushCalldata, '1000000000000000000'); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/expected transaction value 0/); + }); + + it('should reject a TSS direct arbitrary-call prebuild (to = attacker, value = 0)', async function () { + // Zero value kills the native-balance theft, but without the enable-token + // verifier's structural backstop the wallet would still execute an arbitrary + // zero-value call at the attacker's contract, so the destination must be a + // locally derived wallet-owned forwarder. + const flushCalldata = buildFlushERC7984ForwarderTokenCalldata( + CTEST1_TOKEN_ADDRESS, + CONSOLIDATION_BASE_ADDRESS, + CONSOLIDATION_HANDLE + ); + const txHex = await buildRawContractCallTxHex(ATTACKER_CONTRACT_ADDRESS, flushCalldata); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/is not a wallet-owned forwarder address/); + }); + + it('should reject a multisig theft prebuild (sendMultiSig(attacker, balance, flush))', async function () { + const txHex = await buildMultisigConsolidationTxHex(ATTACKER_CONTRACT_ADDRESS, '1000000000000000000'); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/sendMultiSig amount must be 0/); + }); + + it('should reject a multisig arbitrary-call prebuild (sendMultiSig(attacker, 0, flush))', async function () { + const txHex = await buildMultisigConsolidationTxHex(ATTACKER_CONTRACT_ADDRESS); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/is not a wallet-owned forwarder address/); + }); + + it('should reject a multisig prebuild whose outer to is not the wallet contract', async function () { + // sendMultiSig targets the fixture's derived forwarder, but the outer call goes + // to a contract that is not the wallet's base address. + const txHex = await buildMultisigConsolidationTxHex(undefined, '0', ATTACKER_CONTRACT_ADDRESS); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/multisig consolidation must call the wallet contract/); + }); + + it('should reject a non-zero callFromParent value even when the destination is a derived forwarder', async function () { + const inner = buildConfidentialTransferByHandleCalldata(CONSOLIDATION_BASE_ADDRESS, CONSOLIDATION_HANDLE); + const calldata = encodeRawCallFromParent(CTEST1_TOKEN_ADDRESS, '123', inner); + const txHex = await buildRawContractCallTxHex(CONSOLIDATION_FORWARDER, calldata); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/callFromParent must carry value 0/); + }); + + it('should reject a txHex-less prebuild carrying only a consolidateId', async function () { + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: '6a44ebc0326e1be45c1d797542c8c634' } as any, + wallet, + }) + .should.be.rejectedWith(/txPrebuild\.txHex is required/); + }); + + it('should fail closed when no wallet-owned forwarder can be derived', async function () { + // Test seam: statics network configs are frozen, so stub getNetwork to return a + // copy with no forwarder factory addresses configured (original captured before + // stubbing, per the frozen-networks constraint). + const originalNetwork = coin.getNetwork() as EthereumNetwork; + const getNetworkStub = sinon.stub(coin, 'getNetwork').returns({ + ...originalNetwork, + forwarderFactoryAddress: undefined, + walletV2ForwarderFactoryAddress: undefined, + walletV4ForwarderFactoryAddress: undefined, + }); + try { + const flushCalldata = buildFlushERC7984ForwarderTokenCalldata( + CTEST1_TOKEN_ADDRESS, + CONSOLIDATION_BASE_ADDRESS, + CONSOLIDATION_HANDLE + ); + const txHex = await buildRawContractCallTxHex(CONSOLIDATION_FORWARDER, flushCalldata); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/unable to derive any wallet-owned forwarder address/); + } finally { + getNetworkStub.restore(); + } + }); + + 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 flushCalldata = buildFlushERC7984ForwarderTokenCalldata( + CTEST1_TOKEN_ADDRESS, + CONSOLIDATION_BASE_ADDRESS, + CONSOLIDATION_HANDLE + ); + const txHex = await buildRawContractCallTxHex(ATTACKER_CONTRACT_ADDRESS, flushCalldata, '1000000000000000000'); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/expected transaction value 0/); + } finally { + mutableBitgo.env = originalEnv; + } + }); + it('should reject a multisig prebuild with a non-zero outer transaction value', async function () { + const txHex = await buildMultisigConsolidationTxHex(undefined, '0', undefined, '1000000000000000000'); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/expected transaction value 0/); + }); + + it('should verify a valid direct consolidation whose txHex is unprefixed', async function () { + // TransactionBuilder.from() accepts unprefixed serialized txHex (RAW_TX_HEX_REGEX), + // so a producer (e.g. a TSS serializedTxHex) may send it; strict verification must + // normalise with addHexPrefix before ethers parseTransaction, not reject the prebuild. + const txHex = await buildDirectConsolidationTxHex(); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + const result = await coin.verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: '6a44ebc0326e1be45c1d797542c8c634', txHex: txHex.slice(2) } as any, + wallet, + }); + result.should.equal(true); + }); + + it('should verify a v1-derived forwarder for a wallet that carries a fee address', async function () { + // Regression (review): the derivation used to pass the wallet fee address for every + // forwarder version, which switched v1/v2/v5 to the v4 CREATE2 salt layout and + // rejected their legitimate forwarders. Only v4 encodes the fee address into its salt. + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS, feeAddress: ATTACKER_CONTRACT_ADDRESS }, + } as any); + const txHex = await buildDirectConsolidationTxHex(); + + const result = await coin.verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: '6a44ebc0326e1be45c1d797542c8c634', txHex } as any, + wallet, + }); + result.should.equal(true); + }); + + it('should reject a forwarder derived beyond the derivation index cap', async function () { + // Documents the STRICT_CONSOLIDATION_MAX_DERIVATION_INDEX trade-off: an index past + // the cap is not wallet-verifiable offline, and the rejection names the scanned + // range so the staging validation window can diagnose it. + const hoodiNetwork = coin.getNetwork() as EthereumNetwork; + const beyondCapForwarder = coin.generateForwarderAddress( + CONSOLIDATION_BASE_ADDRESS, + '', + hoodiNetwork.forwarderFactoryAddress as string, + hoodiNetwork.forwarderImplementationAddress as string, + 10500 + ); + const inner = buildConfidentialTransferByHandleCalldata(CONSOLIDATION_BASE_ADDRESS, CONSOLIDATION_HANDLE); + const txHex = await buildRawContractCallTxHex( + beyondCapForwarder, + wrapInCallFromParent(CTEST1_TOKEN_ADDRESS, inner) + ); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/verified CREATE2 derivation indices 0\.\.9999/); + }); + + it('should reject a v4-salted forwarder when the wallet record carries no fee address', async function () { + // v4 forwarders encode the enterprise fee address into the CREATE2 salt; without the + // wallet's fee address they are not derivable offline, and the rejection must name + // the missing data instead of silently dropping the v4 layout (review finding). + const hoodiNetwork = coin.getNetwork() as EthereumNetwork; + const v4Forwarder = coin.generateForwarderAddress( + CONSOLIDATION_BASE_ADDRESS, + V4_WALLET_FEE_ADDRESS, + hoodiNetwork.walletV4ForwarderFactoryAddress as string, + hoodiNetwork.walletV4ForwarderImplementationAddress as string, + 1 + ); + const flushCalldata = buildFlushERC7984ForwarderTokenCalldata( + CTEST1_TOKEN_ADDRESS, + CONSOLIDATION_BASE_ADDRESS, + CONSOLIDATION_HANDLE + ); + const txHex = await buildRawContractCallTxHex(v4Forwarder, flushCalldata); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith( + /v4-salted forwarders were NOT verifiable because the wallet record carries no feeAddress/ + ); + }); + + it('should verify a v4-salted forwarder when the wallet carries its fee address', async function () { + const hoodiNetwork = coin.getNetwork() as EthereumNetwork; + const v4Forwarder = coin.generateForwarderAddress( + CONSOLIDATION_BASE_ADDRESS, + V4_WALLET_FEE_ADDRESS, + hoodiNetwork.walletV4ForwarderFactoryAddress as string, + hoodiNetwork.walletV4ForwarderImplementationAddress as string, + 1 + ); + const flushCalldata = buildFlushERC7984ForwarderTokenCalldata( + CTEST1_TOKEN_ADDRESS, + CONSOLIDATION_BASE_ADDRESS, + CONSOLIDATION_HANDLE + ); + const txHex = await buildRawContractCallTxHex(v4Forwarder, flushCalldata); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS, feeAddress: V4_WALLET_FEE_ADDRESS }, + } as any); + + const result = await coin.verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }); + result.should.equal(true); + }); + it('should reject the wallet base address as a flush destination', async function () { + // A legitimate consolidation always targets a forwarder contract; the wallet's own + // base address has no callFromParent and holds no balances to flush. The multisig + // outer `to == base` requirement is enforced separately (review follow-up). + const flushCalldata = buildFlushERC7984ForwarderTokenCalldata( + CTEST1_TOKEN_ADDRESS, + CONSOLIDATION_BASE_ADDRESS, + CONSOLIDATION_HANDLE + ); + const txHex = await buildRawContractCallTxHex(CONSOLIDATION_BASE_ADDRESS, flushCalldata); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS, feeAddress: V4_WALLET_FEE_ADDRESS }, + } as any); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejectedWith(/is not a wallet-owned forwarder address/); + }); + + it('should verify a multisig consolidation to a v4-salted forwarder for a fee-carrying wallet', async function () { + // The multisig shape is the other v4 consumer besides the TSS v5 wallet. + const hoodiNetwork = coin.getNetwork() as EthereumNetwork; + const v4Forwarder = coin.generateForwarderAddress( + CONSOLIDATION_BASE_ADDRESS, + V4_WALLET_FEE_ADDRESS, + hoodiNetwork.walletV4ForwarderFactoryAddress as string, + hoodiNetwork.walletV4ForwarderImplementationAddress as string, + 1 + ); + const txHex = await buildMultisigConsolidationTxHex(v4Forwarder); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS, feeAddress: V4_WALLET_FEE_ADDRESS }, + } as any); + + const result = await coin.verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }); + result.should.equal(true); + }); + + it('should verify a consolidation whose txHex is an unsigned EIP-1559 signable (TSS signableHex form)', async function () { + // The TSS txRequest flow passes unsignedTx.signableHex as txHex; lock in that both + // the builder round trip and ethers parseTransaction accept the unsigned forms. + const inner = buildConfidentialTransferByHandleCalldata(CONSOLIDATION_BASE_ADDRESS, CONSOLIDATION_HANDLE); + const calldata = wrapInCallFromParent(CTEST1_TOKEN_ADDRESS, inner); + const unsignedTx = { + type: 2, + chainId: 560048, // Hoodi + nonce: 1, + gasLimit: 200000, + maxFeePerGas: 1000000000, + maxPriorityFeePerGas: 1000000, + to: CONSOLIDATION_FORWARDER, + value: 0, + data: calldata, + }; + const txHex = ethers.utils.serializeTransaction(unsignedTx); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + const result = await coin.verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }); + result.should.equal(true); + }); + + it('should reject an unsigned legacy EIP-155 signable at the pre-existing builder round trip', async function () { + // The unsigned EIP-155 serialization (v = chainId, r = s = 0) is not parseable by + // the builder's @ethereumjs/tx round trip — on the base branch as well, in both + // envs, since the legacy decode always runs first. Coins whose signableHex takes + // that form (e.g. BSC/XDC) are exactly why TSS_VERIFY_USE_SERIALIZED_TX_HEX exists: + // their verification receives serializedTxHex, which is a parseable serialization. + // eth/Hoodi TSS flows produce EIP-1559, covered by the previous test. + const inner = buildConfidentialTransferByHandleCalldata(CONSOLIDATION_BASE_ADDRESS, CONSOLIDATION_HANDLE); + const calldata = wrapInCallFromParent(CTEST1_TOKEN_ADDRESS, inner); + const unsignedTx = { + chainId: 560048, + nonce: 1, + gasPrice: 1000000000, + gasLimit: 200000, + to: CONSOLIDATION_FORWARDER, + value: 0, + data: calldata, + }; + const txHex = ethers.utils.serializeTransaction(unsignedTx); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + await coin + .verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }) + .should.be.rejected(); + }); + }); + + // ------------------------------------------------------------------------- + describe('CECHO-2719 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 TSS direct theft prebuild on prod (strict checks not yet enforced there)', async function () { + const flushCalldata = buildFlushERC7984ForwarderTokenCalldata( + CTEST1_TOKEN_ADDRESS, + CONSOLIDATION_BASE_ADDRESS, + CONSOLIDATION_HANDLE + ); + const txHex = await buildRawContractCallTxHex(ATTACKER_CONTRACT_ADDRESS, flushCalldata, '1000000000000000000'); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + const result = await coin.verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }); + result.should.equal(true); + }); + + it('should still verify the multisig theft prebuild on prod', async function () { + const txHex = await buildMultisigConsolidationTxHex(ATTACKER_CONTRACT_ADDRESS, '1000000000000000000'); + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + const result = await coin.verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: 'abc123', txHex } as any, + wallet, + }); + result.should.equal(true); + }); + + it('should still verify a txHex-less consolidateId-only prebuild on prod', async function () { + const wallet = new Wallet(bitgo, coin, { + coinSpecific: { baseAddress: CONSOLIDATION_BASE_ADDRESS }, + }); + + const result = await coin.verifyTransaction({ + txParams: { type: 'consolidate' } as any, + txPrebuild: { consolidateId: '6a44ebc0326e1be45c1d797542c8c634' } as any, + wallet, + }); + result.should.equal(true); + }); + }); }); // ---------------------------------------------------------------------------