diff --git a/packages/wasm-solana/README.md b/packages/wasm-solana/README.md index b93b89d5414..7926fcf65db 100644 --- a/packages/wasm-solana/README.md +++ b/packages/wasm-solana/README.md @@ -1,5 +1,21 @@ # wasm-solana +## Legacy transaction decoding + +`Transaction.fromBytes()` accepts canonical, structurally valid legacy transaction +bytes up to Solana's 1232-byte packet limit. `signablePayload()` returns the +serialized Solana message; `toBytes()` preserves the transaction and signature +slots. The required signers are the first `numSignatures` entries of +`accountKeys()`, in the same order as `signatures`. Signature bytes are not +verified, and structural validity does not imply that a transaction can execute. + +`parseTransaction(tx)` is a best-effort semantic decoder, not an admission or +complete review result. Unrecognized instructions are returned as `Unknown` with +their data and message-requested account roles; recognized decodings may also +have limitations. Callers must explicitly determine whether the transaction is +supported. A reference legacy native-payment vector and its regeneration +procedure are documented in `test/fixtures/README.md`. + WASM bindings for Solana cryptographic operations. This package provides Rust-based bindings for Ed25519 keypair generation, public key operations, and signature verification for Solana. ## Building diff --git a/packages/wasm-solana/eslint.config.js b/packages/wasm-solana/eslint.config.js index ac914ad73ab..d1334ecccd2 100644 --- a/packages/wasm-solana/eslint.config.js +++ b/packages/wasm-solana/eslint.config.js @@ -13,7 +13,7 @@ export default tseslint.config( }, }, { - ignores: ["dist/", "pkg/", "target/", "node_modules/", "js/wasm/", "*.config.js"], + ignores: ["dist/", "pkg/", "target/", "node_modules/", "js/wasm/", "reference/", "*.config.js"], }, // Ban Node.js globals in production code { diff --git a/packages/wasm-solana/js/parser.ts b/packages/wasm-solana/js/parser.ts index 538582d203a..1ad3dfc38c9 100644 --- a/packages/wasm-solana/js/parser.ts +++ b/packages/wasm-solana/js/parser.ts @@ -120,9 +120,10 @@ export interface SetComputeUnitLimitParams { units: number; } -/** Set priority fee parameters */ +/** Compute-unit price; this is not the total transaction fee. */ export interface SetPriorityFeeParams { type: "SetPriorityFee"; + /** Micro-lamports per compute unit. */ fee: bigint; } @@ -192,10 +193,11 @@ export interface StakePoolWithdrawStakeParams { poolTokens: bigint; } -/** Account metadata for unknown instructions */ +/** Account metadata for unknown instructions, as requested by the message. */ export interface AccountMeta { pubkey: string; isSigner: boolean; + /** Requested writable role before any runtime demotion. */ isWritable: boolean; } @@ -241,7 +243,8 @@ export interface DurableNonce { } /** - * A fully parsed Solana transaction with decoded instructions. + * A best-effort semantic view of a Solana transaction. Unknown instructions + * remain explicit and do not establish complete transaction understanding. * * This structure matches BitGoJS's TxData interface for seamless integration. * All monetary amounts are returned as bigint directly from WASM. @@ -259,13 +262,13 @@ export interface ParsedTransaction { /** If this is a durable nonce transaction, contains the nonce info */ durableNonce?: DurableNonce; - /** All decoded instructions with semantic types */ + /** Best-effort instruction decodings, including explicit unknown instructions. */ instructionsData: InstructionParams[]; /** All account keys (base58 strings) */ accountKeys: string[]; - /** All signatures (base58 strings). Non-empty signatures indicate signed transaction. */ + /** Signature slots as base58 strings. Their validity has not been checked. */ signatures: string[]; } @@ -274,17 +277,17 @@ export interface ParsedTransaction { // ============================================================================= /** - * Parse a Transaction into a plain data object with decoded instructions. + * Parse a Transaction into a best-effort semantic view. * - * This is the main parsing function that returns structured data with all - * instructions decoded into semantic types (Transfer, StakingActivate, etc.) - * with amounts as bigint. + * Recognized instructions have semantic types such as Transfer, with amounts + * as bigint. Unknown instructions remain explicit; a successful parse does not + * establish that the whole transaction is understood or admitted for signing. * * Accepts a `Transaction` object (from `Transaction.fromBytes()`), avoiding * double deserialization. * * @param tx - A Transaction instance (from Transaction.fromBytes()) - * @returns A ParsedTransaction with all instructions decoded + * @returns A best-effort ParsedTransaction * * @example * ```typescript diff --git a/packages/wasm-solana/js/transaction.ts b/packages/wasm-solana/js/transaction.ts index ef2fa6e3db3..f96d04f01db 100644 --- a/packages/wasm-solana/js/transaction.ts +++ b/packages/wasm-solana/js/transaction.ts @@ -55,7 +55,8 @@ export class Transaction { private constructor(private _wasm: WasmTransaction) {} /** - * Deserialize a transaction from raw bytes + * Deserialize a canonical, structurally valid legacy transaction of at most + * 1232 bytes. Signature slots are preserved, but are not verified. * @param bytes - The raw transaction bytes * @returns A Transaction instance */ @@ -157,7 +158,8 @@ export class Transaction { /** * Get all signatures as byte arrays. * Provides compatibility with @solana/web3.js Transaction.signatures API. - * @returns Array of signature byte arrays + * @returns Unverified signature slots, in the same order as the required + * signer keys at the beginning of `accountKeys()`. */ get signatures(): Uint8Array[] { return Array.from(this._wasm.signatures()) as Uint8Array[]; diff --git a/packages/wasm-solana/reference/generate-native-payment.cjs b/packages/wasm-solana/reference/generate-native-payment.cjs new file mode 100644 index 00000000000..1c982079510 --- /dev/null +++ b/packages/wasm-solana/reference/generate-native-payment.cjs @@ -0,0 +1,46 @@ +// Test-only reference generator. Run with @solana/web3.js 1.66.1 on NODE_PATH. +// Every public key, signature byte and amount is independently invented. +const { + PublicKey, + SystemProgram, + Transaction, + TransactionInstruction, + ComputeBudgetProgram, +} = require("@solana/web3.js"); + +function key(byte) { + return new PublicKey(Buffer.alloc(32, byte)); +} + +const source = key(1); +const nonceAuthority = key(2); +const nonceAccount = key(3); +const destination = key(4); +const blockhash = key(5).toBase58(); +const memoProgram = new PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr"); + +const tx = new Transaction({ feePayer: source, recentBlockhash: blockhash }); +tx.add(SystemProgram.nonceAdvance({ noncePubkey: nonceAccount, authorizedPubkey: nonceAuthority })); +tx.add(ComputeBudgetProgram.setComputeUnitLimit({ units: 200000 })); +tx.add( + new TransactionInstruction({ programId: memoProgram, keys: [], data: Buffer.from("synthetic") }), +); +tx.add(SystemProgram.transfer({ fromPubkey: source, toPubkey: destination, lamports: 123456789 })); +tx.add(SystemProgram.transfer({ fromPubkey: source, toPubkey: destination, lamports: 0 })); +tx.addSignature(nonceAuthority, Buffer.alloc(64, 9)); // unverified test bytes + +const message = tx.compileMessage(); +const output = { + reference: "@solana/web3.js 1.66.1", + transactionBase64: tx + .serialize({ requireAllSignatures: false, verifySignatures: false }) + .toString("base64"), + messageBase64: tx.serializeMessage().toString("base64"), + source: source.toBase58(), + nonceAuthority: nonceAuthority.toBase58(), + nonceAccount: nonceAccount.toBase58(), + destination: destination.toBase58(), + blockhash, + accountKeys: message.accountKeys.map((address) => address.toBase58()), +}; +process.stdout.write(`${JSON.stringify(output, null, 2)}\n`); diff --git a/packages/wasm-solana/src/instructions/decode.rs b/packages/wasm-solana/src/instructions/decode.rs index 09de2403537..f96528f7ebd 100644 --- a/packages/wasm-solana/src/instructions/decode.rs +++ b/packages/wasm-solana/src/instructions/decode.rs @@ -11,6 +11,7 @@ use spl_stake_pool::instruction::StakePoolInstruction; pub struct InstructionContext<'a> { pub program_id: &'a str, pub accounts: &'a [String], + pub account_metas: &'a [AccountMeta], pub data: &'a [u8], } @@ -36,10 +37,13 @@ fn decode_system_instruction(ctx: InstructionContext) -> ParsedInstruction { let Ok(instr) = bincode::deserialize::(ctx.data) else { return make_unknown(ctx); }; + if bincode::serialize(&instr).ok().as_deref() != Some(ctx.data) { + return make_unknown(ctx); + } match instr { SystemInstruction::Transfer { lamports } => { - if ctx.accounts.len() >= 2 { + if ctx.accounts.len() == 2 { ParsedInstruction::Transfer(TransferParams { from_address: ctx.accounts[0].clone(), to_address: ctx.accounts[1].clone(), @@ -67,7 +71,7 @@ fn decode_system_instruction(ctx: InstructionContext) -> ParsedInstruction { } } SystemInstruction::AdvanceNonceAccount => { - if ctx.accounts.len() >= 3 { + if ctx.accounts.len() == 3 && ctx.accounts[1] == SYSVAR_RECENT_BLOCKHASHES { ParsedInstruction::NonceAdvance(NonceAdvanceParams { wallet_nonce_address: ctx.accounts[0].clone(), auth_wallet_address: ctx.accounts[2].clone(), // authority is at index 2 @@ -454,15 +458,7 @@ fn decode_stake_pool_instruction(ctx: InstructionContext) -> ParsedInstruction { fn make_unknown(ctx: InstructionContext) -> ParsedInstruction { ParsedInstruction::Unknown(UnknownInstructionParams { program_id: ctx.program_id.to_string(), - accounts: ctx - .accounts - .iter() - .map(|a| AccountMeta { - pubkey: a.clone(), - is_signer: false, // We don't have this info at decode time - is_writable: false, // We don't have this info at decode time - }) - .collect(), + accounts: ctx.account_metas.to_vec(), data: ctx.data.to_vec(), }) } diff --git a/packages/wasm-solana/src/instructions/mod.rs b/packages/wasm-solana/src/instructions/mod.rs index a66f43d26c0..6fb760c9704 100644 --- a/packages/wasm-solana/src/instructions/mod.rs +++ b/packages/wasm-solana/src/instructions/mod.rs @@ -1,10 +1,8 @@ -//! Internal instruction decoders using official Solana interface crates. -//! -//! This module is NOT publicly exposed. It's used internally by `parseTransaction`. +//! Parsed instruction types used by the existing transaction parser. mod decode; mod try_into_js_value; mod types; pub(crate) use decode::{decode_instruction, InstructionContext}; -pub(crate) use types::*; +pub use types::*; diff --git a/packages/wasm-solana/src/instructions/types.rs b/packages/wasm-solana/src/instructions/types.rs index 946bb53a363..41e17a8a961 100644 --- a/packages/wasm-solana/src/instructions/types.rs +++ b/packages/wasm-solana/src/instructions/types.rs @@ -176,6 +176,7 @@ pub struct SetComputeUnitLimitParams { #[derive(Debug, Clone)] pub struct SetPriorityFeeParams { + /// Compute-unit price in micro-lamports per unit, not the total fee. pub fee: u64, } diff --git a/packages/wasm-solana/src/lib.rs b/packages/wasm-solana/src/lib.rs index 06fdea4e3f5..6a5afd04138 100644 --- a/packages/wasm-solana/src/lib.rs +++ b/packages/wasm-solana/src/lib.rs @@ -24,10 +24,10 @@ //! ``` mod error; -mod instructions; +pub mod instructions; pub mod intent; pub mod keypair; -mod parser; +pub mod parser; pub mod pubkey; pub mod transaction; pub mod versioned; diff --git a/packages/wasm-solana/src/parser.rs b/packages/wasm-solana/src/parser.rs index 6882f78cb32..a66e5d40584 100644 --- a/packages/wasm-solana/src/parser.rs +++ b/packages/wasm-solana/src/parser.rs @@ -1,22 +1,22 @@ //! High-level transaction parser. //! -//! Provides a single `parse_transaction` function that deserializes transaction bytes -//! and decodes all instructions into semantic types matching BitGoJS's TxData format. +//! Best-effort semantic decoding of instructions matching BitGoJS's TxData format. +//! Unknown instructions remain explicit and are not an admission or review result. //! //! This parser returns raw decoded instructions. Instruction combining (e.g., //! CreateAccount + NonceInitialize → CreateNonceAccount) is handled by the //! TypeScript consumer (mapWasmInstructionsToBitGoJS in BitGoJS). -use crate::instructions::{decode_instruction, InstructionContext, ParsedInstruction}; +use crate::instructions::{decode_instruction, AccountMeta, InstructionContext, ParsedInstruction}; use crate::js_obj; use crate::transaction::Transaction; use crate::versioned::VersionedTransactionExt; use crate::wasm::try_into_js_value::{JsConversionError, TryIntoJsValue}; -use solana_message::VersionedMessage; +use solana_message::{MessageHeader, VersionedMessage}; use solana_transaction::versioned::VersionedTransaction; use wasm_bindgen::JsValue; -/// A fully parsed Solana transaction with decoded instructions. +/// A best-effort semantic view of a Solana transaction. /// /// This structure matches BitGoJS's `TxData` interface for seamless integration. #[derive(Debug, Clone)] @@ -39,7 +39,7 @@ pub struct ParsedTransaction { /// All account keys (base58 strings). pub account_keys: Vec, - /// All signatures (base58 strings). Non-empty signatures indicate signed transaction. + /// Signature slots as base58 strings; their validity has not been checked. pub signatures: Vec, } @@ -82,25 +82,24 @@ impl TryIntoJsValue for ParsedTransaction { /// * `bytes` - The raw transaction bytes (wire format) /// /// # Returns -/// A `ParsedTransaction` with all instructions decoded to semantic types. -pub fn parse_transaction(bytes: &[u8]) -> Result { +/// A best-effort `ParsedTransaction` that may contain unknown instructions. +pub(crate) fn parse_transaction(bytes: &[u8]) -> Result { // Deserialize the transaction - VersionedTransaction handles both legacy and V0 let tx = VersionedTransaction::from_bytes(bytes).map_err(|e| e.to_string())?; // Extract account keys and instructions based on message type - let (account_keys, instructions, recent_blockhash, num_required_signatures) = match &tx.message - { + let (account_keys, instructions, recent_blockhash, header) = match &tx.message { VersionedMessage::Legacy(msg) => ( msg.account_keys.iter().map(|k| k.to_string()).collect(), &msg.instructions[..], msg.recent_blockhash.to_string(), - msg.header.num_required_signatures, + &msg.header, ), VersionedMessage::V0(msg) => ( msg.account_keys.iter().map(|k| k.to_string()).collect(), &msg.instructions[..], msg.recent_blockhash.to_string(), - msg.header.num_required_signatures, + &msg.header, ), }; @@ -108,15 +107,16 @@ pub fn parse_transaction(bytes: &[u8]) -> Result { account_keys, instructions, recent_blockhash, - num_required_signatures, + header, &tx.signatures, ) } /// Parse a pre-deserialized legacy Transaction into structured data. /// -/// Same logic as `parse_transaction(bytes)` but skips deserialization. -/// Used when the caller already has a `Transaction` from `fromBytes()`. +/// Use a `Transaction` returned by `TransactionExt::from_bytes` when strict +/// legacy wire validation is required. Parsing is best-effort and does not +/// validate signatures or establish that the transaction is understood. pub fn parse_from_transaction(tx: &Transaction) -> Result { let msg = &tx.message; let account_keys: Vec = msg.account_keys.iter().map(|k| k.to_string()).collect(); @@ -125,7 +125,7 @@ pub fn parse_from_transaction(tx: &Transaction) -> Result, instructions: &[solana_message::compiled_instruction::CompiledInstruction], recent_blockhash: String, - num_required_signatures: u8, + header: &MessageHeader, signatures: &[solana_signature::Signature], ) -> Result { // Extract fee payer (first account key) @@ -144,6 +144,16 @@ fn parse_transaction_inner( .cloned() .ok_or("Transaction has no account keys")?; + let signed = usize::from(header.num_required_signatures); + let writable_signed = signed + .checked_sub(usize::from(header.num_readonly_signed_accounts)) + .ok_or("invalid signed account header")?; + let writable_unsigned_end = account_keys + .len() + .checked_sub(usize::from(header.num_readonly_unsigned_accounts)) + .filter(|end| *end >= signed) + .ok_or("invalid unsigned account header")?; + // Decode all instructions let mut instructions_data = Vec::with_capacity(instructions.len()); let mut durable_nonce = None; @@ -156,16 +166,38 @@ fn parse_transaction_inner( .ok_or_else(|| format!("Invalid program_id_index in instruction {}", idx))?; // Resolve account indices to addresses - let accounts: Vec = instruction + let account_metas: Vec = instruction .accounts .iter() - .filter_map(|&i| account_keys.get(i as usize).cloned()) + .map(|&i| { + let index = usize::from(i); + let pubkey = account_keys.get(index).cloned().ok_or_else(|| { + format!( + "instruction {} references unresolved account index {}", + idx, index + ) + })?; + Ok(AccountMeta { + pubkey, + is_signer: index < signed, + is_writable: if index < signed { + index < writable_signed + } else { + index < writable_unsigned_end + }, + }) + }) + .collect::>()?; + let accounts: Vec = account_metas + .iter() + .map(|meta| meta.pubkey.clone()) .collect(); // Decode the instruction let ctx = InstructionContext { program_id: &program_id, accounts: &accounts, + account_metas: &account_metas, data: &instruction.data, }; let parsed = decode_instruction(ctx); @@ -203,7 +235,7 @@ fn parse_transaction_inner( Ok(ParsedTransaction { fee_payer, - num_signatures: num_required_signatures, + num_signatures: header.num_required_signatures, nonce: recent_blockhash, durable_nonce, instructions_data, diff --git a/packages/wasm-solana/src/transaction.rs b/packages/wasm-solana/src/transaction.rs index 08f47d84756..ae81bc37995 100644 --- a/packages/wasm-solana/src/transaction.rs +++ b/packages/wasm-solana/src/transaction.rs @@ -13,6 +13,7 @@ use crate::error::WasmSolanaError; use solana_address::Address; +use solana_sdk::sanitize::Sanitize; use solana_signature::Signature; use std::str::FromStr; @@ -21,7 +22,7 @@ pub use solana_transaction::Transaction; /// Extension trait for Transaction to add WASM-friendly methods. pub trait TransactionExt { - /// Deserialize a transaction from raw bytes (wire format). + /// Deserialize a canonical, structurally valid legacy transaction. fn from_bytes(bytes: &[u8]) -> Result; /// Get the fee payer address as base58 string. @@ -54,8 +55,28 @@ pub trait TransactionExt { impl TransactionExt for Transaction { fn from_bytes(bytes: &[u8]) -> Result { - bincode::deserialize(bytes) - .map_err(|e| WasmSolanaError::new(&format!("Failed to deserialize transaction: {}", e))) + // A packet can hold at most 19 signatures. Reject impossible signature + // counts before serde can reserve a vector based on untrusted input. + const MAX_PACKET_BYTES: usize = 1232; + let invalid = + || WasmSolanaError::new("Failed to deserialize transaction: invalid wire format"); + if bytes.len() > MAX_PACKET_BYTES { + return Err(invalid()); + } + let count = usize::from(*bytes.first().ok_or_else(invalid)?); + if count > (MAX_PACKET_BYTES - 1) / 64 || 1 + count * 64 >= bytes.len() { + return Err(invalid()); + } + + let transaction: Transaction = bincode::deserialize(bytes).map_err(|_| invalid())?; + transaction.sanitize().map_err(|_| invalid())?; + if transaction.signatures.len() + != usize::from(transaction.message.header.num_required_signatures) + || bincode::serialize(&transaction).map_err(|_| invalid())? != bytes + { + return Err(invalid()); + } + Ok(transaction) } fn fee_payer_string(&self) -> Option { @@ -88,7 +109,7 @@ impl TransactionExt for Transaction { let num_signers = self.message.header.num_required_signatures as usize; // Use the same pattern as Solana's get_signing_keypair_positions - let signed_keys = &self.message.account_keys[0..num_signers]; + let signed_keys = self.message.account_keys.get(..num_signers)?; signed_keys.iter().position(|x| *x == target_address) } diff --git a/packages/wasm-solana/test/fixtures/README.md b/packages/wasm-solana/test/fixtures/README.md new file mode 100644 index 00000000000..0b7206a31e3 --- /dev/null +++ b/packages/wasm-solana/test/fixtures/README.md @@ -0,0 +1,15 @@ +# Native payment reference + +`native-payment.json` is an independently invented protocol vector generated by +published `@solana/web3.js` 1.66.1. It contains no keys or production data. The +nonzero signature slot is synthetic and unverified. It tests a legacy transaction +with a separate durable-nonce authority, compute limit, memo and ordered native +transfers (including a zero amount). It is not a genuine WP/TAT producer export. + +With that exact reference package installed externally, regenerate and compare: + +```sh +NODE_PATH=/path/to/reference/node_modules node reference/generate-native-payment.cjs | diff -u test/fixtures/native-payment.json - +``` + +The package is used only to generate test data; it is not a runtime dependency. diff --git a/packages/wasm-solana/test/fixtures/native-payment.json b/packages/wasm-solana/test/fixtures/native-payment.json new file mode 100644 index 00000000000..46dccae9f81 --- /dev/null +++ b/packages/wasm-solana/test/fixtures/native-payment.json @@ -0,0 +1,20 @@ +{ + "reference": "@solana/web3.js 1.66.1", + "transactionBase64": "AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJAgEECAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADBkZv5SEXMv/srbpyw5vnvIzlu8X3EmssQ5s6QAAAAAVKU1qZKSEGTSTocWDaOHx8NbXdvJK7geQfqEBBBUSNBqfVFxksVo7gioRfc9KXiM8DXDFFshqzRNgGLqlAAAAFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEAwIHAQQEAAAABQAFAkANAwAGAAlzeW50aGV0aWMEAgADDAIAAAAVzVsHAAAAAAQCAAMMAgAAAAAAAAAAAAAA", + "messageBase64": "AgEECAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADBkZv5SEXMv/srbpyw5vnvIzlu8X3EmssQ5s6QAAAAAVKU1qZKSEGTSTocWDaOHx8NbXdvJK7geQfqEBBBUSNBqfVFxksVo7gioRfc9KXiM8DXDFFshqzRNgGLqlAAAAFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEAwIHAQQEAAAABQAFAkANAwAGAAlzeW50aGV0aWMEAgADDAIAAAAVzVsHAAAAAAQCAAMMAgAAAAAAAAAAAAAA", + "source": "4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi", + "nonceAuthority": "8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR", + "nonceAccount": "CktRuQ2mttgRGkXJtyksdKHjUdc2C4TgDzyB98oEzy8", + "destination": "GgBaCs3NCBuZN12kCJgAW63ydqohFkHEdfdEXBPzLHq", + "blockhash": "LbUiWL3xVV8hTFYBVdbTNrpDo41NKS6o3LHHuDzjfcY", + "accountKeys": [ + "4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi", + "8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR", + "CktRuQ2mttgRGkXJtyksdKHjUdc2C4TgDzyB98oEzy8", + "GgBaCs3NCBuZN12kCJgAW63ydqohFkHEdfdEXBPzLHq", + "11111111111111111111111111111111", + "ComputeBudget111111111111111111111111111111", + "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr", + "SysvarRecentB1ockHashes11111111111111111111" + ] +} diff --git a/packages/wasm-solana/test/nativePayment.ts b/packages/wasm-solana/test/nativePayment.ts new file mode 100644 index 00000000000..b76d13af34d --- /dev/null +++ b/packages/wasm-solana/test/nativePayment.ts @@ -0,0 +1,120 @@ +import * as assert from "assert"; +import { createRequire } from "node:module"; +import { parseTransaction } from "../js/parser.js"; +import { Transaction } from "../js/transaction.js"; + +const value: unknown = createRequire(import.meta.url)("./fixtures/native-payment.json"); +function isRecord(input: unknown): input is Record { + return typeof input === "object" && input !== null && !Array.isArray(input); +} +if (!isRecord(value)) { + throw new TypeError("invalid reference fixture"); +} +const fixture: Record = value; + +function text(key: string): string { + if (!(key in fixture) || typeof fixture[key] !== "string") { + throw new TypeError(`invalid fixture field ${key}`); + } + return fixture[key]; +} + +const bytes = Buffer.from(text("transactionBase64"), "base64"); + +describe("legacy native payment reference", () => { + it("preserves message, signer slots, roles, nonce and transfer order", () => { + const tx = Transaction.fromBytes(bytes); + assert.deepStrictEqual(Buffer.from(tx.toBytes()), bytes); + assert.deepStrictEqual( + Buffer.from(tx.signablePayload()), + Buffer.from(text("messageBase64"), "base64"), + ); + assert.strictEqual(tx.feePayer, text("source")); + assert.strictEqual(tx.recentBlockhash, text("blockhash")); + assert.strictEqual(tx.signerIndex(text("source")), 0); + assert.strictEqual(tx.signerIndex(text("nonceAuthority")), 1); + assert.deepStrictEqual(tx.signatures[0], new Uint8Array(64)); + assert.deepStrictEqual(tx.signatures[1], new Uint8Array(64).fill(9)); + + const nonceAccounts = tx.instructions[0].accounts; + assert.deepStrictEqual( + nonceAccounts.map((account) => [account.pubkey, account.isSigner, account.isWritable]), + [ + [text("nonceAccount"), false, true], + ["SysvarRecentB1ockHashes11111111111111111111", false, false], + [text("nonceAuthority"), true, false], + ], + ); + const parsed = parseTransaction(tx); + assert.deepStrictEqual( + parsed.instructionsData.map((item) => item.type), + ["NonceAdvance", "SetComputeUnitLimit", "Memo", "Transfer", "Transfer"], + ); + assert.deepStrictEqual(parsed.durableNonce, { + walletNonceAddress: text("nonceAccount"), + authWalletAddress: text("nonceAuthority"), + }); + const transfers = parsed.instructionsData.slice(3); + assert.deepStrictEqual( + transfers, + [123456789n, 0n].map((amount) => ({ + type: "Transfer", + fromAddress: text("source"), + toAddress: text("destination"), + amount, + })), + ); + }); + + it("rejects truncation, trailing bytes, invalid signature count and oversized packets", () => { + assert.throws(() => Transaction.fromBytes(bytes.subarray(0, bytes.length - 1))); + assert.throws(() => Transaction.fromBytes(Buffer.concat([bytes, Buffer.from([0])]))); + assert.throws(() => Transaction.fromBytes(new Uint8Array(1233))); + assert.throws(() => Transaction.fromBytes(Uint8Array.of(255, 255, 3))); + const mismatchedSlots = Buffer.from(bytes); + mismatchedSlots[1 + 2 * 64] = 3; + assert.throws(() => Transaction.fromBytes(mismatchedSlots)); + }); + + it("preserves native amounts beyond the JavaScript safe integer range", () => { + const data = Buffer.from([2, 0, 0, 0, 21, 205, 91, 7, 0, 0, 0, 0]); + const offset = bytes.indexOf(data); + assert.ok(offset > 0); + const altered = Buffer.from(bytes); + const amount = (1n << 60n) + 7n; + altered.writeBigUInt64LE(amount, offset + 4); + const transfer = parseTransaction(Transaction.fromBytes(altered)).instructionsData[3]; + assert.strictEqual(transfer.type, "Transfer"); + if (transfer.type !== "Transfer") throw new Error("expected transfer"); + assert.strictEqual(transfer.amount, amount); + }); + + it("keeps noncanonical transfer data unknown and preserves its account roles", () => { + const data = Buffer.from([2, 0, 0, 0, 21, 205, 91, 7, 0, 0, 0, 0]); + const offset = bytes.indexOf(data); + assert.ok(offset > 0); + assert.strictEqual(bytes[offset - 1], data.length); + const altered = Buffer.concat([ + bytes.subarray(0, offset - 1), + Buffer.from([data.length + 1]), + data, + Buffer.from([42]), + bytes.subarray(offset + data.length), + ]); + const parsed = parseTransaction(Transaction.fromBytes(altered)); + const instruction = parsed.instructionsData[3]; + assert.strictEqual(instruction.type, "Unknown"); + if (instruction.type !== "Unknown") throw new Error("expected unknown instruction"); + assert.deepStrictEqual( + instruction.accounts.map((account) => [account.pubkey, account.isSigner, account.isWritable]), + [ + [text("source"), true, true], + [text("destination"), false, true], + ], + ); + assert.strictEqual( + instruction.data, + Buffer.concat([data, Buffer.from([42])]).toString("base64"), + ); + }); +}); diff --git a/packages/wasm-solana/tests/native_payment.rs b/packages/wasm-solana/tests/native_payment.rs new file mode 100644 index 00000000000..5a62cf889ab --- /dev/null +++ b/packages/wasm-solana/tests/native_payment.rs @@ -0,0 +1,132 @@ +use base64::{engine::general_purpose::STANDARD, Engine}; +use wasm_solana::{ + instructions::ParsedInstruction, + parser::parse_from_transaction, + transaction::{Transaction, TransactionExt}, +}; + +fn fixture() -> serde_json::Value { + serde_json::from_str(include_str!("../test/fixtures/native-payment.json")).unwrap() +} + +fn bytes() -> Vec { + STANDARD + .decode(fixture()["transactionBase64"].as_str().unwrap()) + .unwrap() +} + +#[test] +fn preserves_reference_message_signer_slots_and_native_payment() { + let expected = fixture(); + let input = bytes(); + let tx = Transaction::from_bytes(&input).unwrap(); + assert_eq!(tx.to_bytes().unwrap(), input); + assert_eq!( + tx.signable_payload(), + STANDARD + .decode(expected["messageBase64"].as_str().unwrap()) + .unwrap() + ); + assert_eq!(tx.signatures[0].as_ref(), &[0; 64]); + assert_eq!(tx.signatures[1].as_ref(), &[9; 64]); + assert_eq!( + tx.signer_index(expected["source"].as_str().unwrap()), + Some(0) + ); + assert_eq!( + tx.signer_index(expected["nonceAuthority"].as_str().unwrap()), + Some(1) + ); + + let parsed = parse_from_transaction(&tx).unwrap(); + assert_eq!(parsed.instructions_data.len(), 5); + match &parsed.instructions_data[0] { + ParsedInstruction::NonceAdvance(nonce) => { + assert_eq!( + nonce.wallet_nonce_address, + expected["nonceAccount"].as_str().unwrap() + ); + assert_eq!( + nonce.auth_wallet_address, + expected["nonceAuthority"].as_str().unwrap() + ); + } + other => panic!("expected nonce advance, got {other:?}"), + } + for (index, amount) in [(3, 123_456_789), (4, 0)] { + match &parsed.instructions_data[index] { + ParsedInstruction::Transfer(transfer) => { + assert_eq!(transfer.from_address, expected["source"].as_str().unwrap()); + assert_eq!( + transfer.to_address, + expected["destination"].as_str().unwrap() + ); + assert_eq!(transfer.amount, amount); + } + other => panic!("expected native transfer, got {other:?}"), + } + } +} + +#[test] +fn rejects_malformed_noncanonical_and_oversized_transactions() { + let input = bytes(); + for end in 0..input.len() { + assert!( + Transaction::from_bytes(&input[..end]).is_err(), + "truncation at {end}" + ); + } + let mut trailing = input.clone(); + trailing.push(0); + assert!(Transaction::from_bytes(&trailing).is_err()); + assert!(Transaction::from_bytes(&vec![0; 1233]).is_err()); + assert!(Transaction::from_bytes(&[0xff, 0xff, 0x03]).is_err()); + + let mut tx = Transaction::from_bytes(&input).unwrap(); + tx.message.header.num_required_signatures = 3; + assert!(Transaction::from_bytes(&tx.to_bytes().unwrap()).is_err()); + let mut tx = Transaction::from_bytes(&input).unwrap(); + tx.message.instructions[0].accounts[0] = 255; + assert!(Transaction::from_bytes(&tx.to_bytes().unwrap()).is_err()); + let mut tx = Transaction::from_bytes(&input).unwrap(); + tx.signatures.pop(); + assert!(Transaction::from_bytes(&tx.to_bytes().unwrap()).is_err()); +} + +#[test] +fn unknown_instruction_keeps_bytes_and_requested_roles() { + let mut tx = Transaction::from_bytes(&bytes()).unwrap(); + tx.message.instructions[3].data.push(42); // trailing data must not become a Transfer + let parsed = parse_from_transaction(&tx).unwrap(); + match &parsed.instructions_data[3] { + ParsedInstruction::Unknown(instruction) => { + assert_eq!(instruction.data, tx.message.instructions[3].data); + assert_eq!(instruction.accounts.len(), 2); + assert!(instruction.accounts[0].is_signer); + assert!(instruction.accounts[0].is_writable); + assert!(!instruction.accounts[1].is_signer); + assert!(instruction.accounts[1].is_writable); + } + other => panic!("unexpected semantic claim: {other:?}"), + } +} + +#[test] +fn parser_does_not_silently_drop_unresolved_operands() { + let mut tx = Transaction::from_bytes(&bytes()).unwrap(); + tx.message.instructions[3].accounts[1] = 255; + assert!(parse_from_transaction(&tx).is_err()); +} + +#[test] +fn nonce_with_wrong_sysvar_remains_unknown() { + let mut tx = Transaction::from_bytes(&bytes()).unwrap(); + tx.message.instructions[0].accounts[1] = 3; + let parsed = parse_from_transaction(&tx).unwrap(); + assert!(matches!( + parsed.instructions_data[0], + ParsedInstruction::Unknown(_) + )); + assert!(parsed.durable_nonce.is_none()); +}