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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions modules/sdk-coin-canton/src/canton.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
VerifyTransactionOptions,
} from '@bitgo/sdk-core';
import { auditEddsaPrivateKey } from '@bitgo/sdk-lib-mpc';
import BigNumber from 'bignumber.js';
import { BaseCoin as StaticsBaseCoin, coins } from '@bitgo/statics';
import { TransactionBuilderFactory } from './lib';
import { KeyPair as CantonKeyPair } from './lib/keyPair';
Expand Down Expand Up @@ -221,9 +222,15 @@ export class Canton extends BaseCoin {
}
return true;
case TransactionType.Send:
if (txParams.numberOfSplits !== undefined && txParams.numberOfSplits > 1) {
return this.verifySplitTransaction(transaction, txParams, params.wallet);
}
Comment on lines +225 to +227

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: pre-existing, security-relevant: a batch transfer with no split count is still checked only by its first transfer, so extra transfers go unverified. The batch check runs only when numberOfSplits > 1, and that value comes from the server-supplied intent. Otherwise the recipient path compares just the first TransferFactory_Transfer that parseRawCantonTransactionData finds. Fix: in the regular Send path, reject any prepared transaction whose root is WalletUserProxy_BatchTransfer or that has more than one TransferFactory_Transfer, or else verify every transfer, so leaving out numberOfSplits cannot skip the batch check.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

The split branch at canton.ts:225 only runs when txParams.numberOfSplits > 1. resolveEffectiveTxParams (recipientUtils.ts:183-187) fills that value in from txRequest.intent, which the server controls. Suppose the intent leaves out numberOfSplits, or sets it to 0 or 1, and the prepared transaction is a WalletUserProxy_BatchTransfer. Verification then falls through to the recipient path at canton.ts:228. explainTransaction there uses parseRawCantonTransactionData, whose default case (utils.ts findExerciseNodeFields('TransferFactory_Transfer')) reads only the first transfer node. If that first transfer matches the user's recipient, the rest of the batch can send funds to other parties and still pass. The base branch behaves the same way, and the PR description names this gap. The new parseBatchTransfers shape check is never applied on this path, so the fix is partial.

Verification: Pre-existing and security-relevant. The new split branch only runs on if (txParams.numberOfSplits !== undefined && txParams.numberOfSplits > 1) (canton.ts:225). In every other case, verification falls through to the old recipient path (canton.ts:228-257). So only the first child of a batch is checked. The base commit has the same Send path.

