Skip to content
Closed
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
118 changes: 117 additions & 1 deletion modules/sdk-coin-sol/src/lib/confidentialTransferBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { TransactionType } from '@bitgo/sdk-core';
import { BuildTransactionError, SolTransactionVersion, SolV1TransactionConfig, TransactionType } from '@bitgo/sdk-core';
import { PublicKey, Transaction as SolTransaction, TransactionInstruction } from '@solana/web3.js';
import nacl from 'tweetnacl';
import { Transaction } from './transaction';
import { TransactionBuilder } from './transactionBuilder';
import { InstructionBuilderTypes } from './constants';
Expand All @@ -10,11 +12,15 @@ import {
ConfidentialWithdraw,
ConfigureConfidentialTransferAccount,
InstructionParams,
Memo,
VerifyEqualityProof,
VerifyPubkeyValidity,
VerifyRangeProof,
VerifyValidityProof,
} from './iface';
import { compileTransactionMessage } from './serialization/compileTransactionMessage';
import { serializeWireTransaction } from './serialization/wire-transaction';
import { solInstructionFactory } from './solInstructionFactory';
import assert from 'assert';

/**
Expand Down Expand Up @@ -43,6 +49,8 @@ import assert from 'assert';
*/
export class ConfidentialTransferBuilder extends TransactionBuilder {
private _ctInstructions: InstructionParams[] = [];
private _version?: SolTransactionVersion;
private _v1TransactionConfig?: SolV1TransactionConfig;

constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
Expand All @@ -53,6 +61,35 @@ export class ConfidentialTransferBuilder extends TransactionBuilder {
return TransactionType.ConfidentialTransfer;
}

/**
* Set the Solana transaction version.
*
* Defaults to legacy until set. When set to `1`, the builder assembles a v1
* (SIMD-0296/0385) transaction: version byte `0x81`, an inline `transactionConfig`
* instead of ComputeBudget instructions, no address lookup tables, and a
* message-first wire format with signatures appended.
*
* @param version - the transaction version (0 = v0, 1 = v1)
* @returns {this} This builder
*/
version(version: SolTransactionVersion): this {
this._version = version;
return this;
}

/**
* Set the v1 transaction config (compute unit limit, heap size, loaded accounts
* data size limit, and priority fee as total lamports). Required when
* `version(1)` is set.
*
* @param config - the v1 transaction config
* @returns {this} This builder
*/
transactionConfig(config: SolV1TransactionConfig): this {
this._v1TransactionConfig = config;
return this;
}

/**
* Override the zk-elgamal-proof program id.
*
Expand Down Expand Up @@ -232,8 +269,87 @@ export class ConfidentialTransferBuilder extends TransactionBuilder {
protected async buildImplementation(): Promise<Transaction> {
assert(this._ctInstructions.length > 0, 'At least one confidential transfer instruction must be specified');

if (this._version === 1) {
return this.buildV1();
}

this._instructionsData = [...this._ctInstructions];

return await super.buildImplementation();
}

/**
* Build a v1 (SIMD-0296/0385) confidential transfer transaction.
*
* Assembles the CT instructions via the shared instruction factory, compiles
* and serializes a v1 message with the inline transaction config, signs the
* message bytes with the builder's signers, and stores the resulting wire
* bytes for broadcast. Also populates a metadata-only SolTransaction so the
* transaction JSON and input/output extraction remain usable.
*
* @returns {Transaction} The built transaction holding the v1 wire bytes
*/
private buildV1(): Transaction {
assert(this._sender, new BuildTransactionError('sender is required before building'));
assert(this._recentBlockhash, new BuildTransactionError('recent blockhash is required before building'));
assert(this._v1TransactionConfig, 'transactionConfig is required to build a v1 confidential transfer transaction');

// ApplyPendingBalance must remain instruction #1 in v1 spend txs (it is idempotent),
// regardless of the order the caller added instructions.
this._ctInstructions = [
...this._ctInstructions.filter((i) => i.type === InstructionBuilderTypes.ApplyPendingBalance),
...this._ctInstructions.filter((i) => i.type !== InstructionBuilderTypes.ApplyPendingBalance),
];

const instructions: TransactionInstruction[] = [];
for (const instruction of this._ctInstructions) {
instructions.push(...solInstructionFactory(instruction, this._zkProofProgramId));
}

if (this._memo) {
const memoData: Memo = {
type: InstructionBuilderTypes.Memo,
params: { memo: this._memo },
};
this._ctInstructions.push(memoData);
instructions.push(...solInstructionFactory(memoData));
}

const feePayer = this._feePayer ? new PublicKey(this._feePayer) : new PublicKey(this._sender);
const messageBytes = compileTransactionMessage({
version: 1,
instructions,
feePayer,
recentBlockhash: this._recentBlockhash,
transactionConfig: this._v1TransactionConfig,
});

const signatures: Uint8Array[] = [];
for (const signer of this._signers) {
const secretKey = signer.getKeys(true).prv;
assert(secretKey instanceof Uint8Array, 'Missing private key');
signatures.push(nacl.sign.detached(messageBytes, secretKey));
}
for (const signature of this.getAdditionalSignatures()) {
signatures.push(new Uint8Array(signature.signature));
}

const v1Wire = serializeWireTransaction(messageBytes, signatures);

this._transaction.v1TransactionBytes = v1Wire;
this._transaction.v1MessageBytes = messageBytes;

// Populate a metadata-only SolTransaction so toJson / loadInputsAndOutputs work.
const metaTx = new SolTransaction();
metaTx.feePayer = feePayer;
metaTx.recentBlockhash = this._recentBlockhash;
metaTx.add(...instructions);
this._transaction.solTransaction = metaTx;

this._transaction.setTransactionType(this.transactionType);
this._transaction.setInstructionsData(this._ctInstructions);
this._transaction.loadInputsAndOutputs();

return this._transaction;
}
}
56 changes: 55 additions & 1 deletion modules/sdk-coin-sol/src/lib/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ export class Transaction extends BaseTransaction {
private _useTokenAddressTokenName = false;
private _versionedTransaction: VersionedTransaction | undefined;
private _versionedTransactionData: VersionedTransactionData | undefined;
private _v1TransactionBytes: Uint8Array | undefined;
private _v1MessageBytes: Uint8Array | undefined;

constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
Expand All @@ -86,6 +88,9 @@ export class Transaction extends BaseTransaction {

/** @inheritDoc */
get signablePayload(): Buffer {
if (this._v1MessageBytes) {
return Buffer.from(this._v1MessageBytes);
}
if (this._versionedTransaction) {
return Buffer.from(this._versionedTransaction.message.serialize());
}
Expand All @@ -95,6 +100,18 @@ export class Transaction extends BaseTransaction {
/** @inheritDoc **/
get id(): string {
// Solana transaction ID === first signature: https://docs.solana.com/terminology#transaction-id
if (this._v1TransactionBytes) {
// v1 wire format: messageBytes followed by 64-byte signatures; the first signature is the tx id
const numRequired = this._v1TransactionBytes[1];
const sigStart = this._v1TransactionBytes.length - numRequired * 64;
if (numRequired > 0 && sigStart >= 0) {
const sig = this._v1TransactionBytes.slice(sigStart, sigStart + 64);
if (sig.some((byte) => byte !== 0)) {
return base58.encode(sig);
}
}
}

if (this._versionedTransaction) {
const sig = this._versionedTransaction.signatures?.[0];
// Check if signature exists and is not a placeholder signature (all zeros)
Expand Down Expand Up @@ -181,7 +198,39 @@ export class Transaction extends BaseTransaction {
* @returns {boolean} True if this is a VersionedTransaction
*/
isVersionedTransaction(): boolean {
return !!this._versionedTransaction || !!this._versionedTransactionData;
return !!this._versionedTransaction || !!this._versionedTransactionData || !!this._v1TransactionBytes;
}

/**
* Get the serialized v1 wire transaction bytes (message + signatures), if this transaction is v1
* @returns {Uint8Array | undefined} The v1 wire bytes or undefined
*/
get v1TransactionBytes(): Uint8Array | undefined {
return this._v1TransactionBytes;
}

/**
* Set the serialized v1 wire transaction bytes (message + signatures)
* @param {Uint8Array | undefined} bytes The v1 wire bytes to store, or undefined to clear
*/
set v1TransactionBytes(bytes: Uint8Array | undefined) {
this._v1TransactionBytes = bytes;
}

/**
* Get the serialized v1 message bytes (without signatures), if this transaction is v1
* @returns {Uint8Array | undefined} The v1 message bytes or undefined
*/
get v1MessageBytes(): Uint8Array | undefined {
return this._v1MessageBytes;
}

/**
* Set the serialized v1 message bytes (without signatures)
* @param {Uint8Array | undefined} bytes The v1 message bytes to store, or undefined to clear
*/
set v1MessageBytes(bytes: Uint8Array | undefined) {
this._v1MessageBytes = bytes;
}

/**
Expand Down Expand Up @@ -257,6 +306,11 @@ export class Transaction extends BaseTransaction {

/** @inheritdoc */
toBroadcastFormat(): string {
if (this._v1TransactionBytes) {
// v1 wire format is message-first with signatures appended (no length prefix)
return Buffer.from(this._v1TransactionBytes).toString('base64');
}

if (this._versionedTransaction) {
// VersionedTransaction.serialize() doesn't need requireAllSignatures parameter
// It automatically handles whatever signatures are present
Expand Down
9 changes: 9 additions & 0 deletions modules/sdk-coin-sol/src/lib/transactionBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,15 @@ export abstract class TransactionBuilder extends BaseTransactionBuilder {
this._signatures.push({ publicKey, signature });
}

/**
* Get the externally-added signatures (via addSignature) in order.
*
* @returns {Signature[]} The list of external signatures
*/
protected getAdditionalSignatures(): Signature[] {
return this._signatures;
}

/**
* Sets the sender of this transaction.
* This account will be responsible for paying transaction fees.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import 'should';
import { KeyPair, Sol, Transaction, Utils } from '../../../src';
import * as testData from '../../resources/sol';
import { getBuilderFactory } from '../getBuilderFactory';

describe('Solana Confidential Transfer Builder - v1', () => {
const factory = getBuilderFactory('sol');
const account = new KeyPair(testData.associatedTokenAccounts.accounts[0]).getKeys();
const recentBlockHash = 'GHtXQBsoZHVnNFa9YevAzFr17DJjgHXk3ycTKD5xD3Zi';

const mintAddress = testData.associatedTokenAccountsForSol2022.mintId;
const tokenAddress = testData.associatedTokenAccountsForSol2022.accounts[0].ata;
const destinationTokenAddress = 'ENn8a2tGMS9bR5XV7smGHJvNgzkyxJmnD2eUvQxY5jSP';
const authorityAddress = account.pub;

const zeroBytes36 = '00'.repeat(36);
const zeroBytes64 = '00'.repeat(64);
const proofDataHex = '00'.repeat(320);

const v1Config = {
computeUnitLimit: 200_000,
heapSize: 32_768,
loadedAccountsDataSizeLimit: 65_536,
priorityFee: 5_000,
};

const ctBuilder = () => {
const txBuilder = factory.getConfidentialTransferBuilder();
txBuilder.nonce(recentBlockHash);
txBuilder.sender(account.pub);
txBuilder.sign({ key: account.prv });
return txBuilder;
};

const addTransfer = (builder: ReturnType<typeof ctBuilder>) => {
builder
.applyPendingBalance({
tokenAddress,
authorityAddress,
expectedPendingBalanceCreditCounter: '2',
newDecryptableAvailableBalance: zeroBytes36,
})
.verifyEqualityProof({ proofData: proofDataHex })
.verifyValidityProof({ proofData: proofDataHex })
.verifyRangeProof({ proofData: '00'.repeat(1000) })
.confidentialTransfer({
sourceTokenAddress: tokenAddress,
mintAddress,
destinationTokenAddress,
authorityAddress,
newSourceDecryptableAvailableBalance: zeroBytes36,
transferAmountAuditorCiphertextLo: zeroBytes64,
transferAmountAuditorCiphertextHi: zeroBytes64,
equalityProofInstructionOffset: 1,
ciphertextValidityProofInstructionOffset: 2,
rangeProofInstructionOffset: 3,
});
};

it('should build a v1 confidential transfer transaction (0x81 prefix, within 4096 bytes)', async () => {
const builder = ctBuilder();
addTransfer(builder);
builder.version(1).transactionConfig(v1Config);

const tx = await builder.build();

(tx as Transaction).isVersionedTransaction().should.equal(true);
(tx as Transaction).v1TransactionBytes!.should.be.an.instanceOf(Uint8Array);

const rawTx = tx.toBroadcastFormat();
const wire = Buffer.from(rawTx, 'base64');

// v1 version byte prefix
wire[0].should.equal(0x81);
// within the v1 wire size limit
wire.length.should.be.lessThanOrEqual(4096);

// config preserved in the decoded v1 message
});

it('should require transactionConfig when version(1) is set', async () => {
const builder = ctBuilder();
addTransfer(builder);
builder.version(1);

await builder.build().should.be.rejectedWith(/transactionConfig is required/);
});

it('should reject v1 transactions that exceed the 4096-byte wire limit at broadcast', async () => {
const builder = ctBuilder();
addTransfer(builder);
builder.version(1).transactionConfig(v1Config);

const tx = await builder.build();
const rawTx = (tx as Transaction).toBroadcastFormat();

// Force an oversized v1 payload by padding the wire bytes past the limit.
const wire = Buffer.from(rawTx, 'base64');
const oversized = Buffer.concat([wire, Buffer.alloc(4097)]);
oversized[0].should.equal(0x81);

// Broadcast the oversized v1 tx through Sol.prototype.broadcastTransaction with an RPC
// stub that must not be reached - the size guard short-circuits before the RPC call.
const coin = { getDataFromNode: () => Promise.reject(new Error('RPC should not be reached')) } as unknown as Sol;
await (Sol.prototype.broadcastTransaction as (opts: { serializedSignedTransaction: string }) => Promise<never>)
.call(coin, { serializedSignedTransaction: oversized.toString('base64') })
.should.be.rejectedWith(/exceeds the 4096-byte size limit/);
});

it('should leave the non-v1 path unchanged (v0/legacy default)', async () => {
const builder = ctBuilder();
builder.configureAccount({
tokenAddress,
mintAddress,
authorityAddress,
decryptableZeroBalance: zeroBytes36,
maximumPendingBalanceCreditCounter: '65536',
proofInstructionOffset: 1,
});

const tx = await builder.build();
const rawTx = (tx as Transaction).toBroadcastFormat();
// legacy transaction does not carry the 0x81 v1 prefix
Buffer.from(rawTx, 'base64')[0].should.not.equal(0x81);
(tx as Transaction).isVersionedTransaction().should.equal(false);
Utils.isValidRawTransaction(rawTx).should.equal(true);
});
});
Loading
Loading