diff --git a/modules/sdk-coin-sol/src/lib/customInstructionBuilder.ts b/modules/sdk-coin-sol/src/lib/customInstructionBuilder.ts index 6fd7e88150..30a42838f3 100644 --- a/modules/sdk-coin-sol/src/lib/customInstructionBuilder.ts +++ b/modules/sdk-coin-sol/src/lib/customInstructionBuilder.ts @@ -4,11 +4,153 @@ import { MessageV0, PublicKey, SystemProgram, SYSVAR_RECENT_BLOCKHASHES_PUBKEY } import { Transaction } from './transaction'; import { TransactionBuilder } from './transactionBuilder'; import { InstructionBuilderTypes } from './constants'; -import { CustomInstruction, VersionedCustomInstruction, VersionedTransactionData } from './iface'; +import { CustomInstruction, DurableNonceParams, VersionedCustomInstruction, VersionedTransactionData } from './iface'; import { isSolLegacyInstruction } from './utils'; import assert from 'assert'; import base58 from 'bs58'; +/** + * Pure deterministic transform that injects a SystemProgram AdvanceNonceAccount instruction + * at index 0 of a Solana v0 VersionedTransactionData envelope, rebuilding staticAccountKeys + * section by section (writable signers, read-only signers, writable non-signers, read-only + * non-signers) and remapping every static and lookup-table instruction account index. + * + * Shared by both CustomInstructionBuilder (build path) and Sol.verifyVersionedTransaction + * (verification path) so the two cannot drift. + */ +export function injectVersionedNonceAdvanceInstruction( + data: VersionedTransactionData, + nonceParams: DurableNonceParams +): VersionedTransactionData { + const { walletNonceAddress, authWalletAddress } = nonceParams; + const SYSTEM_PROGRAM = SystemProgram.programId.toBase58(); + const SYSVAR_RECENT_BLOCKHASHES = SYSVAR_RECENT_BLOCKHASHES_PUBKEY.toBase58(); + + const { numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts } = data.messageHeader; + const oldStaticLen = data.staticAccountKeys.length; + if ( + numReadonlySignedAccounts > numRequiredSignatures || + numRequiredSignatures + numReadonlyUnsignedAccounts > oldStaticLen + ) { + throw new BuildTransactionError( + `Invalid message header: readonly counts (${numReadonlySignedAccounts}, ${numReadonlyUnsignedAccounts}) ` + + `are inconsistent with ${numRequiredSignatures} required signatures and ${oldStaticLen} static account keys` + ); + } + + // Split the original static keys into the four MessageV0 header sections. + const writableSigners = data.staticAccountKeys.slice(0, numRequiredSignatures - numReadonlySignedAccounts); + const readonlySigners = data.staticAccountKeys.slice( + numRequiredSignatures - numReadonlySignedAccounts, + numRequiredSignatures + ); + const writableNonSigners = data.staticAccountKeys.slice( + numRequiredSignatures, + oldStaticLen - numReadonlyUnsignedAccounts + ); + const readonlyNonSigners = data.staticAccountKeys.slice(oldStaticLen - numReadonlyUnsignedAccounts); + + // The nonce authority must be a signer for AdvanceNonceAccount. If it is already present + // as a non-signer, move it into the signers, keeping its writability (a writable + // non-signer becomes a writable signer, a read-only one a read-only signer). + const authorityIsSigner = writableSigners.includes(authWalletAddress) || readonlySigners.includes(authWalletAddress); + if (!authorityIsSigner) { + const asReadonlyNonSigner = readonlyNonSigners.indexOf(authWalletAddress); + const asWritableNonSigner = writableNonSigners.indexOf(authWalletAddress); + if (asReadonlyNonSigner >= 0) { + readonlyNonSigners.splice(asReadonlyNonSigner, 1); + readonlySigners.push(authWalletAddress); + } else if (asWritableNonSigner >= 0) { + writableNonSigners.splice(asWritableNonSigner, 1); + writableSigners.push(authWalletAddress); + } else { + // A brand-new authority is a read-only signer for AdvanceNonceAccount. + readonlySigners.push(authWalletAddress); + } + } + + // The nonce account must be writable for AdvanceNonceAccount. If it is already present, + // keep it in place when writable, or move it into the writable section when read-only. + const nonceAsReadonlyNonSigner = readonlyNonSigners.indexOf(walletNonceAddress); + const nonceAsReadonlySigner = readonlySigners.indexOf(walletNonceAddress); + if (nonceAsReadonlyNonSigner >= 0) { + readonlyNonSigners.splice(nonceAsReadonlyNonSigner, 1); + writableNonSigners.push(walletNonceAddress); + } else if (nonceAsReadonlySigner >= 0) { + readonlySigners.splice(nonceAsReadonlySigner, 1); + writableSigners.push(walletNonceAddress); + } else if (!writableSigners.includes(walletNonceAddress) && !writableNonSigners.includes(walletNonceAddress)) { + writableNonSigners.push(walletNonceAddress); + } + + // The system program and the recent blockhashes sysvar are read-only non-signers for + // AdvanceNonceAccount. + const isPresent = (key: string) => + writableSigners.includes(key) || + readonlySigners.includes(key) || + writableNonSigners.includes(key) || + readonlyNonSigners.includes(key); + if (!isPresent(SYSTEM_PROGRAM)) { + readonlyNonSigners.push(SYSTEM_PROGRAM); + } + if (!isPresent(SYSVAR_RECENT_BLOCKHASHES)) { + readonlyNonSigners.push(SYSVAR_RECENT_BLOCKHASHES); + } + + const newStaticAccountKeys = [...writableSigners, ...readonlySigners, ...writableNonSigners, ...readonlyNonSigners]; + + // Build one full old-index to new-index map covering static and lookup-table indexes. + // Static indexes follow their key to its new position; lookup-table indexes, which are + // appended after the static keys, shift by the number of inserted static keys. + const indexMap = new Map(); + data.staticAccountKeys.forEach((key, oldIdx) => indexMap.set(oldIdx, newStaticAccountKeys.indexOf(key))); + const shift = newStaticAccountKeys.length - oldStaticLen; + const addressLookupTables = data.addressLookupTables ?? []; + const lookupKeyCount = addressLookupTables.reduce( + (sum, alt) => sum + alt.writableIndexes.length + alt.readonlyIndexes.length, + 0 + ); + for (let i = oldStaticLen; i < oldStaticLen + lookupKeyCount; i++) { + indexMap.set(i, i + shift); + } + const remapIndex = (index: number): number => { + const mapped = indexMap.get(index); + if (mapped === undefined) { + throw new BuildTransactionError(`Invalid account key index ${index} in versioned instruction`); + } + return mapped; + }; + + const nonceAdvanceInstruction: SolVersionedInstruction = { + programIdIndex: newStaticAccountKeys.indexOf(SYSTEM_PROGRAM), + accountKeyIndexes: [ + newStaticAccountKeys.indexOf(walletNonceAddress), + newStaticAccountKeys.indexOf(SYSVAR_RECENT_BLOCKHASHES), + newStaticAccountKeys.indexOf(authWalletAddress), + ], + data: '6vx8P', // SystemProgram AdvanceNonceAccount (0x04000000) in base58 + }; + + return { + ...data, + addressLookupTables, + versionedInstructions: [ + nonceAdvanceInstruction, + ...data.versionedInstructions.map((inst) => ({ + programIdIndex: remapIndex(inst.programIdIndex), + accountKeyIndexes: inst.accountKeyIndexes.map(remapIndex), + data: inst.data, + })), + ], + staticAccountKeys: newStaticAccountKeys, + messageHeader: { + numRequiredSignatures: writableSigners.length + readonlySigners.length, + numReadonlySignedAccounts: readonlySigners.length, + numReadonlyUnsignedAccounts: readonlyNonSigners.length, + }, + }; +} + /** * Transaction builder for custom Solana instructions. * Allows building transactions with any set of raw Solana instructions. @@ -163,133 +305,7 @@ export class CustomInstructionBuilder extends TransactionBuilder { * @private */ private injectNonceAdvanceInstruction(data: VersionedTransactionData): VersionedTransactionData { - const { walletNonceAddress, authWalletAddress } = this._nonceInfo!.params; - const SYSTEM_PROGRAM = SystemProgram.programId.toBase58(); - const SYSVAR_RECENT_BLOCKHASHES = SYSVAR_RECENT_BLOCKHASHES_PUBKEY.toBase58(); - - const { numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts } = data.messageHeader; - const oldStaticLen = data.staticAccountKeys.length; - if ( - numReadonlySignedAccounts > numRequiredSignatures || - numRequiredSignatures + numReadonlyUnsignedAccounts > oldStaticLen - ) { - throw new BuildTransactionError( - `Invalid message header: readonly counts (${numReadonlySignedAccounts}, ${numReadonlyUnsignedAccounts}) ` + - `are inconsistent with ${numRequiredSignatures} required signatures and ${oldStaticLen} static account keys` - ); - } - - // Split the original static keys into the four MessageV0 header sections. - const writableSigners = data.staticAccountKeys.slice(0, numRequiredSignatures - numReadonlySignedAccounts); - const readonlySigners = data.staticAccountKeys.slice( - numRequiredSignatures - numReadonlySignedAccounts, - numRequiredSignatures - ); - const writableNonSigners = data.staticAccountKeys.slice( - numRequiredSignatures, - oldStaticLen - numReadonlyUnsignedAccounts - ); - const readonlyNonSigners = data.staticAccountKeys.slice(oldStaticLen - numReadonlyUnsignedAccounts); - - // The nonce authority must be a signer for AdvanceNonceAccount. If it is already present - // as a non-signer, move it into the signers, keeping its writability (a writable - // non-signer becomes a writable signer, a read-only one a read-only signer). - const authorityIsSigner = - writableSigners.includes(authWalletAddress) || readonlySigners.includes(authWalletAddress); - if (!authorityIsSigner) { - const asReadonlyNonSigner = readonlyNonSigners.indexOf(authWalletAddress); - const asWritableNonSigner = writableNonSigners.indexOf(authWalletAddress); - if (asReadonlyNonSigner >= 0) { - readonlyNonSigners.splice(asReadonlyNonSigner, 1); - readonlySigners.push(authWalletAddress); - } else if (asWritableNonSigner >= 0) { - writableNonSigners.splice(asWritableNonSigner, 1); - writableSigners.push(authWalletAddress); - } else { - // A brand-new authority is a read-only signer for AdvanceNonceAccount. - readonlySigners.push(authWalletAddress); - } - } - - // The nonce account must be writable for AdvanceNonceAccount. If it is already present, - // keep it in place when writable, or move it into the writable section when read-only. - const nonceAsReadonlyNonSigner = readonlyNonSigners.indexOf(walletNonceAddress); - const nonceAsReadonlySigner = readonlySigners.indexOf(walletNonceAddress); - if (nonceAsReadonlyNonSigner >= 0) { - readonlyNonSigners.splice(nonceAsReadonlyNonSigner, 1); - writableNonSigners.push(walletNonceAddress); - } else if (nonceAsReadonlySigner >= 0) { - readonlySigners.splice(nonceAsReadonlySigner, 1); - writableSigners.push(walletNonceAddress); - } else if (!writableSigners.includes(walletNonceAddress) && !writableNonSigners.includes(walletNonceAddress)) { - writableNonSigners.push(walletNonceAddress); - } - - // The system program and the recent blockhashes sysvar are read-only non-signers for - // AdvanceNonceAccount. - const isPresent = (key: string) => - writableSigners.includes(key) || - readonlySigners.includes(key) || - writableNonSigners.includes(key) || - readonlyNonSigners.includes(key); - if (!isPresent(SYSTEM_PROGRAM)) { - readonlyNonSigners.push(SYSTEM_PROGRAM); - } - if (!isPresent(SYSVAR_RECENT_BLOCKHASHES)) { - readonlyNonSigners.push(SYSVAR_RECENT_BLOCKHASHES); - } - - const newStaticAccountKeys = [...writableSigners, ...readonlySigners, ...writableNonSigners, ...readonlyNonSigners]; - - // Build one full old-index to new-index map covering static and lookup-table indexes. - // Static indexes follow their key to its new position; lookup-table indexes, which are - // appended after the static keys, shift by the number of inserted static keys. - const indexMap = new Map(); - data.staticAccountKeys.forEach((key, oldIdx) => indexMap.set(oldIdx, newStaticAccountKeys.indexOf(key))); - const shift = newStaticAccountKeys.length - oldStaticLen; - const lookupKeyCount = data.addressLookupTables.reduce( - (sum, alt) => sum + alt.writableIndexes.length + alt.readonlyIndexes.length, - 0 - ); - for (let i = oldStaticLen; i < oldStaticLen + lookupKeyCount; i++) { - indexMap.set(i, i + shift); - } - const remapIndex = (index: number): number => { - const mapped = indexMap.get(index); - if (mapped === undefined) { - throw new BuildTransactionError(`Invalid account key index ${index} in versioned instruction`); - } - return mapped; - }; - - const nonceAdvanceInstruction: SolVersionedInstruction = { - programIdIndex: newStaticAccountKeys.indexOf(SYSTEM_PROGRAM), - accountKeyIndexes: [ - newStaticAccountKeys.indexOf(walletNonceAddress), - newStaticAccountKeys.indexOf(SYSVAR_RECENT_BLOCKHASHES), - newStaticAccountKeys.indexOf(authWalletAddress), - ], - data: '6vx8P', // SystemProgram AdvanceNonceAccount (0x04000000) in base58 - }; - - const processed: VersionedTransactionData = { - ...data, - versionedInstructions: [ - nonceAdvanceInstruction, - ...data.versionedInstructions.map((inst) => ({ - programIdIndex: remapIndex(inst.programIdIndex), - accountKeyIndexes: inst.accountKeyIndexes.map(remapIndex), - data: inst.data, - })), - ], - staticAccountKeys: newStaticAccountKeys, - messageHeader: { - numRequiredSignatures: writableSigners.length + readonlySigners.length, - numReadonlySignedAccounts: readonlySigners.length, - numReadonlyUnsignedAccounts: readonlyNonSigners.length, - }, - }; - + const processed = injectVersionedNonceAdvanceInstruction(data, this._nonceInfo!.params); this.validateInjectedMessage(processed); return processed; } diff --git a/modules/sdk-coin-sol/src/lib/index.ts b/modules/sdk-coin-sol/src/lib/index.ts index 8c7fd1f249..f68b754cd5 100644 --- a/modules/sdk-coin-sol/src/lib/index.ts +++ b/modules/sdk-coin-sol/src/lib/index.ts @@ -4,7 +4,7 @@ import * as Utils from './utils'; export { AtaInitializationBuilder } from './ataInitializationBuilder'; export { CloseAtaBuilder } from './closeAtaBuilder'; export { ConfidentialTransferBuilder } from './confidentialTransferBuilder'; -export { CustomInstructionBuilder } from './customInstructionBuilder'; +export { CustomInstructionBuilder, injectVersionedNonceAdvanceInstruction } from './customInstructionBuilder'; export { KeyPair } from './keyPair'; export { StakingActivateBuilder } from './stakingActivateBuilder'; export { StakingAuthorizeBuilder } from './stakingAuthorizeBuilder'; diff --git a/modules/sdk-coin-sol/src/sol.ts b/modules/sdk-coin-sol/src/sol.ts index 1aae1f293c..8fb7347cb2 100644 --- a/modules/sdk-coin-sol/src/sol.ts +++ b/modules/sdk-coin-sol/src/sol.ts @@ -3,7 +3,16 @@ */ import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token'; -import { AccountInfo, Connection, PublicKey as SolPublicKey, SystemInstruction, SystemProgram } from '@solana/web3.js'; +import { + AccountInfo, + Connection, + MessageV0, + PublicKey as SolPublicKey, + SystemInstruction, + SystemProgram, + SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + VersionedTransaction, +} from '@solana/web3.js'; import BigNumber from 'bignumber.js'; import * as base58 from 'bs58'; import * as _ from 'lodash'; @@ -79,12 +88,15 @@ import { TransactionBuilder, TransactionBuilderFactory, explainSolTransaction, + injectVersionedNonceAdvanceInstruction, } from './lib'; import { AtaClose, AtaRecoverNested, + DurableNonceParams, ExtraAccountMeta, TransactionExplanation as SolLibTransactionExplanation, + VersionedTransactionData, } from './lib/iface'; import { InstructionBuilderTypes, MEMO_PROGRAM_PK } from './lib/constants'; import { @@ -622,67 +634,365 @@ export class Sol extends BaseCoin { } } + private validateVersionedTransactionData(versionedData: SolVersionedTransactionData): VersionedTransactionData { + if (!versionedData || typeof versionedData !== 'object') { + throw new Error('solVersionedTransactionData must be an object'); + } + + if ('version' in versionedData && versionedData.version !== undefined && versionedData.version !== 0) { + throw new Error(`unsupported versioned transaction version: ${String(versionedData.version)}`); + } + + if (!Array.isArray(versionedData.versionedInstructions) || versionedData.versionedInstructions.length === 0) { + throw new Error('versioned transaction must have at least one instruction'); + } + + if (!Array.isArray(versionedData.staticAccountKeys) || versionedData.staticAccountKeys.length === 0) { + throw new Error('versioned transaction must have at least one static account key'); + } + + if (!versionedData.messageHeader || typeof versionedData.messageHeader !== 'object') { + throw new Error('versioned transaction must have a message header'); + } + + const { numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts } = + versionedData.messageHeader; + const staticLen = versionedData.staticAccountKeys.length; + if ( + !Number.isInteger(numRequiredSignatures) || + numRequiredSignatures < 1 || + !Number.isInteger(numReadonlySignedAccounts) || + numReadonlySignedAccounts < 0 || + !Number.isInteger(numReadonlyUnsignedAccounts) || + numReadonlyUnsignedAccounts < 0 || + numReadonlySignedAccounts > numRequiredSignatures || + numRequiredSignatures + numReadonlyUnsignedAccounts > staticLen + ) { + throw new Error('versioned transaction has an invalid message header'); + } + + const seenStaticKeys = new Set(); + for (const key of versionedData.staticAccountKeys) { + let canonical: string; + try { + canonical = new SolPublicKey(key).toBase58(); + } catch { + throw new Error(`versioned transaction contains invalid static account key: ${String(key)}`); + } + if (canonical !== key) { + throw new Error(`versioned transaction contains non-canonical static account key: ${key}`); + } + if (seenStaticKeys.has(key)) { + throw new Error(`versioned transaction contains duplicate static account key: ${key}`); + } + seenStaticKeys.add(key); + } + + if (versionedData.addressLookupTables !== undefined && !Array.isArray(versionedData.addressLookupTables)) { + throw new Error('versioned transaction addressLookupTables must be an array'); + } + const addressLookupTables = versionedData.addressLookupTables ?? []; + let lookupKeyCount = 0; + for (const alt of addressLookupTables) { + if (!alt || typeof alt !== 'object') { + throw new Error('versioned transaction contains invalid address lookup table entry'); + } + let canonicalAlt: string; + try { + canonicalAlt = new SolPublicKey(alt.accountKey).toBase58(); + } catch { + throw new Error(`versioned transaction contains invalid ALT accountKey: ${String(alt.accountKey)}`); + } + if (canonicalAlt !== alt.accountKey) { + throw new Error(`versioned transaction contains non-canonical ALT accountKey: ${alt.accountKey}`); + } + if (!Array.isArray(alt.writableIndexes) || !Array.isArray(alt.readonlyIndexes)) { + throw new Error('versioned transaction ALT writableIndexes and readonlyIndexes must be arrays'); + } + for (const idx of [...alt.writableIndexes, ...alt.readonlyIndexes]) { + if (!Number.isInteger(idx) || idx < 0 || idx > 255) { + throw new Error(`versioned transaction ALT contains invalid index: ${String(idx)}`); + } + } + lookupKeyCount += alt.writableIndexes.length + alt.readonlyIndexes.length; + } + + const totalAccountKeys = staticLen + lookupKeyCount; + for (const ix of versionedData.versionedInstructions) { + if (!ix || typeof ix !== 'object') { + throw new Error('versioned transaction contains invalid instruction'); + } + if (!Number.isInteger(ix.programIdIndex) || ix.programIdIndex < 0 || ix.programIdIndex >= staticLen) { + throw new Error(`versioned transaction instruction has out-of-bounds programIdIndex: ${ix.programIdIndex}`); + } + if (!Array.isArray(ix.accountKeyIndexes)) { + throw new Error('versioned transaction instruction accountKeyIndexes must be an array'); + } + for (const idx of ix.accountKeyIndexes) { + if (!Number.isInteger(idx) || idx < 0 || idx >= totalAccountKeys) { + throw new Error(`versioned transaction instruction has out-of-bounds accountKeyIndex: ${idx}`); + } + } + if (typeof ix.data !== 'string') { + throw new Error('versioned transaction instruction data must be a base58 string'); + } + try { + base58.decode(ix.data); + } catch { + throw new Error('versioned transaction instruction data is not valid base58'); + } + } + + return { + versionedInstructions: versionedData.versionedInstructions, + addressLookupTables, + staticAccountKeys: versionedData.staticAccountKeys, + messageHeader: versionedData.messageHeader, + recentBlockhash: versionedData.recentBlockhash, + }; + } + + private decodeVersionedAdvanceNonceInstruction(message: MessageV0): DurableNonceParams | undefined { + if (message.compiledInstructions.length === 0) { + return undefined; + } + const ix0 = message.compiledInstructions[0]; + const staticKeys = message.staticAccountKeys; + if (ix0.programIdIndex >= staticKeys.length) { + return undefined; + } + if (staticKeys[ix0.programIdIndex].toBase58() !== SystemProgram.programId.toBase58()) { + return undefined; + } + // SystemProgram.AdvanceNonceAccount discriminator is 4-byte little-endian uint32(4). + if (ix0.data.length !== 4 || ix0.data[0] !== 4 || ix0.data[1] !== 0 || ix0.data[2] !== 0 || ix0.data[3] !== 0) { + return undefined; + } + if (ix0.accountKeyIndexes.length !== 3) { + return undefined; + } + const [nonceIdx, sysvarIdx, authIdx] = ix0.accountKeyIndexes; + if (nonceIdx >= staticKeys.length || sysvarIdx >= staticKeys.length || authIdx >= staticKeys.length) { + return undefined; + } + if (staticKeys[sysvarIdx].toBase58() !== SYSVAR_RECENT_BLOCKHASHES_PUBKEY.toBase58()) { + return undefined; + } + + const { numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts } = message.header; + const nonceIsWritable = + nonceIdx < numRequiredSignatures - numReadonlySignedAccounts || + (nonceIdx >= numRequiredSignatures && nonceIdx < staticKeys.length - numReadonlyUnsignedAccounts); + const authIsSigner = authIdx < numRequiredSignatures; + if (!nonceIsWritable || !authIsSigner) { + return undefined; + } + + return { + walletNonceAddress: staticKeys[nonceIdx].toBase58(), + authWalletAddress: staticKeys[authIdx].toBase58(), + }; + } + + private assertVersionedMessageMatchesData(message: MessageV0, expected: VersionedTransactionData): void { + const { header } = message; + if ( + header.numRequiredSignatures !== expected.messageHeader.numRequiredSignatures || + header.numReadonlySignedAccounts !== expected.messageHeader.numReadonlySignedAccounts || + header.numReadonlyUnsignedAccounts !== expected.messageHeader.numReadonlyUnsignedAccounts + ) { + throw new Error('Versioned transaction messageHeader does not match solVersionedTransactionData'); + } + + if (message.staticAccountKeys.length !== expected.staticAccountKeys.length) { + throw new Error('Versioned transaction staticAccountKeys length does not match solVersionedTransactionData'); + } + for (let i = 0; i < expected.staticAccountKeys.length; i++) { + if (message.staticAccountKeys[i].toBase58() !== expected.staticAccountKeys[i]) { + throw new Error(`Versioned transaction staticAccountKeys[${i}] does not match solVersionedTransactionData`); + } + } + + const expectedAlts = expected.addressLookupTables ?? []; + if (message.addressTableLookups.length !== expectedAlts.length) { + throw new Error('Versioned transaction addressTableLookups length does not match solVersionedTransactionData'); + } + for (let i = 0; i < expectedAlts.length; i++) { + const actualAlt = message.addressTableLookups[i]; + const expectedAlt = expectedAlts[i]; + if ( + actualAlt.accountKey.toBase58() !== expectedAlt.accountKey || + !_.isEqual(actualAlt.writableIndexes, expectedAlt.writableIndexes) || + !_.isEqual(actualAlt.readonlyIndexes, expectedAlt.readonlyIndexes) + ) { + throw new Error(`Versioned transaction addressTableLookups[${i}] does not match solVersionedTransactionData`); + } + } + + if (message.compiledInstructions.length !== expected.versionedInstructions.length) { + throw new Error('Versioned transaction instruction count does not match solVersionedTransactionData'); + } + for (let i = 0; i < expected.versionedInstructions.length; i++) { + const actualIx = message.compiledInstructions[i]; + const expectedIx = expected.versionedInstructions[i]; + const expectedData = Buffer.from(base58.decode(expectedIx.data)); + if ( + actualIx.programIdIndex !== expectedIx.programIdIndex || + !_.isEqual(actualIx.accountKeyIndexes, expectedIx.accountKeyIndexes) || + !Buffer.from(actualIx.data).equals(expectedData) + ) { + throw new Error(`Versioned transaction instruction[${i}] does not match solVersionedTransactionData`); + } + } + } + /** - * Verify a versioned Solana transaction with basic structural validation + * Fully deserialize a Solana v0 versioned transaction and verify its message + * (header, staticAccountKeys, addressTableLookups, and compiledInstructions) + * matches txParams.solVersionedTransactionData (or the exact deterministic + * durable-nonce-injected form when Wallet Platform prepends AdvanceNonceAccount). + * + * Note: recentBlockhash is intentionally not pinned to versionedData.recentBlockhash + * because Wallet Platform refreshes stale blockhashes before signing (DEFI-820). + * * @param params - verification parameters * @returns true if verification passes */ private async verifyVersionedTransaction(params: SolVerifyTransactionOptions): Promise { - const { txParams, txPrebuild } = params; + const { txParams, txPrebuild, durableNonce, verification: verificationOptions } = params; const rawTx = txPrebuild.txBase64 || txPrebuild.txHex; if (!rawTx) { throw new Error('missing required tx prebuild property txBase64 or txHex'); } - // Validate that the versioned transaction data is well-formed if (!this.hasSolVersionedTransactionData(txParams)) { throw new Error('solVersionedTransactionData is required for versioned transaction verification'); } - const versionedData = txParams.solVersionedTransactionData; + if (txParams.type !== undefined && txParams.type !== 'customTx') { + throw new Error('solVersionedTransactionData is only supported for customTx transactions'); + } - if (!versionedData.versionedInstructions || versionedData.versionedInstructions.length === 0) { - throw new Error('versioned transaction must have at least one instruction'); + if (txParams.recipients && txParams.recipients.length > 0) { + throw new Error('recipients are not supported with solVersionedTransactionData'); } - if (!versionedData.staticAccountKeys || versionedData.staticAccountKeys.length === 0) { - throw new Error('versioned transaction must have at least one static account key'); + if (txPrebuild.consolidateId !== undefined || verificationOptions?.consolidationToBaseAddress) { + throw new Error('consolidations are not supported with solVersionedTransactionData'); } - if (!versionedData.messageHeader) { - throw new Error('versioned transaction must have a message header'); + const versionedData = this.validateVersionedTransactionData(txParams.solVersionedTransactionData); + + let txBytes: Buffer; + if (HEX_REGEX.test(rawTx) && rawTx.length % 2 === 0) { + txBytes = Buffer.from(rawTx, 'hex'); + } else if (/^[A-Za-z0-9+/]+={0,2}$/.test(rawTx)) { + txBytes = Buffer.from(rawTx, 'base64'); + } else { + throw new Error('failed to validate versioned transaction format: invalid raw transaction encoding'); } - // Validate that we can deserialize the transaction - let rawTxBase64 = rawTx; - if (HEX_REGEX.test(rawTx)) { - rawTxBase64 = Buffer.from(rawTx, 'hex').toString('base64'); + if (txBytes.length < 1) { + throw new Error('failed to validate versioned transaction format: transaction bytes are empty'); } + let deserializedTx: VersionedTransaction; try { - const txBytes = Buffer.from(rawTxBase64, 'base64'); - if (txBytes.length < 1) { - throw new Error('transaction bytes are empty'); - } + deserializedTx = VersionedTransaction.deserialize(txBytes); + } catch (error) { + throw new Error(`failed to deserialize versioned transaction: ${error.message}`); + } + + if (deserializedTx.version !== 0) { + throw new Error(`transaction is not a v0 versioned transaction: got ${String(deserializedTx.version)}`); + } - // Check version byte (after signatures) - const numSignatures = txBytes[0]; - const signatureSize = 64; - const versionByteOffset = 1 + numSignatures * signatureSize; + const reserializedBytes = Buffer.from(deserializedTx.serialize()); + if (!reserializedBytes.equals(txBytes)) { + throw new Error('versioned transaction has non-canonical encoding or trailing bytes'); + } + + const message = deserializedTx.message as MessageV0; + const actualIxCount = message.compiledInstructions.length; + const expectedIxCount = versionedData.versionedInstructions.length; - if (txBytes.length <= versionByteOffset) { - throw new Error('transaction bytes are too short to contain version byte'); + if (actualIxCount === expectedIxCount) { + this.assertVersionedMessageMatchesData(message, versionedData); + + if (durableNonce) { + const decodedNonce = this.decodeVersionedAdvanceNonceInstruction(message); + if ( + !decodedNonce || + decodedNonce.walletNonceAddress !== durableNonce.walletNonceAddress || + decodedNonce.authWalletAddress !== String(durableNonce.authWalletAddress) + ) { + throw new Error('Tx durableNonce does not match with param durableNonce'); + } + } + } else if (actualIxCount === expectedIxCount + 1) { + const decodedNonce = this.decodeVersionedAdvanceNonceInstruction(message); + if (!decodedNonce) { + throw new Error('Versioned transaction contains unexpected extra instruction'); } - const versionByte = txBytes[versionByteOffset]; - const isVersioned = (versionByte & 0x80) !== 0; + if (durableNonce) { + if ( + decodedNonce.walletNonceAddress !== durableNonce.walletNonceAddress || + decodedNonce.authWalletAddress !== String(durableNonce.authWalletAddress) + ) { + throw new Error('Tx durableNonce does not match with param durableNonce'); + } + } else { + // Without an explicit durableNonce param, do not allow nonce injection to escalate + // privileges of accounts already present in the user's staticAccountKeys. + const origHeader = versionedData.messageHeader; + const origStaticLen = versionedData.staticAccountKeys.length; + const existingAuthIdx = versionedData.staticAccountKeys.indexOf(decodedNonce.authWalletAddress); + if (existingAuthIdx >= origHeader.numRequiredSignatures) { + throw new Error('Injected nonce authority cannot escalate an existing non-signer account to a signer'); + } + const existingNonceIdx = versionedData.staticAccountKeys.indexOf(decodedNonce.walletNonceAddress); + if (existingNonceIdx >= 0) { + const wasReadonlySigner = + existingNonceIdx >= origHeader.numRequiredSignatures - origHeader.numReadonlySignedAccounts && + existingNonceIdx < origHeader.numRequiredSignatures; + const wasReadonlyNonSigner = existingNonceIdx >= origStaticLen - origHeader.numReadonlyUnsignedAccounts; + if (wasReadonlySigner || wasReadonlyNonSigner) { + throw new Error('Injected nonce account cannot escalate an existing read-only account to writable'); + } + } + } - if (!isVersioned) { - throw new Error('transaction does not have versioned format'); + const expectedWithNonce = injectVersionedNonceAdvanceInstruction(versionedData, decodedNonce); + this.assertVersionedMessageMatchesData(message, expectedWithNonce); + } else { + throw new Error('Versioned transaction instruction count does not match solVersionedTransactionData'); + } + + const declaredFeePayer = + params.feePayer ?? + (typeof txParams === 'object' && + txParams !== null && + 'feePayer' in txParams && + typeof txParams.feePayer === 'string' + ? txParams.feePayer + : undefined); + const actualFeePayer = message.staticAccountKeys[0].toBase58(); + if (declaredFeePayer && actualFeePayer !== declaredFeePayer) { + throw new Error( + `Tx fee payer ${actualFeePayer} does not match the declared sponsored fee payer ${declaredFeePayer}` + ); + } + + const walletRootAddress = params.wallet?.coinSpecific()?.rootAddress; + if (walletRootAddress) { + const requiredSigners = message.staticAccountKeys + .slice(0, message.header.numRequiredSignatures) + .map((key) => key.toBase58()); + if (!requiredSigners.includes(walletRootAddress)) { + throw new Error('Wallet root address is not a required signer of the versioned transaction'); } - } catch (error) { - throw new Error(`failed to validate versioned transaction format: ${error.message}`); } return true; diff --git a/modules/sdk-coin-sol/test/unit/sol.ts b/modules/sdk-coin-sol/test/unit/sol.ts index 16ed66510b..e1bd98bd98 100644 --- a/modules/sdk-coin-sol/test/unit/sol.ts +++ b/modules/sdk-coin-sol/test/unit/sol.ts @@ -5,7 +5,14 @@ import * as should from 'should'; import * as sinon from 'sinon'; import { getExtraAccountMetaAddress, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token'; -import { Keypair, PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js'; +import { + Keypair, + MessageV0, + PublicKey, + SystemProgram, + TransactionInstruction, + VersionedTransaction, +} from '@solana/web3.js'; import * as base58 from 'bs58'; import * as nacl from 'tweetnacl'; @@ -48,7 +55,13 @@ import { Tsol, } from '../../src'; import { Transaction } from '../../src/lib'; -import { AtaInit, ExtraAccountMeta, InstructionParams, TokenTransfer } from '../../src/lib/iface'; +import { + AtaInit, + ExtraAccountMeta, + InstructionParams, + TokenTransfer, + VersionedTransactionData, +} from '../../src/lib/iface'; import { TOKEN_ACL_FLAG_ACCOUNT_SEED, TOKEN_ACL_MINT_CONFIG_SEED, @@ -1649,6 +1662,671 @@ describe('SOL:', function () { .should.be.rejectedWith('CustomTx prebuild instruction 0 key 0 mismatch'); }); }); + + describe('versioned transactions', () => { + const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'; + const altAccountKey = Keypair.generate().publicKey.toBase58(); + const extraProgramKey = Keypair.generate().publicKey.toBase58(); + const extraWritableKey = Keypair.generate().publicKey.toBase58(); + const extraReadonlyKey = Keypair.generate().publicKey.toBase58(); + const attackerKey = Keypair.generate().publicKey.toBase58(); + const relayerKey = Keypair.generate().publicKey.toBase58(); + const nonceAccountKey = Keypair.generate().publicKey.toBase58(); + const nonceAuthKey = Keypair.generate().publicKey.toBase58(); + const refreshedBlockHash = Keypair.generate().publicKey.toBase58(); + + const makeBasicVersionedData = (): VersionedTransactionData => ({ + versionedInstructions: [ + { + programIdIndex: 1, + accountKeyIndexes: [0], + data: base58.encode(Buffer.from('Hello Versioned Tx', 'utf-8')), + }, + ], + addressLookupTables: [], + staticAccountKeys: [wallet.pub, MEMO_PROGRAM_ID], + messageHeader: { + numRequiredSignatures: 1, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 1, + }, + recentBlockhash: blockHash, + }); + + const makeAltVersionedData = (): VersionedTransactionData => ({ + versionedInstructions: [ + { + programIdIndex: 3, + accountKeyIndexes: [0, 1, 2, 4, 5, 6], + data: base58.encode(Buffer.from([1, 2, 3, 4, 5, 6, 7, 8])), + }, + ], + addressLookupTables: [ + { + accountKey: altAccountKey, + writableIndexes: [0, 2], + readonlyIndexes: [5], + }, + ], + staticAccountKeys: [wallet.pub, extraWritableKey, extraReadonlyKey, extraProgramKey], + messageHeader: { + numRequiredSignatures: 1, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 2, + }, + recentBlockhash: blockHash, + }); + + const buildRawVersionedTx = ( + data: VersionedTransactionData, + overrideBlockhash?: string + ): VersionedTransaction => { + const messageV0 = new MessageV0({ + header: data.messageHeader, + staticAccountKeys: data.staticAccountKeys.map((k) => new PublicKey(k)), + recentBlockhash: overrideBlockhash ?? data.recentBlockhash ?? blockHash, + compiledInstructions: data.versionedInstructions.map((ix) => ({ + programIdIndex: ix.programIdIndex, + accountKeyIndexes: ix.accountKeyIndexes, + data: Buffer.from(base58.decode(ix.data)), + })), + addressTableLookups: (data.addressLookupTables ?? []).map((alt) => ({ + accountKey: new PublicKey(alt.accountKey), + writableIndexes: alt.writableIndexes, + readonlyIndexes: alt.readonlyIndexes, + })), + }); + return new VersionedTransaction(messageV0); + }; + + it('should verify a valid v0 versioned transaction (base64)', async function () { + const versionedData = makeBasicVersionedData(); + const tx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash) + .fromVersionedTransactionData(versionedData) + .build(); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 versioned transaction (hex, matching Wallet Platform serializedTxHex)', async function () { + const versionedData = makeBasicVersionedData(); + const rawHex = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('hex'); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txHex: rawHex }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 versioned transaction with Address Lookup Tables (ALTs)', async function () { + const versionedData = makeAltVersionedData(); + const tx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash) + .fromVersionedTransactionData(versionedData) + .build(); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction after DEFI-820 recentBlockhash refresh', async function () { + const versionedData = makeAltVersionedData(); + const refreshedRaw = Buffer.from(buildRawVersionedTx(versionedData, refreshedBlockHash).serialize()).toString( + 'base64' + ); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: refreshedRaw }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction with a third-party gasless fee payer when wallet root is a required signer', async function () { + const versionedData = { + versionedInstructions: [ + { + programIdIndex: 2, + accountKeyIndexes: [0, 1], + data: base58.encode(Buffer.from('gasless swap', 'utf-8')), + }, + ], + addressLookupTables: [], + staticAccountKeys: [relayerKey, wallet.pub, MEMO_PROGRAM_ID], + messageHeader: { + numRequiredSignatures: 2, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 1, + }, + recentBlockhash: blockHash, + }; + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction with declared sponsored feePayer matching staticAccountKeys[0]', async function () { + const versionedData = { + versionedInstructions: [ + { + programIdIndex: 2, + accountKeyIndexes: [0, 1], + data: base58.encode(Buffer.from('sponsored', 'utf-8')), + }, + ], + addressLookupTables: [], + staticAccountKeys: [relayerKey, wallet.pub, MEMO_PROGRAM_ID], + messageHeader: { + numRequiredSignatures: 2, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 1, + }, + recentBlockhash: blockHash, + }; + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + feePayer: relayerKey, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction with empty instruction data', async function () { + const versionedData = { + ...makeBasicVersionedData(), + versionedInstructions: [ + { + programIdIndex: 1, + accountKeyIndexes: [0], + data: '', + }, + ], + }; + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction with WP-injected durable nonce (including shifted ALT indexes)', async function () { + const versionedData = makeAltVersionedData(); + const tx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }) + .fromVersionedTransactionData(versionedData) + .build(); + + // Without explicit durableNonce param + const validWithoutParam = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + wallet: walletObj, + } as any); + validWithoutParam.should.equal(true); + + // With matching durableNonce param + const validWithParam = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + durableNonce: { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }, + wallet: walletObj, + } as any); + validWithParam.should.equal(true); + }); + + it('should reject a substituted SystemProgram.transfer draining wallet funds', async function () { + const versionedData = makeBasicVersionedData(); + const maliciousTransferIx = SystemProgram.transfer({ + fromPubkey: new PublicKey(wallet.pub), + toPubkey: new PublicKey(attackerKey), + lamports: 1_000_000_000, + }); + const maliciousData = { + versionedInstructions: [ + { + programIdIndex: 2, + accountKeyIndexes: [0, 1], + data: base58.encode(maliciousTransferIx.data), + }, + ], + addressLookupTables: [], + staticAccountKeys: [wallet.pub, attackerKey, SystemProgram.programId.toBase58()], + messageHeader: { + numRequiredSignatures: 1, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 1, + }, + recentBlockhash: blockHash, + }; + const maliciousRaw = Buffer.from(buildRawVersionedTx(maliciousData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: maliciousRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/does not match solVersionedTransactionData/); + }); + + it('should reject modified instruction data bytes', async function () { + const versionedData = makeBasicVersionedData(); + const tamperedData = { + ...versionedData, + versionedInstructions: [ + { + ...versionedData.versionedInstructions[0], + data: base58.encode(Buffer.from('Tampered Data', 'utf-8')), + }, + ], + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/instruction\[0\] does not match/); + }); + + it('should reject modified instruction accountKeyIndexes', async function () { + const versionedData = makeAltVersionedData(); + const tamperedData = { + ...versionedData, + versionedInstructions: [ + { + ...versionedData.versionedInstructions[0], + accountKeyIndexes: [0, 2, 1, 4, 5, 6], + }, + ], + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/instruction\[0\] does not match/); + }); + + it('should reject an extra injected non-nonce instruction', async function () { + const versionedData = makeBasicVersionedData(); + const tamperedData = { + ...versionedData, + versionedInstructions: [ + ...versionedData.versionedInstructions, + { + programIdIndex: 1, + accountKeyIndexes: [0], + data: base58.encode(Buffer.from('extra', 'utf-8')), + }, + ], + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/unexpected extra instruction/); + }); + + it('should reject modified staticAccountKeys', async function () { + const versionedData = makeAltVersionedData(); + const tamperedData = { + ...versionedData, + staticAccountKeys: [wallet.pub, attackerKey, extraReadonlyKey, extraProgramKey], + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/staticAccountKeys\[1\] does not match/); + }); + + it('should reject substituted ALT accountKey or lookup indexes', async function () { + const versionedData = makeAltVersionedData(); + + const tamperedAltKey = { + ...versionedData, + addressLookupTables: [{ ...versionedData.addressLookupTables[0], accountKey: attackerKey }], + }; + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: Buffer.from(buildRawVersionedTx(tamperedAltKey).serialize()).toString('base64') }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/addressTableLookups\[0\] does not match/); + + const tamperedAltIndexes = { + ...versionedData, + addressLookupTables: [{ ...versionedData.addressLookupTables[0], writableIndexes: [0, 9] }], + }; + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { + txBase64: Buffer.from(buildRawVersionedTx(tamperedAltIndexes).serialize()).toString('base64'), + }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/addressTableLookups\[0\] does not match/); + }); + + it('should reject modified messageHeader flags', async function () { + const versionedData = makeAltVersionedData(); + const tamperedHeader = { + ...versionedData, + messageHeader: { ...versionedData.messageHeader, numReadonlyUnsignedAccounts: 1 }, + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedHeader).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/messageHeader does not match/); + }); + + it('should reject nonce injection that escalates an existing non-signer or read-only account', async function () { + const versionedData = makeAltVersionedData(); + + // Attempt to escalate existing non-signer extraWritableKey to signer via nonce authority + const escalatedAuthTx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: nonceAccountKey, authWalletAddress: extraWritableKey }) + .fromVersionedTransactionData(versionedData) + .build(); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: escalatedAuthTx.toBroadcastFormat() }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/cannot escalate an existing non-signer account to a signer/); + + // Attempt to escalate existing read-only extraReadonlyKey to writable via nonce account + const escalatedNonceTx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: extraReadonlyKey, authWalletAddress: nonceAuthKey }) + .fromVersionedTransactionData(versionedData) + .build(); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: escalatedNonceTx.toBroadcastFormat() }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/cannot escalate an existing read-only account to writable/); + }); + + it('should reject mismatched durableNonce param', async function () { + const versionedData = makeAltVersionedData(); + const tx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }) + .fromVersionedTransactionData(versionedData) + .build(); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + durableNonce: { walletNonceAddress: attackerKey, authWalletAddress: nonceAuthKey }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/Tx durableNonce does not match/); + }); + + it('should reject fake 2-byte [0x00, 0x80] stub, legacy tx, v1 wire bytes, and trailing bytes', async function () { + const versionedData = makeBasicVersionedData(); + + // 2-byte [0x00, 0x80] buffer that passed the old stub + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: Buffer.from([0x00, 0x80]).toString('base64') }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/failed to deserialize versioned transaction/); + + // Legacy Solana transaction bytes + const legacyTx = await factory + .getTransferBuilder() + .sender(wallet.pub) + .nonce(blockHash) + .send({ address: attackerKey, amount: '1000' }) + .build(); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: legacyTx.toBroadcastFormat() }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/not a v0 versioned transaction/); + + // v1 (0x81) wire bytes + const v1HeaderBytes = Buffer.concat([Buffer.from([0x00, 0x81]), Buffer.alloc(64)]); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: v1HeaderBytes.toString('base64') }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/failed to deserialize versioned transaction/); + + // Valid v0 tx with trailing smuggled byte + const validBytes = Buffer.from(buildRawVersionedTx(versionedData).serialize()); + const trailingBytes = Buffer.concat([validBytes, Buffer.from([0x00])]); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: trailingBytes.toString('base64') }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/non-canonical encoding or trailing bytes/); + }); + + it('should fail closed on non-customTx type, non-empty recipients, consolidation flags, or version !== 0', async function () { + const versionedData = makeBasicVersionedData(); + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'transfer', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/only supported for customTx/); + + await basecoin + .verifyTransaction({ + txParams: { + type: 'customTx', + recipients: [{ address: attackerKey, amount: '1000' }], + solVersionedTransactionData: versionedData, + }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/recipients are not supported/); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64, consolidateId: 'consolidate-1' }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/consolidations are not supported/); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: { ...versionedData, version: 1 } }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/unsupported versioned transaction version/); + }); + + it('should reject mismatched declared feePayer or wallet root absent from required signers', async function () { + const versionedData = makeBasicVersionedData(); + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + feePayer: relayerKey, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/does not match the declared sponsored fee payer/); + + const nonWalletData = { + ...versionedData, + staticAccountKeys: [relayerKey, MEMO_PROGRAM_ID], + }; + const nonWalletRaw = Buffer.from(buildRawVersionedTx(nonWalletData).serialize()).toString('base64'); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: nonWalletData }, + txPrebuild: { txBase64: nonWalletRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/Wallet root address is not a required signer/); + }); + + it('should verify a real multi-instruction multi-ALT Jupiter v0 swap and reject tampering', async function () { + const jupiterBase64 = + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAFDTWoM5DBCGn7cn5aV56fomo6mhD2K1c5XYhQIan41E6dG9t06ox6DMdvVuBnSEATyN/8qIq246iO5aDm1jm82x4wM40FR8Q7xSZUpUtB0lbvelaZ46oRQ2GM9hWGMukHG1EUsA1R9ZO55ClUvNMyw8IQOrfRmu3ONG50oNeluT4LgaOacN+I4d0HStcu+oh0no4XXgVUwjzk5+egiUaQDkCCjXAlSDAb46ahLAfWeKOqzO/HC/z2WgRk8RS1yc6heMZzBbR3SPDwrNvWlCZGaETaixiH9ufdOJ823Gv+MnxH1SOu6TCsX1+TMskj94D3NElDpado8okFQbUuzaijU9oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIyXJY9OJInxuz0QKRSODYMLWhOZ2v8QhASOe9jb6fhZAwZGb+UhFzL/7K26csOb57yM5bvF9xJrLEObOkAAAAAEedVb8jHAbu50xW7OaBUH/bGy3qP0jlECsc2iVrwTjwbd9uHXZaGT2cvhRs7reawctIXtX1s3kTqM9YV+/wCp+mGpF4I4ZrV12bapJ7p61Babt3ty7HYDUKtMso38OYgHCgAFAooyBAAKAAkDoQ4BAAAAAAAIAgAFDAIAAAAwKyIAAAAAAAsFBQAgDAgJk/F7ZPSErnb/CQYABwAdCAwBAQs/HgAFDg0HIB0MDBwLJg8mEBIODSAdESYeDAwkJgIDBgsmGyYWGQ4EICUaJh4MDCQmGBcBCyIjDCEeBA0VExQfMtGYU5N8/tjpC0ANAwAAAAAAWqwAAAAAAAAyAAAAAAADAAAAJiwaAAMm5AwAAgoQJwIDDAMFAAABCQQpv5UHKk+/BN9xdZPnOLzMIScoFcJHGoDZ+fVVsNSEJQI0IwUAKA4CFyo9SDjsPdfWXAdMF0mu2+xZbw9rbR6rzNAEeFkLmyKwBGBmYWUAMHCJ6Oi0A1Qjpjp1Yv3xP+sPLm2qJ//TKZd5Z9KzjvEDwb3CA77DwOtKd1MCu6h4XJjC42yc8TcL92nhzFUR6HLW3XrAIZOvBo6Ki5CRjQOMk5Q='; + const original = VersionedTransaction.deserialize(Buffer.from(jupiterBase64, 'base64')); + const staticAccountKeys = original.message.staticAccountKeys.map((k) => k.toBase58()); + staticAccountKeys[0] = wallet.pub; + + const versionedData: VersionedTransactionData = { + versionedInstructions: original.message.compiledInstructions.map((ix) => ({ + programIdIndex: ix.programIdIndex, + accountKeyIndexes: ix.accountKeyIndexes, + data: base58.encode(ix.data), + })), + addressLookupTables: (original.message.addressTableLookups ?? []).map((lookup) => ({ + accountKey: lookup.accountKey.toBase58(), + writableIndexes: lookup.writableIndexes, + readonlyIndexes: lookup.readonlyIndexes, + })), + staticAccountKeys, + messageHeader: original.message.header, + recentBlockhash: original.message.recentBlockhash, + }; + + const built = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash) + .fromVersionedTransactionData(versionedData) + .build(); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txHex: Buffer.from(built.toBroadcastFormat(), 'base64').toString('hex') }, + wallet: walletObj, + } as any); + valid.should.equal(true); + + // Tamper with one instruction inside the Jupiter swap + const tamperedData: VersionedTransactionData = { + ...versionedData, + versionedInstructions: versionedData.versionedInstructions.map((ix, i) => + i === versionedData.versionedInstructions.length - 1 + ? { ...ix, data: base58.encode(Buffer.from([0xde, 0xad, 0xbe, 0xef])) } + : ix + ), + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/instruction\[\d+\] does not match/); + }); + + it('should reject a valid WP-injected nonce paired with a tampered user instruction', async function () { + const versionedData = makeAltVersionedData(); + const tamperedUserData: VersionedTransactionData = { + ...versionedData, + versionedInstructions: [ + { + ...versionedData.versionedInstructions[0], + data: base58.encode(Buffer.from([9, 9, 9, 9])), + }, + ], + }; + const tamperedWithNonceTx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }) + .fromVersionedTransactionData(tamperedUserData) + .build(); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedWithNonceTx.toBroadcastFormat() }, + durableNonce: { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/instruction\[1\] does not match/); + }); + }); }); describe('getAmountBasedOnEndianness', () => {