diff --git a/modules/abstract-eth/src/abstractEthLikeNewCoins.ts b/modules/abstract-eth/src/abstractEthLikeNewCoins.ts index b07629af0f..83e5e58f96 100644 --- a/modules/abstract-eth/src/abstractEthLikeNewCoins.ts +++ b/modules/abstract-eth/src/abstractEthLikeNewCoins.ts @@ -54,7 +54,9 @@ import { DeriveAddressOptions, DeriveAddressResult, NO_RECIPIENT_TX_TYPES, + CoinWithSerializedTxHexVerification, CoinWithSignableConsistency, + SignableTransaction, } from '@bitgo/sdk-core'; import { getDerivationPath } from '@bitgo/sdk-lib-mpc'; import { bip32 } from '@bitgo/secp256k1'; @@ -641,7 +643,18 @@ function isCanonicalTssCalldata(data: string, types: string[]): boolean { } } -export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implements CoinWithSignableConsistency { +/** + * True when `decoded` is an RLP list whose items are all flat byte strings + * (i.e. a legacy transaction / signing preimage), not a typed envelope or a digest. + */ +function isFlatByteRlpList(decoded: unknown): decoded is Uint8Array[] { + return Array.isArray(decoded) && decoded.every((item): item is Uint8Array => item instanceof Uint8Array); +} + +export abstract class AbstractEthLikeNewCoins + extends AbstractEthLikeCoin + implements CoinWithSignableConsistency, CoinWithSerializedTxHexVerification +{ static hopTransactionSalt = 'bitgoHopAddressRequestSalt'; protected readonly sendMethodName: 'sendMultiSig' | 'sendMultiSigToken'; @@ -3431,8 +3444,60 @@ export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin implem } /** - * Verify if a tss transaction is valid + * Returns true when `unsignedTx.signableHex` is a legacy (type-0) EIP-155 signing + * preimage — `RLP([nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0])` — + * as opposed to an EIP-2718 typed transaction like `0x02...` or a 32-byte + * pre-hashed digest. + * + * Legacy EIP-155 signing preimages are not parseable serialized transactions under + * `@ethereumjs/tx` (`v` carries the chain id and `r = s = 0`), so routing them to + * `serializedTxHex` ensures full payment verification and `assertSignableConsistency` + * even on EIP-1559 chains. + * + * Policy: only replay-protected (EIP-155) legacy envelopes are supported. Legacy + * lists that are recognizable signing preimages but not EIP-155 fail closed: + * - 6 fields: pre-EIP-155 preimage, which carries no chain id (no replay protection). + * - 9 fields with empty `v`: no chain id, so it is not an EIP-155 preimage. + * A 9-field list with non-empty `r`/`s` is a signed transaction, not a signing + * preimage, and stays off this route. * + * @throws {InvalidTransactionError} when signableHex is an unsupported legacy preimage. + */ + shouldVerifyWithSerializedTxHex(unsignedTx: SignableTransaction): boolean { + const raw = stripHexPrefix(unsignedTx.signableHex?.trim() ?? ''); + if (!raw || raw.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(raw)) { + return false; + } + let decoded: unknown; + try { + decoded = RLP.decode(Buffer.from(raw, 'hex')); + } catch { + return false; + } + // Typed transactions (0x02...) and pre-hashed digests decode to a byte string, not a list. + if (!isFlatByteRlpList(decoded)) { + return false; + } + if (decoded.length === 6) { + throw new InvalidTransactionError( + 'Unsupported legacy type-0 signing preimage: pre-EIP-155 envelopes (6 fields) carry no chain id and are not replay-protected; only EIP-155 legacy transactions are supported' + ); + } + if (decoded.length !== 9) { + return false; + } + // A 9-field list with non-empty r/s is a signed transaction, not an unsigned signing preimage. + if (decoded[7].length !== 0 || decoded[8].length !== 0) { + return false; + } + if (decoded[6].length === 0) { + throw new InvalidTransactionError( + 'Unsupported legacy type-0 signing preimage: 9-field RLP is missing the EIP-155 chain id (v); only EIP-155 legacy transactions are supported' + ); + } + return true; + } + /** @inheritdoc CoinWithSignableConsistency */ assertSignableConsistency(serializedTxHex: string, signableHex: string): void { const common = AbstractEthLikeNewCoins.getCustomChainCommon(this.getChainId()); diff --git a/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts b/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts index 9f0c05234d..b8d343e00a 100644 --- a/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts +++ b/modules/sdk-coin-eth/test/unit/tssPaymentVerification.ts @@ -2,12 +2,14 @@ import 'should'; import sinon from 'sinon'; import { Hash } from 'crypto'; import EthereumAbi from 'ethereumjs-abi'; -import { FeeMarketEIP1559Transaction } from '@ethereumjs/tx'; +import { FeeMarketEIP1559Transaction, Transaction as LegacyTransaction, TransactionFactory } from '@ethereumjs/tx'; +import { addHexPrefix, bufArrToArr, rlp, stripHexPrefix, toBuffer } from 'ethereumjs-util'; import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test'; import { BitGoAPI } from '@bitgo/sdk-api'; import { EcdsaMPCv2Utils, EcdsaUtils, + InvalidTransactionError, RequestTracer, TransactionType, TxIntentMismatchRecipientError, @@ -621,6 +623,356 @@ describe('TSS payment verification', function () { } }); + // CECHO-2681: a legacy (type-0) EVM transaction's signableHex is the EIP-155 signing + // preimage RLP([nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0]) — not a + // parseable serialized transaction. The envelope must route verification to + // serializedTxHex even on an EIP-1559 coin like hteth; type-2 keeps signableHex. + describe('legacy type-0 envelope routing', function () { + function deriveSignableHex(serializedTxHex: string): string { + const common = AbstractEthLikeNewCoins.getCustomChainCommon(coin.getChainId()); + const ethTx = TransactionFactory.fromSerializedData(toBuffer(addHexPrefix(serializedTxHex)), { common }); + if (ethTx instanceof LegacyTransaction) { + return Buffer.from(rlp.encode(bufArrToArr(ethTx.getMessageToSign(false)))).toString('hex'); + } + return Buffer.from(ethTx.getMessageToSign(false)).toString('hex'); + } + async function buildTypedTxBytes( + kind: 'legacy' | 'eip1559', + { to, value = '0', data }: { to: string; value?: string; data?: string } + ): Promise<{ serializedTxHex: string; signableHex: string }> { + const txBuilder = getBuilder('hteth') as TransactionBuilder; + txBuilder.type(data ? TransactionType.ContractCall : TransactionType.SingleSigSend); + txBuilder.counter(1); + txBuilder.contract(to); + txBuilder.value(value); + if (data) { + txBuilder.data(data); + } + if (kind === 'legacy') { + txBuilder.fee({ fee: '10', gasLimit: '100000' }); + } else { + txBuilder.fee({ fee: '10', gasLimit: '100000', eip1559: { maxFeePerGas: '10', maxPriorityFeePerGas: '1' } }); + } + const serializedTxHex = stripHexPrefix((await txBuilder.build()).toBroadcastFormat()); + return { serializedTxHex, signableHex: deriveSignableHex(serializedTxHex) }; + } + + function storedRequest( + txBytes: { serializedTxHex: string; signableHex: string }, + recipients: { address: string; amount: string }[], + opts: { serializedTxHex?: string | undefined } = {} + ): TxRequest { + return { + txRequestId: 'cecho-2681-legacy-envelope', + apiVersion: 'full', + walletId: 'cecho-2681-wallet', + intent: { + intentType: 'payment', + recipients: recipients.map((r) => ({ + address: { address: r.address }, + amount: { value: r.amount, symbol: 'hteth' }, + })), + }, + transactions: [ + { + unsignedTx: { + derivationPath: 'm/0', + ...txBytes, + ...(opts.serializedTxHex !== undefined ? { serializedTxHex: opts.serializedTxHex } : {}), + }, + signatureShares: [], + }, + ], + } as unknown as TxRequest; + } + + function legacyFields(): Buffer[] { + return [ + Buffer.from([1]), + Buffer.from([10]), + Buffer.from([0x52, 0x08]), + toBuffer(recipient), + Buffer.from([1]), + Buffer.from([]), + ]; + } + // Pre-EIP-155 signing preimage (6 fields): no chain id, so no replay protection. + const preEip155Signable = Buffer.from(rlp.encode(legacyFields())).toString('hex'); + // 9-field legacy list whose v is empty: not an EIP-155 signing preimage. + const chainIdLessSignable = Buffer.from( + rlp.encode([...legacyFields(), Buffer.from([]), Buffer.from([]), Buffer.from([])]) + ).toString('hex'); + + it('detects an EIP-155 type-0 envelope and keeps type-2 and pre-hashed signables on their own routes', async function () { + const legacy = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + coin.shouldVerifyWithSerializedTxHex(legacy).should.be.true(); + + const eip1559 = await buildTypedTxBytes('eip1559', { to: recipient, value: '1000' }); + eip1559.signableHex.startsWith('02').should.be.true(); + coin.shouldVerifyWithSerializedTxHex(eip1559).should.be.false(); + + // Signed 9-element legacy RLP (non-empty r/s) is not an unsigned signing preimage. + const signedLike = Buffer.from( + rlp.encode([...legacyFields(), Buffer.from([27]), Buffer.from([1]), Buffer.from([2])]) + ).toString('hex'); + coin + .shouldVerifyWithSerializedTxHex({ serializedTxHex: legacy.serializedTxHex, signableHex: signedLike }) + .should.be.false(); + + // FLR/FLRP atomic shape (32-byte pre-hashed digest) and Tempo 0x76 envelope stay off the legacy route. + coin + .shouldVerifyWithSerializedTxHex({ serializedTxHex: '0000' + 'bb'.repeat(32), signableHex: 'a'.repeat(64) }) + .should.be.false(); + coin + .shouldVerifyWithSerializedTxHex({ serializedTxHex: '0x76f8308080', signableHex: '76f8308080' }) + .should.be.false(); + }); + + it('rejects unsupported legacy type-0 forms instead of routing them to serializedTxHex', async function () { + const legacy = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + // Pre-EIP-155 (6-field) preimages carry no chain id, so there is no replay protection. + (() => + coin.shouldVerifyWithSerializedTxHex({ + serializedTxHex: legacy.serializedTxHex, + signableHex: preEip155Signable, + })).should.throw(/pre-EIP-155/); + // A 9-field legacy list with an empty v has no chain id either. + (() => + coin.shouldVerifyWithSerializedTxHex({ + serializedTxHex: legacy.serializedTxHex, + signableHex: chainIdLessSignable, + })).should.throw(/missing the EIP-155 chain id/); + }); + it('verifies a type-0 payment against its serialized bytes through the full payment verifier', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + ( + await verify( + { type: 'transfer', recipients: [{ address: recipient, amount: '1000' }] }, + txBytes.serializedTxHex + ) + ).should.be.true(); + + const redirected = await buildTypedTxBytes('legacy', { to: otherRecipient, value: '1000' }); + await expectMismatch( + verify({ type: 'transfer', recipients: [{ address: recipient, amount: '1000' }] }, redirected.serializedTxHex), + /destination address does not match/ + ); + }); + + it('cannot verify a type-0 payment from its signableHex preimage alone', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + try { + await verify({ type: 'transfer', recipients: [{ address: recipient, amount: '1000' }] }, txBytes.signableHex); + } catch (e) { + // The EIP-155 preimage (v = chainId, r = 0, s = 0) is not a parseable transaction; + // this is exactly why the envelope must route to serializedTxHex. + (e as Error).should.be.instanceOf(Error); + return; + } + throw new Error('expected signableHex preimage to be unparsable'); + }); + + it('leaves a type-2 payment on the signableHex route', async function () { + const txBytes = await buildTypedTxBytes('eip1559', { to: recipient, value: '1000' }); + ( + await verify({ type: 'transfer', recipients: [{ address: recipient, amount: '1000' }] }, txBytes.signableHex) + ).should.be.true(); + + const redirected = await buildTypedTxBytes('eip1559', { to: otherRecipient, value: '1000' }); + await expectMismatch( + verify({ type: 'transfer', recipients: [{ address: recipient, amount: '1000' }] }, redirected.signableHex), + /destination address does not match/ + ); + }); + + describe('MPCv1 signing entry point (EcdsaUtils)', function () { + const signingBoundaryMessage = 'signing boundary reached after recipient verification'; + const signingMaterial = JSON.stringify({ + pShare: { i: 1, n: 'stub-user-paillier-modulus' }, + backupNShare: { i: 3, n: 'stub-backup-paillier-modulus' }, + }); + + async function runMpcv1Signing(txRequest: TxRequest): Promise<{ error: Error; boundary: Error }> { + const signingWallet = new Wallet(bitgo, coin, { + id: 'cecho-2681-wallet', + multisigType: 'tss', + coinSpecific: { baseAddress }, + }); + const utils = new EcdsaUtils(bitgo, coin, signingWallet); + const boundary = new Error(signingBoundaryMessage); + sinon.stub(utils, 'getOfflineSignerPaillierModulus').throws(boundary); + try { + await utils.signTxRequest({ txRequest, prv: signingMaterial, reqId: new RequestTracer() }); + } catch (e) { + return { error: e as Error, boundary }; + } + throw new Error('expected signTxRequest to reject'); + } + + it('verifies a matching type-0 payment from serializedTxHex and reaches the signing boundary', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + const { error, boundary } = await runMpcv1Signing( + storedRequest(txBytes, [{ address: recipient, amount: '1000' }]) + ); + error.should.be.exactly(boundary); + }); + + it('rejects a mismatched type-0 payment before any signing share is produced', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: otherRecipient, value: '1000' }); + const { error } = await runMpcv1Signing(storedRequest(txBytes, [{ address: recipient, amount: '1000' }])); + error.should.be.instanceOf(TxIntentMismatchRecipientError); + }); + + it('rejects a type-0 payment when signableHex is tampered relative to serializedTxHex', async function () { + const benign = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + const malicious = await buildTypedTxBytes('legacy', { to: otherRecipient, value: '1000' }); + const { error } = await runMpcv1Signing( + storedRequest({ serializedTxHex: benign.serializedTxHex, signableHex: malicious.signableHex }, [ + { address: recipient, amount: '1000' }, + ]) + ); + error.message.should.match(/signableHex is inconsistent with serializedTxHex/); + }); + + it('fails closed when serializedTxHex is missing on the legacy route', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + const { error } = await runMpcv1Signing( + storedRequest(txBytes, [{ address: recipient, amount: '1000' }], { serializedTxHex: '' }) + ); + error.message.should.match(/Missing serializedTxHex for transaction requiring serialized verification/); + }); + + it('rejects unsupported legacy preimages before signing', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + const recipients = [{ address: recipient, amount: '1000' }]; + + const preEip155 = await runMpcv1Signing( + storedRequest({ serializedTxHex: txBytes.serializedTxHex, signableHex: preEip155Signable }, recipients) + ); + preEip155.error.should.be.instanceOf(InvalidTransactionError); + preEip155.error.message.should.match(/pre-EIP-155/); + + const chainIdLess = await runMpcv1Signing( + storedRequest({ serializedTxHex: txBytes.serializedTxHex, signableHex: chainIdLessSignable }, recipients) + ); + chainIdLess.error.should.be.instanceOf(InvalidTransactionError); + chainIdLess.error.message.should.match(/missing the EIP-155 chain id/); + }); + + it('keeps a matching type-2 payment on the direct signableHex route', async function () { + const txBytes = await buildTypedTxBytes('eip1559', { to: recipient, value: '1000' }); + const verifySpy = sinon.spy(coin, 'verifyTransaction'); + const consistencySpy = sinon.spy(coin, 'assertSignableConsistency'); + const { error, boundary } = await runMpcv1Signing( + storedRequest(txBytes, [{ address: recipient, amount: '1000' }]) + ); + error.should.be.exactly(boundary); + verifySpy.callCount.should.eql(1); + (verifySpy.firstCall.args[0].txPrebuild.txHex ?? '').should.eql(txBytes.signableHex); + consistencySpy.callCount.should.eql(0); + }); + }); + + describe('MPCv2 signing entry point (EcdsaMPCv2Utils)', function () { + const signingBoundaryMessage = 'signing boundary reached after recipient verification'; + + async function runMpcv2Signing(txRequest: TxRequest): Promise<{ error: Error; boundary: Error }> { + const signingWallet = new Wallet(bitgo, coin, { + id: 'cecho-2681-wallet', + multisigType: 'tss', + multisigTypeVersion: 'MPCv2', + coinSpecific: { baseAddress }, + }); + const utils = new EcdsaMPCv2Utils(bitgo, coin, signingWallet); + // Avoid the remote GPG lookup; verification does not consume this key. + const stubbableUtils = utils as unknown as Record Promise>; + sinon.stub(stubbableUtils, 'pickBitgoPubGpgKeyForSigning').resolves('stub-bitgo-gpg-key'); + // The MPCv2 flow hashes the verified bytes before exchanging any signature share. + // Throwing here proves verification ran on the routed bytes and accepted the intent. + const boundary = new Error(signingBoundaryMessage); + sinon.stub(coin, 'getHashFunction').returns({ + update: () => { + throw boundary; + }, + } as unknown as Hash); + try { + await utils.signTxRequest({ txRequest, prv: '', reqId: new RequestTracer() }); + } catch (e) { + return { error: e as Error, boundary }; + } + throw new Error('expected signTxRequest to reject'); + } + + it('verifies a matching type-0 payment from serializedTxHex and reaches the signing boundary', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + const { error, boundary } = await runMpcv2Signing( + storedRequest(txBytes, [{ address: recipient, amount: '1000' }]) + ); + error.should.be.exactly(boundary); + }); + + it('rejects a mismatched type-0 payment before any signing share is produced', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: otherRecipient, value: '1000' }); + const { error } = await runMpcv2Signing(storedRequest(txBytes, [{ address: recipient, amount: '1000' }])); + error.should.be.instanceOf(TxIntentMismatchRecipientError); + }); + + it('rejects a type-0 payment when signableHex is tampered relative to serializedTxHex', async function () { + const benign = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + const malicious = await buildTypedTxBytes('legacy', { to: otherRecipient, value: '1000' }); + const { error } = await runMpcv2Signing( + storedRequest({ serializedTxHex: benign.serializedTxHex, signableHex: malicious.signableHex }, [ + { address: recipient, amount: '1000' }, + ]) + ); + error.message.should.match(/signableHex is inconsistent with serializedTxHex/); + }); + + it('fails closed when serializedTxHex is missing on the legacy route', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + const { error } = await runMpcv2Signing( + storedRequest(txBytes, [{ address: recipient, amount: '1000' }], { serializedTxHex: '' }) + ); + error.message.should.match(/Missing serializedTxHex for transaction requiring serialized verification/); + }); + + it('rejects a pre-EIP-155 (6-field) legacy preimage before signing', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + const { error } = await runMpcv2Signing( + storedRequest({ serializedTxHex: txBytes.serializedTxHex, signableHex: preEip155Signable }, [ + { address: recipient, amount: '1000' }, + ]) + ); + error.should.be.instanceOf(InvalidTransactionError); + error.message.should.match(/pre-EIP-155/); + }); + + it('rejects a chain-id-less (empty v) legacy preimage before signing', async function () { + const txBytes = await buildTypedTxBytes('legacy', { to: recipient, value: '1000' }); + const { error } = await runMpcv2Signing( + storedRequest({ serializedTxHex: txBytes.serializedTxHex, signableHex: chainIdLessSignable }, [ + { address: recipient, amount: '1000' }, + ]) + ); + error.should.be.instanceOf(InvalidTransactionError); + error.message.should.match(/missing the EIP-155 chain id/); + }); + + it('keeps a matching type-2 payment on the direct signableHex route', async function () { + const txBytes = await buildTypedTxBytes('eip1559', { to: recipient, value: '1000' }); + const verifySpy = sinon.spy(coin, 'verifyTransaction'); + const consistencySpy = sinon.spy(coin, 'assertSignableConsistency'); + const { error, boundary } = await runMpcv2Signing( + storedRequest(txBytes, [{ address: recipient, amount: '1000' }]) + ); + error.should.be.exactly(boundary); + verifySpy.callCount.should.eql(1); + (verifySpy.firstCall.args[0].txPrebuild.txHex ?? '').should.eql(txBytes.signableHex); + consistencySpy.callCount.should.eql(0); + }); + }); + }); + describe('consolidation to base address', function () { const consolidation = { consolidationToBaseAddress: true }; diff --git a/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsa.ts b/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsa.ts index 9be544f451..f1f4e7d08d 100644 --- a/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsa.ts +++ b/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsa.ts @@ -59,6 +59,7 @@ import { BaseEcdsaUtils } from './base'; import { EncryptionVersion, IRequestTracer } from '../../../../api'; import { resolveEffectiveTxParams } from '../recipientUtils'; import { shouldVerifyWithSerializedTxHex } from '../serializedTxHexVerify'; +import { isCoinWithPreHashedSignable, shouldUsePreHashedSignable } from '../preHashedSignable'; import { isCoinWithSignableConsistency } from '../signableConsistency'; const encryptNShare = ECDSAMethods.encryptNShare; @@ -1065,18 +1066,41 @@ export class EcdsaUtils extends BaseEcdsaUtils { ); } - // For some coins, signableHex is not a parseable transaction. Pass - // serializedTxHex so verifyTransaction can decode the full tx bytes. - // Gated by CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX (ICP hash digests, - // BSC/XDC legacy EIP-155 RLP with v=chainId, etc.). - if (shouldVerifyWithSerializedTxHex(this.baseCoin)) { + // Pre-hashed signables (Avalanche atomic FLR/FLRP, Starknet) are detected from the request. + // MPCv1 cannot sign them: createUserSignatureShare always applies the coin hash to + // signableHex, which is already the final digest. Fail closed before verification instead + // of verifying a digest as if it were a transaction, or signing the wrong preimage. + if (isCoinWithPreHashedSignable(this.baseCoin)) { + const usePreHashedSignable = shouldUsePreHashedSignable(this.baseCoin, unsignedTx); + if (!usePreHashedSignable && !unsignedTx.serializedTxHex?.trim()) { + throw new InvalidTransactionError( + 'Missing serializedTxHex for transaction requiring serialized verification' + ); + } + if (usePreHashedSignable) { + throw new InvalidTransactionError('Pre-hashed signable is not supported by ECDSA MPCv1 signing; use MPCv2'); + } + } + + // For some coins or envelopes, signableHex is not a parseable transaction. + // Pass serializedTxHex so verifyTransaction can decode the full tx bytes: + // - CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX (ICP hash digests, + // BSC/XDC legacy EIP-155 RLP with v=chainId, etc.). + // - Coin-detected legacy type-0 EVM envelopes on EIP-1559 chains. + const verifyWithSerializedTxHex = shouldVerifyWithSerializedTxHex(this.baseCoin, unsignedTx); + if (verifyWithSerializedTxHex) { + if (!unsignedTx.serializedTxHex?.trim()) { + throw new InvalidTransactionError( + 'Missing serializedTxHex for transaction requiring serialized verification' + ); + } await this.baseCoin.verifyTransaction({ txPrebuild: { txHex: unsignedTx.serializedTxHex, txInfo: unsignedTx.signableHex }, txParams: resolveEffectiveTxParams(txRequest, params.txParams, this.baseCoin.getChain()), wallet: this.wallet, walletType: this.wallet.multisigType(), }); - if (shouldVerifyWithSerializedTxHex(this.baseCoin) && isCoinWithSignableConsistency(this.baseCoin)) { + if (isCoinWithSignableConsistency(this.baseCoin)) { this.baseCoin.assertSignableConsistency(unsignedTx.serializedTxHex, unsignedTx.signableHex); } } else { diff --git a/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsaMPCv2.ts b/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsaMPCv2.ts index fdd83d5da3..a66051be09 100644 --- a/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsaMPCv2.ts +++ b/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsaMPCv2.ts @@ -51,7 +51,7 @@ import { isV2Envelope, SignableTransaction, } from '../baseTypes'; -import { shouldUsePreHashedSignable } from '../preHashedSignable'; +import { isCoinWithPreHashedSignable, shouldUsePreHashedSignable } from '../preHashedSignable'; import { shouldVerifyWithSerializedTxHex } from '../serializedTxHexVerify'; import { isCoinWithSignableConsistency } from '../signableConsistency'; import { BaseEcdsaUtils } from './base'; @@ -987,21 +987,36 @@ export class EcdsaMPCv2Utils extends BaseEcdsaUtils { ); } - // For some coins, signableHex is not a parseable transaction. Pass - // serializedTxHex so verifyTransaction can decode the full tx bytes. + // For some coins or envelopes, signableHex is not a parseable transaction. + // Pass serializedTxHex so verifyTransaction can decode the full tx bytes: // - CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX: ICP hash digests, // BSC/XDC legacy EIP-155 RLP with v=chainId, etc. + // - Coin-detected legacy type-0 EVM envelopes on EIP-1559 chains. // - Avalanche atomic (FLRP/FLR cross-chain): signableHex is SHA-256(txBody); // serializedTxHex is the PVM/EVM atomic tx (codec prefix 0x0000). // For other coins, signableHex IS the unsigned transaction (e.g. EIP-1559 RLP). - if (shouldVerifyWithSerializedTxHex(this.baseCoin) || shouldUsePreHashedSignable(this.baseCoin, unsignedTx)) { + const usePreHashedSignable = shouldUsePreHashedSignable(this.baseCoin, unsignedTx); + // A coin with a pre-hashed route (e.g. FLR/FLRP atomic) detects that route from serializedTxHex. + // Without it the route cannot be chosen, and the default branch would verify a digest as if it + // were a transaction, so fail closed before verification. + if (!usePreHashedSignable && isCoinWithPreHashedSignable(this.baseCoin) && !unsignedTx.serializedTxHex?.trim()) { + throw new InvalidTransactionError('Missing serializedTxHex for transaction requiring serialized verification'); + } + const verifyWithSerializedTxHex = + !usePreHashedSignable && shouldVerifyWithSerializedTxHex(this.baseCoin, unsignedTx); + if (verifyWithSerializedTxHex || usePreHashedSignable) { + if (verifyWithSerializedTxHex && !unsignedTx.serializedTxHex?.trim()) { + throw new InvalidTransactionError( + 'Missing serializedTxHex for transaction requiring serialized verification' + ); + } await this.baseCoin.verifyTransaction({ txPrebuild: { txHex: unsignedTx.serializedTxHex, txInfo: unsignedTx.signableHex }, txParams: resolveEffectiveTxParams(txRequest, params.txParams, this.baseCoin.getChain()), wallet: this.wallet, walletType: this.wallet.multisigType(), }); - if (shouldVerifyWithSerializedTxHex(this.baseCoin) && isCoinWithSignableConsistency(this.baseCoin)) { + if (verifyWithSerializedTxHex && isCoinWithSignableConsistency(this.baseCoin)) { this.baseCoin.assertSignableConsistency(unsignedTx.serializedTxHex, unsignedTx.signableHex); } } else { diff --git a/modules/sdk-core/src/bitgo/utils/tss/index.ts b/modules/sdk-core/src/bitgo/utils/tss/index.ts index c5cf3e36cd..5e6a83d7bc 100644 --- a/modules/sdk-core/src/bitgo/utils/tss/index.ts +++ b/modules/sdk-core/src/bitgo/utils/tss/index.ts @@ -21,3 +21,4 @@ export * from './preHashedSignable'; export * from './recipientUtils'; export * from './keyShareEnvelope'; export * from './signableConsistency'; +export * from './serializedTxHexVerify'; diff --git a/modules/sdk-core/src/bitgo/utils/tss/preHashedSignable.ts b/modules/sdk-core/src/bitgo/utils/tss/preHashedSignable.ts index 2e3e2b0d2d..f13d29f227 100644 --- a/modules/sdk-core/src/bitgo/utils/tss/preHashedSignable.ts +++ b/modules/sdk-core/src/bitgo/utils/tss/preHashedSignable.ts @@ -28,7 +28,7 @@ export function isCoinWithPreHashedSignable(coin: unknown): coin is CoinWithPreH * so we check for '0000' not '0x0000'. */ export function isAvalancheAtomicTx(unsignedTx: SignableTransaction): boolean { - return unsignedTx.serializedTxHex.startsWith('0000'); + return typeof unsignedTx.serializedTxHex === 'string' && unsignedTx.serializedTxHex.startsWith('0000'); } export function shouldUsePreHashedSignable(coin: IBaseCoin, unsignedTx: SignableTransaction): boolean { diff --git a/modules/sdk-core/src/bitgo/utils/tss/serializedTxHexVerify.ts b/modules/sdk-core/src/bitgo/utils/tss/serializedTxHexVerify.ts index 2a0509914c..839beb3d73 100644 --- a/modules/sdk-core/src/bitgo/utils/tss/serializedTxHexVerify.ts +++ b/modules/sdk-core/src/bitgo/utils/tss/serializedTxHexVerify.ts @@ -1,12 +1,50 @@ import { CoinFeature } from '@bitgo/statics'; import { IBaseCoin } from '../../baseCoin'; +import { SignableTransaction } from './baseTypes'; + +export interface CoinWithSerializedTxHexVerification { + /** + * Returns true when this specific unsigned transaction must be verified from + * `serializedTxHex` instead of `signableHex` (for example, a legacy type-0 + * EVM EIP-155 signing preimage on an EIP-1559 chain). + * + * Implementations MAY throw when the signable envelope is recognized but + * unsupported (for example a pre-EIP-155 legacy preimage), so callers must let + * that error propagate before signing. + */ + shouldVerifyWithSerializedTxHex(unsignedTx: SignableTransaction): boolean; +} + +export function isCoinWithSerializedTxHexVerification(coin: unknown): coin is CoinWithSerializedTxHexVerification { + return ( + coin !== null && + typeof coin === 'object' && + typeof (coin as CoinWithSerializedTxHexVerification).shouldVerifyWithSerializedTxHex === 'function' + ); +} /** * Returns true when TSS verifyTransaction should decode serializedTxHex instead of - * signableHex (e.g. ICP hash digests, or legacy EIP-155 RLP that fails ethereumjs - * fromSerializedTx). Controlled via CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX. + * signableHex: + * - CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX (ICP hash digests, BSC/XDC legacy + * EIP-155 RLP, etc.) + * - Coin-specific envelope detection when `unsignedTx` is provided (e.g. a legacy + * type-0 EVM transaction on an EIP-1559 chain whose signableHex is an EIP-155 + * signing preimage rather than a parseable serialized transaction). + * + * The coin-specific check runs whenever the coin implements it, including for + * coins whose feature already forces the serialized route, so an unsupported + * envelope (e.g. a pre-EIP-155 legacy preimage) is rejected instead of being + * silently verified. Errors thrown by the coin check propagate to the caller. */ -export function shouldVerifyWithSerializedTxHex(coin: IBaseCoin): boolean { - return coin.getConfig().features?.includes(CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX) ?? false; +export function shouldVerifyWithSerializedTxHex(coin: IBaseCoin, unsignedTx?: SignableTransaction): boolean { + const featureForcesSerializedRoute = coin + .getConfig() + .features?.includes(CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX); + if (unsignedTx && isCoinWithSerializedTxHexVerification(coin)) { + const coinDetectedSerializedRoute = coin.shouldVerifyWithSerializedTxHex(unsignedTx); + return Boolean(featureForcesSerializedRoute) || coinDetectedSerializedRoute; + } + return Boolean(featureForcesSerializedRoute); } diff --git a/modules/sdk-core/test/unit/bitgo/utils/tss/ecdsa/ecdsa.ts b/modules/sdk-core/test/unit/bitgo/utils/tss/ecdsa/ecdsa.ts index 7a9b49f2b4..325d1ecfdb 100644 --- a/modules/sdk-core/test/unit/bitgo/utils/tss/ecdsa/ecdsa.ts +++ b/modules/sdk-core/test/unit/bitgo/utils/tss/ecdsa/ecdsa.ts @@ -130,4 +130,148 @@ describe('EcdsaUtils.signRequestBase - signableHex consistency (WCI-2239)', func await assert.rejects(utils.signTxRequest(params), /SENTINEL_PAST_CONSISTENCY/); }); + + it('routes to serializedTxHex and calls assertSignableConsistency when coin envelope check returns true (CECHO-2681)', async function () { + const verifyTransactionStub = sinon.stub().resolves(); + const consistencySpy = sinon.spy(); + const mockCoin = { + getConfig: sinon.stub().returns({ features: [CoinFeature.EIP1559] }), + shouldVerifyWithSerializedTxHex: sinon.stub().returns(true), + verifyTransaction: verifyTransactionStub, + assertSignableConsistency: consistencySpy, + getChain: sinon.stub().returns('hteth'), + }; + const utils = makeUtils(mockCoin); + sinon.stub(utils, 'getOfflineSignerPaillierModulus').throws(new Error('SENTINEL_PAST_CONSISTENCY')); + + await assert.rejects(utils.signTxRequest(params), /SENTINEL_PAST_CONSISTENCY/); + + assert.strictEqual(verifyTransactionStub.callCount, 1); + assert.strictEqual(verifyTransactionStub.firstCall.args[0].txPrebuild.txHex, serializedTxHex); + assert.strictEqual(verifyTransactionStub.firstCall.args[0].txPrebuild.txInfo, signableHex); + assert.strictEqual(consistencySpy.callCount, 1); + assert.deepStrictEqual(consistencySpy.firstCall.args, [serializedTxHex, signableHex]); + }); + + it('fails closed before signing when serializedTxHex is missing on the serialized route (CECHO-2681)', async function () { + const verifyTransactionStub = sinon.stub().resolves(); + const consistencySpy = sinon.spy(); + const mockCoin = { + getConfig: sinon.stub().returns({ features: [CoinFeature.EIP1559] }), + shouldVerifyWithSerializedTxHex: sinon.stub().returns(true), + verifyTransaction: verifyTransactionStub, + assertSignableConsistency: consistencySpy, + getChain: sinon.stub().returns('hteth'), + }; + const utils = makeUtils(mockCoin); + const paillierSpy = sinon.spy(utils, 'getOfflineSignerPaillierModulus'); + + for (const missingHex of ['', ' ', undefined]) { + const missingTxRequest = { + ...txRequest, + transactions: [{ unsignedTx: { derivationPath: 'm/0', serializedTxHex: missingHex, signableHex } }], + } as unknown as TxRequest; + await assert.rejects( + utils.signTxRequest({ ...params, txRequest: missingTxRequest }), + /Missing serializedTxHex for transaction requiring serialized verification/ + ); + } + + assert.strictEqual(verifyTransactionStub.callCount, 0); + assert.strictEqual(consistencySpy.callCount, 0); + assert.strictEqual(paillierSpy.callCount, 0); + }); + + it('fails closed when a pre-hashed-route coin request is missing serializedTxHex (CECHO-2681)', async function () { + const verifyTransactionStub = sinon.stub().resolves(); + const mockCoin = { + getConfig: sinon.stub().returns({ features: [CoinFeature.EIP1559] }), + isSignablePreHashed: (u: { serializedTxHex?: string }) => u.serializedTxHex?.startsWith('0000') ?? false, + verifyTransaction: verifyTransactionStub, + getChain: sinon.stub().returns('flr'), + }; + const utils = makeUtils(mockCoin); + const paillierSpy = sinon.spy(utils, 'getOfflineSignerPaillierModulus'); + + for (const missingHex of ['', ' ', undefined]) { + const missingTxRequest = { + ...txRequest, + transactions: [{ unsignedTx: { derivationPath: 'm/0', serializedTxHex: missingHex, signableHex } }], + } as unknown as TxRequest; + await assert.rejects( + utils.signTxRequest({ ...params, txRequest: missingTxRequest }), + /Missing serializedTxHex for transaction requiring serialized verification/ + ); + } + + assert.strictEqual(verifyTransactionStub.callCount, 0); + assert.strictEqual(paillierSpy.callCount, 0); + }); + + it('rejects a pre-hashed signable before verification because MPCv1 always hashes signableHex', async function () { + const preHashedHex = '000000000001' + 'aa'.repeat(30); + const preHashedSignable = 'bb'.repeat(32); + const verifyTransactionStub = sinon.stub().resolves(); + const mockCoin = { + getConfig: sinon.stub().returns({ features: [CoinFeature.EIP1559] }), + isSignablePreHashed: (u: { serializedTxHex?: string }) => u.serializedTxHex?.startsWith('0000') ?? false, + verifyTransaction: verifyTransactionStub, + getChain: sinon.stub().returns('flr'), + }; + const utils = makeUtils(mockCoin); + const paillierSpy = sinon.spy(utils, 'getOfflineSignerPaillierModulus'); + + const preHashedTxRequest = { + ...txRequest, + transactions: [ + { unsignedTx: { derivationPath: 'm/0', serializedTxHex: preHashedHex, signableHex: preHashedSignable } }, + ], + } as unknown as TxRequest; + + await assert.rejects( + utils.signTxRequest({ ...params, txRequest: preHashedTxRequest }), + /Pre-hashed signable is not supported by ECDSA MPCv1 signing/ + ); + + assert.strictEqual(verifyTransactionStub.callCount, 0); + assert.strictEqual(paillierSpy.callCount, 0); + }); + + it('keeps a non-pre-hashed request from a pre-hashed-route coin on the normal route', async function () { + const verifyTransactionStub = sinon.stub().resolves(); + const mockCoin = { + getConfig: sinon.stub().returns({ features: [CoinFeature.EIP1559] }), + shouldVerifyWithSerializedTxHex: sinon.stub().returns(true), + isSignablePreHashed: (u: { serializedTxHex?: string }) => u.serializedTxHex?.startsWith('0000') ?? false, + verifyTransaction: verifyTransactionStub, + assertSignableConsistency: sinon.spy(), + getChain: sinon.stub().returns('flr'), + }; + const utils = makeUtils(mockCoin); + sinon.stub(utils, 'getOfflineSignerPaillierModulus').throws(new Error('SENTINEL_PAST_CONSISTENCY')); + + await assert.rejects(utils.signTxRequest(params), /SENTINEL_PAST_CONSISTENCY/); + + assert.strictEqual(verifyTransactionStub.callCount, 1); + assert.strictEqual(verifyTransactionStub.firstCall.args[0].txPrebuild.txHex, serializedTxHex); + }); + + it('propagates coin-hook rejection of an unsupported legacy envelope before verification', async function () { + const verifyTransactionStub = sinon.stub().resolves(); + const mockCoin = { + getConfig: sinon.stub().returns({ features: [CoinFeature.EIP1559] }), + shouldVerifyWithSerializedTxHex: sinon + .stub() + .throws(new InvalidTransactionError('Unsupported legacy type-0 signing preimage: pre-EIP-155')), + verifyTransaction: verifyTransactionStub, + getChain: sinon.stub().returns('hteth'), + }; + const utils = makeUtils(mockCoin); + const paillierSpy = sinon.spy(utils, 'getOfflineSignerPaillierModulus'); + + await assert.rejects(utils.signTxRequest(params), /Unsupported legacy type-0 signing preimage: pre-EIP-155/); + + assert.strictEqual(verifyTransactionStub.callCount, 0); + assert.strictEqual(paillierSpy.callCount, 0); + }); }); diff --git a/modules/sdk-core/test/unit/bitgo/utils/tss/ecdsa/ecdsaMPCv2.ts b/modules/sdk-core/test/unit/bitgo/utils/tss/ecdsa/ecdsaMPCv2.ts index 07d04be91f..8967850169 100644 --- a/modules/sdk-core/test/unit/bitgo/utils/tss/ecdsa/ecdsaMPCv2.ts +++ b/modules/sdk-core/test/unit/bitgo/utils/tss/ecdsa/ecdsaMPCv2.ts @@ -14,6 +14,7 @@ import { } from '@bitgo/public-types'; import { DklsComms, DklsDsg, DklsTypes, DklsUtils } from '@bitgo/sdk-lib-mpc'; import * as sjcl from '@bitgo/sjcl'; +import { CoinFeature } from '@bitgo/statics'; import { BitGoBase, EcdsaMPCv2Utils, @@ -755,6 +756,246 @@ describe('ECDSA MPC v2', async () => { ); }); + it('signRequestBase routes coin-detected legacy envelope to serializedTxHex and asserts consistency (CECHO-2681)', async () => { + const serializedTxHex = 'f86c808504a817c80082520894' + '00'.repeat(20) + '80808080'; + const signableHex = 'f86c808504a817c80082520894' + '11'.repeat(20) + '80808080'; + const derivationPath = 'm/0'; + + const mockBgWithPost = { + getEnv: sinon.stub().returns('test'), + setRequestTracer: sinon.stub(), + } as unknown as BitGoBase; + + const verifyTransactionStub = sinon.stub().resolves(true); + const consistencySpy = sinon.spy(); + const hashFunctionSpy = sinon.stub().returns({ + update: () => { + throw new Error('SENTINEL_PAST_CONSISTENCY'); + }, + } as unknown as Hash); + const mockCoinForLegacyEnvelope = { + getHashFunction: hashFunctionSpy, + verifyTransaction: verifyTransactionStub, + shouldVerifyWithSerializedTxHex: sinon.stub().returns(true), + assertSignableConsistency: consistencySpy, + getMPCAlgorithm: sinon.stub().returns('ecdsa'), + getChain: sinon.stub().returns('hteth'), + getConfig: sinon.stub().returns({ family: 'eth', features: [CoinFeature.EIP1559] }), + } as unknown as IBaseCoin; + + const mockWallet = { + id: sinon.stub().returns(walletID), + multisigType: sinon.stub().returns('tss'), + multisigTypeVersion: sinon.stub().returns('MPCv2'), + }; + + const utils = new EcdsaMPCv2Utils(mockBgWithPost, mockCoinForLegacyEnvelope, mockWallet as unknown as IWallet); + // pickBitgoPubGpgKeyForSigning is private; the cast is test-only. + sinon + .stub(utils as unknown as Record Promise>, 'pickBitgoPubGpgKeyForSigning') + .resolves(bitgoGpgKey.public); + + const txRequest = { + txRequestId: 'cecho-2681-mpcv2-legacy', + apiVersion: 'full', + walletId: walletID, + transactions: [{ unsignedTx: { derivationPath, signableHex, serializedTxHex }, signatureShares: [] }], + } as unknown as TxRequest; + + await assert.rejects( + utils.signTxRequest({ + txRequest, + txParams: { recipients: [{ address: '0x' + '00'.repeat(20), amount: '1000' }] }, + prv: userShare.toString('base64'), + reqId: { inc: sinon.stub(), toString: sinon.stub().returns('test-req') } as unknown as RequestTracer, + }), + /SENTINEL_PAST_CONSISTENCY/ + ); + + assert.strictEqual(verifyTransactionStub.callCount, 1); + assert.strictEqual(verifyTransactionStub.firstCall.args[0].txPrebuild.txHex, serializedTxHex); + assert.strictEqual(verifyTransactionStub.firstCall.args[0].txPrebuild.txInfo, signableHex); + assert.strictEqual(consistencySpy.callCount, 1); + assert.deepStrictEqual(consistencySpy.firstCall.args, [serializedTxHex, signableHex]); + }); + + it('signRequestBase fails closed before signing when serializedTxHex is missing on the legacy route (CECHO-2681)', async () => { + const signableHex = 'f86c808504a817c80082520894' + '11'.repeat(20) + '80808080'; + const mockBgWithPost = { + getEnv: sinon.stub().returns('test'), + setRequestTracer: sinon.stub(), + } as unknown as BitGoBase; + + const verifyTransactionStub = sinon.stub().resolves(true); + const consistencySpy = sinon.spy(); + const hashFunctionSpy = sinon.stub().callsFake(() => createKeccakHash('keccak256') as Hash); + const mockCoinForLegacyEnvelope = { + getHashFunction: hashFunctionSpy, + verifyTransaction: verifyTransactionStub, + shouldVerifyWithSerializedTxHex: sinon.stub().returns(true), + assertSignableConsistency: consistencySpy, + getMPCAlgorithm: sinon.stub().returns('ecdsa'), + getChain: sinon.stub().returns('hteth'), + getConfig: sinon.stub().returns({ family: 'eth', features: [CoinFeature.EIP1559] }), + } as unknown as IBaseCoin; + + const mockWallet = { + id: sinon.stub().returns(walletID), + multisigType: sinon.stub().returns('tss'), + multisigTypeVersion: sinon.stub().returns('MPCv2'), + }; + + const utils = new EcdsaMPCv2Utils(mockBgWithPost, mockCoinForLegacyEnvelope, mockWallet as unknown as IWallet); + // pickBitgoPubGpgKeyForSigning is private; the cast is test-only. + sinon + .stub(utils as unknown as Record Promise>, 'pickBitgoPubGpgKeyForSigning') + .resolves(bitgoGpgKey.public); + + for (const missingHex of ['', ' ', undefined]) { + const txRequest = { + txRequestId: 'cecho-2681-mpcv2-missing', + apiVersion: 'full', + walletId: walletID, + transactions: [ + { unsignedTx: { derivationPath: 'm/0', signableHex, serializedTxHex: missingHex }, signatureShares: [] }, + ], + } as unknown as TxRequest; + + await assert.rejects( + utils.signTxRequest({ + txRequest, + txParams: { recipients: [{ address: '0x' + '00'.repeat(20), amount: '1000' }] }, + prv: userShare.toString('base64'), + reqId: { inc: sinon.stub(), toString: sinon.stub().returns('test-req') } as unknown as RequestTracer, + }), + /Missing serializedTxHex for transaction requiring serialized verification/ + ); + } + + assert.strictEqual(verifyTransactionStub.callCount, 0); + assert.strictEqual(consistencySpy.callCount, 0); + assert.strictEqual(hashFunctionSpy.callCount, 0); + }); + + it('signRequestBase preserves pre-hashed Avalanche atomic route without running EVM assertSignableConsistency (CECHO-2681)', async () => { + const serializedTxHex = '0000000000010000007278db5c' + 'aa'.repeat(32); + const signableHex = createHash('sha256').update(Buffer.from(serializedTxHex, 'hex')).digest('hex'); + const mockBgWithPost = { + getEnv: sinon.stub().returns('test'), + setRequestTracer: sinon.stub(), + url: sinon.stub().returns('https://mock.bitgo.test'), + post: sinon.stub().returns({ + send: sinon.stub().returnsThis(), + set: sinon.stub().returnsThis(), + result: sinon.stub().rejects(new Error('SENTINEL_NETWORK')), + }), + } as unknown as BitGoBase; + const verifyTransactionStub = sinon.stub().resolves(true); + const consistencySpy = sinon.spy(); + const envelopeSpy = sinon.stub().returns(true); + const hashFunctionSpy = sinon.stub().callsFake(() => createKeccakHash('keccak256') as Hash); + const mockFlrCoin = { + getHashFunction: hashFunctionSpy, + verifyTransaction: verifyTransactionStub, + shouldVerifyWithSerializedTxHex: envelopeSpy, + assertSignableConsistency: consistencySpy, + isSignablePreHashed: (u: { serializedTxHex?: string }) => u.serializedTxHex?.startsWith('0000') ?? false, + getMPCAlgorithm: sinon.stub().returns('ecdsa'), + getChain: sinon.stub().returns('flr'), + getConfig: sinon.stub().returns({ family: 'flr', features: [CoinFeature.EIP1559] }), + } as unknown as IBaseCoin; + + const mockWallet = { + id: sinon.stub().returns(walletID), + multisigType: sinon.stub().returns('tss'), + multisigTypeVersion: sinon.stub().returns('MPCv2'), + }; + + const utils = new EcdsaMPCv2Utils(mockBgWithPost, mockFlrCoin, mockWallet as unknown as IWallet); + // pickBitgoPubGpgKeyForSigning is private; the cast is test-only. + sinon + .stub(utils as unknown as Record Promise>, 'pickBitgoPubGpgKeyForSigning') + .resolves(bitgoGpgKey.public); + + const txRequest = { + txRequestId: 'cecho-2681-flr-atomic', + apiVersion: 'full', + walletId: walletID, + transactions: [{ unsignedTx: { derivationPath: 'm/0', signableHex, serializedTxHex }, signatureShares: [] }], + } as unknown as TxRequest; + + await assert.rejects( + utils.signTxRequest({ + txRequest, + txParams: { recipients: [{ address: '0x' + '00'.repeat(20), amount: '1000' }] }, + prv: userShare.toString('base64'), + reqId: { inc: sinon.stub(), toString: sinon.stub().returns('test-req') } as unknown as RequestTracer, + }), + /SENTINEL_NETWORK/ + ); + + assert.strictEqual(verifyTransactionStub.callCount, 1); + assert.strictEqual(verifyTransactionStub.firstCall.args[0].txPrebuild.txHex, serializedTxHex); + assert.strictEqual(envelopeSpy.callCount, 0); + assert.strictEqual(consistencySpy.callCount, 0); + assert.strictEqual(hashFunctionSpy.callCount, 0); + }); + + it('signRequestBase fails closed when a pre-hashed-route coin request is missing serializedTxHex (CECHO-2681)', async () => { + const signableHex = createHash('sha256').update(Buffer.from('00', 'hex')).digest('hex'); + const mockBgWithPost = { + getEnv: sinon.stub().returns('test'), + setRequestTracer: sinon.stub(), + } as unknown as BitGoBase; + const verifyTransactionStub = sinon.stub().resolves(true); + const hashFunctionSpy = sinon.stub().callsFake(() => createKeccakHash('keccak256') as Hash); + const mockFlrCoin = { + getHashFunction: hashFunctionSpy, + verifyTransaction: verifyTransactionStub, + shouldVerifyWithSerializedTxHex: sinon.stub().returns(false), + assertSignableConsistency: sinon.spy(), + isSignablePreHashed: (u: { serializedTxHex?: string }) => u.serializedTxHex?.startsWith('0000') ?? false, + getMPCAlgorithm: sinon.stub().returns('ecdsa'), + getChain: sinon.stub().returns('flr'), + getConfig: sinon.stub().returns({ family: 'flr', features: [CoinFeature.EIP1559] }), + } as unknown as IBaseCoin; + const mockWallet = { + id: sinon.stub().returns(walletID), + multisigType: sinon.stub().returns('tss'), + multisigTypeVersion: sinon.stub().returns('MPCv2'), + }; + + const utils = new EcdsaMPCv2Utils(mockBgWithPost, mockFlrCoin, mockWallet as unknown as IWallet); + // pickBitgoPubGpgKeyForSigning is private; the cast is test-only. + sinon + .stub(utils as unknown as Record Promise>, 'pickBitgoPubGpgKeyForSigning') + .resolves(bitgoGpgKey.public); + + for (const missingHex of ['', ' ', undefined]) { + const txRequest = { + txRequestId: 'cecho-2681-flr-missing', + apiVersion: 'full', + walletId: walletID, + transactions: [ + { unsignedTx: { derivationPath: 'm/0', signableHex, serializedTxHex: missingHex }, signatureShares: [] }, + ], + } as unknown as TxRequest; + + await assert.rejects( + utils.signTxRequest({ + txRequest, + txParams: { recipients: [{ address: '0x' + '00'.repeat(20), amount: '1000' }] }, + prv: userShare.toString('base64'), + reqId: { inc: sinon.stub(), toString: sinon.stub().returns('test-req') } as unknown as RequestTracer, + }), + /Missing serializedTxHex for transaction requiring serialized verification/ + ); + } + + assert.strictEqual(verifyTransactionStub.callCount, 0); + assert.strictEqual(hashFunctionSpy.callCount, 0); + }); + // Regression test for CGD-1815 / DEFI-661: resolveEffectiveTxParams() special-cases wrap-native // and unwrap-native so the no-recipients guard in verifyTssTransaction doesn't reject them. That // bypass is security-sensitive (it's what lets a DeFi vault wrap/unwrap tx skip recipient diff --git a/modules/sdk-core/test/unit/bitgo/utils/tss/preHashedSignable.ts b/modules/sdk-core/test/unit/bitgo/utils/tss/preHashedSignable.ts index 78d356439f..3c9a9e3307 100644 --- a/modules/sdk-core/test/unit/bitgo/utils/tss/preHashedSignable.ts +++ b/modules/sdk-core/test/unit/bitgo/utils/tss/preHashedSignable.ts @@ -17,8 +17,14 @@ describe('preHashedSignable', function () { }), false ); + assert.strictEqual( + isAvalancheAtomicTx({ + serializedTxHex: undefined as unknown as string, + signableHex: 'abc', + }), + false + ); }); - it('isCoinWithPreHashedSignable type guard', function () { assert.strictEqual(isCoinWithPreHashedSignable({ isSignablePreHashed: () => true }), true); assert.strictEqual(isCoinWithPreHashedSignable({}), false); diff --git a/modules/sdk-core/test/unit/bitgo/utils/tss/serializedTxHexVerify.ts b/modules/sdk-core/test/unit/bitgo/utils/tss/serializedTxHexVerify.ts new file mode 100644 index 0000000000..0dcafd3dcf --- /dev/null +++ b/modules/sdk-core/test/unit/bitgo/utils/tss/serializedTxHexVerify.ts @@ -0,0 +1,80 @@ +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import { CoinFeature } from '@bitgo/statics'; +import { IBaseCoin } from '../../../../../src/bitgo/baseCoin'; +import { + isCoinWithSerializedTxHexVerification, + shouldVerifyWithSerializedTxHex, +} from '../../../../../src/bitgo/utils/tss/serializedTxHexVerify'; +import { SignableTransaction } from '../../../../../src/bitgo/utils/tss/baseTypes'; + +describe('serializedTxHexVerify', function () { + const sampleTx: SignableTransaction = { + serializedTxHex: 'f86c808504a817c80082520894' + '00'.repeat(20) + '80808080', + signableHex: 'f86c808504a817c80082520894' + '00'.repeat(20) + '80808080', + }; + + it('returns true when coin has TSS_VERIFY_USE_SERIALIZED_TX_HEX feature', function () { + const coin = { + getConfig: () => ({ features: [CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX] }), + } as unknown as IBaseCoin; + + assert.strictEqual(shouldVerifyWithSerializedTxHex(coin), true); + assert.strictEqual(shouldVerifyWithSerializedTxHex(coin, sampleTx), true); + }); + + it('delegates to coin.shouldVerifyWithSerializedTxHex when unsignedTx is provided', function () { + const check = sinon.stub().returns(true); + const coin = { + getConfig: () => ({ features: [CoinFeature.EIP1559] }), + shouldVerifyWithSerializedTxHex: check, + } as unknown as IBaseCoin; + + assert.strictEqual(isCoinWithSerializedTxHexVerification(coin), true); + assert.strictEqual(shouldVerifyWithSerializedTxHex(coin, sampleTx), true); + assert.strictEqual(check.callCount, 1); + assert.strictEqual(check.firstCall.args[0], sampleTx); + }); + + it('returns false when coin hook returns false or unsignedTx is omitted', function () { + const check = sinon.stub().returns(false); + const coin = { + getConfig: () => ({ features: [CoinFeature.EIP1559] }), + shouldVerifyWithSerializedTxHex: check, + } as unknown as IBaseCoin; + + assert.strictEqual(shouldVerifyWithSerializedTxHex(coin, sampleTx), false); + assert.strictEqual(shouldVerifyWithSerializedTxHex(coin), false); + assert.strictEqual(check.callCount, 1); + }); + + it('keeps the serialized route for feature coins but still validates through the coin hook', function () { + const check = sinon.stub().returns(false); + const coin = { + getConfig: () => ({ features: [CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX] }), + shouldVerifyWithSerializedTxHex: check, + } as unknown as IBaseCoin; + + assert.strictEqual(shouldVerifyWithSerializedTxHex(coin, sampleTx), true); + assert.strictEqual(check.callCount, 1); + assert.strictEqual(check.firstCall.args[0], sampleTx); + assert.strictEqual(shouldVerifyWithSerializedTxHex(coin), true); + assert.strictEqual(check.callCount, 1); + }); + + it('propagates coin-hook rejection of an unsupported envelope even for feature coins', function () { + const check = sinon.stub().throws(new Error('Unsupported legacy type-0 signing preimage')); + const coin = { + getConfig: () => ({ features: [CoinFeature.TSS_VERIFY_USE_SERIALIZED_TX_HEX] }), + shouldVerifyWithSerializedTxHex: check, + } as unknown as IBaseCoin; + + assert.throws(() => shouldVerifyWithSerializedTxHex(coin, sampleTx), /Unsupported legacy type-0 signing preimage/); + }); + + it('isCoinWithSerializedTxHexVerification type guard', function () { + assert.strictEqual(isCoinWithSerializedTxHexVerification({ shouldVerifyWithSerializedTxHex: () => true }), true); + assert.strictEqual(isCoinWithSerializedTxHexVerification({}), false); + assert.strictEqual(isCoinWithSerializedTxHexVerification(null), false); + }); +});