Skip to content

Commit d74a70d

Browse files
harman-bitgoclaude
andcommitted
fix(sdk-coin-trx): validate consolidation destination in TransferContract and TriggerSmartContract
validateTransferContract and validateTriggerSmartContract skipped destination validation when txParams.recipients was absent (consolidation flow), returning true after checking only that amount > 0. A compromised platform could return a consolidation prebuild sending funds to an attacker address, and verifyTransaction would sign it without inspecting the destination. Now: - When recipients is absent/empty, validate the destination matches the wallet's base address (via wallet.coinSpecific().baseAddress). - When recipients has >1 entry (sendMany/bulk withdrawal), validate the prebuild matches at least one recipient. - Extract shared validateConsolidationDestination helper for both paths. - Pass wallet from verifyTransaction down to both validators. TICKET: CHALO-2125 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 6a32872 commit d74a70d

4 files changed

Lines changed: 384 additions & 20 deletions

File tree

‎modules/sdk-coin-trx/src/trx.ts‎

Lines changed: 65 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ import {
4141
import { auditEcdsaPrivateKey } from '@bitgo/sdk-lib-mpc';
4242
import { Enum, Interface, Utils, WrappedBuilder, KeyPair as TronKeyPair } from './lib';
4343
import { ValueFields, TransactionReceipt, RawData } from './lib/iface';
44+
45+
/** Narrow wallet shape needed by consolidation destination validation. */
46+
interface WalletWithCoinSpecific {
47+
coinSpecific?(): { baseAddress?: string; rootAddress?: string } | undefined;
48+
}
4449
import { getBuilder } from './lib/builder';
4550
import { isInteger, isUndefined } from 'lodash';
4651

@@ -394,7 +399,7 @@ export class Trx extends BaseCoin {
394399
}
395400

396401
async verifyTransaction(params: VerifyTransactionOptions): Promise<boolean> {
397-
const { txParams, txPrebuild, walletType } = params;
402+
const { txParams, txPrebuild, walletType, wallet } = params;
398403

399404
if (!txParams) {
400405
throw new Error('missing txParams');
@@ -425,7 +430,7 @@ export class Trx extends BaseCoin {
425430
if (!Array.isArray(decodedTx.contract) || decodedTx.contract.length !== 1) {
426431
throw new Error('Invalid Transfer contract structure.');
427432
}
428-
return this.validateTransferContract(decodedTx.contract[0], txParams, true);
433+
return this.validateTransferContract(decodedTx.contract[0], txParams, wallet, true);
429434
}
430435

431436
if (decodedTx.contractType === Enum.ContractType.TriggerSmartContract) {
@@ -434,7 +439,7 @@ export class Trx extends BaseCoin {
434439
// trx:<token> wallet), which routes their verification here, so validate the recipient
435440
// and amount instead of throwing (CECHO-2248). This is the same validation performed by
436441
// TrxToken.verifyTransaction and still fails closed on any mismatch.
437-
return this.validateTriggerSmartContract(decodedTx, txParams, txPrebuild);
442+
return this.validateTriggerSmartContract(decodedTx, txParams, txPrebuild, wallet);
438443
}
439444

440445
return true;
@@ -454,7 +459,7 @@ export class Trx extends BaseCoin {
454459
const contract = txJson.raw_data.contract[0];
455460

456461
if (contract.type === 'TransferContract') {
457-
return this.validateTransferContract(contract, txParams);
462+
return this.validateTransferContract(contract, txParams, wallet);
458463
} else {
459464
return true;
460465
}
@@ -484,10 +489,16 @@ export class Trx extends BaseCoin {
484489
*
485490
* @param contract The contract object from the transaction
486491
* @param txParams The original transaction parameters
492+
* @param wallet The wallet object, used to verify consolidation destinations
487493
* @param addressesInBase58 When true, addresses are already in base58 format (TSS path via protobuf decoding).
488494
* When false (default), addresses are in hex and need conversion (on-chain multisig path via builder JSON).
489495
*/
490-
private validateTransferContract(contract: any, txParams: any, addressesInBase58 = false): boolean {
496+
private validateTransferContract(
497+
contract: any,
498+
txParams: any,
499+
wallet: WalletWithCoinSpecific | undefined,
500+
addressesInBase58 = false
501+
): boolean {
491502
if (!('parameter' in contract) || !contract.parameter?.value) {
492503
throw new Error('Invalid Transfer contract structure');
493504
}
@@ -499,16 +510,17 @@ export class Trx extends BaseCoin {
499510
throw new Error('Invalid transfer amount');
500511
}
501512

502-
// If txParams has recipients, validate against expected values
513+
const actualDestination = addressesInBase58
514+
? Utils.getBase58AddressFromHexAddress(value.to_address)
515+
: Utils.getBase58AddressFromHex(value.to_address);
516+
503517
if (txParams.recipients && txParams.recipients.length === 1) {
518+
// Client-supplied recipients: validate destination and amount match exactly
504519
const recipient = txParams.recipients[0];
505520
const expectedAmount = recipient.amount.toString();
506521
// Canonicalize client-supplied address (base58 / 0x... / 41...) before comparing (COINS-1575).
507522
const expectedDestination = Utils.getBase58AddressFromHexAddress(recipient.address);
508523
const actualAmount = value.amount.toString();
509-
const actualDestination = addressesInBase58
510-
? Utils.getBase58AddressFromHexAddress(value.to_address)
511-
: Utils.getBase58AddressFromHex(value.to_address);
512524

513525
if (expectedAmount !== actualAmount) {
514526
throw new Error('transaction amount in txPrebuild does not match the value given by client');
@@ -517,24 +529,59 @@ export class Trx extends BaseCoin {
517529
if (expectedDestination.toLowerCase() !== actualDestination.toLowerCase()) {
518530
throw new Error('destination address does not match with the recipient address');
519531
}
532+
} else if (txParams.recipients && txParams.recipients.length > 1) {
533+
// Bulk withdrawal (sendMany): the platform builds one TransferContract per recipient,
534+
// so txParams.recipients has all entries but this prebuild matches only one.
535+
// Verify the prebuild's destination + amount matches at least one recipient.
536+
const actualAmount = value.amount.toString();
537+
const matched = txParams.recipients.some((recipient: Recipient) => {
538+
const expectedDestination = Utils.getBase58AddressFromHexAddress(recipient.address);
539+
const expectedAmount = recipient.amount.toString();
540+
return expectedAmount === actualAmount && expectedDestination.toLowerCase() === actualDestination.toLowerCase();
541+
});
542+
if (!matched) {
543+
throw new Error('transaction in txPrebuild does not match any recipient in txParams');
544+
}
545+
} else {
546+
// No recipients (consolidation flow): destination must be a wallet-owned address (CHALO-2125)
547+
this.validateConsolidationDestination(wallet, actualDestination);
520548
}
521549

522550
return true;
523551
}
524552

553+
/**
554+
* Validate that a consolidation destination is the wallet's own base address.
555+
* Shared by both native TRX and TRC20 validation paths (CHALO-2125).
556+
*/
557+
private validateConsolidationDestination(
558+
wallet: WalletWithCoinSpecific | undefined,
559+
actualDestination: string
560+
): void {
561+
const coinSpecific = wallet?.coinSpecific?.();
562+
const baseAddress = coinSpecific?.baseAddress || coinSpecific?.rootAddress;
563+
if (!baseAddress) {
564+
throw new Error('missing wallet base address for consolidation destination validation');
565+
}
566+
if (Utils.getBase58AddressFromHexAddress(baseAddress).toLowerCase() !== actualDestination.toLowerCase()) {
567+
throw new Error('consolidation destination address does not match wallet base address');
568+
}
569+
}
570+
525571
/**
526572
* Validate a TriggerSmartContract (TRC20 token transfer) on the TSS path.
527573
* Shared by native Trx.verifyTransaction (which receives token transfers whose verification
528574
* was routed through the native coin) and TrxToken.verifyTransaction.
529575
*
530-
* Always verifies contract structure and ABI decodability. Intent validation (address + amount
531-
* comparison) is performed only when recipients are present — absent recipients indicates a
532-
* server-determined transfer (e.g. consolidation) where the server owns the intent.
576+
* Always verifies contract structure and ABI decodability. When recipients are present,
577+
* validates destination and amount against client intent. When absent (consolidation),
578+
* validates the destination is the wallet's base address (CHALO-2125).
533579
*/
534580
protected validateTriggerSmartContract(
535581
decodedTx: RawData,
536582
txParams: TransactionParams,
537-
txPrebuild: BaseTransactionPrebuild
583+
txPrebuild: BaseTransactionPrebuild,
584+
wallet?: WalletWithCoinSpecific
538585
): boolean {
539586
if (!Array.isArray(decodedTx.contract) || decodedTx.contract.length !== 1) {
540587
throw new Error('Invalid TriggerSmartContract structure');
@@ -555,19 +602,21 @@ export class Trx extends BaseCoin {
555602
throw new Error(`Failed to decode TRC20 transfer ABI data: ${e instanceof Error ? e.message : String(e)}`);
556603
}
557604

605+
// recipientHex has '41' hex prefix; convert to base58 for comparison.
606+
const actualDestination = Utils.getBase58AddressFromHex(recipientHex);
607+
558608
const recipients =
559609
txParams.recipients || (txPrebuild.txInfo as { recipients?: Recipient[] } | undefined)?.recipients;
560610
if (!recipients || recipients.length === 0) {
561-
// No recipients — server-determined transfer (e.g. consolidation); structural check above is sufficient.
611+
// No recipients (consolidation flow): destination must be a wallet-owned address (CHALO-2125)
612+
this.validateConsolidationDestination(wallet, actualDestination);
562613
return true;
563614
}
564615
if (recipients.length !== 1) {
565616
throw new Error('invalid required property recipients');
566617
}
567618

568-
// recipientHex has '41' hex prefix; convert to base58 for comparison.
569619
// Canonicalize the client-supplied address too so 0x... / 41... match base58 outputs (COINS-1575).
570-
const actualDestination = Utils.getBase58AddressFromHex(recipientHex);
571620
const actualAmount = transferAmount.toString();
572621
const expectedDestination = Utils.getBase58AddressFromHexAddress(recipients[0].address);
573622
const expectedAmount = recipients[0].amount.toString();

‎modules/sdk-coin-trx/src/trxToken.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ export class TrxToken extends Trx {
111111
);
112112
}
113113

114-
return this.validateTriggerSmartContract(decodedTx, txParams, txPrebuild);
114+
return this.validateTriggerSmartContract(decodedTx, txParams, txPrebuild, params.wallet);
115115
}
116116

117117
const rawTx = txPrebuild.txHex;

‎modules/sdk-coin-trx/test/unit/trxToken.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,15 +105,29 @@ describe('TrxToken verifyTransaction:', function () {
105105
);
106106
});
107107

108-
it('should return true when recipients is empty array (consolidation path)', async function () {
108+
it('should return true when recipients is empty and destination matches wallet base address (consolidation path)', async function () {
109+
const recipientBase58 = Utils.getBase58AddressFromHex(TRC20_RECIPIENT_HEX);
109110
const result = await tokenCoin.verifyTransaction({
110111
txPrebuild: { txHex: TRC20_RAW_DATA_HEX },
111112
txParams: { recipients: [] },
113+
wallet: { coinSpecific: () => ({ baseAddress: recipientBase58 }) },
112114
walletType: 'tss',
113115
} as any);
114116
assert.strictEqual(result, true);
115117
});
116118

119+
it('should fail consolidation when destination does not match wallet base address', async function () {
120+
await assert.rejects(
121+
tokenCoin.verifyTransaction({
122+
txPrebuild: { txHex: TRC20_RAW_DATA_HEX },
123+
txParams: { recipients: [] },
124+
wallet: { coinSpecific: () => ({ baseAddress: 'TLWh67P93KgtnZNCtGnEHM1H33Nhq2uvvN' }) },
125+
walletType: 'tss',
126+
} as any),
127+
{ message: 'consolidation destination address does not match wallet base address' }
128+
);
129+
});
130+
117131
it('should throw when contract type is not TriggerSmartContract', async function () {
118132
// Use a native TRX Transfer protobuf as txHex — TrxToken only handles TriggerSmartContract
119133
const recipientBase58 = Utils.getBase58AddressFromHex(TRC20_RECIPIENT_HEX);

0 commit comments

Comments
 (0)