SPB Git

Repository Public

Targets+Solana.swift 51.6 KB 712 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Sources/FuzzTargets/Targets+Solana.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 QyvoraEd2551945import QyvoraMath46import QyvoraNetworking47@testable import QyvoraSolana48@testable import QyvoraWallet4950// Solana: everything that reads bytes or text this wallet did not write — messages and transactions (a cold device51// decodes what the online device hands it), instructions, addresses, the answers of JSON-RPC endpoints, the history —52// and the planner, which computes with figures an endpoint supplied.5354/// Fixed public material of the Solana harnesses. The two key pairs come from published constant seeds (7…7 and55/// 9…9): they protect nothing.56enum SolanaFixture {57    static let payerSeed = Bytes(repeating: 7, count: 32)58    static let payer = try! SolanaKeys.publicKey(privateSeed: payerSeed)59    static let other = try! SolanaKeys.publicKey(privateSeed: Bytes(repeating: 9, count: 32))60    static let mint = SolanaPublicKey(base58: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")!61    static let blockhash = SolanaBlockhash(blockhash: Bytes(repeating: 5, count: 32), lastValidBlockHeight: 1_000)62    static let signature = Base58.bitcoin.encode(Bytes(repeating: 9, count: 64))63    /// Keys an instruction harness can name with one byte.64    static let pool: [SolanaPublicKey] = [SolanaProgram.system, SolanaProgram.token, SolanaProgram.token2022, SolanaProgram.associatedToken,65                                          SolanaProgram.computeBudget, SolanaProgram.memo, payer, other]6667    static func mintInfo(_ program: SolanaTokenProgram.Kind, extensions: [String] = []) -> SolanaMintInfo {68        SolanaMintInfo(address: mint, program: program, decimals: 6, supply: 1_000_000_000, isInitialized: true, extensions: extensions)69    }7071    static func plans() -> [SolanaSendPlan] {72        let sol = SolanaChainSnapshot(senderLamports: 5_000_000_000, recipient: .system(lamports: 5_000_000), systemAccountRent: 890_880, blockhash: blockhash)73        func token(_ program: SolanaTokenProgram.Kind, exists: Bool) -> SolanaChainSnapshot {74            SolanaChainSnapshot(senderLamports: 50_000_000, recipient: .system(lamports: 1), systemAccountRent: 890_880, blockhash: blockhash,75                                token: .init(mint: mintInfo(program), senderBalance: 9_000_000, recipientAccountExists: exists, tokenAccountRent: 2_039_280))76        }77        let requests: [(SolanaSendRequest, SolanaChainSnapshot)] = [78            (SolanaSendRequest(sender: payer, recipient: other, asset: .sol, amount: .exact(1_234_567_890)), sol),79            (SolanaSendRequest(sender: payer, recipient: other, asset: .sol, amount: .max, memo: "Invoice 42"), sol),80            (SolanaSendRequest(sender: payer, recipient: other, asset: .token(mint: mint), amount: .exact(1_500_000)), token(.token, exists: true)),81            (SolanaSendRequest(sender: payer, recipient: other, asset: .token(mint: mint), amount: .max, memo: "merci ✓", computeUnitPrice: 77_777), token(.token, exists: false)),82            (SolanaSendRequest(sender: payer, recipient: other, asset: .token(mint: mint), amount: .exact(1)), token(.token2022, exists: false)),83        ]84        return requests.compactMap { try? SolanaSendPlanner.plan($0.0, snapshot: $0.1) }85    }8687    /// A version-0 message with one address lookup table: a System transfer to an account loaded from the table.88    static let versioned: Bytes = {89        var b: Bytes = [0x80, 1, 0, 1, 2]90        b += payer.bytes + SolanaProgram.system.bytes + blockhash.blockhash91        b += [1, 1, 2, 0, 2, 12] + Endian.le32(2) + Endian.le64(5)92        b += [1] + other.bytes + [1, 0, 0]93        return b94    }()9596    /// Things a payment never contains but a cold device may be shown: an approval, an account closing, an unknown program.97    static func foreignInstructions() -> [SolanaInstruction] {98        let account = (try? SolanaAddress.associatedTokenAccount(owner: payer, mint: mint)) ?? other99        func token(_ data: Bytes, _ keys: [SolanaPublicKey]) -> SolanaInstruction {100            SolanaInstruction(programID: SolanaProgram.token, accounts: keys.enumerated().map { SolanaAccountMeta($1, isSigner: $0 == keys.count - 1, isWritable: $0 == 0) }, data: data)101        }102        return [103            token([4] + Endian.le64(.max), [account, other, payer]),104            token([13] + Endian.le64(5) + [6], [account, mint, other, payer]),105            token([5], [account, payer]),106            token([9], [account, other, payer]),107            token([3] + Endian.le64(7), [account, other, payer]),108            token([17], [account]),109            SolanaInstruction(programID: SolanaProgram.system, accounts: [SolanaAccountMeta(payer, isSigner: true, isWritable: true), SolanaAccountMeta(other, isSigner: true, isWritable: true)],110                              data: Endian.le32(0) + Endian.le64(890_880) + Endian.le64(0) + SolanaProgram.system.bytes),111            SolanaInstruction(programID: SolanaProgram.computeBudget, accounts: [], data: [1] + Endian.le32(65_536)),112            SolanaInstruction(programID: SolanaProgram.computeBudget, accounts: [], data: [4] + Endian.le32(1_000)),113            SolanaInstruction(programID: SolanaProgram.memoV1, accounts: [], data: Bytes("old memo".utf8)),114            SolanaInstruction(programID: other, accounts: [SolanaAccountMeta(payer, isSigner: true, isWritable: true)], data: [1, 2, 3]),115            // AdvanceNonceAccount: a durable-nonce transaction never expires; it is not recognised, hence blind116            SolanaInstruction(programID: SolanaProgram.system, accounts: [SolanaAccountMeta(other, isSigner: false, isWritable: true), SolanaAccountMeta(payer, isSigner: true, isWritable: false)],117                              data: Endian.le32(4)),118        ]119    }120121    static func messages() -> [SolanaMessage] {122        var out = plans().map(\.transaction.message)123        for extra in foreignInstructions() {124            let base = [SolanaComputeBudget.setComputeUnitLimit(5_000), SolanaComputeBudget.setComputeUnitPrice(microLamports: 5_000)]125            if let m = try? SolanaMessage(feePayer: payer, instructions: base + [extra], recentBlockhash: blockhash.blockhash) { out.append(m) }126        }127        if let v0 = try? SolanaMessage.decode(versioned) { out.append(v0) }128        return out129    }130131    static func unsignedTransactions() -> [Bytes] { messages().compactMap { try? SolanaTransaction(message: $0).serialize() } }132133    /// Transactions signed by the fixed payer (those it is the only signer of): public bytes, valid signatures.134    static func signedTransactions() -> [Bytes] {135        messages().compactMap { message -> Bytes? in136            guard message.signers == [payer] else { return nil }137            var tx = SolanaTransaction(message: message)138            guard (try? tx.sign(privateSeed: payerSeed)) != nil else { return nil }139            return try? tx.serialize()140        }141    }142143    /// One instruction as the `solana-instructions` harness reads it: program, account count, accounts, data; a key144    /// is one byte when it is in `pool`, 0xff and 32 bytes otherwise.145    static func encode(_ instruction: SolanaInstruction) -> Bytes {146        func key(_ k: SolanaPublicKey) -> Bytes { pool.firstIndex(of: k).map { [UInt8($0)] } ?? ([0xff] + k.bytes) }147        var out = key(instruction.programID)148        out.append(UInt8(min(instruction.accounts.count, 11)))149        for a in instruction.accounts.prefix(11) { out += key(a.publicKey) }150        return out + instruction.data151    }152153    static func decodeInstruction(_ bytes: Bytes) -> SolanaInstruction {154        var input = FuzzInput(bytes)155        func key(_ input: inout FuzzInput) -> SolanaPublicKey {156            let b = input.byte()157            return Int(b) < pool.count ? pool[Int(b)] : SolanaPublicKey(bytes: input.take(32))!158        }159        let program = key(&input)160        let count = Int(input.byte()) % 12161        var accounts = [SolanaAccountMeta]()162        for n in 0..<count { accounts.append(SolanaAccountMeta(key(&input), isSigner: n == 0, isWritable: n < 2)) }163        return SolanaInstruction(programID: program, accounts: accounts, data: input.rest())164    }165166    /// The instruction the builders of the module give for a decoded one, when the module has a builder for it.167    static func rebuild(_ decoded: SolanaDecodedInstruction) -> SolanaInstruction? {168        switch decoded {169        case .systemTransfer(let from, let to, let lamports): return SolanaSystemProgram.transfer(from: from, to: to, lamports: lamports)170        case .computeUnitLimit(let units): return SolanaComputeBudget.setComputeUnitLimit(units)171        case .computeUnitPrice(let price): return SolanaComputeBudget.setComputeUnitPrice(microLamports: price)172        case .tokenTransferChecked(let program, let source, let mint, let destination, let authority, let amount, let decimals):173            return SolanaTokenProgram.transferChecked(source: source, mint: mint, destination: destination, owner: authority, amount: amount, decimals: decimals, program: program)174        case .createAssociatedTokenAccount(let payer, let account, let owner, let mint, let tokenProgram, true):175            guard let kind = SolanaTokenProgram.Kind(programID: tokenProgram) else { return nil }176            return SolanaAssociatedTokenProgram.createIdempotent(payer: payer, associatedAccount: account, owner: owner, mint: mint, tokenProgram: kind)177        case .memo(let text): return SolanaMemoProgram.memo(text)178        default: return nil179        }180    }181182    /// Invariants of a decoded instruction against the instruction it was decoded from: what is shown is what the183    /// bytes say.184    static func check(_ decoded: SolanaDecodedInstruction, against original: SolanaInstruction) {185        let summary = decoded.summary186        fuzzCheck(!summary.isEmpty && summary.unicodeScalars.allSatisfy(SolanaMemoProgram.isDisplayable), "summary with a character that can disguise the review")187        fuzzUse(summary.utf8.count)188        if case .unknown(let program, let accounts, let data) = decoded {189            fuzzCheck(program == original.programID && data == original.data && accounts.count == original.accounts.count, "unknown instruction lost its content")190            return191        }192        guard let rebuilt = rebuild(decoded) else { return }193        fuzzCheck(rebuilt.data == original.data, "a recognised instruction rebuilds to other data")194        if case .memo = decoded { return }  // a memo may carry any signers195        fuzzCheck(rebuilt.programID == original.programID, "a recognised instruction rebuilds to another program")196        fuzzCheck(rebuilt.accounts.map(\.publicKey) == original.accounts.map(\.publicKey), "a recognised instruction rebuilds to other accounts")197    }198199    /// What a cold device does with a decoded message, and what must hold.200    static func review(_ message: SolanaMessage) {201        let review = message.review()202        fuzzCheck(review.instructions.count == message.instructions.count, "the review lost an instruction")203        fuzzCheck(review.feePayer == message.accountKeys[0] && review.signers.count == Int(message.numRequiredSignatures), "signers of the review")204        fuzzCheck(review.signers.first == review.feePayer, "the fee payer is not the first signer")205        var unknown = false206        for (n, decoded) in review.instructions.enumerated() {207            if decoded.isUnknown { unknown = true }208            if let original = message.instruction(at: n) {209                check(decoded, against: original)210            } else {211                fuzzCheck(decoded.isUnknown, "an instruction with accounts from a lookup table was decoded")212                fuzzUse(decoded.summary.utf8.count)213            }214        }215        fuzzCheck(review.requiresBlindSigning == (unknown || !message.addressTableLookups.isEmpty), "blind-signing flag")216        fuzzCheck(review.signatureFee == UInt64(message.numRequiredSignatures) * 5_000, "signature fee")217        fuzzUse(review.priorityFee ?? .max)218        let outflow = WalletService.solanaOutflow(review, owner: review.feePayer)219        fuzzCheck(!review.requiresBlindSigning || outflow.blind, "a blind review is not blind for the limits")220        fuzzUse(outflow.lamports)221        fuzzUse(outflow.tokens.count + outflow.other.count + outflow.createsAccounts)222        FuzzOutcome.note(outflow.blind ? "blind" : (outflow.other.isEmpty ? "payment" : "other"))223    }224}225226private func solanaRPCSeeds() -> [Bytes] {227    let f = SolanaFixture.self228    let payer = f.payer.base58, other = f.other.base58, mint = f.mint.base58229    let hash = f.blockhash.base58230    let wallet = #"{"data":["","base64"],"executable":false,"lamports":5000000,"owner":"11111111111111111111111111111111","rentEpoch":0,"space":0}"#231    let mintAccount = #"{"data":{"parsed":{"info":{"decimals":6,"freezeAuthority":null,"isInitialized":true,"mintAuthority":null,"supply":"1000000000000","extensions":[{"extension":"permanentDelegate","state":{}}]},"type":"mint"},"program":"spl-token-2022","space":82},"executable":false,"lamports":1461600,"owner":"TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb","space":82}"#232    let tokenAccount = #"{"data":{"parsed":{"info":{"isNative":false,"mint":"\#(mint)","owner":"\#(payer)","state":"initialized","tokenAmount":{"amount":"18446744073709551615","decimals":6,"uiAmount":1.0,"uiAmountString":"1"}},"type":"account"},"program":"spl-token","space":165},"executable":false,"lamports":2039280,"owner":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","space":165}"#233    func value(_ v: String) -> String { #"{"context":{"slot":5},"value":\#(v)}"# }234    let status = #"{"slot":7,"confirmations":3,"err":null,"confirmationStatus":"confirmed"}"#235    let results: [(String, String)] = [236        ("a", value("18446744073709551615")),237        ("b", value(#"{"blockhash":"\#(hash)","lastValidBlockHeight":4150}"#)),238        ("c", value(wallet)), ("c", value("null")),239        ("d", value(mintAccount)),240        ("e", value(#"[{"account":\#(tokenAccount),"pubkey":"\#(other)"}]"#)),241        ("f", value(tokenAccount)),242        ("g", #"[{"blockTime":1796448657,"confirmationStatus":"finalized","err":null,"memo":null,"signature":"\#(f.signature)","slot":5}]"#),243        ("h", solanaHistorySeed()), ("h", "null"),244        ("i", value(#"{"err":null,"logs":["Program log: ok"],"unitsConsumed":450}"#)),245        ("i", value(#"{"err":{"InstructionError":[2,{"Custom":1}]},"logs":[],"unitsConsumed":0}"#)),246        ("j", value("[\(status)]")), ("j", value("[null]")),247        ("k", #"[{"slot":1,"prioritizationFee":0},{"slot":2,"prioritizationFee":18446744073709551615}]"#),248        ("l", value("5000")), ("m", "890880"), ("n", "5"), ("o", "4000"),249        ("p", "\"\(SolanaNetwork.devnet.genesisHash)\""),250        ("q", "\"\(f.signature)\""),251        ("r", value("[\(status)]")), ("r", value("[null]")),252        ("s", value("true")), ("s", value("false")),253        ("t", value(wallet)), ("u", value(mintAccount)), ("v", "[]"),254    ]255    return results.map { Bytes(($0.0 + #"{"jsonrpc":"2.0","id":1,"result":"# + $0.1 + "}").utf8) }256        + [Bytes(#"q{"jsonrpc":"2.0","id":1,"error":{"code":-32002,"message":"Transaction simulation failed: Blockhash not found"}}"#.utf8),257           Bytes(#"a{"jsonrpc":"2.0","id":1,"error":{"code":429,"message":"Too many requests"}}"#.utf8)]258}259260private func solanaHistorySeed() -> String {261    let f = SolanaFixture.self262    func balance(_ index: Int, _ owner: String, _ amount: String) -> String {263        #"{"accountIndex":\#(index),"mint":"\#(f.mint.base58)","owner":"\#(owner)","programId":"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","uiTokenAmount":{"amount":"\#(amount)","decimals":6,"uiAmount":null,"uiAmountString":"0"}}"#264    }265    return #"{"blockTime":1796448657,"slot":5,"version":"legacy","meta":{"err":null,"fee":5025,"preBalances":[5000000000,1,1],"postBalances":[3765427085,1234567891,1],"#266        + #""preTokenBalances":[\#(balance(1, f.payer.base58, "9000000")),\#(balance(2, f.other.base58, "5"))],"postTokenBalances":[\#(balance(1, f.payer.base58, "7500000")),\#(balance(2, f.other.base58, "1500005"))]},"#267        + #""transaction":{"message":{"accountKeys":[{"pubkey":"\#(f.payer.base58)","signer":true,"source":"transaction","writable":true},{"pubkey":"\#(f.other.base58)","signer":false,"writable":true},"11111111111111111111111111111111"],"recentBlockhash":"\#(f.blockhash.base58)"},"signatures":["\#(f.signature)"]}}"#268}269270let solanaTargets: [FuzzTarget] = [271    FuzzTarget(272        "solana-compact-u16", "Solana compact-u16 length: strict decoding (shortest form only, at most 3 bytes, below 2^16) and its inverse", maxLength: 8,273        tokens: [[0x00], [0x7f], [0x80, 0x01], [0xff, 0x7f], [0x80, 0x80, 0x01], [0xff, 0xff, 0x03], [0x80, 0x00], [0x80, 0x80, 0x00], [0xff, 0xff, 0x04], [0xff, 0xff, 0xff, 0x01]],274        seeds: { [[0x00], [0x7f], [0x80, 0x01], [0xff, 0x7f], [0x80, 0x80, 0x01], [0xff, 0xff, 0x03], [0x05, 0xaa]] }275    ) { input in276        var offset = 0277        if let value = SolanaCompactU16.decode(input, at: &offset) {278            FuzzOutcome.note("ok\(offset)")279            fuzzCheck(offset >= 1 && offset <= 3 && offset <= input.count, "offset out of range")280            fuzzCheck(SolanaCompactU16.encode(value) == Bytes(input[0..<offset]), "a non-canonical length was accepted")281        } else {282            FuzzOutcome.note("refused")283            fuzzCheck(offset <= min(3, input.count), "the cursor went past the input")284            // nothing shorter than three bytes is refused unless it is truncated or over-long285            if let first = input.first, first & 0x80 == 0 { fuzzFail("a one-byte length was refused") }286        }287        // every value encodes to something that decodes to itself, consuming exactly its bytes288        var input2 = FuzzInput(input)289        let value = UInt16(input2.byte()) << 8 | UInt16(input2.byte())290        let encoded = SolanaCompactU16.encode(value)291        var cursor = 0292        fuzzCheck(SolanaCompactU16.decode(encoded + input, at: &cursor) == value && cursor == encoded.count, "encode then decode")293    },294295    FuzzTarget(296        "solana-address", "Solana address text (strict base58 of 32 bytes), curve membership, program-derived addresses", maxLength: 600, text: true,297        dictionary: ["11111111111111111111111111111111", "1", "l", "0", "O", "I", " ", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG"],298        seeds: {299            let f = SolanaFixture.self300            let ata = (try? SolanaAddress.associatedTokenAccount(owner: f.payer, mint: f.mint).base58) ?? ""301            return ([f.payer.base58, f.other.base58, f.mint.base58, ata, "11111111111111111111111111111111", "So11111111111111111111111111111111111111112",302                     "1111111111111111111111111111111", "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", "TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH",303                     "JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG"] + [f.signature]).map { Bytes($0.utf8) }304        }305    ) { input in306        let text = fuzzString(input)307        let key = SolanaPublicKey(base58: text)308        fuzzCheck((key != nil) == SolanaAddress.isValid(text), "isValid disagrees with the parser")309        if let key {310            FuzzOutcome.note(key.isOnCurve ? "on-curve" : "off-curve")311            fuzzCheck(key.bytes.count == 32 && key.base58 == text, "an address is not the canonical text of its bytes")312            fuzzCheck(SolanaPublicKey(bytes: key.bytes) == key && key.description == text, "bytes round trip")313            fuzzCheck(key.isOnCurve == Ed25519.isOnCurve(key.bytes), "curve membership")314        } else {315            FuzzOutcome.note("refused")316        }317        // the bytes themselves as seeds and program of a derived address318        var cursor = FuzzInput(input)319        let program = SolanaPublicKey(bytes: cursor.take(32))!320        fuzzCheck(SolanaPublicKey(base58: program.base58) == program, "base58 of 32 bytes does not parse back")321        var seeds = [Bytes]()322        for _ in 0..<(Int(cursor.byte()) % 18) { seeds.append(cursor.upTo(Int(cursor.byte()) % 34)) }323        let created = SolanaAddress.createProgramAddress(seeds: seeds, programID: program)324        if let created { fuzzCheck(!created.isOnCurve, "a program address on the curve") }325        if let found = attempt("pda-", { try SolanaAddress.findProgramAddress(seeds: seeds, programID: program) }) {326            fuzzCheck(!found.address.isOnCurve, "a found program address on the curve")327            fuzzCheck(SolanaAddress.createProgramAddress(seeds: seeds + [[found.bump]], programID: program) == found.address, "find and create disagree")328            fuzzCheck(seeds.count < 16 && seeds.allSatisfy { $0.count <= 32 }, "seed limits")329        }330        fuzzUse(created?.bytes.first ?? 0)331    },332333    FuzzTarget(334        "solana-base64", "Strict base64 of the Solana transport (RFC 4648 with padding, canonical trailing bits)", maxLength: 2048, text: true,335        dictionary: ["=", "==", "+", "/", "A", "AA==", "AAA=", "AAAA", "-", "_", "\n"],336        seeds: { [[], [0], [0, 1], [0, 1, 2], Bytes(repeating: 0xff, count: 64)].map { Bytes(SolanaBase64.encode($0).utf8) } + SolanaFixture.unsignedTransactions().prefix(2).map { Bytes(SolanaBase64.encode($0).utf8) } }337    ) { input in338        let text = fuzzString(input)339        if let bytes = SolanaBase64.decode(text) {340            FuzzOutcome.note("ok")341            fuzzCheck(SolanaBase64.encode(bytes) == text, "a non-canonical base64 text was accepted")342            fuzzCheck(Data(base64Encoded: text).map { Bytes($0) } == bytes, "Foundation decodes it differently")343        } else {344            FuzzOutcome.note("refused")345        }346        fuzzCheck(SolanaBase64.decode(SolanaBase64.encode(input)) == input, "encode then decode")347        attempt("tx-") { try SolanaTransaction.decode(base64: text) }348    },349350    FuzzTarget(351        "solana-message", "Solana message (legacy and version 0): strict decoding, canonical re-encoding, account roles, recompilation", maxLength: 1400,352        tokens: [[0x80], [0x81], [0x80, 0x00], [0x80, 0x80, 0x00], [0xff, 0xff, 0x03], [0x01, 0x00, 0x01], SolanaProgram.system.bytes, SolanaProgram.computeBudget.bytes,353                 SolanaProgram.token.bytes, [0x02, 0x00, 0x00, 0x00], [0x0c]],354        seeds: { SolanaFixture.messages().map { $0.serialize() } + [SolanaFixture.versioned] }355    ) { input in356        guard let message = attempt({ try SolanaMessage.decode(input) }) else { return }357        fuzzCheck(message.serialize() == input, "a decoded message does not serialize to the bytes it came from")358        FuzzOutcome.note(message.version == .v0 ? "v0" : "legacy")359        let keys = message.accountKeys.count360        fuzzCheck(keys >= 1 && keys <= 256 && Set(message.accountKeys).count == keys, "account keys")361        fuzzCheck(message.signers.count == Int(message.numRequiredSignatures) && message.signers.first == message.feePayer, "signers")362        fuzzCheck(message.isSigner(index: 0) && message.isWritable(index: 0), "the fee payer must be a writable signer")363        fuzzCheck(keys + message.lookedUpAccountCount <= 256, "more than 256 accounts")364        var writable = 0365        for index in 0..<keys where message.isWritable(index: index) { writable += 1 }366        fuzzCheck(writable == keys - Int(message.numReadonlySignedAccounts) - Int(message.numReadonlyUnsignedAccounts), "writable accounts do not match the header")367        var resolved = [SolanaInstruction]()368        for position in 0...message.instructions.count {369            guard let instruction = message.instruction(at: position) else { continue }370            fuzzCheck(instruction.programID != message.feePayer, "the fee payer used as a program")371            resolved.append(instruction)372        }373        SolanaFixture.review(message)374        // without lookup tables every instruction resolves, and the module's own compiler gives a message it accepts375        guard message.addressTableLookups.isEmpty else { return }376        fuzzCheck(resolved.count == message.instructions.count, "an instruction of a message without lookups did not resolve")377        guard let compiled = attempt("compile-", { try SolanaMessage(feePayer: message.feePayer, instructions: resolved, recentBlockhash: message.recentBlockhash) }) else { return }378        let again = try? SolanaMessage.decode(compiled.serialize())379        fuzzCheck(again == compiled, "a compiled message is refused or changed by the decoder")380        fuzzCheck(compiled.accountKeys.count <= keys && Set(compiled.accountKeys).isSubset(of: Set(message.accountKeys)), "compilation invented an account")381        for index in 0..<compiled.accountKeys.count {382            // a role is never widened beyond what the decoded message granted383            guard let before = message.accountKeys.firstIndex(of: compiled.accountKeys[index]) else { continue }384            fuzzCheck(!compiled.isSigner(index: index) || message.isSigner(index: before), "compilation made a signer")385            fuzzCheck(!compiled.isWritable(index: index) || message.isWritable(index: before), "compilation made an account writable")386        }387        for (n, wanted) in resolved.enumerated() {388            guard let got = compiled.instruction(at: n) else { fuzzFail("a compiled instruction does not resolve") }389            fuzzCheck(got.programID == wanted.programID && got.data == wanted.data && got.accounts.map(\.publicKey) == wanted.accounts.map(\.publicKey), "compilation changed an instruction")390        }391    },392393    FuzzTarget(394        "solana-transaction", "Solana transaction, signed or not: strict decoding, signature count, canonical re-encoding; only the committed signed seeds verify",395        maxLength: 1400, acceptOnlySeeds: true,396        tokens: [[0x00], [0x01], [0x02], [0x80], Bytes(repeating: 0, count: 64), SolanaFixture.payer.bytes, [0x80, 0x00]],397        seeds: { SolanaFixture.signedTransactions() + SolanaFixture.unsignedTransactions() }398    ) { input in399        guard let tx = attempt({ try SolanaTransaction.decode(input) }) else { return }400        fuzzCheck(input.count <= SolanaTransaction.maximumSize, "a transaction above the packet size was accepted")401        fuzzCheck((try? tx.serialize()) == input, "a decoded transaction does not serialize to the bytes it came from")402        fuzzCheck(tx.signatures.count == Int(tx.message.numRequiredSignatures) && tx.signatures.allSatisfy { $0.count == 64 }, "signature count")403        fuzzCheck((tx.id == nil) == (tx.signatures[0] == Bytes(repeating: 0, count: 64)), "identifier of an unsigned transaction")404        fuzzCheck(tx.id.map(SolanaRPC.isSignature) ?? true, "the identifier is not a signature")405        fuzzCheck((try? SolanaTransaction.decode(base64: SolanaBase64.encode(input))) == tx, "base64 transport")406        if tx.verifySignatures() {407            fuzzCheck(tx.isFullySigned, "a transaction with an empty signature slot verifies")408            FuzzOutcome.accept()409        } else {410            FuzzOutcome.note(tx.isFullySigned ? "bad-signature" : "unsigned")411        }412        // signing by a key that is not a signer is refused and changes nothing; signing by the fixed payer verifies413        var copy = tx414        if tx.message.signers.contains(SolanaFixture.payer) {415            fuzzCheck((try? copy.sign(privateSeed: SolanaFixture.payerSeed)) != nil, "a required signer could not sign")416            fuzzCheck(copy.message == tx.message, "signing changed the message")417            if tx.message.signers == [SolanaFixture.payer] { fuzzCheck(copy.verifySignatures() && copy.isFullySigned, "our own signature does not verify") }418        } else {419            fuzzCheck((try? copy.sign(privateSeed: SolanaFixture.payerSeed)) == nil && copy == tx, "a key that is not a signer signed")420        }421    },422423    FuzzTarget(424        "solana-instructions", "Solana instruction classification (System, Compute Budget, Token, Token-2022, Associated Token Account, Memo): exact layouts only",425        maxLength: 512,426        tokens: [[0x02, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00], [0x0c], [0x03], [0x04], [0x05], [0x09], [0x0d], [0x11], [0x01], [0xff], Endian.le64(.max), [0xe2, 0x80, 0xae], [0x0a]],427        seeds: {428            var list = SolanaFixture.foreignInstructions()429            for message in SolanaFixture.messages() { list += (0..<message.instructions.count).compactMap { message.instruction(at: $0) } }430            return list.map(SolanaFixture.encode) + [Bytes([5, 0]) + Bytes("a\nWarning: x".utf8), Bytes([5, 0, 0xff, 0xfe])]431        }432    ) { input in433        let instruction = SolanaFixture.decodeInstruction(input)434        let decoded = SolanaDecodedInstruction.decode(instruction)435        FuzzOutcome.note(String(describing: decoded))436        SolanaFixture.check(decoded, against: instruction)437        // a recognised instruction of a fixed layout is recognised whatever the roles the message gives its accounts438        if !decoded.isUnknown {439            let flipped = SolanaInstruction(programID: instruction.programID, accounts: instruction.accounts.map { SolanaAccountMeta($0.publicKey, isSigner: !$0.isSigner, isWritable: !$0.isWritable) }, data: instruction.data)440            fuzzCheck(SolanaDecodedInstruction.decode(flipped) == decoded, "classification depends on the account roles")441        }442        // one more byte of data or one more account is another instruction: never the same recognised one443        if !decoded.isUnknown, instruction.programID != SolanaProgram.memo, instruction.programID != SolanaProgram.memoV1 {444            // (the Associated Token Account program reads no data and a single zero byte as the same instruction, Create)445            let longer = SolanaInstruction(programID: instruction.programID, accounts: instruction.accounts, data: instruction.data + [0])446            fuzzCheck(SolanaDecodedInstruction.decode(longer) != decoded || (instruction.programID == SolanaProgram.associatedToken && instruction.data.isEmpty), "trailing data ignored by the classification")447            let wider = SolanaInstruction(programID: instruction.programID, accounts: instruction.accounts + [SolanaAccountMeta(SolanaFixture.other, isSigner: true, isWritable: true)], data: instruction.data)448            fuzzCheck(SolanaDecodedInstruction.decode(wider).isUnknown, "an extra account (multisignature, hook) was ignored by the classification")449        }450    },451452    FuzzTarget(453        "solana-review", "Unsigned Solana transaction as a cold device receives it (base64 text): canonical bytes, review, limits view; what is reviewed is what is signed",454        maxLength: 2048, text: true,455        dictionary: ["AQ", "gA", "=", "==", "AAAA", "/", "+"],456        seeds: { (SolanaFixture.unsignedTransactions() + SolanaFixture.signedTransactions().prefix(2)).map { Bytes(SolanaBase64.encode($0).utf8) } }457    ) { input in458        // exactly what `WalletService.decodeSolana` does with the payload of a cold envelope459        guard let bytes = SolanaBase64.decode(fuzzString(input)) else {460            FuzzOutcome.note("not-base64")461            return462        }463        guard let tx = attempt({ try SolanaTransaction.decode(bytes) }) else { return }464        fuzzCheck((try? tx.serialize()) == bytes, "the reviewed transaction is not the bytes received")465        SolanaFixture.review(tx.message)466        // the bytes a signature would cover are the reviewed message, byte for byte467        var signed = tx468        if tx.message.signers == [SolanaFixture.payer], (try? signed.sign(privateSeed: SolanaFixture.payerSeed)) != nil {469            fuzzCheck(signed.message == tx.message && signed.message.serialize() == tx.message.serialize(), "signing changed the reviewed message")470            fuzzCheck(Ed25519.verify(signature: signed.signatures[0], message: tx.message.serialize(), publicKey: SolanaFixture.payer.bytes), "the signature does not cover the reviewed bytes")471            let wire = try? signed.serialize()472            fuzzCheck(wire.flatMap { try? SolanaTransaction.decode($0) }?.message.review() == tx.message.review(), "the signed transaction reviews differently")473        }474    },475476    FuzzTarget(477        "solana-json", "Strict JSON reader of the Solana client (exact 64-bit integers, bounded depth, no duplicate key)", maxLength: 4096, text: true,478        dictionary: ["{", "}", "[", "]", "\"", ":", ",", "null", "true", "false", "18446744073709551615", "18446744073709551616", "-9223372036854775808", "-0", "1e999", "\\u0000", "\\ud83d\\ude00", "\\ud83d", "\"a\":1,\"a\":2"],479        seeds: { solanaRPCSeeds().map { Bytes($0.dropFirst()) } + [Bytes(#"{"a":[1,2.5,-3e2,"x\né",null,true,{"b":{}}]}"#.utf8), Bytes((String(repeating: "[", count: 64) + String(repeating: "]", count: 64)).utf8)] }480    ) { input in481        guard let value = SolanaJSON.parse(input) else {482            FuzzOutcome.note("refused")483            fuzzCheck(SolanaJSON.parse(input, maximumDepth: 8) == nil, "accepted with a smaller depth limit")484            return485        }486        FuzzOutcome.note("ok")487        let text = value.serialized()488        fuzzCheck(SolanaJSON.parse(Bytes(text.utf8)) == value, "serialize then parse")489        fuzzCheck(SolanaJSON.parse(Bytes(text.utf8))?.serialized() == text, "serialization is not stable")490        func walk(_ v: SolanaJSON, _ depth: Int) {491            fuzzCheck(depth <= SolanaJSON.defaultMaximumDepth, "nesting beyond the limit")492            switch v {493            case .number:494                if let u = v.uint64 { fuzzCheck(v == .number(String(u)) && SolanaJSON.integer(u) == v, "uint64 of a number that is not its text") }495                if let i = v.int64, i >= 0, let u = v.uint64 { fuzzCheck(UInt64(i) == u, "int64 and uint64 disagree") }496            case .array(let a): a.forEach { walk($0, depth + 1) }497            case .object(let o): o.values.forEach { walk($0, depth + 1) }498            default: break499            }500        }501        walk(value, 0)502    },503504    FuzzTarget(505        "solana-json-rpc", "Solana JSON-RPC answers: balance, blockhash, accounts, mints, token accounts, signatures, transactions, simulation, statuses, fees, send, tracking, snapshot",506        maxLength: 4096, text: true,507        dictionary: ["\"result\":", "\"value\":", "\"error\":", "null", "18446744073709551615", "18446744073709551616", "-1", "1e3", "\"lamports\":", "\"owner\":", "\"decimals\":", "256",508                     "\"amount\":\"", "\"extensions\":", "\"extension\":\"transferHook\"", "\"state\":\"frozen\"", "\"err\":", "\"confirmationStatus\":\"finalized\"", "\"id\":2",509                     "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", "11111111111111111111111111111111", "\"type\":\"mint\"", "\"type\":\"account\""],510        seeds: solanaRPCSeeds511    ) { input in512        guard let selector = input.first else { return }513        let f = SolanaFixture.self514        let client = SolanaRPC(network: .devnet, endpoints: SolanaEndpoints(rpc: ["devnet": ["https://solana.fuzz.test", "https://solana2.fuzz.test"]]),515                               transport: StubTransport(body: Data(input.dropFirst()), status: 200))516        let choice = fuzzSelector(selector, 22)517        fuzzAwait {518            do {519                switch choice {520                case 0: fuzzUse(try await client.balance(of: f.payer))521                case 1:522                    let hash = try await client.latestBlockhash()523                    fuzzCheck(hash.blockhash.count == 32 && Base58.bitcoin.decode(hash.base58) == hash.blockhash, "blockhash")524                case 2:525                    if let account = try await client.accountInfo(f.other) { fuzzUse(account.lamports &+ account.space) }526                case 3:527                    if let mint = try await client.mintInfo(f.mint) {528                        fuzzCheck(mint.address == f.mint && mint.extensions.count <= 64 && mint.extensions.allSatisfy { $0.count <= 64 }, "mint")529                        // the refusal rule: a Token-2022 mint is sendable only when every extension is known harmless530                        if mint.transferRefusal == nil, mint.program == .token2022 {531                            fuzzCheck(mint.extensionsKnown && mint.isInitialized && Set(mint.extensions).isSubset(of: SolanaMintInfo.harmlessExtensions), "an unsupported mint is sendable")532                        }533                        FuzzOutcome.note(mint.transferRefusal == nil ? "sendable" : "refused-mint")534                    }535                case 4:536                    let accounts = try await client.tokenAccounts(owner: f.payer)537                    fuzzCheck(accounts.count <= SolanaRPC.maximumTokenAccounts && accounts.allSatisfy { $0.owner == f.payer && $0.state.count <= 32 }, "token accounts of another owner, or too many")538                case 5:539                    if let account = try await client.tokenAccount(f.other) { fuzzCheck(account.address == f.other && account.state.count <= 32, "token account") }540                case 6:541                    let list = try await client.signatures(for: f.payer, limit: 7)542                    fuzzCheck(list.count <= 7 && list.allSatisfy { SolanaRPC.isSignature($0.signature) }, "signatures")543                case 7:544                    if let json = try await client.transaction(f.signature) { fuzzUse(try SolanaHistory.entry(transaction: json, signature: f.signature, for: f.payer).fee) }545                case 8:546                    guard let tx = f.plans().first?.transaction else { return }547                    let simulation = try await client.simulate(tx)548                    fuzzCheck(simulation.logs.count <= SolanaRPC.maximumLogLines && simulation.logs.allSatisfy { $0.count <= 500 } && (simulation.error?.count ?? 0) <= 200, "simulation bounds")549                    fuzzCheck(simulation.succeeded == (simulation.error == nil), "simulation verdict")550                case 9:551                    let statuses = try await client.signatureStatuses([f.signature])552                    fuzzCheck(statuses.count == 1 && (statuses[0]?.error?.count ?? 0) <= 200, "statuses")553                case 10:554                    let fees = try await client.recentPrioritizationFees(accounts: [f.payer])555                    let price = SolanaFees.suggestedUnitPrice(recentFees: fees)556                    fuzzCheck(fees.count <= 150 && price >= SolanaFees.minimumUnitPrice && price <= SolanaFees.maximumUnitPrice, "suggested price outside its bounds")557                case 11:558                    guard let message = f.plans().first?.transaction.message else { return }559                    fuzzUse(try await client.feeForMessage(message) ?? 0)560                case 12: fuzzUse(try await client.minimumBalanceForRentExemption(dataLength: 165))561                case 13: fuzzUse(try await client.slot())562                case 14: fuzzUse(try await client.blockHeight())563                case 15: try await client.verifyChain()564                case 16:565                    guard let bytes = f.signedTransactions().first, let tx = try? SolanaTransaction.decode(bytes) else { return }566                    let id = try await client.send(tx)567                    fuzzCheck(id == tx.id, "send returned an identifier that is not the first signature")568                case 17:569                    let verdict = try await client.track(signature: f.signature, lastValidBlockHeight: 100)570                    FuzzOutcome.note(String(describing: verdict))571                case 18: fuzzUse(try await client.isRecentBlockhash(f.blockhash.blockhash))572                case 19, 20:573                    // the whole read of a send, then the planner on whatever it returned574                    let asset: SolanaSendRequest.Asset = choice == 19 ? .sol : .token(mint: f.mint)575                    let request = SolanaSendRequest(sender: f.payer, recipient: f.other, asset: asset, amount: .max)576                    let snapshot = try await client.snapshot(for: request)577                    if let plan = try? SolanaSendPlanner.plan(request, snapshot: snapshot) { solanaCheckPlan(plan, request: request, snapshot: snapshot) }578                default:579                    let history = try await client.history(of: f.payer, limit: 3)580                    fuzzCheck(history.count <= 3, "history page")581                }582                FuzzOutcome.note("ok\(choice)")583            } catch {584                FuzzOutcome.note("error\(choice)")585            }586        }587    },588589    FuzzTarget(590        "solana-history", "getTransaction answer (jsonParsed) to balance changes of one account, then to the wallet's activity lines", maxLength: 4096, text: true,591        dictionary: ["\"preBalances\":", "\"postBalances\":", "\"preTokenBalances\":", "\"postTokenBalances\":", "\"owner\":", "\"mint\":", "\"amount\":\"", "\"decimals\":", "\"fee\":",592                     "18446744073709551615", "\"err\":null", "\"err\":{}", "\"accountKeys\":", "\"pubkey\":", "\"signatures\":", "\"blockTime\":-1", "9223372036854775807", "null"],593        seeds: {594            let seed = solanaHistorySeed()595            return [Bytes(seed.utf8), Bytes(seed.replacingOccurrences(of: #""err":null"#, with: #""err":{"InstructionError":[0,"Custom"]}"#).utf8),596                    Bytes(seed.replacingOccurrences(of: "\"fee\":5025", with: "\"fee\":18446744073709551615").utf8)]597        }598    ) { input in599        let f = SolanaFixture.self600        guard let json = SolanaJSON.parse(input) else {601            FuzzOutcome.note("not-json")602            return603        }604        for owner in [f.payer, f.other] {605            guard let entry = attempt("entry-", { try SolanaHistory.entry(transaction: json, signature: f.signature, for: owner) }) else { continue }606            fuzzCheck(entry.signature == f.signature && entry.tokenChanges.allSatisfy { !$0.change.isZero }, "a zero token change is reported")607            fuzzCheck(Set(entry.tokenChanges.map(\.mint)).count == entry.tokenChanges.count && entry.tokenChanges.count <= 2048, "one line per mint")608            fuzzCheck(!(entry.nativeChange.isNegative && entry.nativeChange.isZero), "negative zero")609            let info = SolanaSignatureInfo(signature: f.signature, slot: entry.slot, blockTime: entry.blockTime, failed: !entry.succeeded, confirmationStatus: .finalized)610            let lines = WalletService.activity(entry, info: info, owner: owner, chain: .solanaDevnet, tokens: [:])611            fuzzCheck(!lines.isEmpty && lines.count <= entry.tokenChanges.count + 1, "activity lines")612            fuzzCheck(lines.filter { $0.fee != nil }.count <= 1, "the fee is shown more than once")613            fuzzCheck(lines.allSatisfy { $0.amount.uint64 != nil && $0.hash == f.signature }, "an amount beyond 64 bits")614            fuzzCheck(Set(lines.map(\.id)).count == lines.count, "activity identifiers are not unique")615            if entry.isInitiator(owner) { fuzzCheck(lines.contains { $0.fee == UInt256(entry.fee) }, "the fee the account paid is not shown") }616        }617    },618619    FuzzTarget(620        "solana-planner", "Solana send planner on hostile chain figures (balances, rent minimums, prices, limits from an endpoint): no trap, sound plans", maxLength: 96,621        tokens: [Endian.le64(.max), Endian.le64(.max - 1), Endian.le64(0), Endian.le64(1), Endian.le64(890_880), Endian.le64(2_039_280), Endian.le64(5_025), Endian.le64(5_000), Endian.le64(10_000_000),622                 Endian.le64(UInt64(Int64.max))],623        seeds: {624            func seed(_ flags: UInt8, _ values: [UInt64], limit: UInt32 = 0, decimals: UInt8 = 6) -> Bytes {625                [flags] + values.flatMap(Endian.le64) + Endian.le32(limit) + [decimals]626            }627            // sender lamports, recipient lamports, rent, token rent, amount, price, token balance628            return [seed(0x00, [5_000_000_000, 5_000_000, 890_880, 2_039_280, 1_234_567_890, 5_000, 0]),629                    seed(0x02, [5_000_000_000, 0, 890_880, 2_039_280, 0, 5_000, 0]),630                    seed(0x01, [50_000_000, 1, 890_880, 2_039_280, 1_500_000, 5_000, 9_000_000]),631                    seed(0x0d, [50_000_000, 1, 890_880, 2_074_080, 1, 77_777, 9_000_000], limit: 200_000),632                    seed(0x00, [1_000_000, .max, .max, .max, 1, 5_000, 0]),633                    seed(0x41, [.max, .max, .max, .max, .max, .max, .max], limit: .max, decimals: 255)]634        }635    ) { input in636        var cursor = FuzzInput(input)637        let flags = cursor.byte()638        func u64(_ c: inout FuzzInput) -> UInt64 { c.take(8).withUnsafeBufferPointer { Endian.loadLE64($0.baseAddress!) } }639        let senderLamports = u64(&cursor), recipientLamports = u64(&cursor), rent = u64(&cursor), tokenRent = u64(&cursor)640        let amount = u64(&cursor), price = u64(&cursor), balance = u64(&cursor)641        let limit = cursor.take(4).withUnsafeBufferPointer { Endian.loadLE32($0.baseAddress!) }642        let decimals = cursor.byte()643        let f = SolanaFixture.self644        let isToken = flags & 0x01 != 0645        let program: SolanaTokenProgram.Kind = flags & 0x04 != 0 ? .token2022 : .token646        let extensions: [String] = flags & 0x20 != 0 ? ["permanentDelegate", flags & 0x10 != 0 ? "transferHook" : "tokenMetadata"] : []647        let recipientAccount: SolanaChainSnapshot.Account = flags & 0x40 != 0 ? .other(owner: SolanaProgram.token) : (recipientLamports == 0 ? .missing : .system(lamports: recipientLamports))648        let recipient = flags & 0x80 != 0 ? ((try? SolanaAddress.associatedTokenAccount(owner: f.other, mint: f.mint)) ?? f.other) : f.other649        let mint = SolanaMintInfo(address: f.mint, program: program, decimals: decimals, supply: balance, isInitialized: true, extensions: extensions)650        let token = SolanaChainSnapshot.Token(mint: mint, senderBalance: flags & 0x10 != 0 && balance % 7 == 0 ? nil : balance, senderFrozen: false, recipientAccountExists: flags & 0x08 == 0,651                                              tokenAccountRent: tokenRent)652        let snapshot = SolanaChainSnapshot(senderLamports: senderLamports, recipient: recipientAccount, systemAccountRent: rent, blockhash: f.blockhash, token: isToken ? token : nil)653        let request = SolanaSendRequest(sender: f.payer, recipient: recipient, asset: isToken ? .token(mint: f.mint) : .sol, amount: flags & 0x02 != 0 ? .max : .exact(amount),654                                        memo: flags & 0x20 != 0 && !isToken ? "note" : nil, computeUnitPrice: price, computeUnitLimit: limit == 0 ? nil : limit)655        do {656            let plan = try SolanaSendPlanner.plan(request, snapshot: snapshot)657            FuzzOutcome.note("plan")658            solanaCheckPlan(plan, request: request, snapshot: snapshot)659        } catch let error as SolanaSendRefusal {660            FuzzOutcome.note(error: error)661            // a refusal carries figures that are consistent with the snapshot662            if case .senderBelowRentExemption(let remaining, let minimum, let sendable) = error {663                fuzzCheck(remaining > 0 && remaining < minimum && minimum == rent && sendable <= senderLamports, "rent refusal figures")664            }665            if case .insufficientLamports(_, let available) = error { fuzzCheck(available == senderLamports, "available lamports of the refusal") }666        } catch {667            fuzzFail("the planner threw something that is not a refusal")668        }669    },670]671672/// What must hold for every plan the planner accepts, whatever the snapshot said.673func solanaCheckPlan(_ plan: SolanaSendPlan, request: SolanaSendRequest, snapshot: SolanaChainSnapshot) {674    let f = SolanaFixture.self675    let available = snapshot.senderLamports, rent = snapshot.systemAccountRent676    // arithmetic: nothing leaves the sender beyond what it has, and it ends empty or rent-exempt677    let (partial, o1) = plan.signatureFee.addingReportingOverflow(plan.priorityFee)678    let (withCreation, o2) = partial.addingReportingOverflow(plan.accountCreationCost)679    let (total, o3) = withCreation.addingReportingOverflow(plan.asset == .sol ? plan.amount : 0)680    fuzzCheck(!o1 && !o2 && !o3 && total <= available && plan.totalLamports == total, "the plan spends more lamports than the sender has")681    fuzzCheck(plan.senderLamportsAfter == available - total && (plan.senderLamportsAfter == 0 || plan.senderLamportsAfter >= rent), "the sender is left below the rent-exempt minimum")682    fuzzCheck(plan.priorityFee <= SolanaSendPlanner.maximumPriorityFee && plan.signatureFee == 5_000, "fee ceiling")683    fuzzCheck(plan.computeUnitLimit >= 1 && plan.computeUnitLimit <= SolanaComputeBudget.maximumUnitLimit, "compute-unit limit")684    fuzzCheck(plan.amount > 0, "a plan for nothing")685    if case .max = request.amount, plan.asset == .sol { fuzzCheck(plan.senderLamportsAfter == 0 && plan.warnings.contains(.emptiesSender), "send-max leaves lamports") }686    if case .exact(let wanted) = request.amount { fuzzCheck(plan.amount == wanted, "the amount of the plan is not the amount asked") }687    if let token = snapshot.token, plan.asset != .sol {688        fuzzCheck(plan.amount <= (token.senderBalance ?? 0) && plan.decimals == token.mint.decimals && token.mint.transferRefusal == nil, "token plan")689        fuzzCheck(plan.accountCreationCost == (token.recipientAccountExists ? 0 : token.tokenAccountRent), "account creation cost")690    }691    fuzzCheck(!SolanaProgram.reserved.contains(request.recipient) && request.recipient != request.sender, "reserved recipient")692    fuzzCheck(plan.warnings.contains(.recipientOffCurve) == !request.recipient.isOnCurve, "off-curve warning")693    // the bytes: within the packet size, strict round trip, signed by the sender alone694    let tx = plan.transaction695    guard let wire = try? tx.serialize(), let again = try? SolanaTransaction.decode(wire) else { fuzzFail("the planned transaction does not serialize or decode") }696    fuzzCheck(again == tx && wire.count <= SolanaTransaction.maximumSize, "wire round trip")697    fuzzCheck(tx.message.version == .legacy && tx.message.signers == [f.payer] && tx.message.recentBlockhash == snapshot.blockhash.blockhash, "signers and blockhash")698    // what the review decodes from those bytes is what the plan says699    let review = plan.review700    fuzzCheck(!review.requiresBlindSigning && review.priorityFee == plan.priorityFee && review.signatureFee == plan.signatureFee, "review fees")701    let outflow = WalletService.solanaOutflow(review, owner: f.payer)702    fuzzCheck(!outflow.blind && outflow.other.isEmpty && outflow.createsAccounts == (plan.asset != .sol && snapshot.token?.recipientAccountExists == false ? 1 : 0), "outflow shape")703    switch plan.asset {704    case .sol:705        fuzzCheck(outflow.lamports == plan.amount && outflow.tokens.isEmpty, "lamports of the review")706        fuzzCheck(review.instructions.contains(.systemTransfer(from: f.payer, to: request.recipient, lamports: plan.amount)), "transfer of the review")707    case .token(let mint):708        fuzzCheck(outflow.lamports == 0 && outflow.tokens.count == 1 && outflow.tokens[mint.base58]?.amount == plan.amount && outflow.tokens[mint.base58]?.decimals == plan.decimals, "tokens of the review")709        fuzzCheck(plan.sourceTokenAccount != nil && plan.destinationTokenAccount != nil && plan.sourceTokenAccount != plan.destinationTokenAccount, "token accounts")710    }711}712
Files main
Menu

Theme