Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Tests/PropertyAuditTests/SolanaProperties.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 AuditSupport42import Foundation43import QyvoraCore44import QyvoraMath45import Testing4647@testable import QyvoraSolana48@testable import QyvoraWallet4950// Invariants of the Solana module that need no reference: the length encoding and its strict inverse, the message51// codec, the account-ordering rules of a compiled message, the arithmetic of fees and rent on any 64-bit figure an52// endpoint may send, send-max, the strictness of the instruction classification, and the view the limits take of a53// transaction.5455private func key(_ rng: inout AuditRNG) -> SolanaPublicKey { SolanaPublicKey(bytes: rng.bytes(32))! }5657private func randomInstructions(_ rng: inout AuditRNG, payer: SolanaPublicKey, pool: [SolanaPublicKey], programs: [SolanaPublicKey]) -> [SolanaInstruction] {58 (0..<rng.int(0...6)).map { _ in59 let metas = (0..<rng.int(0...8)).map { _ in SolanaAccountMeta(rng.int(0...6) == 0 ? payer : rng.pick(pool), isSigner: rng.int(0...3) == 0, isWritable: rng.bool()) }60 return SolanaInstruction(programID: rng.pick(programs), accounts: metas, data: rng.bytes(rng.pick([0, 1, 4, 9, 12, 127, 128, 129, 400])))61 }62}6364@Suite struct SolanaEncodingProperties {65 @Test func compactU16IsABijectionOnItsCanonicalForms() {66 var prop = Prop("every value encodes to its shortest form and decodes back; of all strings of 1, 2 and 3 bytes exactly the canonical ones decode; longer or padded forms are refused",67 algorithm: "Solana compact-u16", parameterSet: "exhaustive: 65 536 values, 256 + 65 536 + 16 777 216 byte strings")68 var canonical = Set<[UInt8]>()69 for v in 0...0xffff {70 let value = UInt16(v)71 let encoded = SolanaCompactU16.encode(value)72 canonical.insert(encoded)73 var offset = 074 prop.check(encoded.count == (v < 0x80 ? 1 : (v < 0x4000 ? 2 : 3)) && SolanaCompactU16.decode(encoded, at: &offset) == value && offset == encoded.count, "value \(v)")75 // decoding stops at the end of the length: what follows is not read76 offset = 077 prop.check(SolanaCompactU16.decode(encoded + [0xff, 0xff], at: &offset) == value && offset == encoded.count, "value \(v) followed by data")78 // truncated79 if encoded.count > 1 {80 offset = 081 prop.check(SolanaCompactU16.decode(Bytes(encoded.dropLast()), at: &offset) == nil, "truncated value \(v)")82 }83 }84 prop.check(canonical.count == 65_536, "encodings are not distinct")85 var accepted = 0, failures = 086 // every string of exactly n bytes: it is "a length" when decoding consumes all n bytes87 for n in 1...3 {88 for word in 0..<(1 << (8 * n)) {89 let bytes = (0..<n).map { UInt8(truncatingIfNeeded: word >> (8 * $0)) }90 var offset = 091 let value = SolanaCompactU16.decode(bytes, at: &offset)92 if let value {93 if offset == n { accepted += 1 }94 if SolanaCompactU16.encode(value) != Array(bytes[0..<offset]) { failures += 1 }95 } else if canonical.contains(bytes) {96 failures += 197 }98 }99 }100 prop.check(failures == 0, "\(failures) byte strings decoded to a value whose encoding differs, or canonical strings refused")101 prop.check(accepted == 65_536, "\(accepted) strings of 1 to 3 bytes decode entirely; exactly 65 536 must")102 prop.cases += 256 + 65_536 + 16_777_216 - 2103 // named non-canonical and out-of-range forms104 for bad: Bytes in [[0x80, 0x00], [0x81, 0x00], [0xff, 0x00], [0x80, 0x80, 0x00], [0x80, 0x81, 0x00], [0xff, 0xff, 0x04], [0xff, 0xff, 0x7f], [0x80, 0x80, 0x80], [0x80, 0x80, 0x80, 0x00],105 [0xff, 0xff, 0xff, 0x01], [], [0x80], [0xff, 0xff]] {106 var offset = 0107 prop.check(SolanaCompactU16.decode(bad, at: &offset) == nil, "accepted \(Hex.encode(bad))")108 }109 // an offset at or past the end is a refusal, not a trap110 var end = 3111 prop.check(SolanaCompactU16.decode([1, 2, 3], at: &end) == nil && end == 3, "offset at the end")112 prop.finish()113 }114115 @Test func messageCodecIsStrictBothWays() {116 let seed = AuditSeed.make("solana.message.roundtrip")117 var rng = AuditRNG(seed: seed)118 var prop = Prop("decode(serialize(m)) = m for compiled messages; serialize(decode(b)) = b for every accepted b; a trailing byte, a truncation and a padded length are refused; transactions the same",119 algorithm: "Solana message and transaction", seed: seed)120 var accepted = 0, refused = 0121 for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {122 let payer = key(&rng)123 let pool = (0..<rng.int(1...10)).map { _ in key(&rng) }124 let programs = (0..<rng.int(1...3)).map { _ in key(&rng) }125 let instructions = randomInstructions(&rng, payer: payer, pool: pool, programs: programs)126 guard let message = try? SolanaMessage(feePayer: payer, instructions: instructions, recentBlockhash: rng.bytes(32)) else {127 prop.check(false, "compilation refused")128 continue129 }130 let bytes = message.serialize()131 prop.check((try? SolanaMessage.decode(bytes)) == message, "decode(serialize(m)) differs")132 prop.check((try? SolanaMessage.decode(bytes + [0])) == nil && (try? SolanaMessage.decode(Bytes(bytes.dropLast()))) == nil, "trailing byte or truncation accepted")133 // the account count on two bytes134 var padded = bytes135 padded[3] |= 0x80136 padded.insert(0, at: 4)137 prop.check((try? SolanaMessage.decode(padded)) == nil, "padded account count accepted")138 // transaction139 let tx = SolanaTransaction(message: message)140 if let wire = try? tx.serialize() {141 prop.check((try? SolanaTransaction.decode(wire)) == tx && (try? SolanaTransaction.decode(wire + [0])) == nil, "transaction round trip")142 prop.check((try? SolanaTransaction.decode(base64: SolanaBase64.encode(wire))) == tx, "base64 transport")143 // one signature more or less than the required signers144 let fewer = SolanaCompactU16.encode(UInt16(tx.signatures.count - 1)) + Bytes(wire.dropFirst(1 + 64))145 let more = SolanaCompactU16.encode(UInt16(tx.signatures.count + 1)) + Bytes(repeating: 0, count: 64) + Bytes(wire.dropFirst(1))146 prop.check((try? SolanaTransaction.decode(fewer)) == nil && (try? SolanaTransaction.decode(more)) == nil, "signature count that differs from the header accepted")147 } else {148 prop.check(1 + 64 * tx.signatures.count + bytes.count > SolanaTransaction.maximumSize, "a transaction within the packet size did not serialize")149 }150 // altered bytes: whatever is accepted serializes back to exactly the input151 for _ in 0..<4 {152 var b = bytes153 switch rng.int(0...4) {154 case 0: b[rng.int(0...(b.count - 1))] = UInt8(truncatingIfNeeded: rng.next())155 case 1: b[rng.int(0...min(3, b.count - 1))] = UInt8(rng.int(0...4))156 case 2: b.remove(at: rng.int(0...(b.count - 1)))157 case 3: b.insert(UInt8(truncatingIfNeeded: rng.next()), at: rng.int(0...b.count))158 default: b[b.count - 1 - rng.int(0...min(8, b.count - 1))] = UInt8(truncatingIfNeeded: rng.next())159 }160 if let again = try? SolanaMessage.decode(b) {161 accepted += 1162 prop.check(again.serialize() == b, "serialize(decode(b)) differs from b: \(Hex.encode(b))")163 prop.check(Set(again.accountKeys).count == again.accountKeys.count && again.isWritable(index: 0) && again.numRequiredSignatures >= 1, "accepted message breaks a rule")164 } else {165 refused += 1166 prop.check(true)167 }168 }169 }170 prop.check(accepted > 0 && refused > 0, "the altered inputs must be both accepted and refused (\(accepted), \(refused))")171 prop.finish(note: "altered inputs: \(accepted) accepted, \(refused) refused")172 }173174 @Test func accountOrderingRules() {175 let seed = AuditSeed.make("solana.message.ordering")176 var rng = AuditRNG(seed: seed)177 var prop = Prop("fee payer first; signers before non-signers; writable before read-only in each; byte order inside a role; one entry per key; a privilege asked once is granted, none is invented",178 algorithm: "Solana legacy message compilation", seed: seed)179 for _ in 0..<AuditMode.cases(quick: 3000, full: 30000) {180 let payer = key(&rng)181 // keys that share prefixes, so that the byte order is exercised beyond the first byte182 let stem = rng.bytes(32)183 let pool: [SolanaPublicKey] = (0..<rng.int(1...10)).map { _ in184 var b = rng.bool() ? stem : rng.bytes(32)185 b[rng.int(0...31)] = UInt8(truncatingIfNeeded: rng.next())186 return SolanaPublicKey(bytes: b)!187 }188 let programs = (0..<rng.int(1...3)).map { _ in rng.int(0...4) == 0 ? rng.pick(pool) : key(&rng) }.filter { $0 != payer }189 let instructions = randomInstructions(&rng, payer: payer, pool: pool, programs: programs.isEmpty ? [SolanaProgram.system] : programs)190 guard let m = try? SolanaMessage(feePayer: payer, instructions: instructions, recentBlockhash: rng.bytes(32)) else {191 prop.check(false, "compilation refused")192 continue193 }194 var signer = [SolanaPublicKey: Bool](), writable = [SolanaPublicKey: Bool]()195 for i in instructions {196 signer[i.programID] = signer[i.programID] ?? false197 writable[i.programID] = writable[i.programID] ?? false198 for a in i.accounts {199 signer[a.publicKey] = (signer[a.publicKey] ?? false) || a.isSigner200 writable[a.publicKey] = (writable[a.publicKey] ?? false) || a.isWritable201 }202 }203 signer[payer] = true204 writable[payer] = true205 let keys = m.accountKeys206 var ok = keys.first == payer && Set(keys).count == keys.count && Set(keys) == Set(signer.keys)207 let signed = Int(m.numRequiredSignatures), readonlySigned = Int(m.numReadonlySignedAccounts), readonlyUnsigned = Int(m.numReadonlyUnsignedAccounts)208 ok = ok && signed == signer.values.filter { $0 }.count && signed >= 1 && readonlySigned < signed && signed + readonlyUnsigned <= keys.count209 for (n, k) in keys.enumerated() {210 ok = ok && m.isSigner(index: n) == signer[k] && m.isWritable(index: n) == writable[k]211 }212 // inside each of the four roles the keys are in byte order (the fee payer apart)213 let roles = [Array(keys[1..<max(1, signed - readonlySigned)]), Array(keys[max(1, signed - readonlySigned)..<signed]), Array(keys[signed..<(keys.count - readonlyUnsigned)]),214 Array(keys[(keys.count - readonlyUnsigned)...])]215 for role in roles { ok = ok && role == role.sorted() && zip(role, role.dropFirst()).allSatisfy { $0.bytes.lexicographicallyPrecedes($1.bytes) } }216 // every instruction resolves to what was asked, with the merged privileges217 for (n, i) in instructions.enumerated() {218 guard let r = m.instruction(at: n) else {219 ok = false220 continue221 }222 ok = ok && r.programID == i.programID && r.data == i.data && r.accounts.map(\.publicKey) == i.accounts.map(\.publicKey)223 ok = ok && r.accounts.allSatisfy { $0.isSigner == signer[$0.publicKey] && $0.isWritable == writable[$0.publicKey] }224 }225 ok = ok && m.instruction(at: instructions.count) == nil && m.instruction(at: -1) == nil && m.version == .legacy && m.addressTableLookups.isEmpty226 prop.check(ok, "payer=\(payer) message=\(Hex.encode(m.serialize()))")227 }228 // more than 256 accounts cannot be compiled229 let payer = key(&rng)230 let many = (0..<256).map { _ in SolanaAccountMeta(key(&rng), isSigner: false, isWritable: false) }231 prop.check((try? SolanaMessage(feePayer: payer, instructions: [SolanaInstruction(programID: SolanaProgram.system, accounts: many, data: [])], recentBlockhash: rng.bytes(32))) == nil,232 "258 accounts compiled")233 prop.check((try? SolanaMessage(feePayer: payer, instructions: [], recentBlockhash: rng.bytes(31))) == nil, "a 31-byte blockhash accepted")234 prop.finish()235 }236237 @Test func instructionClassificationIsExact() {238 let seed = AuditSeed.make("solana.instructions.exact")239 var rng = AuditRNG(seed: seed)240 var prop = Prop("each recognised layout is recognised only at its exact data length and account count; anything else is unknown, and unknown means blind signing",241 algorithm: "Solana instruction decoding", seed: seed)242 for _ in 0..<AuditMode.cases(quick: 2000, full: 20000) {243 let a = key(&rng), b = key(&rng), c = key(&rng), d = key(&rng)244 let amount = rng.pick([0, 1, rng.next(), UInt64.max]), decimals = UInt8(truncatingIfNeeded: rng.next())245 let kind = rng.pick(SolanaTokenProgram.Kind.allCases)246 let ata = SolanaAssociatedTokenProgram.createIdempotent(payer: a, associatedAccount: b, owner: c, mint: d, tokenProgram: kind)247 let recognised: [(SolanaInstruction, SolanaDecodedInstruction)] = [248 (SolanaSystemProgram.transfer(from: a, to: b, lamports: amount), .systemTransfer(from: a, to: b, lamports: amount)),249 (SolanaComputeBudget.setComputeUnitLimit(UInt32(truncatingIfNeeded: amount)), .computeUnitLimit(units: UInt32(truncatingIfNeeded: amount))),250 (SolanaComputeBudget.setComputeUnitPrice(microLamports: amount), .computeUnitPrice(microLamports: amount)),251 (SolanaTokenProgram.transferChecked(source: a, mint: b, destination: c, owner: d, amount: amount, decimals: decimals, program: kind),252 .tokenTransferChecked(program: kind, source: a, mint: b, destination: c, authority: d, amount: amount, decimals: decimals)),253 (ata, .createAssociatedTokenAccount(payer: a, associatedAccount: b, owner: c, mint: d, tokenProgram: kind.programID, idempotent: true)),254 (SolanaInstruction(programID: kind.programID, accounts: [a, b, c].map { SolanaAccountMeta($0, isSigner: false, isWritable: true) }, data: [4] + Endian.le64(amount)),255 .tokenApprove(program: kind, source: a, delegate: b, owner: c, amount: amount)),256 (SolanaInstruction(programID: kind.programID, accounts: [a, b, c].map { SolanaAccountMeta($0, isSigner: false, isWritable: true) }, data: [9]),257 .tokenCloseAccount(program: kind, account: a, destination: b, owner: c)),258 ]259 for (instruction, expected) in recognised {260 let decoded = SolanaDecodedInstruction.decode(instruction)261 var ok = decoded == expected && !decoded.isUnknown262 // one byte more or less of data, one account more or less: not this instruction any more263 let longer = SolanaInstruction(programID: instruction.programID, accounts: instruction.accounts, data: instruction.data + [UInt8(truncatingIfNeeded: rng.next())])264 let shorter = SolanaInstruction(programID: instruction.programID, accounts: instruction.accounts, data: Bytes(instruction.data.dropLast()))265 let wider = SolanaInstruction(programID: instruction.programID, accounts: instruction.accounts + [SolanaAccountMeta(key(&rng), isSigner: true, isWritable: true)], data: instruction.data)266 let narrower = SolanaInstruction(programID: instruction.programID, accounts: Array(instruction.accounts.dropLast()), data: instruction.data)267 ok = ok && SolanaDecodedInstruction.decode(longer) != expected && SolanaDecodedInstruction.decode(wider).isUnknown268 if !instruction.data.isEmpty, instruction.programID != SolanaProgram.associatedToken { ok = ok && SolanaDecodedInstruction.decode(shorter) != expected }269 if !instruction.accounts.isEmpty { ok = ok && SolanaDecodedInstruction.decode(narrower).isUnknown }270 // the same bytes for another program are unknown271 let foreign = SolanaInstruction(programID: key(&rng), accounts: instruction.accounts, data: instruction.data)272 ok = ok && SolanaDecodedInstruction.decode(foreign) == .unknown(programID: foreign.programID, accounts: foreign.accounts.map(\.publicKey), data: foreign.data)273 prop.check(ok, "\(expected)")274 }275 // a message with one unknown instruction, or with a lookup table, requires blind signing276 let unknown = SolanaInstruction(programID: key(&rng), accounts: [SolanaAccountMeta(a, isSigner: true, isWritable: true)], data: rng.bytes(rng.int(0...40)))277 let plain = try? SolanaMessage(feePayer: a, instructions: recognised.prefix(3).map(\.0), recentBlockhash: rng.bytes(32))278 let blind = try? SolanaMessage(feePayer: a, instructions: recognised.prefix(3).map(\.0) + [unknown], recentBlockhash: rng.bytes(32))279 prop.check(plain?.review().requiresBlindSigning == false && blind?.review().requiresBlindSigning == true, "blind-signing flag")280 }281 // the System instruction that makes a transaction durable (AdvanceNonceAccount) is not recognised: blind282 let a = key(&rng), nonce = key(&rng)283 let advance = SolanaInstruction(programID: SolanaProgram.system, accounts: [SolanaAccountMeta(nonce, isSigner: false, isWritable: true),284 SolanaAccountMeta(SolanaPublicKey(base58: "SysvarRecentB1ockHashes11111111111111111111")!, isSigner: false, isWritable: false),285 SolanaAccountMeta(a, isSigner: true, isWritable: false)], data: Endian.le32(4))286 prop.check(SolanaDecodedInstruction.decode(advance).isUnknown, "AdvanceNonceAccount recognised")287 let durable = try? SolanaMessage(feePayer: a, instructions: [advance, SolanaSystemProgram.transfer(from: a, to: nonce, lamports: 1)], recentBlockhash: rng.bytes(32))288 prop.check(durable?.review().requiresBlindSigning == true && WalletService.solanaOutflow(durable!.review(), owner: a).blind, "a durable-nonce transaction is not blind")289 prop.finish()290 }291292 @Test func exactIntegersInAnswers() {293 let seed = AuditSeed.make("solana.json.integers")294 var rng = AuditRNG(seed: seed)295 var prop = Prop("64-bit integers of an answer are read exactly; a sign, a fraction, an exponent or a 65th bit is not an amount", algorithm: "Solana JSON reader", seed: seed)296 for _ in 0..<AuditMode.cases(quick: 5000, full: 50000) {297 let v: UInt64 = rng.pick([rng.next(), rng.next() >> UInt64(rng.int(0...63)), UInt64.max, UInt64.max - 1, 1 << 53, (1 << 53) + 1, 0] as [UInt64])298 let parsed = SolanaJSON.parse(Bytes("{\"value\":\(v),\"n\":-\(v),\"f\":\(v).0,\"e\":\(v)e0,\"s\":\"\(v)\"}".utf8))299 var ok = parsed?["value"]?.uint64 == v && parsed?["n"]?.uint64 == nil && parsed?["f"]?.uint64 == nil && parsed?["e"]?.uint64 == nil && parsed?["s"]?.uint64 == nil300 ok = ok && SolanaJSON.integer(v).serialized() == String(v) && parsed.map { SolanaJSON.parse(Bytes($0.serialized().utf8)) == $0 } == true301 prop.check(ok, "value \(v)")302 }303 for text in ["18446744073709551616", "99999999999999999999999999", "1e3", "1.0", "-1", "-0", "01", "+1", "0x10", " 1 "] {304 let parsed = SolanaJSON.parse(Bytes("[\(text)]".utf8))305 prop.check(parsed?.array?.first?.uint64 == nil || text == " 1 ", "\(text) read as an amount")306 }307 // depth: 64 levels pass, 65 are refused; a megabyte of brackets does not exhaust the stack308 prop.check(SolanaJSON.parse(Bytes((String(repeating: "[", count: 64) + String(repeating: "]", count: 64)).utf8)) != nil, "64 levels refused")309 prop.check(SolanaJSON.parse(Bytes((String(repeating: "[", count: 65) + String(repeating: "]", count: 65)).utf8)) == nil, "65 levels accepted")310 prop.check(SolanaJSON.parse(Bytes(repeating: UInt8(ascii: "["), count: 1 << 20)) == nil, "a megabyte of brackets")311 prop.finish()312 }313}314315@Suite struct SolanaPlannerProperties {316 static let payer = try! SolanaKeys.publicKey(privateSeed: Bytes(repeating: 7, count: 32))317 static let other = try! SolanaKeys.publicKey(privateSeed: Bytes(repeating: 9, count: 32))318 static let mint = SolanaPublicKey(base58: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")!319 static let blockhash = SolanaBlockhash(blockhash: Bytes(repeating: 5, count: 32), lastValidBlockHeight: 1_000)320321 static func figure(_ rng: inout AuditRNG) -> UInt64 {322 rng.pick([0, 1, 4_999, 5_000, 5_025, 5_026, 890_879, 890_880, 890_881, 2_039_280, 10_000_000, 1_000_000_000, UInt64(Int64.max), UInt64.max - 5_026, UInt64.max - 1, UInt64.max,323 rng.next(), rng.next() >> UInt64(rng.int(1...63)), rng.next() >> UInt64(rng.int(30...63))])324 }325326 /// The exact ⌈limit × price / 10^6⌉ on 128 bits.327 static func exactPriorityFee(_ limit: UInt32, _ price: UInt64) -> (high: UInt64, low: UInt64) {328 let product = UInt64(limit).multipliedFullWidth(by: price)329 let (low, carry) = product.low.addingReportingOverflow(999_999)330 let high = product.high + (carry ? 1 : 0)331 let (q, _) = UInt64(1_000_000).dividingFullWidth((high % 1_000_000, low))332 return (high / 1_000_000, q)333 }334335 @Test func feeAndRentArithmeticOnAnyFigure() {336 let seed = AuditSeed.make("solana.planner.arithmetic")337 var rng = AuditRNG(seed: seed)338 var prop = Prop("on any 64-bit balance, rent minimum, amount, price and limit the planner gives a plan or a refusal (no overflow); a plan never spends more than the balance, leaves the sender empty or rent-exempt, and its bytes say what it says",339 algorithm: "Solana send planner", parameterSet: "u64 boundaries and random figures, SOL and tokens", seed: seed)340 var plans = 0341 var refusals = [String: Int]()342 for _ in 0..<AuditMode.cases(quick: 20_000, full: 200_000) {343 let available = Self.figure(&rng), rent = Self.figure(&rng), tokenRent = Self.figure(&rng), balance = Self.figure(&rng), amount = Self.figure(&rng)344 let price = rng.pick([0, 1, 5_000, 2_000_000, Self.figure(&rng)])345 let limit: UInt32? = rng.pick([nil, nil, 1, 5_000, 1_400_000, 1_400_001, 0, UInt32.max, UInt32(truncatingIfNeeded: rng.next())])346 let isToken = rng.bool()347 let recipientLamports = Self.figure(&rng)348 let recipient: SolanaChainSnapshot.Account = rng.int(0...9) == 0 ? .other(owner: SolanaProgram.token) : (recipientLamports == 0 ? .missing : .system(lamports: recipientLamports))349 let program = rng.pick(SolanaTokenProgram.Kind.allCases)350 let creates = rng.bool()351 let token = SolanaChainSnapshot.Token(mint: SolanaMintInfo(address: Self.mint, program: program, decimals: UInt8(truncatingIfNeeded: rng.next()), supply: balance, isInitialized: true,352 extensions: rng.int(0...5) == 0 ? ["permanentDelegate"] : []),353 senderBalance: rng.int(0...9) == 0 ? nil : balance, senderFrozen: rng.int(0...19) == 0, recipientAccountExists: !creates, tokenAccountRent: tokenRent)354 let snapshot = SolanaChainSnapshot(senderLamports: available, recipient: recipient, systemAccountRent: rent, blockhash: Self.blockhash, token: isToken ? token : nil)355 let request = SolanaSendRequest(sender: Self.payer, recipient: Self.other, asset: isToken ? .token(mint: Self.mint) : .sol, amount: rng.int(0...3) == 0 ? .max : .exact(amount),356 memo: rng.int(0...5) == 0 ? "note" : nil, computeUnitPrice: price, computeUnitLimit: limit)357 do {358 let plan = try SolanaSendPlanner.plan(request, snapshot: snapshot)359 plans += 1360 // 128-bit accounting of what leaves the sender361 let lamportAmount = plan.asset == .sol ? plan.amount : 0362 let (s1, o1) = plan.signatureFee.addingReportingOverflow(plan.priorityFee)363 let (s2, o2) = s1.addingReportingOverflow(plan.accountCreationCost)364 let (total, o3) = s2.addingReportingOverflow(lamportAmount)365 var ok = !o1 && !o2 && !o3 && total <= available && plan.totalLamports == total && plan.senderLamportsAfter == available - total366 ok = ok && (plan.senderLamportsAfter == 0 || plan.senderLamportsAfter >= rent)367 let exact = Self.exactPriorityFee(plan.computeUnitLimit, plan.computeUnitPrice)368 ok = ok && exact.high == 0 && exact.low == plan.priorityFee && plan.priorityFee <= SolanaSendPlanner.maximumPriorityFee && plan.signatureFee == 5_000369 ok = ok && plan.computeUnitLimit >= 1 && plan.computeUnitLimit <= SolanaComputeBudget.maximumUnitLimit && plan.amount > 0370 if isToken {371 ok = ok && plan.amount <= balance && plan.accountCreationCost == (creates ? tokenRent : 0) && plan.decimals == token.mint.decimals372 } else if case .system(let before) = recipient {373 // the recipient ends rent-exempt (or beyond 64 bits, which the chain would refuse by itself)374 let (after, overflow) = before.addingReportingOverflow(plan.amount)375 ok = ok && (overflow || after >= rent)376 } else {377 ok = ok && plan.amount >= rent378 }379 // the bytes: what the limits and a cold device read in them is what the plan says380 let outflow = WalletService.solanaOutflow(plan.review, owner: Self.payer)381 ok = ok && !outflow.blind && outflow.other.isEmpty && outflow.priorityFee == plan.priorityFee && outflow.lamports == lamportAmount382 ok = ok && (isToken ? outflow.tokens[Self.mint.base58]?.amount == plan.amount && outflow.tokens[Self.mint.base58]?.decimals == plan.decimals : outflow.tokens.isEmpty)383 ok = ok && outflow.createsAccounts == (isToken && creates ? 1 : 0)384 let wire = try? plan.transaction.serialize()385 ok = ok && wire != nil && (wire?.count ?? .max) <= SolanaTransaction.maximumSize && wire.flatMap { try? SolanaTransaction.decode($0) } == plan.transaction386 ok = ok && plan.transaction.message.signers == [Self.payer] && plan.transaction.message.recentBlockhash == Self.blockhash.blockhash387 prop.check(ok, "request=\(request) snapshot=\(snapshot) plan=\(plan)")388 } catch let error as SolanaSendRefusal {389 refusals[String(describing: error).split(separator: "(").first.map(String.init) ?? "?", default: 0] += 1390 var ok = true391 switch error {392 case .senderBelowRentExemption(let remaining, let minimum, let sendable):393 ok = remaining > 0 && remaining < minimum && minimum == rent && sendable <= available394 // the amount it suggests is one the planner accepts (when the recipient's own rule allows it) and leaves exactly the minimum395 if sendable > 0, !isToken, let suggested = try? SolanaSendPlanner.plan(SolanaSendRequest(sender: Self.payer, recipient: Self.other, asset: .sol, amount: .exact(sendable),396 memo: request.memo, computeUnitPrice: price, computeUnitLimit: limit), snapshot: snapshot) {397 ok = ok && suggested.senderLamportsAfter == rent398 }399 case .insufficientLamports(let required, let had): ok = had == available && (required > available || required == .max)400 case .insufficientTokens(let required, let had): ok = had == (token.senderBalance ?? 0) && required > had401 case .priorityFeeTooHigh(let lamports):402 let exact = Self.exactPriorityFee(limit ?? SolanaSendPlanner.defaultUnitLimit(asset: request.asset, program: isToken ? program : nil, hasMemo: request.memo != nil), price)403 let product = UInt64(limit ?? SolanaSendPlanner.defaultUnitLimit(asset: request.asset, program: isToken ? program : nil, hasMemo: request.memo != nil)).multipliedFullWidth(by: price)404 ok = lamports.map { $0 > SolanaSendPlanner.maximumPriorityFee && exact.high == 0 && exact.low == $0 } ?? !(product.high == 0 && product.low <= UInt64.max - 999_999)405 case .recipientBelowRentExemption(let minimum): ok = !isToken && minimum > 0 && minimum <= rent406 default: break407 }408 prop.check(ok, "refusal=\(error) request=\(request) snapshot=\(snapshot)")409 } catch {410 prop.check(false, "the planner threw something that is not a refusal: \(error)")411 }412 }413 prop.check(plans > 100 && refusals.count >= 6, "the campaign must reach plans and several refusals (\(plans), \(refusals))")414 prop.finish(note: "\(plans) plans; refusals: " + refusals.sorted { $0.key < $1.key }.map { "\($0.key) \($0.value)" }.joined(separator: ", "))415 }416417 @Test func priorityFeeNeverOverflowsAndHasACeiling() {418 let seed = AuditSeed.make("solana.fee.priority")419 var rng = AuditRNG(seed: seed)420 var prop = Prop("priorityFee = ⌈limit × price / 10^6⌉ exactly or nil; the suggested price stays in its bounds on hostile samples, and with the default limits its fee is far below the ceiling",421 algorithm: "Solana priority fee", seed: seed)422 for _ in 0..<AuditMode.cases(quick: 20_000, full: 200_000) {423 let limit = rng.pick([0, 1, 1_400_000, UInt32.max, UInt32(truncatingIfNeeded: rng.next())]), price = Self.figure(&rng)424 let exact = Self.exactPriorityFee(limit, price)425 let ours = SolanaComputeBudget.priorityFee(unitLimit: limit, microLamportsPerUnit: price)426 // nil only when limit × price + 999 999 does not fit in 64 bits (the exact fee may still fit: the refusal is conservative)427 let product = UInt64(limit).multipliedFullWidth(by: price)428 let fits = product.high == 0 && product.low <= UInt64.max - 999_999429 prop.check(fits ? (ours == exact.low && exact.high == 0) : ours == nil, "limit=\(limit) price=\(price) ours=\(String(describing: ours))")430 // suggested price from a hostile sample of recent fees431 let sample = (0..<rng.int(0...200)).map { _ in Self.figure(&rng) }432 let suggested = SolanaFees.suggestedUnitPrice(recentFees: sample)433 var ok = suggested >= SolanaFees.minimumUnitPrice && suggested <= SolanaFees.maximumUnitPrice434 for asset in [SolanaSendRequest.Asset.sol, .token(mint: Self.mint)] {435 for program in [nil, SolanaTokenProgram.Kind.token, .token2022] {436 for memo in [false, true] {437 let units = SolanaSendPlanner.defaultUnitLimit(asset: asset, program: program, hasMemo: memo)438 // even doubled by the "fast" tier (clamped to the maximum price) the fee is below the ceiling439 let fee = SolanaComputeBudget.priorityFee(unitLimit: units, microLamportsPerUnit: min(SolanaFees.maximumUnitPrice, suggested &* 2))440 ok = ok && fee != nil && (fee ?? .max) <= 300_000 && (fee ?? .max) <= SolanaSendPlanner.maximumPriorityFee && units <= SolanaComputeBudget.maximumUnitLimit441 }442 }443 }444 prop.check(ok, "sample of \(sample.count) fees, suggested \(suggested)")445 }446 prop.check(SolanaSendPlanner.maximumPriorityFee == 10_000_000 && MainnetPolicy.solanaLimits.feePerTransaction == 10_000_000 && MainnetPolicy.solanaAccountCreationLamportsCeiling == 10_000_000,447 "the ceilings changed: 0.01 SOL of priority fee, 0.01 SOL of rent for a new token account")448 prop.finish()449 }450451 @Test func sendMaxNeverExceedsTheBalance() {452 let seed = AuditSeed.make("solana.planner.sendmax")453 var rng = AuditRNG(seed: seed)454 var prop = Prop("send-max of SOL transfers exactly balance − fee and empties the account; of a token, exactly the token balance, and the lamports left are zero or rent-exempt; never more than the balance",455 algorithm: "Solana send planner", parameterSet: "send-max", seed: seed)456 for _ in 0..<AuditMode.cases(quick: 10_000, full: 100_000) {457 let available: UInt64 = rng.pick([rng.next() >> UInt64(rng.int(20...60)), 5_025, 5_026, 5_024, 890_880 + 5_025, 890_880 + 5_024, UInt64.max, 0] as [UInt64])458 let rent: UInt64 = rng.pick([890_880, 329_600, 1])459 let price: UInt64 = rng.pick([0, 5_000, 2_000_000] as [UInt64])460 let recipient: SolanaChainSnapshot.Account = rng.bool() ? .missing : .system(lamports: rng.pick([1, rent, 1_000_000_000] as [UInt64]))461 let fee = 5_000 + (SolanaComputeBudget.priorityFee(unitLimit: 5_000, microLamportsPerUnit: price) ?? 0)462 let request = SolanaSendRequest(sender: Self.payer, recipient: Self.other, asset: .sol, amount: .max, computeUnitPrice: price)463 let snapshot = SolanaChainSnapshot(senderLamports: available, recipient: recipient, systemAccountRent: rent, blockhash: Self.blockhash)464 do {465 let plan = try SolanaSendPlanner.plan(request, snapshot: snapshot)466 var ok = plan.amount == available - fee && plan.fee == fee && plan.totalLamports == available && plan.senderLamportsAfter == 0 && plan.warnings.contains(.emptiesSender)467 ok = ok && plan.review.instructions.contains(.systemTransfer(from: Self.payer, to: Self.other, lamports: available - fee))468 if case .missing = recipient { ok = ok && plan.amount >= rent && plan.warnings.contains(.recipientIsNew) }469 prop.check(ok, "available=\(available) plan=\(plan)")470 } catch let error as SolanaSendRefusal {471 // refused only when nothing would be left to send, or when the recipient would be created below the minimum472 var ok = false473 if case .insufficientLamports(let required, let had) = error { ok = available <= fee && required == fee + 1 && had == available }474 if case .recipientBelowRentExemption = error { ok = available > fee }475 prop.check(ok, "available=\(available) rent=\(rent) refusal=\(error)")476 } catch {477 prop.check(false, "the planner threw something that is not a refusal: \(error)")478 }479 // tokens: the whole token balance, and the lamport rule for the fee (and the creation of the recipient's account)480 let balance: UInt64 = rng.pick([0, 1, rng.next(), UInt64.max] as [UInt64])481 let creates = rng.bool()482 let tokenRent: UInt64 = 2_039_280483 let token = SolanaChainSnapshot.Token(mint: SolanaMintInfo(address: Self.mint, program: .token, decimals: 6, supply: balance, isInitialized: true, extensions: []), senderBalance: balance,484 recipientAccountExists: !creates, tokenAccountRent: tokenRent)485 let tokenSnapshot = SolanaChainSnapshot(senderLamports: available, recipient: recipient, systemAccountRent: rent, blockhash: Self.blockhash, token: token)486 let tokenRequest = SolanaSendRequest(sender: Self.payer, recipient: Self.other, asset: .token(mint: Self.mint), amount: .max, computeUnitPrice: price)487 let tokenFee = 5_000 + (SolanaComputeBudget.priorityFee(unitLimit: 80_000, microLamportsPerUnit: price) ?? 0)488 if let plan = try? SolanaSendPlanner.plan(tokenRequest, snapshot: tokenSnapshot) {489 let spent = tokenFee + (creates ? tokenRent : 0)490 prop.check(plan.amount == balance && balance > 0 && plan.totalLamports == spent && spent <= available && (available - spent == 0 || available - spent >= rent),491 "token send-max available=\(available) balance=\(balance) plan=\(plan)")492 } else {493 let spent = tokenFee + (creates ? tokenRent : 0)494 prop.check(balance == 0 || spent > available || (available - spent > 0 && available - spent < rent), "token send-max refused without reason: available=\(available) balance=\(balance)")495 }496 }497 prop.finish()498 }499500 @Test func theLimitsSeeEveryLamportThatLeaves() {501 let seed = AuditSeed.make("solana.limits.outflow")502 var rng = AuditRNG(seed: seed)503 var prop = Prop("the outflow the limits are computed from adds every System transfer and every TransferChecked of the owner found in the bytes (saturating), flags every instruction that is not a payment, and is blind as soon as one instruction is unknown or the priority fee cannot be computed",504 algorithm: "Solana per-transaction limits", parameterSet: "view of a transaction (WalletService.solanaOutflow)", seed: seed)505 for _ in 0..<AuditMode.cases(quick: 5_000, full: 50_000) {506 let owner = Self.payer507 var instructions = [SolanaInstruction]()508 var lamports: UInt64 = 0, saturated = false509 var tokens = [String: UInt64]()510 var other = 0, unknown = false, creates = 0511 let hasLimit = rng.int(0...5) > 0, hasPrice = rng.int(0...5) > 0512 let limit = UInt32(rng.int(1...1_400_000)), price = rng.pick([0, 5_000, rng.next() >> 30])513 if hasLimit { instructions.append(SolanaComputeBudget.setComputeUnitLimit(limit)) }514 if hasPrice { instructions.append(SolanaComputeBudget.setComputeUnitPrice(microLamports: price)) }515 for _ in 0..<rng.int(0...6) {516 switch rng.int(0...6) {517 case 0, 1:518 let amount = rng.pick([1, rng.next() >> 20, UInt64.max, UInt64.max / 2 + 1])519 instructions.append(SolanaSystemProgram.transfer(from: owner, to: key(&rng), lamports: amount))520 let (sum, overflow) = lamports.addingReportingOverflow(amount)521 lamports = overflow ? .max : sum522 saturated = saturated || overflow523 case 2:524 let mint = rng.pick([Self.mint, SolanaProgram.nativeMint]), amount = rng.next() >> 10525 instructions.append(SolanaTokenProgram.transferChecked(source: key(&rng), mint: mint, destination: key(&rng), owner: owner, amount: amount, decimals: 6))526 let (sum, overflow) = (tokens[mint.base58] ?? 0).addingReportingOverflow(amount)527 tokens[mint.base58] = overflow ? .max : sum528 case 3:529 instructions.append(SolanaAssociatedTokenProgram.createIdempotent(payer: owner, associatedAccount: key(&rng), owner: key(&rng), mint: Self.mint))530 creates += 1531 case 4:532 instructions.append(SolanaInstruction(programID: SolanaProgram.token, accounts: [key(&rng), key(&rng), owner].map { SolanaAccountMeta($0, isSigner: $0 == owner, isWritable: true) },533 data: rng.pick([[4] + Endian.le64(.max), [9], [3] + Endian.le64(5)])))534 other += 1535 case 5:536 instructions.append(SolanaInstruction(programID: key(&rng), accounts: [SolanaAccountMeta(owner, isSigner: true, isWritable: true)], data: rng.bytes(rng.int(0...20))))537 unknown = true538 default: instructions.append(SolanaMemoProgram.memo("note", signers: [owner]))539 }540 }541 guard let message = try? SolanaMessage(feePayer: owner, instructions: instructions, recentBlockhash: rng.bytes(32)) else {542 prop.check(false, "compilation refused")543 continue544 }545 let review = message.review()546 let outflow = WalletService.solanaOutflow(review, owner: owner)547 let feeUnknown = hasPrice && price > 0 && !hasLimit548 let feeOverflows = hasPrice && price > 0 && hasLimit && SolanaComputeBudget.priorityFee(unitLimit: limit, microLamportsPerUnit: price) == nil549 if feeUnknown || feeOverflows {550 // without a computable priority fee nothing can be checked against a limit551 prop.check(outflow.blind, "a transaction whose priority fee cannot be computed is not blind")552 continue553 }554 var ok = outflow.blind == unknown && outflow.lamports == lamports && outflow.other.count == other && outflow.createsAccounts == creates555 ok = ok && outflow.tokens.mapValues(\.amount) == tokens && outflow.tokens.values.allSatisfy { $0.decimals == 6 }556 ok = ok && outflow.priorityFee == (hasPrice && price > 0 ? SolanaComputeBudget.priorityFee(unitLimit: limit, microLamportsPerUnit: price) ?? .max : 0)557 // a transfer signed by somebody else is not the owner's outflow, and it makes that somebody a signer558 ok = ok && review.signers == [owner] && review.requiresBlindSigning == unknown559 prop.check(ok, "instructions=\(review.instructions.map(\.summary)) outflow=\(outflow)")560 _ = saturated561 }562 prop.finish()563 }564565 @Test func historyReportsExactlyTheBalanceChanges() {566 let seed = AuditSeed.make("solana.history.changes")567 var rng = AuditRNG(seed: seed)568 var prop = Prop("native and token changes of an account are post − pre of the answer, summed over its token accounts, with the sign; the fee is shown once, to the account that paid it; a transaction under another signature is refused",569 algorithm: "Solana history normalisation", seed: seed)570 let signature = Base58.bitcoin.encode(Bytes(repeating: 9, count: 64))571 for _ in 0..<AuditMode.cases(quick: 3_000, full: 30_000) {572 let me = key(&rng)573 let keys = (0..<rng.int(1...6)).map { _ in key(&rng) }574 let position = rng.int(0...keys.count)575 var accounts = keys576 let present = rng.int(0...5) > 0577 if present { accounts.insert(me, at: position) }578 let pre = accounts.map { _ in rng.pick([0, 1, rng.next() >> 20, UInt64.max]) }, post = accounts.map { _ in rng.pick([0, 1, rng.next() >> 20, UInt64.max]) }579 let fee = rng.pick([5_000, 0, rng.next() >> 40, UInt64.max])580 let mints = (0..<rng.int(0...3)).map { _ in key(&rng) }581 var before = [SolanaPublicKey: UInt64](), after = [SolanaPublicKey: UInt64]()582 func balances(_ sums: inout [SolanaPublicKey: UInt64]) -> String {583 var items = [String]()584 for mint in mints {585 for _ in 0..<rng.int(0...2) {586 let mine = rng.bool()587 let amount = rng.next() >> UInt64(rng.int(2...40))588 if mine { sums[mint, default: 0] += amount }589 items.append(#"{"accountIndex":1,"mint":"\#(mint)","owner":"\#(mine ? me : keys[0])","uiTokenAmount":{"amount":"\#(amount)","decimals":6,"uiAmount":null}}"#)590 }591 }592 return "[" + items.joined(separator: ",") + "]"593 }594 let preTokens = balances(&before), postTokens = balances(&after)595 let failed = rng.int(0...4) == 0596 let json = #"{"slot":\#(rng.next() >> 20),"blockTime":\#(rng.pick(["null", "1796448657", "-5", "0"])),"meta":{"err":\#(failed ? #"{"InstructionError":[0,"Custom"]}"# : "null"),"fee":\#(fee),"#597 + #""preBalances":[\#(pre.map(String.init).joined(separator: ","))],"postBalances":[\#(post.map(String.init).joined(separator: ","))],"preTokenBalances":\#(preTokens),"postTokenBalances":\#(postTokens)},"#598 + #""transaction":{"message":{"accountKeys":[\#(accounts.map { rng.bool() ? "\"\($0)\"" : #"{"pubkey":"\#($0)","signer":false,"writable":true}"# }.joined(separator: ","))]},"signatures":["\#(signature)"]}}"#599 guard let parsed = SolanaJSON.parse(Bytes(json.utf8)), let entry = try? SolanaHistory.entry(transaction: parsed, signature: signature, for: me) else {600 prop.check(false, "a well-formed answer was refused: \(json.prefix(300))")601 continue602 }603 var ok = entry.succeeded == !failed && entry.fee == fee && entry.feePayer == accounts[0]604 if present {605 let b = pre[position], a = post[position]606 ok = ok && entry.nativeChange == SolanaSignedAmount(isNegative: a < b, magnitude: a < b ? b - a : a - b)607 } else {608 ok = ok && entry.nativeChange == .zero609 }610 var expected = [SolanaPublicKey: SolanaSignedAmount]()611 for mint in mints {612 let b = before[mint] ?? 0, a = after[mint] ?? 0613 if a != b { expected[mint] = SolanaSignedAmount(isNegative: a < b, magnitude: a < b ? b - a : a - b) }614 }615 ok = ok && Dictionary(uniqueKeysWithValues: entry.tokenChanges.map { ($0.mint, $0.change) }) == expected && entry.tokenChanges.allSatisfy { $0.decimals == 6 }616 // the wallet's lines: the fee once, on the payer's side only; amounts within 64 bits617 let info = SolanaSignatureInfo(signature: signature, slot: entry.slot, blockTime: entry.blockTime, failed: failed, confirmationStatus: .finalized)618 let lines = WalletService.activity(entry, info: info, owner: me, chain: .solanaDevnet, tokens: [:])619 let paid = present && position == 0620 ok = ok && !lines.isEmpty && lines.filter { $0.fee != nil }.count == (paid ? 1 : 0) && lines.allSatisfy { $0.amount.uint64 != nil } && Set(lines.map(\.id)).count == lines.count621 ok = ok && lines.allSatisfy { ($0.time.map { $0.timeIntervalSince1970 > 0 } ?? true) }622 prop.check(ok, "entry=\(entry) lines=\(lines.count)")623 // the same answer asked under another signature is refused624 prop.check((try? SolanaHistory.entry(transaction: parsed, signature: Base58.bitcoin.encode(Bytes(repeating: 8, count: 64)), for: me)) == nil, "signature mismatch accepted")625 }626 prop.finish()627 }628}629