SPB Git

Repository Public

SolanaDiffTests.swift 42.4 KB 643 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/DifferentialAuditTests/SolanaDiffTests.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 Testing4748@testable import QyvoraSolana4950// Solana against solders 0.29 (the Rust solana-sdk types behind Python bindings; ed25519-dalek and51// curve25519-dalek), with libsodium (PyNaCl) as a second signer and bip-utils for SLIP-0010:52//   addresses      base58 both ways, validity of text, curve membership (non-canonical and small-order encodings53//                  included: a different verdict would move every program-derived address);54//   derived        find_program_address with its bump, associated token accounts under both token programs;55//   payments       message, unsigned and signed transaction, signature, for random payments as the planner lays56//                  them out;57//   compilation    Message::new_with_blockhash on random instruction lists (ordering, de-duplication, privilege58//                  merging, several signers);59//   decoding       what solders builds decodes here to the same fields; altered and non-canonical encodings are60//                  refused here, and the campaign states where solders (bincode) is more lenient;61//   derivation     the account key from a BIP-39 seed.6263private let script = "solana"6465private func reference(_ what: String = "solana-sdk types, ed25519-dalek") -> String { MCOracle.label(script, "solders", what) }6667private func sameFields(_ message: SolanaMessage?, _ answer: Case) -> Bool {68    guard let message else { return false }69    guard answer.string("version") == (message.version == .v0 ? "v0" : "legacy") else { return false }70    guard answer["header"] as? [Int] == [Int(message.numRequiredSignatures), Int(message.numReadonlySignedAccounts), Int(message.numReadonlyUnsignedAccounts)] else { return false }71    guard answer["keys"] as? [String] == message.accountKeys.map({ hex($0.bytes) }), answer.string("blockhash") == hex(message.recentBlockhash) else { return false }72    let instructions = (answer["instructions"] as? [[Any]] ?? []).map { "\($0[0])|\($0[1])|\($0[2])" }73    guard instructions == message.instructions.map({ "\($0.programIDIndex)|\(hex($0.accountIndices))|\(hex($0.data))" }) else { return false }74    let lookups = (answer["lookups"] as? [[String]] ?? []).map { $0.joined(separator: "|") }75    return lookups == message.addressTableLookups.map { "\(hex($0.tableAddress.bytes))|\(hex($0.writableIndices))|\(hex($0.readonlyIndices))" }76}7778private func randomKey(_ rng: inout AuditRNG) -> SolanaPublicKey { SolanaPublicKey(bytes: rng.bytes(32))! }7980/// Encodings of curve points and of non-points that implementations are known to treat differently.81private let curveEdges: [Bytes] = {82    var out = [Bytes]()83    // y = p … p + 18 (non-canonical: the same y as 0 … 18), with both sign bits84    for k in 0..<19 {85        var b = Bytes(repeating: 0xff, count: 32)86        b[0] = UInt8(0xed + k)87        b[31] = 0x7f88        out.append(b)89        b[31] = 0xff90        out.append(b)91    }92    // y = 0 … 3, and the same with the sign bit (x = 0 has no negative: "negative zero" for y = 1)93    for y in 0..<4 {94        var b = Bytes(repeating: 0, count: 32)95        b[0] = UInt8(y)96        out.append(b)97        b[31] = 0x8098        out.append(b)99    }100    // the eight points of small order (canonical encodings)101    out.append([0xec] + Bytes(repeating: 0xff, count: 30) + [0x7f])102    for text in ["0100000000000000000000000000000000000000000000000000000000000000",103                 "0000000000000000000000000000000000000000000000000000000000000080", "0000000000000000000000000000000000000000000000000000000000000000",104                 "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a", "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",105                 "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05", "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85"] {106        out.append(Hex.decode(text)!)107    }108    out.append(Bytes(repeating: 0xff, count: 32))109    out.append(Bytes(repeating: 0x7f, count: 32))110    return out111}()112113@Suite struct SolanaAddressDifferential {114    @Test func bytesToTextAndCurve() throws {115        let name = "solana-address-bytes"116        guard MCOracle.available(script, campaign: name, needs: ["solders", "base58"]) else { return }117        let seed = DiffSeed.make(name)118        var rng = AuditRNG(seed: seed)119        var tally = DiffTally(name, algorithm: "Solana address", parameterSet: "32 bytes to base58 (two codecs), is_on_curve (random, leading zeros, non-canonical y, small order)",120                              oracle: reference("Pubkey, curve25519-dalek") + ", " + MCOracle.label(script, "base58"), seed: seed)121        var inputs = curveEdges122        for _ in 0..<AuditMode.cases(quick: 4000, full: 40000) {123            var b = rng.bytes(32)124            // leading zero bytes change the length of the text (32 to 44 characters)125            if rng.int(0...7) == 0 { for i in 0..<rng.int(1...31) { b[i] = 0 } }126            // a real public key now and then: always on the curve127            if rng.int(0...7) == 0, let pk = try? Ed25519.publicKey(seed: b) { b = pk }128            inputs.append(b)129        }130        let answers = try MCOracle.batch(script, "address", inputs.map { ["bytes": hex($0)] })131        var onCurve = 0132        for (b, a) in zip(inputs, answers) {133            let key = SolanaPublicKey(bytes: b)134            if key?.isOnCurve == true { onCurve += 1 }135            let ok = key != nil && key?.base58 == a.string("base58") && a.string("base58") == a.string("base58_alt") && key?.isOnCurve == a.bool("on_curve")136                && SolanaPublicKey(base58: key?.base58 ?? "") == key && (32...44).contains(key?.base58.utf8.count ?? 0)137            tally.verdict(key?.isOnCurve == true)138            tally.check(ok, "bytes=\(hex(b)) ours=\(key?.base58 ?? "nil") on_curve=\(String(describing: key?.isOnCurve)) reference=\(a)")139        }140        #expect(tally.finish() == 0)141        #expect(onCurve > inputs.count / 4 && onCurve < inputs.count * 3 / 4)142    }143144    @Test func textValidity() throws {145        let name = "solana-address-text"146        guard MCOracle.available(script, campaign: name, needs: ["solders"]) else { return }147        let seed = DiffSeed.make(name)148        var rng = AuditRNG(seed: seed)149        var tally = DiffTally(name, algorithm: "Solana address", parameterSet: "text accepted or refused, decoded bytes (valid, wrong length, foreign characters, white space, other chains)",150                              oracle: reference("Pubkey.from_string"), seed: seed)151        let alphabet = Array("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")152        var texts = ["", "1", "11111111111111111111111111111111", "1111111111111111111111111111111", "111111111111111111111111111111111", " 11111111111111111111111111111111",153                     "11111111111111111111111111111111 ", "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed", "TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH", "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4",154                     "JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG", "JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFGJEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG",155                     String(repeating: "z", count: 44), String(repeating: "z", count: 43), String(repeating: "2", count: 44), "So11111111111111111111111111111111111111112"]156        for _ in 0..<AuditMode.cases(quick: 3000, full: 30000) {157            let length = rng.pick([32, 32, 32, 32, 31, 33, 30, 34, 20, 64])158            var b = rng.bytes(length)159            if rng.int(0...5) == 0 { for i in 0..<min(length, rng.int(1...4)) { b[i] = 0 } }160            var text = Array(Base58.bitcoin.encode(b))161            switch rng.int(0...9) {162            case 0: if !text.isEmpty { text[rng.int(0...(text.count - 1))] = rng.pick(Array("0OIl+/_- \n=é")) }163            case 1: if !text.isEmpty { text.remove(at: rng.int(0...(text.count - 1))) }164            case 2: text.insert(rng.pick(alphabet), at: rng.int(0...text.count))165            case 3: text.insert(rng.pick([" ", "\n", "\t"]), at: rng.pick([0, text.count]))166            case 4: text = text.map { $0.isLetter && rng.bool() ? Character($0.uppercased()) : $0 }167            default: break168            }169            texts.append(String(text))170        }171        let answers = try MCOracle.batch(script, "address", texts.map { ["text": $0] })172        var stricter = 0173        for (text, a) in zip(texts, answers) {174            let ours = SolanaPublicKey(base58: text)175            tally.verdict(ours != nil)176            // accepted here: the reference must accept it and read the same bytes. Refused here although the177            // reference accepts would be a documented policy difference; none is expected for 32-byte keys.178            if ours == nil, a.oracleError == nil { stricter += 1 }179            let ok = ours.map { hex($0.bytes) == a.string("bytes") && $0.isOnCurve == a.bool("on_curve") } ?? (a.oracleError != nil)180            tally.check(ok && SolanaAddress.isValid(text) == (ours != nil), "text=\(text.debugDescription) ours=\(ours.map { hex($0.bytes) } ?? "refused") reference=\(a)")181        }182        #expect(tally.finish() == 0)183        #expect(stricter == 0)184        #expect(tally.accepted > texts.count / 4 && tally.accepted < texts.count)185    }186187    @Test func programDerivedAddresses() throws {188        let name = "solana-pda"189        guard MCOracle.available(script, campaign: name, needs: ["solders"]) else { return }190        let seed = DiffSeed.make(name)191        var rng = AuditRNG(seed: seed)192        var tally = DiffTally(name, algorithm: "Solana program-derived address", parameterSet: "find_program_address (address and bump) and create_program_address, random seeds and programs",193                              oracle: reference("Pubkey.find_program_address"), seed: seed)194        var finds = [(seeds: [Bytes], program: SolanaPublicKey)]()195        for _ in 0..<AuditMode.cases(quick: 2500, full: 25000) {196            let count = rng.pick([0, 1, 1, 2, 3, 3, 4, 8, 15, 16, 17])197            finds.append(((0..<count).map { _ in rng.bytes(rng.pick([0, 1, 8, 31, 32, 32, 32, 33])) }, rng.int(0...3) == 0 ? rng.pick([SolanaProgram.associatedToken, SolanaProgram.token, SolanaProgram.system]) : randomKey(&rng)))198        }199        let found = try MCOracle.batch(script, "pda", finds.map { ["seeds": $0.seeds.map(hex), "program": hex($0.program.bytes)] })200        var bumps = Set<UInt8>()201        for (i, a) in zip(finds, found) {202            let ours = try? SolanaAddress.findProgramAddress(seeds: i.seeds, programID: i.program)203            if let ours { bumps.insert(ours.bump) }204            tally.verdict(ours != nil)205            let ok = ours.map { hex($0.address.bytes) == a.string("address") && Int($0.bump) == a["bump"] as? Int && !$0.address.isOnCurve } ?? (a.oracleError != nil)206            tally.check(ok, "find seeds=\(i.seeds.map(hex)) program=\(i.program) ours=\(String(describing: ours)) reference=\(a)")207        }208        // create_program_address: about half of the inputs are on the curve and refused by both209        let created = try MCOracle.batch(script, "pda", finds.map { ["seeds": $0.seeds.map(hex), "program": hex($0.program.bytes), "create": true] })210        for (i, a) in zip(finds, created) {211            let ours = SolanaAddress.createProgramAddress(seeds: i.seeds, programID: i.program)212            tally.verdict(ours != nil)213            tally.check(ours.map { hex($0.bytes) == a.string("address") } ?? (a.oracleError != nil), "create seeds=\(i.seeds.map(hex)) program=\(i.program) ours=\(String(describing: ours)) reference=\(a)")214        }215        #expect(tally.finish() == 0)216        #expect(bumps.count >= 3, "bumps seen: \(bumps.sorted())")217    }218219    @Test func associatedTokenAccounts() throws {220        let name = "solana-ata"221        guard MCOracle.available(script, campaign: name, needs: ["solders"]) else { return }222        let seed = DiffSeed.make(name)223        var rng = AuditRNG(seed: seed)224        var tally = DiffTally(name, algorithm: "Solana associated token account", parameterSet: "Token and Token-2022, random owners (wallet keys and off-curve addresses) and mints",225                              oracle: reference("find_program_address and solders.token.associated"), seed: seed)226        var inputs = [(owner: SolanaPublicKey, mint: SolanaPublicKey, program: SolanaTokenProgram.Kind)]()227        for _ in 0..<AuditMode.cases(quick: 2500, full: 25000) {228            let mint = rng.int(0...3) == 0 ? rng.pick(SolanaToken.builtIn(.mainnetBeta).map(\.mint) + [SolanaProgram.nativeMint]) : randomKey(&rng)229            inputs.append((randomKey(&rng), mint, rng.pick(SolanaTokenProgram.Kind.allCases)))230        }231        let answers = try MCOracle.batch(script, "ata", inputs.map { ["owner": hex($0.owner.bytes), "mint": hex($0.mint.bytes), "program": $0.program.rawValue] })232        for (i, a) in zip(inputs, answers) {233            let ours = try? SolanaAddress.associatedTokenAccount(owner: i.owner, mint: i.mint, tokenProgram: i.program)234            let ok = ours != nil && hex(ours?.bytes ?? []) == a.string("address") && a.string("helper") == a.string("address") && ours?.base58 == a.string("base58") && ours?.isOnCurve == false235            tally.check(ok, "owner=\(i.owner) mint=\(i.mint) program=\(i.program.rawValue) ours=\(ours?.base58 ?? "nil") reference=\(a)")236        }237        #expect(tally.finish() == 0)238    }239240    @Test func accountDerivation() throws {241        let name = "solana-key-derivation"242        guard MCOracle.available(script, campaign: name, needs: ["solders", "bip-utils"]) else { return }243        let seed = DiffSeed.make(name)244        var rng = AuditRNG(seed: seed)245        var tally = DiffTally(name, algorithm: "Solana account key", parameterSet: "SLIP-0010 Ed25519 at m/44'/501'/a'/0', m/44'/501'/a' and m/44'/501', random BIP-39 seeds and accounts",246                              oracle: MCOracle.label(script, "bip-utils", "Bip32Slip10Ed25519") + ", " + reference("Keypair.from_seed"), seed: seed)247        var inputs = [(seed: Bytes, account: UInt32, style: SolanaKeys.DerivationStyle)]()248        for _ in 0..<AuditMode.cases(quick: 300, full: 3000) {249            inputs.append((rng.bytes(rng.pick([64, 64, 64, 16, 32])), rng.pick([0, 0, 1, 2, 7, 255, 65_536, UInt32(Int32.max)] as [UInt32]), rng.pick(SolanaKeys.DerivationStyle.allCases)))250        }251        func path(_ i: (seed: Bytes, account: UInt32, style: SolanaKeys.DerivationStyle)) -> [Int] {252            switch i.style {253            case .bip44Change: return [44, 501, Int(i.account), 0]254            case .bip44: return [44, 501, Int(i.account)]255            case .bip44Root: return [44, 501]256            }257        }258        let answers = try MCOracle.batch(script, "derive_path", inputs.map { ["seed": hex($0.seed), "path": path($0)] })259        for (i, a) in zip(inputs, answers) {260            var secret = (try? SolanaKeys.privateSeed(bip39Seed: i.seed, account: i.account, style: i.style)) ?? []261            let address = try? SolanaKeys.address(bip39Seed: i.seed, account: i.account, style: i.style)262            let ok = hex(secret) == a.string("private") && address?.base58 == a.string("address") && (try? SolanaKeys.publicKey(privateSeed: secret)) == address263                && SolanaKeys.derivationPath(account: i.account, style: i.style).description == "m/" + path(i).map { "\($0)'" }.joined(separator: "/")264            SecureMemory.zero(&secret)265            tally.check(ok, "bip39_seed=\(hex(i.seed)) account=\(i.account) style=\(i.style.rawValue) ours=\(address?.base58 ?? "nil") reference=\(a.string("address") ?? a.oracleError ?? "?")")266        }267        // an account index that is not below 2^31 is refused (it could not be hardened)268        tally.check((try? SolanaKeys.privateSeed(bip39Seed: Bytes(repeating: 1, count: 64), account: 0x8000_0000)) == nil, "account 2^31 accepted")269        #expect(tally.finish() == 0)270    }271}272273/// A random payment as the planner lays it out, and its independent construction by the reference.274private struct Payment {275    let seed: Bytes276    let recipient: SolanaPublicKey277    let mint: SolanaPublicKey?278    let program: SolanaTokenProgram.Kind279    let createATA: Bool280    let amount: UInt64281    let decimals: UInt8282    let memo: String?283    let unitLimit: UInt32284    let unitPrice: UInt64285    let blockhash: Bytes286287    var oracleCase: Case {288        var c: Case = ["seed": hex(seed), "recipient": hex(recipient.bytes), "blockhash": hex(blockhash), "unit_limit": Int(unitLimit), "unit_price": String(unitPrice),289                       "amount": String(amount), "decimals": Int(decimals)]290        if let mint {291            c["mint"] = hex(mint.bytes)292            c["program"] = program.rawValue293            c["create_ata"] = createATA294        }295        if let memo { c["memo"] = memo }296        return c297    }298299    func planned(_ payer: SolanaPublicKey) -> SolanaSendPlan? {300        let request = SolanaSendRequest(sender: payer, recipient: recipient, asset: mint.map { .token(mint: $0) } ?? .sol, amount: .exact(amount), memo: memo, computeUnitPrice: unitPrice,301                                        computeUnitLimit: unitLimit)302        var token: SolanaChainSnapshot.Token?303        if let mint {304            token = .init(mint: SolanaMintInfo(address: mint, program: program, decimals: decimals, supply: amount, isInitialized: true, extensions: []), senderBalance: amount,305                          recipientAccountExists: !createATA, tokenAccountRent: 2_039_280)306        }307        let snapshot = SolanaChainSnapshot(senderLamports: UInt64.max / 2, recipient: .system(lamports: 1_000_000), systemAccountRent: 890_880,308                                           blockhash: SolanaBlockhash(blockhash: blockhash, lastValidBlockHeight: 1), token: token)309        return try? SolanaSendPlanner.plan(request, snapshot: snapshot)310    }311312    func built(_ payer: SolanaPublicKey) -> SolanaTransaction? {313        var instructions = [SolanaComputeBudget.setComputeUnitLimit(unitLimit), SolanaComputeBudget.setComputeUnitPrice(microLamports: unitPrice)]314        if let mint {315            guard let source = try? SolanaAddress.associatedTokenAccount(owner: payer, mint: mint, tokenProgram: program),316                  let destination = try? SolanaAddress.associatedTokenAccount(owner: recipient, mint: mint, tokenProgram: program) else { return nil }317            if createATA { instructions.append(SolanaAssociatedTokenProgram.createIdempotent(payer: payer, associatedAccount: destination, owner: recipient, mint: mint, tokenProgram: program)) }318            instructions.append(SolanaTokenProgram.transferChecked(source: source, mint: mint, destination: destination, owner: payer, amount: amount, decimals: decimals, program: program))319        } else {320            instructions.append(SolanaSystemProgram.transfer(from: payer, to: recipient, lamports: amount))321        }322        if let memo { instructions.append(SolanaMemoProgram.memo(memo, signers: [payer])) }323        return (try? SolanaMessage(feePayer: payer, instructions: instructions, recentBlockhash: blockhash)).map { SolanaTransaction(message: $0) }324    }325}326327@Suite struct SolanaTransactionDifferential {328    @Test func payments() throws {329        let name = "solana-payment-bytes"330        guard MCOracle.available(script, campaign: name, needs: ["solders", "pynacl"]) else { return }331        let seed = DiffSeed.make(name)332        var rng = AuditRNG(seed: seed)333        var tally = DiffTally(name, algorithm: "Solana payment transaction",334                              parameterSet: "legacy message, unsigned and signed transaction, signature; SOL, SPL Token and Token-2022 TransferChecked, with and without CreateIdempotent and memo",335                              oracle: reference("Message.new_with_blockhash, Transaction, Keypair") + ", " + MCOracle.label(script, "pynacl", "libsodium"), seed: seed)336        let memos = ["a", "Invoice 42", "merci ✓ — 日本語", String(repeating: "m", count: 256), "x y z"]337        var cases = [Payment]()338        for _ in 0..<AuditMode.cases(quick: 1500, full: 15000) {339            let token = rng.int(0...2) > 0340            let recipient = rng.bool() ? ((try? SolanaKeys.publicKey(privateSeed: rng.bytes(32))) ?? randomKey(&rng)) : randomKey(&rng)341            let amount: UInt64 = rng.pick([1, 2, 890_880, 1_000_000_000, rng.next() >> UInt64(rng.int(0...63)), rng.next() >> 1, UInt64.max, UInt64.max - 1] as [UInt64])342            let limit: UInt32 = rng.pick([1, 150, 5_000, 80_000, 200_000, 1_400_000, UInt32(rng.int(1...1_400_000))] as [UInt32])343            // a price whose priority fee stays under the planner's ceiling most of the time, and beyond it sometimes344            let price: UInt64 = rng.pick([0, 1, 5_000, 2_000_000, rng.next() % 5_000_000, rng.next()] as [UInt64])345            cases.append(Payment(seed: rng.bytes(32), recipient: recipient, mint: token ? randomKey(&rng) : nil, program: rng.pick(SolanaTokenProgram.Kind.allCases), createATA: rng.bool(),346                                 amount: amount, decimals: UInt8(rng.pick([0, 6, 9, 18, 255, rng.int(0...255)])), memo: rng.int(0...3) == 0 ? rng.pick(memos) : nil, unitLimit: limit, unitPrice: price,347                                 blockhash: rng.bytes(32, orEdge: [Bytes(repeating: 0, count: 32), Bytes(repeating: 0xff, count: 32)], oneIn: 20)))348        }349        let answers = try MCOracle.batch(script, "payment", cases.map(\.oracleCase))350        var planned = 0351        var wires = [Case]()352        for (c, a) in zip(cases, answers) {353            guard let payer = try? SolanaKeys.publicKey(privateSeed: c.seed), var tx = c.built(payer) else {354                tally.check(false, "could not build \(c.oracleCase)")355                wires.append(["bytes": ""])356                continue357            }358            var ok = hex(payer.bytes) == a.string("payer")359            // the planner, when it accepts the request, emits exactly the builders' transaction, and its figures describe it360            if let plan = c.planned(payer) {361                planned += 1362                ok = ok && plan.transaction == tx && plan.amount == c.amount && plan.review.priorityFee == plan.priorityFee363                    && plan.priorityFee == SolanaComputeBudget.priorityFee(unitLimit: c.unitLimit, microLamportsPerUnit: c.unitPrice)364            }365            ok = ok && hex(tx.message.serialize()) == a.string("message") && (try? tx.serialize()).map(hex) == a.string("unsigned")366            ok = ok && (try? tx.sign(privateSeed: c.seed)) != nil367            ok = ok && (try? tx.serialize()).map(hex) == a.string("signed") && hex(tx.signatures.first ?? []) == a.string("signature") && a.string("signature") == a.string("signature_libsodium")368            ok = ok && tx.id == a.string("signature_b58") && tx.verifySignatures() && tx.isFullySigned369            // strict decoding gives the transaction back370            ok = ok && (try? SolanaTransaction.decode(Hex.decode(a.string("signed") ?? "") ?? [])) == tx371            tally.check(ok, "case=\(c.oracleCase) ours_message=\(hex(tx.message.serialize())) reference=\(a.string("message") ?? a.oracleError ?? "?")")372            wires.append(["bytes": (try? tx.serialize()).map(hex) ?? ""])373        }374        // the reference decodes our signed bytes: same fields, canonical, signatures verify375        let decoded = try MCOracle.batch(script, "decode_transaction", wires)376        for (w, d) in zip(wires, decoded) {377            let ours = try? SolanaTransaction.decode(Hex.decode(w["bytes"] as? String ?? "") ?? [])378            tally.check(ours != nil && sameFields(ours?.message, d) && d.bool("canonical") == true && d.bool("verifies") == true && d.string("sanitize") == "",379                        "reference decoding of ours=\(w) reference=\(d)")380        }381        #expect(tally.finish() == 0)382        #expect(planned > cases.count / 4, "planner accepted \(planned) of \(cases.count)")383    }384385    /// Random instruction lists over a small pool of keys, so that accounts repeat with different privileges.386    @Test func compilation() throws {387        let name = "solana-message-compilation"388        guard MCOracle.available(script, campaign: name, needs: ["solders"]) else { return }389        let seed = DiffSeed.make(name)390        var rng = AuditRNG(seed: seed)391        var tally = DiffTally(name, algorithm: "Solana legacy message",392                              parameterSet: "account ordering (fee payer, writable signers, read-only signers, writable, read-only; byte order inside a role), de-duplication, privilege merging, several signers",393                              oracle: reference("Message.new_with_blockhash, Transaction"), seed: seed)394        struct Input {395            let seeds: [Bytes]396            let payer: Int397            let instructions: [SolanaInstruction]398            let blockhash: Bytes399        }400        var inputs = [Input]()401        for _ in 0..<AuditMode.cases(quick: 1500, full: 15000) {402            let seeds = (0..<rng.int(1...5)).map { _ in rng.bytes(32) }403            let signers = seeds.map { try! SolanaKeys.publicKey(privateSeed: $0) }404            let others = (0..<rng.int(0...6)).map { _ in randomKey(&rng) } + [SolanaProgram.system, SolanaProgram.token]405            let programs = (0..<rng.int(1...3)).map { _ in randomKey(&rng) } + [SolanaProgram.system, SolanaProgram.computeBudget]406            var instructions = [SolanaInstruction]()407            for _ in 0..<rng.int(0...6) {408                var metas = [SolanaAccountMeta]()409                for _ in 0..<rng.int(0...7) {410                    // a signer flag only on keys the test can sign with411                    if rng.bool() { metas.append(SolanaAccountMeta(rng.pick(signers), isSigner: rng.bool(), isWritable: rng.bool())) } else { metas.append(SolanaAccountMeta(rng.pick(others), isSigner: false, isWritable: rng.bool())) }412                }413                instructions.append(SolanaInstruction(programID: rng.pick(programs), accounts: metas, data: rng.bytes(rng.pick([0, 1, 4, 9, 12, 127, 128, 300]))))414            }415            inputs.append(Input(seeds: seeds, payer: rng.int(0...(seeds.count - 1)), instructions: instructions, blockhash: rng.bytes(32)))416        }417        func oracleCase(_ i: Input) -> Case {418            ["payer": hex((try! SolanaKeys.publicKey(privateSeed: i.seeds[i.payer])).bytes), "blockhash": hex(i.blockhash), "seeds": i.seeds.map(hex),419             "instructions": i.instructions.map { ["program": hex($0.programID.bytes), "data": hex($0.data), "accounts": $0.accounts.map { [hex($0.publicKey.bytes), $0.isSigner, $0.isWritable] as [Any] }] as Case }]420        }421        let answers = try MCOracle.batch(script, "compile", inputs.map(oracleCase))422        var multi = 0, oversize = 0423        for (i, a) in zip(inputs, answers) {424            let payer = try! SolanaKeys.publicKey(privateSeed: i.seeds[i.payer])425            guard let message = try? SolanaMessage(feePayer: payer, instructions: i.instructions, recentBlockhash: i.blockhash) else {426                tally.check(false, "ours refused to compile \(oracleCase(i))")427                continue428            }429            var ok = hex(message.serialize()) == a.string("message") && a["keys"] as? [String] == message.accountKeys.map { hex($0.bytes) }430            ok = ok && a["header"] as? [Int] == [Int(message.numRequiredSignatures), Int(message.numReadonlySignedAccounts), Int(message.numReadonlyUnsignedAccounts)]431            // the reference signs with exactly the required signers: it answers an error when a seed is not one of them432            var tx = SolanaTransaction(message: message)433            let required = Set(message.signers)434            var signedAll = true435            for s in i.seeds {436                let key = try! SolanaKeys.publicKey(privateSeed: s)437                if required.contains(key) { signedAll = signedAll && (try? tx.sign(privateSeed: s)) != nil } else { ok = ok && (try? tx.sign(privateSeed: s)) == nil }438            }439            if required.count > 1 { multi += 1 }440            if let signed = a.string("signed") {441                ok = ok && signedAll && tx.isFullySigned && tx.verifySignatures()442                let wire = SolanaCompactU16.encode(UInt16(tx.signatures.count)) + tx.signatures.flatMap { $0 } + message.serialize()443                if wire.count <= SolanaTransaction.maximumSize {444                    ok = ok && (try? tx.serialize()).map(hex) == signed445                } else {446                    // policy difference: the engine does not serialize a transaction a validator would not receive447                    // (more than 1232 bytes); solders serializes any size. Signatures and layout still agree.448                    oversize += 1449                    ok = ok && (try? tx.serialize()) == nil && hex(wire) == signed450                }451            } else {452                // every required signer has its seed in the case: the reference must have signed453                ok = false454            }455            // decoding our own compiled bytes gives the message back (a program that is the fee payer is refused by the decoder)456            let decoded = try? SolanaMessage.decode(message.serialize())457            ok = ok && (decoded == message || i.instructions.contains { $0.programID == payer })458            tally.check(ok, "case=\(oracleCase(i)) ours=\(hex(message.serialize())) reference=\(a)")459        }460        AuditRecorder.record(area: "differential", name: name + "/packet-size", algorithm: "Solana legacy message", oracle: reference("Transaction"), cases: oversize, failed: 0, seed: seed,461                             note: "policy difference, not a failure: transactions above 1232 bytes that solders serializes and the engine refuses to serialize (SolanaError.transactionTooLarge); their signatures and layout were compared field by field")462        #expect(tally.finish() == 0)463        #expect(multi > inputs.count / 4)464    }465466    /// One decoding question for the reference and for the engine: same verdict, same fields.467    private static func judge(_ bytes: Bytes, _ answer: Case, transaction: Bool) -> (accepted: Bool, ok: Bool, lenient: Bool, why: String) {468        let ours: SolanaMessage?469        var why = ""470        do {471            ours = transaction ? try SolanaTransaction.decode(bytes).message : try SolanaMessage.decode(bytes)472        } catch {473            ours = nil474            why = "\(error)"475        }476        guard let ours else {477            // refused here: fine whatever the reference says; a reference that accepts is more lenient, and that is counted478            return (false, true, answer.oracleError == nil, why)479        }480        // accepted here: the reference must read the same fields and find the encoding canonical481        var ok = answer.oracleError == nil && sameFields(ours, answer) && answer.bool("canonical") == true482        if transaction, let tx = try? SolanaTransaction.decode(bytes) {483            ok = ok && tx.signatures.map(hex) == answer["signatures"] as? [String] && (try? tx.serialize()) == bytes484            // signatures: same verdict as the reference485            ok = ok && tx.verifySignatures() == (answer.bool("verifies") == true)486        } else {487            ok = ok && ours.serialize() == bytes488        }489        return (true, ok, false, "")490    }491492    @Test func strictDecodingAgainstTheReference() throws {493        let name = "solana-strict-decoding"494        guard MCOracle.available(script, campaign: name, needs: ["solders"]) else { return }495        let seed = DiffSeed.make(name)496        var rng = AuditRNG(seed: seed)497        var tally = DiffTally(name, algorithm: "Solana message and transaction decoding",498                              parameterSet: "bytes built by solders (legacy and version 0 with lookup tables) decode to the same fields; altered bytes: accepted here implies accepted, identical and canonical for solders",499                              oracle: reference("Message.from_bytes, from_bytes_versioned, VersionedTransaction.from_bytes (bincode)"), seed: seed)500501        // 1. messages and signed transactions compiled by the reference, legacy and version 0502        var builds = [Case]()503        var versioned = [Bool]()504        let count = AuditMode.cases(quick: 600, full: 6000)505        for _ in 0..<count {506            let seeds = (0..<rng.int(1...3)).map { _ in rng.bytes(32) }507            let signers = seeds.map { try! SolanaKeys.publicKey(privateSeed: $0) }508            let tableKeys = (0..<rng.int(1...6)).map { _ in randomKey(&rng) }509            let others = (0..<rng.int(1...4)).map { _ in randomKey(&rng) }510            let isV0 = rng.bool()511            var instructions = [Case]()512            for _ in 0..<rng.int(1...4) {513                var accounts: [[Any]] = [[hex(signers[0].bytes), true, true]]514                for _ in 0..<rng.int(0...5) {515                    switch rng.int(0...2) {516                    case 0: accounts.append([hex(rng.pick(signers).bytes), true, rng.bool()])517                    case 1: accounts.append([hex(rng.pick(others).bytes), false, rng.bool()])518                    default: accounts.append([hex(rng.pick(isV0 ? tableKeys : others).bytes), false, rng.bool()])519                    }520                }521                instructions.append(["program": hex(rng.pick([SolanaProgram.system, SolanaProgram.token, others[0]]).bytes), "data": hex(rng.bytes(rng.pick([0, 1, 9, 12, 130]))), "accounts": accounts])522            }523            var c: Case = ["payer": hex(signers[0].bytes), "blockhash": hex(rng.bytes(32)), "seeds": seeds.map(hex), "instructions": instructions]524            if isV0 { c["tables"] = [["key": hex(randomKey(&rng).bytes), "addresses": tableKeys.map { hex($0.bytes) }]] }525            builds.append(c)526            versioned.append(isV0)527        }528        let legacyAnswers = try MCOracle.batch(script, "compile", zip(builds, versioned).filter { !$0.1 }.map(\.0))529        let v0Answers = try MCOracle.batch(script, "v0", zip(builds, versioned).filter { $0.1 }.map(\.0))530        var messages = [Bytes]()531        var transactions = [Bytes]()532        var withLookups = 0533        for a in legacyAnswers + v0Answers {534            guard let m = a.bytes("message") else {535                tally.check(false, "the reference did not build: \(a)")536                continue537            }538            let ours = try? SolanaMessage.decode(m)539            if ours?.addressTableLookups.isEmpty == false { withLookups += 1 }540            // version-0 answers carry their fields; legacy answers carry keys and header541            var ok = ours != nil && ours?.serialize() == m && a["keys"] as? [String] == ours?.accountKeys.map { hex($0.bytes) }542            if a["version"] != nil { ok = ok && sameFields(ours, a) }543            if let review = ours?.review() { ok = ok && review.usesAddressLookupTables == (ours?.addressTableLookups.isEmpty == false) && (!review.usesAddressLookupTables || review.requiresBlindSigning) }544            tally.check(ok, "message built by the reference: \(hex(m)) ours=\(String(describing: ours))")545            messages.append(m)546            if let t = a.bytes("signed") {547                let tx = try? SolanaTransaction.decode(t)548                tally.check(tx != nil && tx?.message == ours && tx?.verifySignatures() == true && (try? tx?.serialize()) == t, "transaction built by the reference: \(hex(t))")549                transactions.append(t)550            }551        }552553        // 2. altered encodings of those bytes554        func mutate(_ base: Bytes) -> Bytes {555            var b = base556            switch rng.int(0...9) {557            case 0: b.append(UInt8(truncatingIfNeeded: rng.next()))                                   // trailing byte558            case 1: b.removeLast(min(b.count, rng.int(1...40)))                                        // truncation559            case 2: b[rng.int(0...min(3, b.count - 1))] = UInt8(truncatingIfNeeded: rng.next())        // header or version560            case 3: b[rng.int(0...(b.count - 1))] ^= UInt8(1 << rng.int(0...7))                        // one bit anywhere561            case 4: b.insert(UInt8(truncatingIfNeeded: rng.next()), at: rng.int(0...b.count))562            case 5: b.remove(at: rng.int(0...(b.count - 1)))563            case 6:                                                                                    // a length written on one more byte than needed564                let at = rng.int(0...(b.count - 1))565                if b[at] < 0x80 { b[at] |= 0x80; b.insert(0, at: at + 1) }566            case 7:                                                                                    // an account key copied over another567                if b.count > 70 { let from = 4 + 32 * rng.int(0...1), to = 4 + 32 * rng.int(0...1); b.replaceSubrange(to..<(to + 32), with: Array(b[from..<(from + 32)])) }568            case 8: b[rng.int(max(0, b.count - 12)...(b.count - 1))] = rng.pick([0xff, 0x80, 0x7f, 0x00])  // an index or a length near the end569            default: for _ in 0..<rng.int(2...6) { b[rng.int(0...(b.count - 1))] = UInt8(truncatingIfNeeded: rng.next()) }570            }571            return b572        }573        var lenient = [String: Int]()574        func campaign(_ bases: [Bytes], transaction: Bool, rounds: Int) throws {575            guard !bases.isEmpty else { return }576            var inputs = [Bytes]()577            for _ in 0..<rounds { inputs.append(mutate(rng.pick(bases))) }578            let answers = try MCOracle.batch(script, transaction ? "decode_transaction" : "decode_message", inputs.map { ["bytes": hex($0)] })579            for (b, a) in zip(inputs, answers) {580                let r = Self.judge(b, a, transaction: transaction)581                tally.verdict(r.accepted)582                if r.lenient {583                    // which rule of ours the reference does not apply584                    var rule = r.why585                    if let open = rule.firstIndex(of: "\""), let close = rule.lastIndex(of: "\""), open < close { rule = String(rule[rule.index(after: open)..<close]) }586                    rule = rule.replacingOccurrences(of: #"[0-9]+"#, with: "N", options: .regularExpression)587                    lenient[(transaction ? "transaction: " : "message: ") + rule + (a.string("sanitize") == "" ? " [sanitize passes]" : " [sanitize refuses]"), default: 0] += 1588                }589                tally.check(r.ok, "\(transaction ? "transaction" : "message")=\(hex(b)) ours accepted=\(r.accepted) reference=\(a)")590            }591        }592        try campaign(messages, transaction: false, rounds: AuditMode.cases(quick: 4000, full: 40000))593        try campaign(transactions, transaction: true, rounds: AuditMode.cases(quick: 4000, full: 40000))594595        // 3. the non-canonical forms of the brief, hand-made from one legacy message of the reference: each must be refused here596        if let base = messages.first(where: { $0.first.map { $0 & 0x80 == 0 } ?? false }), let message = try? SolanaMessage.decode(base), message.accountKeys.count >= 2 {597            var forms = [(String, Bytes)]()598            var b = base599            b.insert(0x00, at: 4); b[3] |= 0x80600            forms.append(("non-minimal compact-u16 (account count on two bytes)", b))601            forms.append(("trailing byte", base + [0]))602            b = base; b.replaceSubrange(36..<68, with: Array(base[4..<36]))603            forms.append(("duplicate account key", b))604            b = base; b[0] = 0605            forms.append(("no required signature", b))606            b = base; b[0] = UInt8(message.accountKeys.count + 1)607            forms.append(("more signers than accounts", b))608            b = base; b[1] = b[0]609            forms.append(("read-only fee payer", b))610            b = base; b[2] = UInt8(message.accountKeys.count)611            forms.append(("header counts above the account count", b))612            b = base; b[0] = 0x81613            forms.append(("unknown message version 1", b))614            if let first = message.instructions.first {615                let at = 4 + 32 * message.accountKeys.count + 32 + 1616                b = base; b[at] = 0xfe617                forms.append(("program index out of range", b))618                b = base; b[at] = 0619                forms.append(("the fee payer as a program", b))620                if !first.accountIndices.isEmpty {621                    b = base; b[at + 2] = 0xff622                    forms.append(("account index out of range", b))623                }624            }625            let answers = try MCOracle.batch(script, "decode_message", forms.map { ["bytes": hex($0.1)] })626            for (form, a) in zip(forms, answers) {627                let refused = (try? SolanaMessage.decode(form.1)) == nil628                tally.verdict(!refused)629                if refused, a.oracleError == nil {630                    lenient["message (hand-made): " + form.0 + (a.string("sanitize") == "" ? " [sanitize passes]" : " [sanitize refuses]"), default: 0] += 1631                }632                tally.check(refused, "\(form.0) accepted here: \(hex(form.1))")633            }634        }635        let report = lenient.sorted { $0.value > $1.value }.map { "\($0.key) ×\($0.value)" }.joined(separator: "; ")636        AuditRecorder.record(area: "differential", name: name + "/reference-more-lenient", algorithm: "Solana message and transaction decoding", oracle: reference("bincode decoding"),637                             cases: lenient.values.reduce(0, +), failed: 0, seed: seed,638                             note: "inputs refused here and decoded by the reference (a policy difference, not a failure), by rule: " + (report.isEmpty ? "none" : String(report.prefix(1500))))639        #expect(tally.finish() == 0)640        #expect(withLookups > count / 8 && tally.accepted > 0 && tally.accepted < tally.judged)641    }642}643
Files main
Menu

Theme