Skip to content
Merged
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
156 changes: 155 additions & 1 deletion modules/sdk-coin-sol/src/lib/serialization/codecs/v1/message.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import bs58 from 'bs58';
import { PublicKey } from '@solana/web3.js';
import { BuildTransactionError } from '@bitgo/sdk-core';
import { encodeConfigMaskAndValues, ConfigValue } from './config';
import {
encodeConfigMaskAndValues,
ConfigValue,
PRIORITY_FEE_BITS,
COMPUTE_UNIT_LIMIT_BIT,
LOADED_ACCOUNTS_DATA_SIZE_LIMIT_BIT,
HEAP_SIZE_BIT,
} from './config';
import { encodeInstructions, CompiledInstruction } from './instruction';

/**
Expand Down Expand Up @@ -72,3 +79,150 @@ export function encodeV1Message(args: {
}

export { encodeConfigMaskAndValues };

const V1_VERSION_PREFIX = 0x81;
const KNOWN_CONFIG_MASK =
PRIORITY_FEE_BITS | COMPUTE_UNIT_LIMIT_BIT | LOADED_ACCOUNTS_DATA_SIZE_LIMIT_BIT | HEAP_SIZE_BIT;
const MAX_ACCOUNTS = 64;
const MAX_INSTRUCTIONS = 64;
const MAX_ACCOUNTS_PER_INSTRUCTION = 255;
const STATIC_ACCOUNT_BYTES = 32;

export type V1DecodedMessage = {
header: V1MessageHeader;
configMask: number;
configValues: ConfigValue[];
blockhash: string;
staticAccounts: string[];
compiledInstructions: CompiledInstruction[];
byteLength: number;
};

function readU8(b: Uint8Array, o: number): number {
return b[o];
}
function readU16LE(b: Uint8Array, o: number): number {
return b[o] | (b[o + 1] << 8);
}
function readU32LE(b: Uint8Array, o: number): number {
return (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
}
function readU64LE(b: Uint8Array, o: number): bigint {
let v = 0n;
for (let i = 0; i < 8; i++) {
v |= BigInt(b[o + i]) << BigInt(8 * i);
}
return v;
}

function ensureAvailable(b: Uint8Array, off: number, size: number): void {
if (off + size > b.length) {
throw new BuildTransactionError('Invalid v1 message: truncated');
}
}

export function decodeV1Message(bytes: Uint8Array): V1DecodedMessage {
if (!bytes || bytes.length < 42) {
throw new BuildTransactionError('Invalid v1 message: too short');
}
let off = 0;
if (bytes[off++] !== V1_VERSION_PREFIX) {
throw new BuildTransactionError(`Invalid v1 version prefix: 0x${bytes[0].toString(16)}`);
}
const numSignerAccounts = readU8(bytes, off++);
const numReadonlySignerAccounts = readU8(bytes, off++);
const numReadonlyNonSignerAccounts = readU8(bytes, off++);
const configMask = readU32LE(bytes, off);
off += 4;
if ((configMask & ~KNOWN_CONFIG_MASK) !== 0) {
throw new BuildTransactionError(`Unknown config mask bits: ${(configMask & ~KNOWN_CONFIG_MASK).toString(2)}`);
}
const blockhash = bs58.encode(bytes.slice(off, off + STATIC_ACCOUNT_BYTES));
off += STATIC_ACCOUNT_BYTES;
const numInstructions = readU8(bytes, off++);
const numStaticAccounts = readU8(bytes, off++);
if (numStaticAccounts > MAX_ACCOUNTS) {
throw new BuildTransactionError('Invalid v1 message: too many static accounts');
}
if (numInstructions > MAX_INSTRUCTIONS) {
throw new BuildTransactionError('Invalid v1 message: too many instructions');
}
if (numReadonlySignerAccounts > numSignerAccounts) {
throw new BuildTransactionError('Invalid v1 header: readonly signers exceed signers');
}
if (numSignerAccounts + numReadonlyNonSignerAccounts > numStaticAccounts) {
throw new BuildTransactionError('Invalid v1 header: signers + readonly non-signers exceed static accounts');
}

const staticAccounts: string[] = [];
for (let i = 0; i < numStaticAccounts; i++) {
ensureAvailable(bytes, off, STATIC_ACCOUNT_BYTES);
staticAccounts.push(bs58.encode(bytes.slice(off, off + STATIC_ACCOUNT_BYTES)));
off += STATIC_ACCOUNT_BYTES;
}

const configValues: ConfigValue[] = [];
if (configMask & PRIORITY_FEE_BITS) {
ensureAvailable(bytes, off, 8);
configValues.push({ kind: 'u64', value: readU64LE(bytes, off) });
off += 8;
}
if (configMask & COMPUTE_UNIT_LIMIT_BIT) {
ensureAvailable(bytes, off, 4);
configValues.push({ kind: 'u32', value: readU32LE(bytes, off) });
off += 4;
}
if (configMask & LOADED_ACCOUNTS_DATA_SIZE_LIMIT_BIT) {
ensureAvailable(bytes, off, 4);
configValues.push({ kind: 'u32', value: readU32LE(bytes, off) });
off += 4;
}
if (configMask & HEAP_SIZE_BIT) {
ensureAvailable(bytes, off, 4);
configValues.push({ kind: 'u32', value: readU32LE(bytes, off) });
off += 4;
}

const headers: Array<{ programAddressIndex: number; accountCount: number; dataLength: number }> = [];
for (let i = 0; i < numInstructions; i++) {
ensureAvailable(bytes, off, 4);
const programAddressIndex = readU8(bytes, off++);
const accountCount = readU8(bytes, off++);
const dataLength = readU16LE(bytes, off);
off += 2;
if (programAddressIndex >= numStaticAccounts) {
throw new BuildTransactionError('Invalid v1 instruction: program index out of range');
}
if (accountCount > MAX_ACCOUNTS_PER_INSTRUCTION) {
throw new BuildTransactionError('Invalid v1 instruction: too many accounts');
}
headers.push({ programAddressIndex, accountCount, dataLength });
}

const compiledInstructions: CompiledInstruction[] = [];
for (const h of headers) {
ensureAvailable(bytes, off, h.accountCount);
const accountIndices: number[] = [];
for (let i = 0; i < h.accountCount; i++) {
const idx = readU8(bytes, off++);
if (idx >= numStaticAccounts) {
throw new BuildTransactionError('Invalid v1 instruction: account index out of range');
}
accountIndices.push(idx);
}
ensureAvailable(bytes, off, h.dataLength);
const data = bytes.slice(off, off + h.dataLength);
off += h.dataLength;
compiledInstructions.push({ programAddressIndex: h.programAddressIndex, accountIndices, data });
}

return {
header: { numSignerAccounts, numReadonlySignerAccounts, numReadonlyNonSignerAccounts },
configMask,
configValues,
blockhash,
staticAccounts,
compiledInstructions,
byteLength: off,
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { BuildTransactionError } from '@bitgo/sdk-core';
import nacl from 'tweetnacl';
import { PublicKey } from '@solana/web3.js';
import { decodeV1Message } from './codecs/v1/message';

const SIGNATURE_BYTE_LENGTH = 64;
const V1_VERSION_PREFIX = 0x81;
const V1_TRANSACTION_SIZE_LIMIT = 4096;

export type ParsedWireTransaction = {
messageBytes: Uint8Array;
signatures: Uint8Array[];
signerPublicKeys: string[];
};

export function parseWireTransaction(wireBytes: Uint8Array): ParsedWireTransaction {
if (!wireBytes || wireBytes.length === 0) {
throw new BuildTransactionError('Invalid v1 transaction: empty');
}
if (wireBytes[0] !== V1_VERSION_PREFIX) {
throw new BuildTransactionError(
`Invalid v1 transaction: expected version prefix 0x${V1_VERSION_PREFIX.toString(
16
)}, got 0x${wireBytes[0].toString(16)}`
);
}
if (wireBytes.length < 42) {
throw new BuildTransactionError('Invalid v1 transaction: too short');
}
if (wireBytes.length > V1_TRANSACTION_SIZE_LIMIT) {
throw new BuildTransactionError(
`Invalid v1 transaction: exceeds the ${V1_TRANSACTION_SIZE_LIMIT}-byte size limit: ${wireBytes.length} bytes`
);
}
const decoded = decodeV1Message(wireBytes);
const messageLength = decoded.byteLength;
const numSignatures = decoded.header.numSignerAccounts;
const expectedSigBytes = numSignatures * SIGNATURE_BYTE_LENGTH;

if (wireBytes.length - messageLength !== expectedSigBytes) {
throw new BuildTransactionError(
`Invalid v1 transaction: expected ${expectedSigBytes} signature bytes after message, got ${
wireBytes.length - messageLength
}`
);
}

const messageBytes = wireBytes.slice(0, messageLength);
const signatures: Uint8Array[] = [];
for (let i = 0; i < numSignatures; i++) {
signatures.push(
wireBytes.slice(messageLength + i * SIGNATURE_BYTE_LENGTH, messageLength + (i + 1) * SIGNATURE_BYTE_LENGTH)
);
}
return { messageBytes, signatures, signerPublicKeys: decoded.staticAccounts.slice(0, numSignatures) };
}

export function verifyV1Signatures(
messageBytes: Uint8Array,
signatures: Uint8Array[],
signerPublicKeys: string[]
): void {
if (signatures.length !== signerPublicKeys.length) {
throw new BuildTransactionError('Signature count does not match signer count');
}
for (let i = 0; i < signatures.length; i++) {
const pubkey = new PublicKey(signerPublicKeys[i]).toBuffer();
if (!nacl.sign.detached.verify(messageBytes, signatures[i], pubkey)) {
throw new BuildTransactionError(`Signature verification failed for signer ${i}`);
}
}
}

export function validateRawTransactionV1(wireBytes: Uint8Array): void {
const { messageBytes, signatures, signerPublicKeys } = parseWireTransaction(wireBytes);
verifyV1Signatures(messageBytes, signatures, signerPublicKeys);
}
22 changes: 21 additions & 1 deletion modules/sdk-coin-sol/src/sol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ import {
isValidPublicKey,
validateRawTransaction,
} from './lib/utils';
import { validateRawTransactionV1 } from './lib/serialization/parseWireTransaction';

export const DEFAULT_SCAN_FACTOR = 20; // default number of receive addresses to scan for funds

Expand Down Expand Up @@ -2159,7 +2160,26 @@ export class Sol extends BaseCoin {
async broadcastTransaction({
serializedSignedTransaction,
}: BaseBroadcastTransactionOptions): Promise<BaseBroadcastTransactionResult> {
validateRawTransaction(serializedSignedTransaction, true, true);
let rawBytes: Buffer | undefined;
let isV1 = false;
try {
rawBytes = Buffer.from(serializedSignedTransaction, 'base64');
// v1 (SIMD-0296/0385) transactions start with the 0x81 version prefix.
isV1 = rawBytes.length > 0 && rawBytes[0] === 0x81;
} catch {
// Malformed or non-string input: not a v1 transaction. Fall through to the
// legacy validateRawTransaction path, which raises a descriptive error.
}

if (isV1) {
// Structural + signature validation parity with the legacy path (which uses
// validateRawTransaction(raw, true, true)). The 4096-byte v1 size limit is
// enforced inside validateRawTransactionV1 (parseWireTransaction).
validateRawTransactionV1(rawBytes!);
} else {
validateRawTransaction(serializedSignedTransaction, true, true);
}

const response = await this.getDataFromNode({
payload: {
id: '1',
Expand Down
66 changes: 66 additions & 0 deletions modules/sdk-coin-sol/test/unit/serialization/decodeV1Message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import 'should';
import { BuildTransactionError } from '@bitgo/sdk-core';
import { decodeV1Message, encodeV1Message } from '../../../src/lib/serialization/codecs/v1/message';
import { encodeConfigMaskAndValues } from '../../../src/lib/serialization/codecs/v1/config';

const A = '3h1zGmCwsRJn5kU4LdYD8QfUoXjW8YqZcZsRsYxVvNpq';
const B = '9xQeWvGcCvsftH8sN4jWQcBpkT2yLdMfZqNpVxKjRwSb';
const BLOCKHASH = 'GHtXQBsoZHVnNFa9YevAzFr17DJjgHXk3ycTKD5xD3Zi';

function sampleMessage(): Uint8Array {
const config = encodeConfigMaskAndValues({
computeUnitLimit: 200_000,
heapSize: 32_768,
loadedAccountsDataSizeLimit: 65_536,
priorityFee: 5_000,
});
return encodeV1Message({
header: { numSignerAccounts: 1, numReadonlySignerAccounts: 0, numReadonlyNonSignerAccounts: 1 },
configMask: config.mask,
configValues: config.values,
blockhash: BLOCKHASH,
staticAccounts: [A, B],
compiledInstructions: [{ programAddressIndex: 1, accountIndices: [0, 1], data: new Uint8Array([1, 2, 3]) }],
});
}

describe('decodeV1Message', () => {
it('round-trips an encoded v1 message', () => {
const bytes = sampleMessage();
const decoded = decodeV1Message(bytes);
decoded.header.numSignerAccounts.should.equal(1);
decoded.header.numReadonlySignerAccounts.should.equal(0);
decoded.header.numReadonlyNonSignerAccounts.should.equal(1);
decoded.configMask.should.equal(0b11 | 0b100 | 0b1000 | 0b10000);
decoded.configValues.should.eql([
{ kind: 'u64', value: 5_000n },
{ kind: 'u32', value: 200_000 },
{ kind: 'u32', value: 65_536 },
{ kind: 'u32', value: 32_768 },
]);
decoded.blockhash.should.equal(BLOCKHASH);
decoded.staticAccounts.should.eql([A, B]);
decoded.compiledInstructions.should.eql([
{ programAddressIndex: 1, accountIndices: [0, 1], data: new Uint8Array([1, 2, 3]) },
]);
decoded.byteLength.should.equal(bytes.length);
});

it('rejects an unknown config mask bit', () => {
const bytes = sampleMessage();
bytes[4] = 0xff;
(() => decodeV1Message(bytes)).should.throw(BuildTransactionError, { message: /Unknown config mask/ });
});

it('rejects an out-of-range program index', () => {
const bytes = sampleMessage();
const programIdxByte = 42 + 2 * 32 + 4 + 8 + 4 + 4;
bytes[programIdxByte] = 0xff;
(() => decodeV1Message(bytes)).should.throw(BuildTransactionError, { message: /program index/ });
});

it('rejects a truncated message', () => {
const bytes = sampleMessage();
(() => decodeV1Message(bytes.subarray(0, bytes.length - 1))).should.throw(BuildTransactionError);
});
});
Loading
Loading