if (txParams.recipients !== undefined) {
const filteredRecipients = txParams.recipients?.map((recipient) => {
const { address, amount, tokenName } = recipient;
if (!address) {
throw new Error('Recipient address is required to verify a Canton transfer');
}
const [addressPart, memoId] = address.split('?memoId=');
return {
address: addressPart,
Expand Down Expand Up @@ -251,6 +258,58 @@ export class Canton extends BaseCoin {
}
}
}
/**
* A split (fanout) moves value from the wallet to itself: one batch of `numberOfSplits` self-transfers.
* The intent carries the full amount of the selected unspents, so the transaction is verified as a whole
* rather than against its first transfer.
*/
private verifySplitTransaction(
transaction: BaseTransaction,
txParams: TransactionParams,
wallet: VerifyTransactionOptions['wallet']
): boolean {
const numberOfSplits = txParams.numberOfSplits as number;
const rawPrepared = (transaction as Transaction).prepareCommand?.preparedTransaction;
if (!rawPrepared) {
throw new Error('Split verifyTransaction: missing preparedTransaction protobuf');
}
if (txParams.recipients?.length !== 1) {
throw new Error('Split verifyTransaction: expected exactly one recipient');
}
const { address, amount, tokenName } = txParams.recipients[0];
if (!address) {
throw new Error('Recipient address is required to verify a Canton split');
}
const [expectedParty] = address.split('?memoId=');
const walletRootAddress = wallet?.coinSpecific?.()?.rootAddress;
if (walletRootAddress && walletRootAddress.split('?memoId=')[0] !== expectedParty) {
throw new Error(`Split recipient '${expectedParty}' is not the wallet's own address`);
}
// A token coin instance resolves its token from the coin itself; native Canton Coin has none.
const expectedToken = tokenName ?? (coins.get(this.getChain()).isToken ? this.getChain() : undefined);

const transfers = utils.parseBatchTransfers(rawPrepared);
if (transfers.length !== numberOfSplits) {
throw new Error(`Split transaction has ${transfers.length} transfers, expected ${numberOfSplits}`);
}
let total = new BigNumber(0);
for (const transfer of transfers) {
if (transfer.sender !== expectedParty || transfer.receiver !== expectedParty) {
throw new Error('Split transaction transfers funds to a party other than the wallet itself');
}
if (transfer.token !== expectedToken) {
throw new Error(`Split transaction token '${transfer.token}' does not match expected '${expectedToken}'`);
}
total = total.plus(transfer.amount);
}
// Equal-value outputs may leave less than one atomic unit per split of rounding dust in the change holding.
const unsplit = new BigNumber(amount).minus(total);
Comment on lines +305 to +306

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) A Canton split passes verification for any batch total when the expected amount is missing or not numeric. The amount check fails open. new BigNumber(amount) turns an undefined or non-numeric amount into NaN. Both isNegative() and gte(numberOfSplits) return false for NaN, so no error is thrown. Fix: reject the split unless the expected amount is a finite, non-negative integer string (BigNumber.isFinite()) before comparing totals. Then a broken or missing intent amount can no longer skip the check.

Why this was flagged

In verifySplitTransaction (canton.ts:289), amount comes from txParams.recipients[0]. On the TSS path resolveEffectiveTxParams sets it to intentRecipient.amount.value (recipientUtils.ts:157), a server-supplied value, and the code never checks that it exists or is numeric. If it is undefined or non-numeric, new BigNumber(amount) is NaN, unsplit at canton.ts:305 is NaN, and unsplit.isNegative() || unsplit.gte(numberOfSplits) is false. The 'does not match expected amount' error never fires, so the batch total goes unchecked and the split is approved for signing. The check is new in this PR. The other checks (sender, receiver, token, count) do not stand in for the amount bound.

Verification: nit. Trigger: the split recipient's amount reaches verifySplitTransaction as undefined or non-numeric. At canton.ts:307-309: const unsplit = new BigNumber(amount).minus(total); if (unsplit.isNegative() || unsplit.gte(numberOfSplits)) throw .... The error never fires and the method returns true. It is lost validation, not a fund-loss path.

if (unsplit.isNegative() || unsplit.gte(numberOfSplits)) {
throw new Error(`Split transaction total ${total.toFixed()} does not match expected amount ${amount}`);
}
return true;
}

private verifyBroadridgeStandingDelegationTransaction(
transaction: BaseTransaction,
executorPartyId: string
Expand Down
9 changes: 9 additions & 0 deletions modules/sdk-coin-canton/src/lib/iface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ export interface PreparedTxnParsedInfo {
broadridgeSettlementAuthorizationData?: BroadridgeSettlementAuthorizationData;
}

export interface PreparedTransferInfo {
sender: string;
receiver: string;
/** Amount in the lowest unit of the asset. */
amount: string;
/** Token name; absent for native Canton Coin. */
token?: string;
}

export interface BroadridgeSettlementIdentity {
executor?: string;
executors?: string[];
Expand Down
69 changes: 69 additions & 0 deletions modules/sdk-coin-canton/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
BroadridgeSettlementAuthorizationData,
CantonCommandInfo,
PreparedTransaction as IPreparedTransaction,
PreparedTransferInfo,
PreparedTxnParsedInfo,
} from './iface';
import {
Expand Down Expand Up @@ -681,6 +682,74 @@ export class Utils implements BaseUtils {
return parsedData;
}

/**
* Returns every transfer of a split (fanout) transaction, which is a single root WalletUserProxy_BatchTransfer
* whose children are all TransferFactory_Transfer exercises. Throws on any other shape so a caller never
* verifies a partial view of what the transaction moves.
*/
parseBatchTransfers(rawData: string): PreparedTransferInfo[] {
const decoded = this.decodePreparedTransaction(rawData);
const nodes = decoded.transaction?.nodes ?? [];
const roots = decoded.transaction?.roots ?? [];
const getField = (fields: RecordField[], label: string) => fields.find((f) => f.label === label)?.value?.sum;
const getExercise = (nodeId: string) => {
const versioned = nodes.find((n) => n.nodeId === nodeId)?.versionedNode;
if (!versioned || versioned.oneofKind !== 'v1') return undefined;
const nodeType = versioned.v1.nodeType;
return nodeType.oneofKind === 'exercise' ? nodeType.exercise : undefined;
};

if (roots.length !== 1) {
throw new Error(`invalid split transaction: expected a single root node, got ${roots.length}`);
}
const batch = getExercise(roots[0]);
if (batch?.choiceId !== 'WalletUserProxy_BatchTransfer') {
throw new Error('invalid split transaction: root node is not a batch transfer');
}

return batch.children.map((childId) => {
const child = getExercise(childId);
if (child?.choiceId !== 'TransferFactory_Transfer') {
throw new Error('invalid split transaction: batch contains a node that is not a transfer');
}
const argument = child.chosenValue?.sum;
const transferSum =
argument?.oneofKind === 'record' ? getField(argument.record?.fields ?? [], 'transfer') : undefined;
if (transferSum?.oneofKind !== 'record') {
throw new Error('invalid split transaction: transfer record is missing');
}
const transfer = transferSum.record?.fields ?? [];
const senderSum = getField(transfer, 'sender');
const receiverSum = getField(transfer, 'receiver');
const amountSum = getField(transfer, 'amount');
const instrumentSum = getField(transfer, 'instrumentId');
if (
senderSum?.oneofKind !== 'party' ||
receiverSum?.oneofKind !== 'party' ||
amountSum?.oneofKind !== 'numeric' ||
instrumentSum?.oneofKind !== 'record'
) {
throw new Error('invalid split transaction: transfer is missing sender, receiver, amount or instrument');
}
const instrument = instrumentSum.record?.fields ?? [];
const adminSum = getField(instrument, 'admin');
const idSum = getField(instrument, 'id');
const info: PreparedTransferInfo = {
sender: senderSum.party,
receiver: receiverSum.party,
amount: this.convertAmountToLowestUnit(new BigNumber(amountSum.numeric)),
};
if (
adminSum?.oneofKind === 'party' &&
idSum?.oneofKind === 'text' &&
!this.isNativeInstrument(adminSum.party, idSum.text)
) {
info.token = this.findTokenNameByContractAddress(`${adminSum.party}:${idSum.text}`);
}
return info;
});
}

/** Parses `"Pkg:Module:Entity"` into parts. */
parseCantonTemplateId(value: string): { pkg: string; moduleName: string; entityName: string } | undefined {
if (typeof value !== 'string') return undefined;
Expand Down
100 changes: 100 additions & 0 deletions modules/sdk-coin-canton/test/splitFixtures.ts

Large diffs are not rendered by default.

Loading
Loading