Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraSolanaTests/SolanaTransactionTests.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0512// Last Modified : 2026-12-0513//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraCore43import QyvoraEd2551944import QyvoraMath45import Testing46@testable import QyvoraSolana4748func hex(_ s: some StringProtocol) -> Bytes { Bytes(hex: String(s))! }49func key(_ s: some StringProtocol) -> SolanaPublicKey { SolanaPublicKey(base58: String(s))! }50func fields(_ line: Substring) -> [Substring] { line.split(separator: "|", omittingEmptySubsequences: false) }51func lines(_ text: String) -> [Substring] { text.split(separator: "\n") }5253enum Fixture {54 static let payerSeed = hex(ReferenceVectors.payerSeed)55 static let payer = key(ReferenceVectors.payer)56 static let other = key(ReferenceVectors.other)57 static let third = key(ReferenceVectors.third)58 static let blockhash = Base58.bitcoin.decode(ReferenceVectors.blockhash)!59 static let usdc = key("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")60 static let usdt = key("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB")61 static let pyusd = key("2b1kV6DkPAnxd5ixfnxCpjxmKwqjjaYmCZfHsFu24GXo")6263 /// name → (message, unsigned transaction, signed transaction, signature)64 static let legacy: [String: (message: Bytes, unsigned: Bytes, signed: Bytes, signature: String)] = {65 var out = [String: (message: Bytes, unsigned: Bytes, signed: Bytes, signature: String)]()66 for line in lines(ReferenceVectors.legacyTransactions) {67 let f = fields(line)68 out[String(f[0])] = (hex(f[1]), hex(f[2]), hex(f[3]), String(f[4]))69 }70 return out71 }()7273 static let solTransfer = SolanaSystemProgram.transfer(from: payer, to: other, lamports: 1_234_567_890)7475 static func tokenInstructions(mint: SolanaPublicKey, program: SolanaTokenProgram.Kind, to owner: SolanaPublicKey, amount: UInt64,76 create: Bool) throws -> [SolanaInstruction] {77 let source = try SolanaAddress.associatedTokenAccount(owner: payer, mint: mint, tokenProgram: program)78 let destination = try SolanaAddress.associatedTokenAccount(owner: owner, mint: mint, tokenProgram: program)79 var out = [SolanaComputeBudget.setComputeUnitLimit(program == .token ? 80_000 : 120_000), SolanaComputeBudget.setComputeUnitPrice(microLamports: 5_000)]80 if create {81 out.append(SolanaAssociatedTokenProgram.createIdempotent(payer: payer, associatedAccount: destination, owner: owner, mint: mint, tokenProgram: program))82 }83 out.append(SolanaTokenProgram.transferChecked(source: source, mint: mint, destination: destination, owner: payer, amount: amount, decimals: 6, program: program))84 return out85 }8687 /// The same instruction lists as the reference script `ref_sol.py`.88 static func instructions(_ name: String) throws -> [SolanaInstruction] {89 switch name {90 case "plainTransfer": return [solTransfer]91 case "transfer": return [SolanaComputeBudget.setComputeUnitLimit(5_000), SolanaComputeBudget.setComputeUnitPrice(microLamports: 12_345), solTransfer]92 case "transferMemo":93 return [SolanaComputeBudget.setComputeUnitLimit(25_000), SolanaComputeBudget.setComputeUnitPrice(microLamports: 5_000), solTransfer,94 SolanaMemoProgram.memo("hello Qyvora \u{2713}", signers: [payer])]95 case "tokenCreate": return try tokenInstructions(mint: usdc, program: .token, to: other, amount: 2_500_000, create: true)96 case "token": return try tokenInstructions(mint: usdt, program: .token, to: third, amount: .max, create: false)97 case "token2022Create": return try tokenInstructions(mint: pyusd, program: .token2022, to: other, amount: 1, create: true)98 default: throw SolanaError.malformed("unknown fixture \(name)")99 }100 }101}102103@Suite struct SolanaAddressTests {104 @Test func strictBase58() {105 let text = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"106 let k = SolanaPublicKey(base58: text)107 #expect(k != nil && k!.base58 == text && k!.bytes.count == 32 && k!.description == text)108 #expect(SolanaAddress.isValid(text))109 #expect(SolanaAddress.isValid("11111111111111111111111111111111"))110 #expect(SolanaProgram.system.bytes == Bytes(repeating: 0, count: 32))111 for bad in ["", " " + text, text + " ", text + "\n", text + "1", "0" + text.dropFirst(), "O" + text.dropFirst(),112 "l" + text.dropFirst(), "1111111111111111111111111111111", "111111111111111111111111111111111",113 "0x" + String(repeating: "ab", count: 32), String(repeating: "z", count: 44), "é" + text.dropFirst(2)] {114 #expect(!SolanaAddress.isValid(bad), "\(bad) must be refused")115 }116 // no checksum: an address that lost its last character is still a valid (different) address117 #expect(SolanaPublicKey(base58: String(text.dropLast())) != nil && SolanaPublicKey(base58: String(text.dropLast())) != k)118 #expect(SolanaPublicKey(bytes: Bytes(repeating: 1, count: 31)) == nil && SolanaPublicKey(bytes: Bytes(repeating: 1, count: 33)) == nil)119 // every 32-byte value round-trips120 for _ in 0..<500 {121 let bytes = SystemRandom.bytes(32)122 let k = SolanaPublicKey(bytes: bytes)!123 #expect(SolanaPublicKey(base58: k.base58) == k)124 }125 #expect(SolanaPublicKey(bytes: Bytes(repeating: 0, count: 32))! < SolanaPublicKey(bytes: [0] + Bytes(repeating: 1, count: 31))!)126 #expect(SolanaProgram.reserved.count == 16)127 #expect(SolanaTokenProgram.Kind(programID: SolanaProgram.token) == .token && SolanaTokenProgram.Kind(programID: SolanaProgram.token2022) == .token2022)128 #expect(SolanaTokenProgram.Kind(programID: SolanaProgram.system) == nil)129 }130131 /// Associated token accounts computed by solders (`Pubkey.find_program_address`) and solana-py.132 @Test func associatedTokenAccountVectors() throws {133 var count = 0134 for line in lines(ReferenceVectors.associatedTokenAccounts) {135 let f = fields(line)136 let program = try #require(SolanaTokenProgram.Kind(programID: key(f[2])))137 let (address, bump) = try SolanaAddress.findProgramAddress(seeds: [key(f[0]).bytes, key(f[2]).bytes, key(f[1]).bytes], programID: SolanaProgram.associatedToken)138 #expect(address == key(f[3]) && bump == UInt8(f[4])!)139 #expect(try SolanaAddress.associatedTokenAccount(owner: key(f[0]), mint: key(f[1]), tokenProgram: program) == key(f[3]))140 #expect(!address.isOnCurve)141 count += 1142 }143 #expect(count == 12)144 }145146 @Test func programDerivedAddressVectors() throws {147 var count = 0148 for line in lines(ReferenceVectors.programDerivedAddresses) {149 let f = fields(line)150 let seeds = f[0].isEmpty ? [] : f[0].split(separator: ",", omittingEmptySubsequences: false).map { hex($0) }151 let (address, bump) = try SolanaAddress.findProgramAddress(seeds: seeds, programID: key(f[1]))152 #expect(address == key(f[2]) && bump == UInt8(f[3])!, "PDA \(count)")153 #expect(SolanaAddress.createProgramAddress(seeds: seeds + [[bump]], programID: key(f[1])) == address)154 count += 1155 }156 #expect(count == 40)157 #expect(throws: SolanaError.invalidProgramAddressSeeds) {158 try SolanaAddress.findProgramAddress(seeds: [Bytes(repeating: 0, count: 33)], programID: SolanaProgram.system)159 }160 #expect(throws: SolanaError.invalidProgramAddressSeeds) {161 try SolanaAddress.findProgramAddress(seeds: Array(repeating: [1], count: 16), programID: SolanaProgram.system)162 }163 #expect(SolanaAddress.createProgramAddress(seeds: Array(repeating: [1], count: 17), programID: SolanaProgram.system) == nil)164 }165166 @Test func onCurveVectors() {167 var count = 0, on = 0168 for line in lines(ReferenceVectors.onCurve) {169 let f = fields(line)170 let k = SolanaPublicKey(bytes: hex(f[0]))!171 #expect(k.isOnCurve == (f[1] == "1"))172 if k.isOnCurve { on += 1 }173 count += 1174 }175 #expect(count == 64 && on > 0 && on < 64)176 }177178 /// "abandon … about": BIP-39 seed, SLIP-0010 keys and addresses computed by bip_utils + solders (and an179 /// independent HMAC implementation). m/44'/501'/0'/0' is the first Phantom / Solflare account.180 @Test func derivationVectors() throws {181 let words = BIP39.words(from: ReferenceVectors.mnemonic)182 let seed = try BIP39.seed(mnemonic: words)183 #expect(seed == hex(ReferenceVectors.bip39Seed))184 let expected: [(SolanaKeys.DerivationStyle, UInt32)] = [(.bip44Change, 0), (.bip44Change, 1), (.bip44Change, 2), (.bip44, 0), (.bip44Root, 0)]185 var count = 0186 for (line, (style, account)) in zip(lines(ReferenceVectors.derivation), expected) {187 let f = fields(line)188 #expect(SolanaKeys.derivationPath(account: account, style: style) == DerivationPath(String(f[0])))189 let secret = try SolanaKeys.privateSeed(bip39Seed: seed, account: account, style: style)190 #expect(secret == hex(f[1]), "private key at \(f[0])")191 #expect(try SolanaKeys.publicKey(privateSeed: secret) == key(f[2]))192 #expect(try SolanaKeys.address(bip39Seed: seed, account: account, style: style) == key(f[2]))193 count += 1194 }195 #expect(count == 5)196 #expect(try SolanaKeys.address(bip39Seed: seed).base58 == "HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk")197 #expect(SolanaKeys.derivationPath().description == "m/44'/501'/0'/0'")198 #expect(throws: SolanaError.invalidSeed) { try SolanaKeys.privateSeed(bip39Seed: [1, 2, 3]) }199 #expect(throws: SolanaError.invalidSeed) { try SolanaKeys.privateSeed(bip39Seed: seed, account: 0x8000_0000) }200 #expect(throws: SolanaError.invalidSeed) { try SolanaKeys.publicKey(privateSeed: [1]) }201 }202203 @Test func networks() {204 #expect(SolanaNetwork.allCases.map(\.rawValue) == ["mainnet-beta", "devnet", "testnet"])205 #expect(!SolanaNetwork.mainnetBeta.isTest && SolanaNetwork.devnet.isTest && SolanaNetwork.testnet.isTest)206 for network in SolanaNetwork.allCases {207 #expect(Base58.bitcoin.decode(network.genesisHash)?.count == 32)208 #expect(!SolanaEndpoints.default.urls(for: network).isEmpty)209 #expect(SolanaEndpoints.default.urls(for: network).allSatisfy { $0.scheme == "https" })210 }211 #expect(Set(SolanaNetwork.allCases.map(\.genesisHash)).count == 3)212 let custom = SolanaEndpoints(rpc: ["devnet": ["http://example.com", "ftp://x", "http://192.168.1.5:8899", "https://ok.example"]])213 #expect(custom.urls(for: .devnet).map(\.absoluteString) == ["http://192.168.1.5:8899", "https://ok.example"])214 #expect(custom.urls(for: .mainnetBeta).isEmpty)215 #expect(SolanaToken.builtIn(.mainnetBeta).map(\.symbol) == ["USDC", "USDT"])216 #expect(SolanaToken.builtIn(.mainnetBeta).map(\.mint) == [Fixture.usdc, Fixture.usdt])217 #expect(SolanaToken.builtIn(.devnet).isEmpty && SolanaToken.builtIn(.testnet).isEmpty)218 }219}220221@Suite struct SolanaWireFormatTests {222 @Test func compactU16() {223 #expect(SolanaCompactU16.encode(0) == [0] && SolanaCompactU16.encode(0x7f) == [0x7f] && SolanaCompactU16.encode(0x80) == [0x80, 0x01])224 #expect(SolanaCompactU16.encode(0x3fff) == [0xff, 0x7f] && SolanaCompactU16.encode(0x4000) == [0x80, 0x80, 0x01])225 #expect(SolanaCompactU16.encode(0xffff) == [0xff, 0xff, 0x03])226 for v in 0...0xffff {227 let encoded = SolanaCompactU16.encode(UInt16(v))228 var offset = 0229 #expect(SolanaCompactU16.decode(encoded + [0xaa], at: &offset) == UInt16(v) && offset == encoded.count)230 }231 for bad: Bytes in [[], [0x80], [0x80, 0x80], [0x80, 0x00], [0x80, 0x80, 0x00], [0xff, 0xff, 0x04], [0x80, 0x80, 0x80, 0x01], [0xff, 0xff, 0xff], [0x81, 0x00]] {232 var offset = 0233 #expect(SolanaCompactU16.decode(bad, at: &offset) == nil, "\(bad.hex) must be refused")234 }235 }236237 @Test func base64() {238 #expect(SolanaBase64.encode([]) == "" && SolanaBase64.encode(Bytes("f".utf8)) == "Zg==" && SolanaBase64.encode(Bytes("fo".utf8)) == "Zm8=")239 #expect(SolanaBase64.encode(Bytes("foobar".utf8)) == "Zm9vYmFy")240 for n in 0..<200 {241 let bytes = SystemRandom.bytes(n)242 let text = SolanaBase64.encode(bytes)243 #expect(text == Data(bytes).base64EncodedString())244 #expect(SolanaBase64.decode(text) == bytes)245 }246 for bad in ["Zg", "Zg=", "Z===", "Zg==Zg==", "Zm9v\n", " Zm9v", "Zm9-", "Zm9_", "Zh==", "Zm9=", "====", "Zg=a", "é==="] {247 #expect(SolanaBase64.decode(bad) == nil, "\(bad) must be refused")248 }249 }250251 /// Messages, unsigned and signed transactions and identifiers, byte for byte against solders / solana-py.252 @Test func legacyTransactionsMatchTheReference() throws {253 #expect(Fixture.legacy.count == 6)254 for (name, reference) in Fixture.legacy {255 let message = try SolanaMessage(feePayer: Fixture.payer, instructions: try Fixture.instructions(name), recentBlockhash: Fixture.blockhash)256 #expect(message.serialize() == reference.message, "message of \(name)")257 var transaction = SolanaTransaction(message: message)258 #expect(try transaction.serialize() == reference.unsigned, "unsigned \(name)")259 #expect(!transaction.isFullySigned && transaction.id == nil && !transaction.verifySignatures())260 try transaction.sign(privateSeed: Fixture.payerSeed)261 #expect(try transaction.serialize() == reference.signed, "signed \(name)")262 #expect(transaction.id == reference.signature)263 #expect(transaction.isFullySigned && transaction.verifySignatures())264 #expect(try transaction.base64() == Data(reference.signed).base64EncodedString())265 #expect(SolanaRPC.isSignature(reference.signature))266 }267 }268269 /// Three signers, a read-only signer, accounts shared between instructions with different roles.270 @Test func multiSignerOrderingMatchesTheReference() throws {271 let f = fields(lines(ReferenceVectors.multiSignerTransaction)[0])272 let memo = SolanaInstruction(programID: SolanaProgram.memo, accounts: [SolanaAccountMeta(Fixture.third, isSigner: true, isWritable: false),273 SolanaAccountMeta(Fixture.other, isSigner: true, isWritable: true)],274 data: Bytes("two signers".utf8))275 let custom = SolanaInstruction(programID: SolanaPublicKey(bytes: Bytes(repeating: 9, count: 32))!, accounts: [276 SolanaAccountMeta(Fixture.other, isSigner: false, isWritable: false), SolanaAccountMeta(Fixture.usdc, isSigner: false, isWritable: true),277 SolanaAccountMeta(Fixture.usdt, isSigner: false, isWritable: false), SolanaAccountMeta(Fixture.payer, isSigner: false, isWritable: false),278 SolanaAccountMeta(Fixture.usdc, isSigner: false, isWritable: false),279 ], data: Bytes(0..<40))280 let message = try SolanaMessage(feePayer: Fixture.payer, instructions: [memo, Fixture.solTransfer, custom], recentBlockhash: Fixture.blockhash)281 #expect(message.serialize() == hex(f[0]))282 #expect(message.accountKeys.map(\.base58) == f[2].split(separator: ",").map(String.init))283 #expect(message.numRequiredSignatures == 3 && message.numReadonlySignedAccounts == 1 && message.numReadonlyUnsignedAccounts == 4)284 #expect(message.signers == [Fixture.payer, Fixture.other, Fixture.third])285 var transaction = SolanaTransaction(message: message)286 // signing in any order fills the right slot287 for seed in ReferenceVectors.multiSeeds.reversed() {288 #expect(!transaction.isFullySigned)289 try transaction.sign(privateSeed: hex(seed))290 }291 #expect(try transaction.serialize() == hex(f[1]))292 #expect(transaction.verifySignatures())293 #expect(throws: SolanaError.notASigner) { try transaction.sign(privateSeed: Bytes(repeating: 0x55, count: 32)) }294 #expect(throws: SolanaError.invalidSeed) { try transaction.sign(privateSeed: [1, 2]) }295 // decoded roles296 let decoded = try SolanaTransaction.decode(hex(f[1]))297 #expect(decoded == transaction)298 #expect(decoded.message.isWritable(index: 0) && decoded.message.isWritable(index: 1) && !decoded.message.isWritable(index: 2))299 #expect(decoded.message.isWritable(index: 3) && !decoded.message.isWritable(index: 4) && !decoded.message.isWritable(index: 7))300 #expect(decoded.message.isSigner(index: 2) && !decoded.message.isSigner(index: 3))301 #expect(decoded.message.instruction(at: 0) == memo && decoded.message.instruction(at: 2)?.programID == custom.programID)302 #expect(decoded.message.instruction(at: 3) == nil)303 let review = decoded.message.review()304 #expect(review.requiresBlindSigning && review.signatureFee == 15_000 && review.priorityFee == 0)305 #expect(review.instructions[0] == .memo("two signers") && review.instructions[2].isUnknown)306 }307308 @Test func decodeRoundTripsAndReview() throws {309 for (name, reference) in Fixture.legacy {310 for bytes in [reference.unsigned, reference.signed] {311 let transaction = try SolanaTransaction.decode(bytes)312 #expect(try transaction.serialize() == bytes, "round trip of \(name)")313 #expect(transaction.message.serialize() == reference.message)314 #expect(try SolanaMessage.decode(reference.message) == transaction.message)315 #expect(try SolanaTransaction.decode(base64: SolanaBase64.encode(bytes)) == transaction)316 #expect(transaction.message.feePayer == Fixture.payer && transaction.message.version == .legacy)317 #expect(transaction.message.recentBlockhashBase58 == ReferenceVectors.blockhash)318 }319 let signed = try SolanaTransaction.decode(reference.signed)320 #expect(signed.verifySignatures() && signed.id == reference.signature)321 let review = signed.message.review()322 #expect(!review.requiresBlindSigning && !review.usesAddressLookupTables, "\(name) is fully decoded")323 #expect(review.signers == [Fixture.payer] && review.signatureFee == 5_000)324 #expect(review.instructions.allSatisfy { !$0.summary.isEmpty })325 }326 let transfer = try SolanaTransaction.decode(Fixture.legacy["transfer"]!.signed).message.review()327 #expect(transfer.instructions == [.computeUnitLimit(units: 5_000), .computeUnitPrice(microLamports: 12_345),328 .systemTransfer(from: Fixture.payer, to: Fixture.other, lamports: 1_234_567_890)])329 #expect(transfer.priorityFee == 62) // ⌈5000 × 12345 / 10^6⌉330 #expect(try SolanaTransaction.decode(Fixture.legacy["plainTransfer"]!.signed).message.review().priorityFee == 0)331 let memo = try SolanaTransaction.decode(Fixture.legacy["transferMemo"]!.signed).message.review()332 #expect(memo.instructions.last == .memo("hello Qyvora \u{2713}"))333334 let tokenCreate = try SolanaTransaction.decode(Fixture.legacy["tokenCreate"]!.signed).message.review()335 let source = try SolanaAddress.associatedTokenAccount(owner: Fixture.payer, mint: Fixture.usdc)336 let destination = try SolanaAddress.associatedTokenAccount(owner: Fixture.other, mint: Fixture.usdc)337 #expect(tokenCreate.instructions == [338 .computeUnitLimit(units: 80_000), .computeUnitPrice(microLamports: 5_000),339 .createAssociatedTokenAccount(payer: Fixture.payer, associatedAccount: destination, owner: Fixture.other, mint: Fixture.usdc,340 tokenProgram: SolanaProgram.token, idempotent: true),341 .tokenTransferChecked(program: .token, source: source, mint: Fixture.usdc, destination: destination, authority: Fixture.payer,342 amount: 2_500_000, decimals: 6),343 ])344 #expect(tokenCreate.priorityFee == 400)345 let token = try SolanaTransaction.decode(Fixture.legacy["token"]!.signed).message.review()346 if case .tokenTransferChecked(let program, _, let mint, _, _, let amount, _) = token.instructions[2] {347 #expect(program == .token && mint == Fixture.usdt && amount == .max)348 } else {349 Issue.record("expected TransferChecked")350 }351 let token2022 = try SolanaTransaction.decode(Fixture.legacy["token2022Create"]!.signed).message.review()352 if case .tokenTransferChecked(let program, _, let mint, _, _, let amount, _) = token2022.instructions[3] {353 #expect(program == .token2022 && mint == Fixture.pyusd && amount == 1)354 } else {355 Issue.record("expected TransferChecked")356 }357 }358359 @Test func signatureTamperingIsDetected() throws {360 let reference = Fixture.legacy["transfer"]!361 for position in [1, 30, 64, 65 + 3, reference.signed.count - 1] {362 var bytes = reference.signed363 bytes[position] ^= 0x01364 if let transaction = try? SolanaTransaction.decode(bytes) {365 #expect(!transaction.verifySignatures(), "bit flipped at \(position)")366 }367 }368 }369370 /// A version-0 message with an address lookup table: parsed and re-serialized exactly, never fully reviewable.371 @Test func versionZeroParsing() throws {372 let f = fields(lines(ReferenceVectors.versionedTransaction)[0])373 let message = try SolanaMessage.decode(hex(f[0]))374 #expect(message.version == .v0 && message.serialize() == hex(f[0]))375 #expect(message.accountKeys == [Fixture.payer, SolanaProgram.computeBudget, SolanaProgram.memo])376 #expect(message.addressTableLookups.count == 1 && message.addressTableLookups[0].tableAddress.bytes == Bytes(repeating: 7, count: 32))377 #expect(message.addressTableLookups[0].writableIndices == [3] && message.addressTableLookups[0].readonlyIndices == [1])378 #expect(message.lookedUpAccountCount == 2)379 let transaction = try SolanaTransaction.decode(hex(f[1]))380 #expect(transaction.message == message)381 #expect(try transaction.serialize() == hex(f[1]))382 #expect(transaction.verifySignatures())383 let review = message.review()384 #expect(review.version == .v0 && review.usesAddressLookupTables && review.requiresBlindSigning)385 #expect(review.instructions[0] == .computeUnitLimit(units: 777))386 if case .unknown(let program, let accounts, let data) = review.instructions[1] {387 #expect(program == SolanaProgram.memo && data == Bytes("v0".utf8))388 #expect(accounts.count == 3 && accounts[0] == Fixture.payer && accounts[1] == nil && accounts[2] == nil)389 } else {390 Issue.record("an instruction with looked-up accounts must be unknown")391 }392 // version 1 and above are refused393 var v1 = hex(f[0])394 v1[0] = 0x81395 #expect(throws: SolanaError.malformed("unsupported message version 1")) { try SolanaMessage.decode(v1) }396 }397398 @Test func instructionDecoderIsStrict() {399 let a = Fixture.payer, b = Fixture.other, c = Fixture.third400 func meta(_ k: SolanaPublicKey) -> SolanaAccountMeta { SolanaAccountMeta(k, isSigner: false, isWritable: false) }401 func decode(_ program: SolanaPublicKey, _ keys: [SolanaPublicKey], _ data: Bytes) -> SolanaDecodedInstruction {402 SolanaDecodedInstruction.decode(SolanaInstruction(programID: program, accounts: keys.map(meta), data: data))403 }404 // exact layouts405 #expect(decode(SolanaProgram.token, [a, b, c], [3] + Endian.le64(7)) == .tokenTransfer(program: .token, source: a, destination: b, authority: c, amount: 7))406 #expect(decode(SolanaProgram.token2022, [a, b, c], [4] + Endian.le64(.max)) == .tokenApprove(program: .token2022, source: a, delegate: b, owner: c, amount: .max))407 #expect(decode(SolanaProgram.token, [a, b], [5]) == .tokenRevoke(program: .token, source: a, owner: b))408 #expect(decode(SolanaProgram.token, [a, b, c], [9]) == .tokenCloseAccount(program: .token, account: a, destination: b, owner: c))409 #expect(decode(SolanaProgram.token, [a], [17]) == .tokenSyncNative(program: .token, account: a))410 #expect(decode(SolanaProgram.token, [a, Fixture.usdc, b, c], [13] + Endian.le64(5) + [6])411 == .tokenApproveChecked(program: .token, source: a, mint: Fixture.usdc, delegate: b, owner: c, amount: 5, decimals: 6))412 #expect(decode(SolanaProgram.computeBudget, [], [1] + Endian.le32(65_536)) == .computeHeapFrame(bytes: 65_536))413 #expect(decode(SolanaProgram.computeBudget, [], [4] + Endian.le32(9)) == .computeLoadedAccountsDataSizeLimit(bytes: 9))414 #expect(decode(SolanaProgram.system, [a, b], Endian.le32(0) + Endian.le64(1) + Endian.le64(165) + SolanaProgram.token.bytes)415 == .systemCreateAccount(payer: a, newAccount: b, lamports: 1, space: 165, owner: SolanaProgram.token))416 #expect(decode(SolanaProgram.associatedToken, [a, b, c, Fixture.usdc, SolanaProgram.system, SolanaProgram.token], [])417 == .createAssociatedTokenAccount(payer: a, associatedAccount: b, owner: c, mint: Fixture.usdc, tokenProgram: SolanaProgram.token, idempotent: false))418 #expect(decode(SolanaProgram.memoV1, [], Bytes("x".utf8)) == .memo("x"))419 // anything else is unknown: wrong length, extra accounts (multisignature, transfer hook), other instruction, other program420 let unknown: [SolanaDecodedInstruction] = [421 decode(SolanaProgram.system, [a, b], Endian.le32(2) + Endian.le64(1) + [0]),422 decode(SolanaProgram.system, [a, b, c], Endian.le32(2) + Endian.le64(1)),423 decode(SolanaProgram.system, [a, b], Endian.le32(1) + SolanaProgram.token.bytes),424 decode(SolanaProgram.system, [a], [2]),425 decode(SolanaProgram.system, [], []),426 decode(SolanaProgram.token, [a, Fixture.usdc, b, c, a], [12] + Endian.le64(1) + [6]),427 decode(SolanaProgram.token, [a, Fixture.usdc, b, c], [12] + Endian.le64(1)),428 decode(SolanaProgram.token, [a, b, c], [6, 0, 1] + a.bytes),429 decode(SolanaProgram.token, [a, b, c], []),430 decode(SolanaProgram.computeBudget, [a], [2] + Endian.le32(1)),431 decode(SolanaProgram.computeBudget, [], [3] + Endian.le32(1)),432 decode(SolanaProgram.computeBudget, [], [9]),433 decode(SolanaProgram.associatedToken, [a, b, c, Fixture.usdc, SolanaProgram.token, SolanaProgram.token], [1]),434 decode(SolanaProgram.associatedToken, [a, b, c, Fixture.usdc, SolanaProgram.system, SolanaProgram.token], [2]),435 decode(SolanaProgram.memo, [], [0xff, 0xfe]),436 decode(SolanaProgram.nativeMint, [a], [1, 2, 3]),437 ]438 for (i, instruction) in unknown.enumerated() {439 #expect(instruction.isUnknown, "case \(i) must be unknown")440 #expect(instruction.summary.hasPrefix("Unknown instruction"))441 }442 }443444 @Test func compilerLimits() throws {445 #expect(throws: SolanaError.invalidBlockhash) { try SolanaMessage(feePayer: Fixture.payer, instructions: [], recentBlockhash: [1]) }446 let many = (0..<256).map { i -> SolanaAccountMeta in447 SolanaAccountMeta(SolanaPublicKey(bytes: Bytes(repeating: UInt8(i), count: 31) + [0xee])!, isSigner: false, isWritable: i % 2 == 0)448 }449 let big = SolanaInstruction(programID: SolanaProgram.memo, accounts: many, data: [])450 #expect(throws: SolanaError.tooManyAccounts) { try SolanaMessage(feePayer: Fixture.payer, instructions: [big], recentBlockhash: Fixture.blockhash) }451 // 255 accounts + payer + program fits in a message but not in a packet452 let fits = SolanaInstruction(programID: SolanaProgram.memo, accounts: Array(many.prefix(254)), data: [])453 let message = try SolanaMessage(feePayer: Fixture.payer, instructions: [fits], recentBlockhash: Fixture.blockhash)454 #expect(message.accountKeys.count == 256)455 #expect(try SolanaMessage.decode(message.serialize()) == message)456 #expect(throws: SolanaError.self) { try SolanaTransaction(message: message).serialize() }457 // a memo that makes the transaction exceed 1232 bytes458 let long = SolanaMemoProgram.memo(String(repeating: "a", count: 1200), signers: [Fixture.payer])459 let tooLarge = SolanaTransaction(message: try SolanaMessage(feePayer: Fixture.payer, instructions: [long], recentBlockhash: Fixture.blockhash))460 #expect(throws: SolanaError.transactionTooLarge(1371)) { try tooLarge.serialize() }461 }462}463464@Suite struct SolanaHostileInputTests {465 static func expectRefused(_ bytes: Bytes, _ what: String) {466 #expect(throws: SolanaError.self, "\(what)") { try SolanaTransaction.decode(bytes) }467 }468469 /// Every truncation and every one-byte extension of valid transactions is refused; no input traps.470 @Test func truncationsAndTrailingBytes() throws {471 let v0 = hex(fields(lines(ReferenceVectors.versionedTransaction)[0])[1])472 for bytes in Fixture.legacy.values.map(\.signed) + [v0] {473 for n in 0..<bytes.count { Self.expectRefused(Bytes(bytes.prefix(n)), "truncated to \(n)") }474 Self.expectRefused(bytes + [0], "trailing byte")475 #expect(throws: SolanaError.self) { try SolanaMessage.decode(Bytes(bytes.dropFirst(65)) + [0]) }476 }477 Self.expectRefused(Bytes(repeating: 0, count: 1233), "oversized")478 #expect(throws: SolanaError.self) { try SolanaTransaction.decode(base64: "not base64!") }479 #expect(throws: SolanaError.self) { try SolanaMessage.decode([]) }480 }481482 @Test func structuralViolations() throws {483 let reference = Fixture.legacy["transfer"]!484 let message = reference.message485 // header: 01 00 02, 4 keys486 #expect(message[0] == 1 && message[1] == 0 && message[2] == 2 && message[3] == 4)487 func mutated(_ change: (inout Bytes) -> Void) -> Bytes {488 var m = message489 change(&m)490 return m491 }492 let cases: [(String, Bytes)] = [493 ("no signer", mutated { $0[0] = 0 }),494 ("read-only fee payer", mutated { $0[1] = 1 }),495 ("more read-only accounts than keys", mutated { $0[2] = 4 }),496 ("more signers than keys", mutated { $0[0] = 5 }),497 ("repeated key", mutated { m in for i in 0..<32 { m[4 + 32 + i] = m[4 + i] } }),498 ("over-long key count", mutated { $0.replaceSubrange(3..<4, with: [0x84, 0x00]) }),499 ("program index out of range", mutated { $0[4 + 4 * 32 + 32 + 1] = 4 }),500 ("program is the fee payer", mutated { $0[4 + 4 * 32 + 32 + 1] = 0 }),501 ("account index out of range", mutated { $0[$0.count - 12 - 1 - 1] = 9 }),502 ("unsupported version", [0x82] + message),503 ]504 for (what, bytes) in cases {505 #expect(throws: SolanaError.self, "\(what)") { try SolanaMessage.decode(bytes) }506 }507 // signature count must match the header508 Self.expectRefused([2] + Bytes(repeating: 0, count: 128) + message, "two signatures for one signer")509 Self.expectRefused([0] + message, "no signature slot")510 // sanity: the unmodified message is accepted511 #expect(try SolanaMessage.decode(message).accountKeys.count == 4)512 }513514 /// Random bytes and random mutations of valid transactions: the decoder returns or throws, never traps, and515 /// whatever it accepts re-serializes to the same bytes.516 @Test func randomInputsNeverTrap() throws {517 var rng = SystemRandomNumberGenerator()518 var accepted = 0519 let seeds = Fixture.legacy.values.map(\.signed) + [hex(fields(lines(ReferenceVectors.versionedTransaction)[0])[1])]520 for round in 0..<60_000 {521 var bytes: Bytes522 if round % 3 == 0 {523 bytes = SystemRandom.bytes(Int(rng.next() % 300))524 } else {525 bytes = seeds[Int(rng.next() % UInt64(seeds.count))]526 for _ in 0..<(1 + Int(rng.next() % 3)) {527 let position = Int(rng.next() % UInt64(bytes.count))528 switch rng.next() % 4 {529 case 0: bytes[position] = UInt8(truncatingIfNeeded: rng.next())530 case 1: bytes[position] ^= 1 << UInt8(rng.next() % 8)531 case 2: bytes.remove(at: position)532 default: bytes.insert(UInt8(truncatingIfNeeded: rng.next()), at: position)533 }534 }535 }536 if let transaction = try? SolanaTransaction.decode(bytes) {537 accepted += 1538 #expect(try transaction.serialize() == bytes)539 _ = transaction.message.review().instructions.map(\.summary)540 _ = transaction.verifySignatures()541 }542 _ = try? SolanaMessage.decode(bytes)543 }544 // mutations inside signatures, amounts or data still parse: the decoder is exercised on both outcomes545 #expect(accepted > 1_000)546 }547}548