Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Sources/AuditSupport/Oracles+Diff.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//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 QyvoraMath4344// Additions used by the differential tests: discovery of the optional oracles and a tally that45// turns one differential campaign into exactly one record of the audit run.4647extension Oracle {48 /// The FFI library of the owner's Rust implementation spb-quantum-crypto (`QY_SPBPQC_DYLIB`, else the audit copy49 /// in `security/.tools/lib`). Loaded by the Python oracle through ctypes, never by the engine.50 public static var spbDylib: URL? {51 let candidates = [52 ProcessInfo.processInfo.environment["QY_SPBPQC_DYLIB"],53 AuditPaths.security.appendingPathComponent(".tools/lib/libspb_pqc.dylib").path,54 ].compactMap { $0 }55 return candidates.first { FileManager.default.fileExists(atPath: $0) }.map { URL(fileURLWithPath: $0) }56 }5758 /// Versions of the Python references (`op_versions` of oracle.py), nil when the Python environment is missing.59 /// A package that is not installed has no entry.60 public static let pythonVersions: [String: String]? = {61 guard python != nil, let answer = try? pythonBatch(op: "versions", cases: [[:]]).first else { return nil }62 var out = [String: String]()63 for (k, v) in answer { if let s = v as? String { out[k] = s } }64 return out65 }()6667 /// Why the Python oracle cannot serve a campaign needing `packages`, or nil when it can.68 public static func pythonUnavailable(_ packages: [String]) -> String? {69 guard let versions = pythonVersions else {70 return "audit Python environment missing (security/.tools/venv; run security/audit/install-tools.sh)"71 }72 let missing = packages.filter { versions[$0] == nil }73 return missing.isEmpty ? nil : "Python package(s) not installed: " + missing.joined(separator: ", ")74 }7576 /// "coincurve 21.0.0 (libsecp256k1)"-style label for the records.77 public static func label(_ package: String, _ what: String = "") -> String {78 let v = pythonVersions?[package] ?? "?"79 return what.isEmpty ? "\(package) \(v)" : "\(package) \(v) (\(what))"80 }81}8283/// Seed of a differential campaign. `QY_AUDIT_REPLAY_SEED=<seed of a record>` together with `--filter <test>`84/// replays that campaign exactly; otherwise the seed is the one `AuditSeed` gives (system, or `QY_AUDIT_SEED`).85public enum DiffSeed {86 public static func make(_ label: String) -> UInt64 {87 if let s = ProcessInfo.processInfo.environment["QY_AUDIT_REPLAY_SEED"], let v = UInt64(s) { return v }88 return AuditSeed.make(label)89 }90}9192/// One differential campaign: counts the cases, keeps the first mismatches with their inputs and writes93/// one record `(algorithm, parameter set, oracle, cases, failed, seed)` when finished.94public struct DiffTally {95 public let name: String96 public let algorithm: String97 public let parameterSet: String98 public let oracle: String99 public let seed: UInt64100 public private(set) var cases = 0101 public private(set) var failed = 0102 public private(set) var failures: [String] = []103 /// For campaigns over altered inputs: how many inputs were judged, and how many of them were accepted (valid).104 /// Reported in the record so that a campaign in which everything is rejected cannot pass for a real comparison.105 public private(set) var judged = 0106 public private(set) var accepted = 0107108 public init(_ name: String, algorithm: String, parameterSet: String = "", oracle: String, seed: UInt64) {109 self.name = name110 self.algorithm = algorithm111 self.parameterSet = parameterSet112 self.oracle = oracle113 self.seed = seed114 }115116 /// Counts one case; `detail` (the reproduction data) is evaluated only on a mismatch.117 public mutating func check(_ ok: Bool, _ detail: @autoclosure () -> String) {118 cases += 1119 if !ok {120 failed += 1121 if failures.count < 5 { failures.append(detail()) }122 }123 }124125 /// Notes the verdict of the engine on one altered input (see `judged` / `accepted`).126 public mutating func verdict(_ isAccepted: Bool) {127 judged += 1128 if isAccepted { accepted += 1 }129 }130131 /// Writes the record (and the mismatches, in `differential-failures.jsonl`) and returns the number of mismatches.132 @discardableResult133 public func finish() -> Int {134 var note = failures.isEmpty ? "" : "first mismatch: " + String(failures[0].prefix(600))135 if judged > 0 {136 note = "verdicts on altered or edge inputs: \(accepted) accepted, \(judged - accepted) refused" + (note.isEmpty ? "" : "; " + note)137 }138 AuditRecorder.record(139 area: "differential", name: name, algorithm: algorithm, parameterSet: parameterSet, oracle: oracle,140 cases: cases, failed: failed, seed: seed, note: note)141 if !failures.isEmpty {142 let url = AuditPaths.out.appendingPathComponent("differential-failures.jsonl")143 let obj: [String: Any] = [144 "name": name, "algorithm": algorithm, "parameter_set": parameterSet, "oracle": oracle,145 "seed": String(seed), "failed": failed, "cases": cases, "examples": failures,146 ]147 if let data = try? JSONSerialization.data(withJSONObject: obj, options: [.sortedKeys]) {148 if !FileManager.default.fileExists(atPath: url.path) { FileManager.default.createFile(atPath: url.path, contents: nil) }149 if let h = try? FileHandle(forWritingTo: url) {150 _ = try? h.seekToEnd()151 try? h.write(contentsOf: data + Data([0x0a]))152 try? h.close()153 }154 }155 }156 return failed157 }158}159160extension AuditRNG {161 /// A length that exercises block boundaries: 0, 1, block ± 1, multiples of the block, and random sizes.162 public mutating func edgeLength(block: Int, max: Int = 600) -> Int {163 switch int(0...9) {164 case 0: return pick([0, 1, block - 1, block, block + 1])165 case 1: return pick([2 * block - 1, 2 * block, 2 * block + 1, 3 * block, 4 * block + 1])166 case 2: return int(0...Swift.max(max, 4 * block) * 4)167 default: return int(0...max)168 }169 }170171 /// Either an edge value from `edges` (one time in `oneIn`) or `count` random bytes.172 public mutating func bytes(_ count: Int, orEdge edges: [Bytes], oneIn: Int = 16) -> Bytes {173 if !edges.isEmpty, int(0...(oneIn - 1)) == 0 { return pick(edges) }174 return bytes(count)175 }176}177178/// References of the multi-chain differential tests: one Python script per family under179/// `security/tests/oracles/mc/`, run with the interpreter of `security/.tools/venv-mc`180/// (`requirements-multichain.txt`). Test environment only.181public enum MCOracle {182 public static var python: URL? {183 let u = AuditPaths.security.appendingPathComponent(".tools/venv-mc/bin/python3")184 return FileManager.default.isExecutableFile(atPath: u.path) ? u : nil185 }186187 static func scriptURL(_ script: String) -> URL {188 AuditPaths.security.appendingPathComponent("tests/oracles/mc/\(script).py")189 }190191 /// Batch call of `mc/<script>.py <op>`: a JSON array of cases in, an array of the same length out.192 public static func batch(_ script: String, _ op: String, _ cases: [[String: Any]]) throws -> [[String: Any]] {193 if cases.isEmpty { return [] }194 guard let py = python else {195 throw Oracle.Failure(description: "multi-chain Python environment missing (security/.tools/venv-mc; run security/audit/install-tools.sh)")196 }197 let input = try JSONSerialization.data(withJSONObject: cases)198 let out = try Oracle.run(py, ["-I", scriptURL(script).path, op], input: input)199 guard let arr = try JSONSerialization.jsonObject(with: out) as? [[String: Any]], arr.count == cases.count else {200 throw Oracle.Failure(description: "oracle mc/\(script) \(op): malformed answer")201 }202 return arr203 }204205 private static let cacheLock = NSLock()206 nonisolated(unsafe) private static var versionCache = [String: [String: String]]()207208 /// Versions reported by a script (`versions` operation); nil when the environment or the script is missing.209 public static func versions(_ script: String) -> [String: String]? {210 cacheLock.lock()211 defer { cacheLock.unlock() }212 if let v = versionCache[script] { return v.isEmpty ? nil : v }213 var out = [String: String]()214 if python != nil, FileManager.default.fileExists(atPath: scriptURL(script).path),215 let answer = try? batch(script, "versions", [[:]]).first {216 for (k, v) in answer { if let s = v as? String { out[k] = s } }217 }218 versionCache[script] = out219 return out.isEmpty ? nil : out220 }221222 /// True when the campaign can run; otherwise records it as NOT RUN (never as passed) and returns false.223 public static func available(_ script: String, campaign: String, area: String = "differential", needs packages: [String] = []) -> Bool {224 guard let v = versions(script) else {225 AuditRecorder.notRun(226 area: area, name: campaign,227 reason: "multi-chain Python oracle mc/\(script).py unavailable (security/.tools/venv-mc; run security/audit/install-tools.sh)")228 return false229 }230 let missing = packages.filter { v[$0] == nil }231 if !missing.isEmpty {232 AuditRecorder.notRun(area: area, name: campaign, reason: "Python package(s) not installed: " + missing.joined(separator: ", "))233 return false234 }235 return true236 }237238 /// "solders 0.29.0 (ed25519-dalek)"-style label for the records.239 public static func label(_ script: String, _ package: String, _ what: String = "") -> String {240 let v = versions(script)?[package] ?? "?"241 return what.isEmpty ? "\(package) \(v)" : "\(package) \(v) (\(what))"242 }243}244