Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraQuantumShieldTests/ShieldTests.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 Testing43import QyvoraMath44import QyvoraCore45import QyvoraBitcoin46import QyvoraEthereum47import QyvoraStorage48import QyvoraVault49@testable import QyvoraQuantumShield5051@Suite struct QuantumShieldTests {52 static let now = Date(timeIntervalSince1970: 1_800_000_000)5354 static func script(_ n: UInt8) -> Bytes { try! BitcoinScript.p2wpkh(publicKeyHash: Bytes(repeating: n, count: 20)) }55 static func txid(_ n: UInt8) -> String { String(repeating: String(format: "%02x", n), count: 32) }56 static func utxo(_ tx: UInt8, _ script: Bytes, _ value: UInt64, confirmations: UInt32 = 6) -> BitcoinUTXO {57 BitcoinUTXO(outPoint: BitcoinOutPoint(txid: txid(tx), vout: 0)!, value: value, scriptPubKey: script, confirmations: confirmations)58 }5960 static func vaultReport() async throws -> VaultReport {61 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("qy-shield-\(UUID().uuidString)")62 defer { try? FileManager.default.removeItem(at: dir) }63 let vault = Vault(fileStore: try FileStore(root: dir), keychain: InMemoryKeychainStore(),64 configuration: .init(kdf: .insecureForTesting))65 try await vault.create(password: "correct horse battery staple")66 return try await vault.report()67 }6869 static func vaultInput(_ report: VaultReport?, quality: PasswordQuality.Level? = .strong, autoLock: AutoLockPolicy = .after(seconds: 300),70 backup: Date? = now.addingTimeInterval(-86_400), signed: Bool? = true, verified: Bool = true,71 watchOnly: Bool = false) -> VaultSecurity.Input {72 .init(report: report, passwordQuality: quality, autoLock: autoLock, lastBackup: backup, lastBackupSigned: signed,73 recoveryPhraseVerified: verified, isWatchOnly: watchOnly, now: now)74 }7576 static let capabilities = [77 ProtocolCapability(id: "eth.eoa", title: "EOA", detail: "", status: .available, requirement: nil, quantumResistant: false),78 ProtocolCapability(id: "eth.eip1559", title: "1559", detail: "", status: .available, requirement: nil, quantumResistant: false),79 ProtocolCapability(id: "eth.pq-validation", title: "PQ", detail: "", status: .awaitingProtocol, requirement: "precompile", quantumResistant: true),80 ]8182 @Test func vaultSectionGoodConfiguration() async throws {83 let section = QuantumShield.vaultSecurity(Self.vaultInput(try await Self.vaultReport()))84 // the test vault uses the deliberately weak KDF parameters: that is the only warning85 #expect(section.findings.filter { $0.severity == .warning }.map(\.id) == ["vault.kdf"])86 #expect(section.level == .attention)87 #expect(section.findings.contains { $0.id == "vault.password.strong" && $0.severity == .good })88 #expect(section.findings.contains { $0.id == "vault.backup.recent" })89 #expect(section.findings.contains { $0.id == "vault.phrase.verified" })90 #expect(section.algorithms.contains("AES-256-GCM"))91 // most severe first92 let ranks = section.findings.map(\.severity)93 #expect(ranks == ranks.sorted(by: >))94 }9596 @Test func vaultSectionProblems() async throws {97 let report = try await Self.vaultReport()98 let section = QuantumShield.vaultSecurity(Self.vaultInput(report, quality: .weak, autoLock: .never,99 backup: Self.now.addingTimeInterval(-200 * 86_400), signed: false, verified: false))100 #expect(section.level == .critical)101 let ids = Set(section.findings.map(\.id))102 #expect(ids.isSuperset(of: ["vault.password.weak", "vault.autolock.never", "vault.backup.old", "vault.backup.unsigned", "vault.phrase.unverified"]))103 #expect(section.findings.first?.severity == .critical)104 for f in section.findings where f.severity >= .warning { #expect(f.recommendation != nil) }105106 let none = QuantumShield.vaultSecurity(Self.vaultInput(report, backup: nil, signed: nil))107 #expect(none.findings.contains { $0.id == "vault.backup.none" && $0.severity == .warning })108 let long = QuantumShield.vaultSecurity(Self.vaultInput(report, autoLock: .after(seconds: 3_600)))109 #expect(long.findings.contains { $0.id == "vault.autolock.long" })110 let unknown = QuantumShield.vaultSecurity(Self.vaultInput(report, quality: nil))111 #expect(unknown.findings.contains { $0.id == "vault.password.unknown" && $0.severity == .info })112 }113114 @Test func vaultSectionWithoutVault() {115 let watch = QuantumShield.vaultSecurity(Self.vaultInput(nil, watchOnly: true))116 #expect(watch.level == .good)117 #expect(watch.findings.map(\.id) == ["vault.watch-only"])118 let missing = QuantumShield.vaultSecurity(Self.vaultInput(nil))119 #expect(missing.level == .unknown)120 }121122 @Test func bitcoinFreshWallet() {123 let a = Self.script(1), b = Self.script(2)124 let input = KeyExposure.BitcoinInput(network: .signet, utxos: [Self.utxo(0xa1, a, 50_000), Self.utxo(0xa2, b, 70_000)], activity: [125 ScriptActivity(scriptPubKey: a, kind: .funded, txid: Self.txid(0xa1), height: 100),126 ScriptActivity(scriptPubKey: b, kind: .funded, txid: Self.txid(0xa2), height: 101),127 ])128 let r = QuantumShield.bitcoinKeyExposure(input)129 #expect(r.totals.hashedUnrevealed == 120_000)130 #expect(r.totals.revealed == 0)131 #expect(r.hashedUnrevealedShareBasisPoints == 10_000)132 #expect(r.exposedUTXOCount == 0)133 #expect(r.reusedAddresses.isEmpty)134 #expect(r.scriptTypesInUse == [.p2wpkh])135 #expect(r.vulnerableScripts.isEmpty)136 #expect(r.findings.map(\.id) == ["btc.exposure.none"])137 #expect(r.addresses.count == 2)138 #expect(r.addresses.allSatisfy { $0.address?.hasPrefix("tb1q") == true && $0.exposure == .hashedUnrevealed })139 #expect(!r.longTermStorageAdvice.isEmpty)140 }141142 @Test func bitcoinSpentFromAndReused() throws {143 let a = Self.script(1), b = Self.script(2), c = Self.script(3)144 let taproot = try BitcoinScript.p2tr(outputKey: Bytes(repeating: 7, count: 32))145 let input = KeyExposure.BitcoinInput(146 network: .signet,147 utxos: [Self.utxo(0xb1, a, 30_000), Self.utxo(0xb2, b, 10_000), Self.utxo(0xb3, c, 60_000), Self.utxo(0xb4, taproot, 5_000)],148 activity: [149 // a: funded, spent, funded again → revealed by spend and reused after spend150 ScriptActivity(scriptPubKey: a, kind: .funded, txid: Self.txid(0x01), height: 10),151 ScriptActivity(scriptPubKey: a, kind: .spent, txid: Self.txid(0x02), height: 20),152 ScriptActivity(scriptPubKey: a, kind: .funded, txid: Self.txid(0xb1), height: 30),153 // b: funded twice, never spent → reused, key still hidden154 ScriptActivity(scriptPubKey: b, kind: .funded, txid: Self.txid(0xb2), height: 12),155 ScriptActivity(scriptPubKey: b, kind: .funded, txid: Self.txid(0x03), height: 13),156 ScriptActivity(scriptPubKey: c, kind: .funded, txid: Self.txid(0xb3), height: 14),157 ScriptActivity(scriptPubKey: taproot, kind: .funded, txid: Self.txid(0xb4), height: 15),158 ])159 let r = QuantumShield.bitcoinKeyExposure(input)160 #expect(r.totals.revealedBySpend == 30_000)161 #expect(r.totals.revealedByScript == 5_000)162 #expect(r.totals.hashedUnrevealed == 70_000)163 #expect(r.totals.total == 105_000)164 #expect(r.totals[.revealedBySpend] == 30_000)165 #expect(r.hashedUnrevealedShareBasisPoints == 6_666)166 #expect(r.exposedUTXOCount == 2)167 #expect(Set(r.reusedAddresses.map(\.scriptPubKey)) == [a, b])168 #expect(r.reusedAddresses.first { $0.scriptPubKey == a }?.fundedAfterSpend == true)169 #expect(r.reusedAddresses.first { $0.scriptPubKey == b }?.fundedAfterSpend == false)170 #expect(r.scriptTypesInUse == [.p2wpkh, .p2tr])171 #expect(r.vulnerableScripts == [.p2tr])172 #expect(r.utxos.first { $0.scriptType == .p2tr }?.exposure == .revealedByScript)173 let ids = Set(r.findings.map(\.id))174 #expect(ids == ["btc.exposure.revealed", "btc.reuse", "btc.script.revealing"])175 #expect(r.findings.allSatisfy { $0.severity == .warning })176177 let figures = QuantumShield.analyze(.init(vault: Self.vaultInput(nil, watchOnly: true), bitcoin: input, ethereum: nil, networks: [])).migrationFigures178 #expect(figures.exposedBitcoinUTXOs == 2)179 #expect(figures.reusedBitcoinAddresses == 2)180 #expect(!figures.ethereumKeyExposed)181 }182183 @Test func bitcoinEmptyWallet() {184 let r = QuantumShield.bitcoinKeyExposure(.init(network: .testnet, utxos: [], activity: []))185 #expect(r.hashedUnrevealedShareBasisPoints == nil)186 #expect(r.findings.map(\.id) == ["btc.exposure.empty"])187 #expect(r.totals.total == 0)188 }189190 @Test func ethereumExposureAndApprovals() throws {191 let owner = try #require(EthereumAddress("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"))192 let spender = try #require(EthereumAddress("0x70997970C51812dc3A010C7d01b50e0d17dc79C8"))193 let token = TokenInfo(network: .sepolia, address: try #require(EthereumAddress("0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238")),194 symbol: "USDC", name: "USD Coin", decimals: 6)195196 let fresh = QuantumShield.ethereumKeyExposure(.init(network: .sepolia, address: owner, outgoingTransactionCount: 0, openApprovals: [],197 capabilities: Self.capabilities))198 #expect(fresh.publicKeyRecoverable == false)199 #expect(fresh.accountType == .externallyOwned)200 #expect(Set(fresh.findings.map(\.id)) == ["eth.exposure.none", "eth.approvals.none"])201 #expect(fresh.compatibilityNotes.map(\.id) == ["eth.eoa", "eth.pq-validation"])202203 let unlimited = TokenApprovalExposure(token: token, spender: spender, allowance: .max)204 let limited = TokenApprovalExposure(token: token, spender: owner, allowance: UInt256(1_000_000))205 #expect(unlimited.isUnlimited && !limited.isUnlimited)206 let used = QuantumShield.ethereumKeyExposure(.init(network: .sepolia, address: owner, outgoingTransactionCount: 3,207 openApprovals: [unlimited, limited], capabilities: Self.capabilities))208 #expect(used.publicKeyRecoverable == true)209 #expect(used.findings.first?.id == "eth.approvals.open")210 #expect(used.findings.first?.severity == .critical)211 #expect(used.findings.contains { $0.id == "eth.exposure.revealed" && $0.severity == .warning })212213 let onlyLimited = QuantumShield.ethereumKeyExposure(.init(network: .sepolia, address: owner, outgoingTransactionCount: 1,214 openApprovals: [limited], capabilities: []))215 #expect(onlyLimited.findings.first { $0.id == "eth.approvals.open" }?.severity == .warning)216217 let unmeasured = QuantumShield.ethereumKeyExposure(.init(network: .sepolia, address: owner, outgoingTransactionCount: nil,218 openApprovals: nil, capabilities: []))219 #expect(unmeasured.publicKeyRecoverable == nil)220 #expect(unmeasured.openApprovals == nil)221 #expect(Set(unmeasured.findings.map(\.id)) == ["eth.exposure.unknown", "eth.approvals.unknown"])222 #expect(unmeasured.findings.allSatisfy { $0.severity == .info })223 }224225 @Test func networkResistanceIsFactualAndSeparate() async throws {226 let awaiting = ProtocolCapability(id: "btc.pq-output", title: "PQ output", detail: "", status: .awaitingProtocol, requirement: "soft fork",227 quantumResistant: true)228 let available = ProtocolCapability(id: "btc.p2wpkh", title: "P2WPKH", detail: "", status: .available, requirement: nil, quantumResistant: false)229 let section = QuantumShield.networkResistance([230 .init(chain: .bitcoin, networkName: "Bitcoin Signet", offersQuantumResistance: false, capabilities: [available, awaiting]),231 .init(chain: .ethereum, networkName: "Ethereum Sepolia", offersQuantumResistance: false, capabilities: Self.capabilities),232 ])233 #expect(section.chains.count == 2)234 #expect(section.chains.allSatisfy { !$0.offersQuantumResistance })235 #expect(section.chains[0].signatureSchemes == ["secp256k1 ECDSA", "secp256k1 Schnorr (BIP-340)"])236 #expect(section.chains[0].statement.contains("Neither resists a large quantum computer"))237 #expect(section.chains[0].awaitingProtocol == [awaiting])238 #expect(section.chains[1].awaitingProtocol.map(\.id) == ["eth.pq-validation"])239 #expect(section.findings.map(\.id) == ["network.bitcoin.not-resistant", "network.ethereum.not-resistant"])240 #expect(section.findings.allSatisfy { $0.severity == .info })241242 // The three sections stay separate: a perfect vault changes neither exposure nor the networks, and the report243 // exposes no combined score.244 let a = Self.script(1)245 let exposed = KeyExposure.BitcoinInput(network: .signet, utxos: [Self.utxo(0xc1, a, 1_000)], activity: [246 ScriptActivity(scriptPubKey: a, kind: .funded, txid: Self.txid(0xc1), height: 5),247 ScriptActivity(scriptPubKey: a, kind: .spent, txid: Self.txid(0xc2), height: 6),248 ])249 let report = QuantumShield.analyze(.init(vault: Self.vaultInput(try await Self.vaultReport()), bitcoin: exposed, ethereum: nil, networks: [250 .init(chain: .bitcoin, networkName: "Bitcoin Signet", offersQuantumResistance: false, capabilities: [awaiting]),251 ]))252 #expect(report.keyExposure.level == .attention)253 #expect(report.keyExposure.bitcoin?.exposedUTXOCount == 1)254 #expect(report.networkResistance.chains.first?.offersQuantumResistance == false)255 #expect(report.disclaimer == QuantumShield.localCryptographyDisclaimer)256 #expect(report.disclaimer.contains("does not make Bitcoin or Ethereum quantum-resistant"))257 #expect(report.generatedAt == Self.now)258 let names = Mirror(reflecting: report).children.compactMap(\.label)259 #expect(Set(names) == ["generatedAt", "vaultSecurity", "keyExposure", "networkResistance", "disclaimer"])260261 let nothing = QuantumShield.keyExposure(bitcoin: nil, ethereum: nil)262 #expect(nothing.level == .unknown)263 }264265 /// A chain that was not measured is never counted as safe: the level of the section is "not assessed" unless266 /// something that was measured calls for attention.267 @Test func unmeasuredChainsAreNeverInGoodOrder() throws {268 let owner = try #require(EthereumAddress("0x9858EfFD232B4033E47d90003D41EC34EcaEda94"))269 let a = Self.script(1)270 let hidden = KeyExposure.BitcoinInput(network: .signet, utxos: [Self.utxo(0xd1, a, 5_000)], activity: [271 ScriptActivity(scriptPubKey: a, kind: .funded, txid: Self.txid(0xd1), height: 5),272 ])273 let exposed = KeyExposure.BitcoinInput(network: .signet, utxos: [Self.utxo(0xd2, a, 5_000)], activity: [274 ScriptActivity(scriptPubKey: a, kind: .funded, txid: Self.txid(0xd2), height: 5),275 ScriptActivity(scriptPubKey: a, kind: .spent, txid: Self.txid(0xd3), height: 6),276 ])277 func ethereum(_ count: UInt64?, approvals: [TokenApprovalExposure]?) -> KeyExposure.EthereumInput {278 .init(network: .sepolia, address: owner, outgoingTransactionCount: count, openApprovals: approvals, capabilities: [])279 }280281 // everything measured, nothing wrong282 let measured = QuantumShield.keyExposure(bitcoin: hidden, ethereum: ethereum(0, approvals: []))283 #expect(measured.level == .good && !measured.isPartlyUnmeasured)284285 // Ethereum never synchronized: only "not measured" findings (severity info) used to read as "good"286 let onlyUnmeasured = QuantumShield.keyExposure(bitcoin: nil, ethereum: ethereum(nil, approvals: nil), hasBitcoinAccount: false)287 #expect(onlyUnmeasured.findings.allSatisfy { $0.severity == .info })288 #expect(onlyUnmeasured.level == .unknown && onlyUnmeasured.isPartlyUnmeasured)289290 // one chain measured and fine, the other not measured291 let bitcoinOnly = QuantumShield.keyExposure(bitcoin: hidden, ethereum: ethereum(nil, approvals: nil))292 #expect(bitcoinOnly.level == .unknown && bitcoinOnly.isPartlyUnmeasured)293 let ethereumOnly = QuantumShield.keyExposure(bitcoin: nil, ethereum: ethereum(0, approvals: []))294 #expect(ethereumOnly.level == .unknown && ethereumOnly.isPartlyUnmeasured)295 // ... unless the wallet has no Bitcoin account at all296 let noBitcoinAccount = QuantumShield.keyExposure(bitcoin: nil, ethereum: ethereum(0, approvals: []), hasBitcoinAccount: false)297 #expect(noBitcoinAccount.level == .good && !noBitcoinAccount.isPartlyUnmeasured)298 // approvals that could not be looked up are a missing measurement too299 let noApprovals = QuantumShield.keyExposure(bitcoin: hidden, ethereum: ethereum(0, approvals: nil))300 #expect(noApprovals.level == .unknown && noApprovals.isPartlyUnmeasured)301302 // what was measured is never hidden by what is missing303 let warned = QuantumShield.keyExposure(bitcoin: exposed, ethereum: ethereum(nil, approvals: nil))304 #expect(warned.level != .unknown && warned.level != .good && warned.isPartlyUnmeasured)305 let sent = QuantumShield.keyExposure(bitcoin: nil, ethereum: ethereum(2, approvals: nil))306 #expect(sent.level == .attention && sent.isPartlyUnmeasured)307308 // the rule itself309 let info = ShieldFinding(id: "x.info", title: "", detail: "", severity: .info)310 let good = ShieldFinding(id: "x.good", title: "", detail: "", severity: .good)311 let warning = ShieldFinding(id: "x.warning", title: "", detail: "", severity: .warning)312 let critical = ShieldFinding(id: "x.critical", title: "", detail: "", severity: .critical)313 #expect(ShieldLevel.from([]) == .unknown)314 #expect(ShieldLevel.from([info, good]) == .good)315 #expect(ShieldLevel.from([info, good], fullyMeasured: false) == .unknown)316 #expect(ShieldLevel.from([good, warning], fullyMeasured: false) == .attention)317 #expect(ShieldLevel.from([warning, critical], fullyMeasured: false) == .critical)318319 // through the report320 let report = QuantumShield.analyze(.init(vault: Self.vaultInput(nil, watchOnly: true), bitcoin: nil, ethereum: ethereum(nil, approvals: nil),321 networks: []))322 #expect(report.keyExposure.level == .unknown)323 }324}325