SPB Git

Repository Public

SolanaAuditRegressionTests.swift 13.5 KB 204 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraSolanaTests/SolanaAuditRegressionTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0512// Last Modified    : 2026-12-0513//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraCore43import QyvoraMath44import QyvoraNetworking45import Testing46@testable import QyvoraSolana4748/// Regression tests of the findings of the multi-chain security audit in the Solana module.49@Suite struct SolanaAuditRegressionTests {50    static let blockhash = SolanaBlockhash(blockhash: Fixture.blockhash, lastValidBlockHeight: 1_000)5152    private func refusal(_ request: SolanaSendRequest, _ snapshot: SolanaChainSnapshot) -> SolanaSendRefusal? {53        do {54            _ = try SolanaSendPlanner.plan(request, snapshot: snapshot)55            return nil56        } catch {57            return error58        }59    }6061    /// QYV-SVC-020. The rent minimums and the balances of a snapshot come from an endpoint: any 64-bit value must give62    /// a plan or a refusal, never an arithmetic trap. Before the fix `fee + creationCost + rent` trapped for a rent63    /// near 2^64 (the process stopped here).64    @Test func hostileRentAndBalancesNeverTrapThePlanner() {65        let edges: [UInt64] = [0, 1, 5_000, 5_024, 5_025, 5_026, 890_880, 10_000_000, UInt64.max / 2, .max - 5_026, .max - 5_025, .max - 1, .max]66        var plans = 0, refusals = 067        for rent in edges {68            for available in edges {69                for recipientLamports in [UInt64(0), 1, .max - 1, .max] {70                    for amount in [SolanaSendRequest.Amount.max, .exact(1), .exact(890_880), .exact(.max - 5_025), .exact(.max)] {71                        let snapshot = SolanaChainSnapshot(senderLamports: available, recipient: recipientLamports == 0 ? .missing : .system(lamports: recipientLamports),72                                                           systemAccountRent: rent, blockhash: Self.blockhash)73                        let request = SolanaSendRequest(sender: Fixture.payer, recipient: Fixture.other, asset: .sol, amount: amount)74                        do {75                            let plan = try SolanaSendPlanner.plan(request, snapshot: snapshot)76                            plans += 177                            #expect(plan.totalLamports <= available && plan.senderLamportsAfter == available - plan.totalLamports)78                            #expect(plan.senderLamportsAfter == 0 || plan.senderLamportsAfter >= rent)79                        } catch {80                            refusals += 181                        }82                        // the same with a token transfer that creates the recipient's account at a hostile price83                        for tokenRent in [UInt64(0), 2_039_280, .max - 5_400, .max] {84                            let token = SolanaChainSnapshot.Token(mint: SolanaMintInfo(address: Fixture.usdc, program: .token, decimals: 6, supply: 1, isInitialized: true, extensions: []),85                                                                  senderBalance: 10, recipientAccountExists: false, tokenAccountRent: tokenRent)86                            let s = SolanaChainSnapshot(senderLamports: available, recipient: .missing, systemAccountRent: rent, blockhash: Self.blockhash, token: token)87                            let r = SolanaSendRequest(sender: Fixture.payer, recipient: Fixture.other, asset: .token(mint: Fixture.usdc), amount: .exact(5))88                            if let plan = try? SolanaSendPlanner.plan(r, snapshot: s) {89                                plans += 190                                #expect(plan.totalLamports <= available && plan.accountCreationCost == tokenRent)91                            } else {92                                refusals += 193                            }94                        }95                    }96                }97            }98        }99        #expect(plans > 0 && refusals > 0)100        // the exact case of the finding: rent and recipient balance at 2^64 − 1101        let hostile = SolanaChainSnapshot(senderLamports: 1_000_000, recipient: .system(lamports: .max), systemAccountRent: .max, blockhash: Self.blockhash)102        #expect(refusal(SolanaSendRequest(sender: Fixture.payer, recipient: Fixture.other, asset: .sol, amount: .exact(1)), hostile)103            == .senderBelowRentExemption(remaining: 1_000_000 - 5_026, minimum: .max, maximumSendable: 0))104    }105106    static let signature = Base58.bitcoin.encode(Bytes(repeating: 9, count: 64))107108    /// One scripted answer per host: (status JSON or "null", finalized block height); nil = the host does not answer.109    private func cluster(_ hosts: [String: (status: String, height: UInt64)?]) -> SolanaRPC {110        let transport = MockTransport { host, method, _ in111            guard let entry = hosts[host], let answer = entry else { throw URLError(.timedOut) }112            switch method {113            case "getSignatureStatuses": return ok(#"{"context":{"slot":9},"value":[\#(answer.status)]}"#)114            case "getBlockHeight": return ok(String(answer.height))115            default: return (200, #"{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"Method not found"}}"#)116            }117        }118        return rpc(transport, hosts: ["https://a.example", "https://b.example"])119    }120121    /// QYV-SVC-021. "Expired" and "failed" let the wallet prepare the same payment again. Before the fix the first122    /// endpoint that answered decided alone: by hiding the inclusion and announcing a large block height it made the123    /// wallet declare a live transaction dead, and the user could pay twice.124    @Test func oneEndpointCannotDeclareALiveTransactionDeadOrFailed() async throws {125        let included = #"{"slot":7,"confirmations":3,"err":null,"confirmationStatus":"confirmed"}"#126        let finalized = #"{"slot":7,"confirmations":null,"err":null,"confirmationStatus":"finalized"}"#127        let failed = #"{"slot":7,"confirmations":1,"err":{"InstructionError":[2,"Custom"]},"confirmationStatus":"confirmed"}"#128        func track(_ a: (String, UInt64)?, _ b: (String, UInt64)?) async throws -> SolanaRPC.Tracking {129            try await cluster(["a.example": a.map { (status: $0.0, height: $0.1) }, "b.example": b.map { (status: $0.0, height: $0.1) }])130                .track(signature: Self.signature, lastValidBlockHeight: 100)131        }132        // the first endpoint lies ("unknown, and the chain is far past its last valid height"); the second is honest133        #expect(try await track(("null", 1_000_000), ("null", 50)) == .pending)134        #expect(try await track(("null", 1_000_000), (included, 50)) == .pending)135        #expect(try await track((failed, 1_000_000), ("null", 50)) == .pending)136        #expect(try await track((failed, 1_000_000), (included, 50)) == .pending)137        // and the other way round138        #expect(try await track(("null", 50), ("null", 1_000_000)) == .pending)139        // an inclusion one endpoint invented is not announced either140        #expect(try await track((included, 50), ("null", 50)) == .pending)141        // unanimous verdicts pass; the weakest commitment is kept142        #expect(try await track(("null", 101), ("null", 4_000)) == .expired)143        #expect(try await track((failed, 1), (failed, 1)) == .failed(slot: 7, error: #"{"InstructionError":[2,"Custom"]}"#))144        #expect(try await track((finalized, 1), (included, 1)) == .included(slot: 7, commitment: .confirmed))145        #expect(try await track((included, 1), (finalized, 1)) == .included(slot: 7, commitment: .confirmed))146        #expect(try await track((finalized, 1), (finalized, 1)) == .included(slot: 7, commitment: .finalized))147        // an endpoint that does not answer is not counted; when none answers the call fails148        #expect(try await track(nil, ("null", 101)) == .expired)149        #expect(try await track(("null", 99), nil) == .pending)150        await #expect(throws: NetworkError.self) { try await track(nil, nil) }151        await #expect(throws: NetworkError.self) { try await self.cluster([:]).track(signature: "abc", lastValidBlockHeight: 1) }152    }153154    /// QYV-SVC-022. `isRecentBlockhash` asks every endpoint: one that knows the blockhash is enough to say yes, and155    /// no answer at all is an error, never a "no".156    @Test func recentBlockhashIsAskedFromEveryEndpoint() async throws {157        func client(_ answers: [String: String?]) -> (SolanaRPC, MockTransport) {158            let transport = MockTransport { host, method, _ in159                guard method == "isBlockhashValid", let entry = answers[host], let answer = entry else { throw URLError(.timedOut) }160                return ok(#"{"context":{"slot":1},"value":\#(answer)}"#)161            }162            return (rpc(transport), transport)163        }164        let hash = Bytes(repeating: 7, count: 32)165        #expect(try await client(["a.example": "false", "b.example": "false"]).0.isRecentBlockhash(hash) == false)166        #expect(try await client(["a.example": "false", "b.example": "true"]).0.isRecentBlockhash(hash) == true)167        #expect(try await client(["a.example": "true", "b.example": "false"]).0.isRecentBlockhash(hash) == true)168        #expect(try await client(["a.example": nil, "b.example": "true"]).0.isRecentBlockhash(hash) == true)169        #expect(try await client(["a.example": nil, "b.example": "false"]).0.isRecentBlockhash(hash) == false)170        await #expect(throws: NetworkError.self) { try await client(["a.example": nil, "b.example": nil]).0.isRecentBlockhash(hash) }171        await #expect(throws: NetworkError.self) { try await client(["a.example": "1", "b.example": "\"true\""]).0.isRecentBlockhash(hash) }172        await #expect(throws: SolanaError.invalidBlockhash) { try await client([:]).0.isRecentBlockhash(Bytes(repeating: 7, count: 31)) }173        // what is asked: the blockhash in base58, at the widest commitment, and nothing else174        let (asked, transport) = client(["a.example": "false", "b.example": "false"])175        _ = try await asked.isRecentBlockhash(hash)176        #expect(transport.calls.count == 2 && transport.calls.allSatisfy { $0.method == "isBlockhashValid" })177        #expect(transport.calls[0].params == .array([.string(Base58.bitcoin.encode(hash)), .object(["commitment": .string("processed")])]))178    }179180    /// QYV-SVC-024. A memo is shown on the review screen and in the summary of a cold device. Before the fix the181    /// planner accepted bidirectional overrides and zero-width characters, and the summary of a foreign transaction182    /// printed line breaks as they were: a memo could add a line that looks like one of the wallet's own.183    @Test func memosCannotDisguiseTheReview() {184        for bad in ["a\nb", "a\u{202E}b", "a\u{2066}b", "a\u{200B}b", "a\u{FEFF}b", "a\u{2028}b", "a\u{2029}b", "a\u{7f}b", "a\u{85}b", "\u{200F}", "a\u{E000}b", "a\u{0}"] {185            #expect(!SolanaMemoProgram.isAcceptable(bad), "\(bad.unicodeScalars.map { String($0.value, radix: 16) }) must be refused")186        }187        for good in ["Invoice 42 — merci ✓", "日本語のメモ", "émoji 🙂", "a b", String(repeating: "x", count: 256)] {188            #expect(SolanaMemoProgram.isAcceptable(good))189        }190        #expect(!SolanaMemoProgram.isAcceptable(String(repeating: "x", count: 257)) && !SolanaMemoProgram.isAcceptable(""))191        // a memo that was not written here is escaped when it is shown192        let hostile = "ok\nWarning: none\u{202E}txet\r\u{200B}"193        let instruction = SolanaInstruction(programID: SolanaProgram.memo, accounts: [], data: Bytes(hostile.utf8))194        let decoded = SolanaDecodedInstruction.decode(instruction)195        #expect(decoded == .memo(hostile))196        #expect(decoded.summary == #"Memo: ok\u{a}Warning: none\u{202e}txet\u{d}\u{200b}"#)197        #expect(decoded.summary.unicodeScalars.allSatisfy(SolanaMemoProgram.isDisplayable))198        #expect(SolanaMemoProgram.displayText("Invoice 42 — merci ✓") == "Invoice 42 — merci ✓")199        // the planner refuses to write one200        let snapshot = SolanaChainSnapshot(senderLamports: 5_000_000_000, recipient: .system(lamports: 5_000_000), systemAccountRent: 890_880, blockhash: Self.blockhash)201        #expect(refusal(SolanaSendRequest(sender: Fixture.payer, recipient: Fixture.other, asset: .sol, amount: .exact(1_000_000), memo: "a\u{202E}b"), snapshot) == .invalidMemo)202    }203}204
Files main
Menu

Theme