SPB Git

Repository Public

ShieldReport.swift 63.5 KB 1,064 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraQuantumShield/ShieldReport.swift8// Module           : Qyvora Quantum Shield9// 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 QyvoraMath43import QyvoraCore44import QyvoraBitcoin45import QyvoraEthereum46import QyvoraVault4748/// Severity of one finding of the Quantum Shield.49public enum ShieldSeverity: String, Sendable, Codable, CaseIterable, Comparable {50    /// Neutral fact.51    case info52    /// Something that is in good order.53    case good54    /// Something the user should improve.55    case warning56    /// Something that puts funds or the vault at risk now.57    case critical5859    var rank: Int {60        switch self {61        case .info: return 062        case .good: return 163        case .warning: return 264        case .critical: return 365        }66    }6768    public static func < (a: ShieldSeverity, b: ShieldSeverity) -> Bool { a.rank < b.rank }69}7071/// One statement of the report, with what to do about it when something can be done.72public struct ShieldFinding: Sendable, Equatable, Identifiable, Codable {73    /// Stable identifier (e.g. "vault.password.weak"), usable as a localization or test key.74    public let id: String75    public let title: String76    public let detail: String77    public let severity: ShieldSeverity78    /// nil when nothing is to be done.79    public let recommendation: String?8081    public init(id: String, title: String, detail: String, severity: ShieldSeverity, recommendation: String? = nil) {82        self.id = id83        self.title = title84        self.detail = detail85        self.severity = severity86        self.recommendation = recommendation87    }88}8990/// Summary level of ONE section. The three sections of a `ShieldReport` are never combined into a single score.91public enum ShieldLevel: String, Sendable, Codable, CaseIterable {92    /// No warning and no critical finding.93    case good94    /// At least one warning, no critical finding.95    case attention96    /// At least one critical finding.97    case critical98    /// The section could not be assessed (no data).99    case unknown100101    /// The level of a section from its findings. What was found is never hidden: a critical finding or a warning102    /// decides, whatever else is missing. Without either, the section is in good order only when everything it covers103    /// was measured (`fullyMeasured`) and at least one finding says so; otherwise it is `.unknown` — what was not104    /// measured is never counted as safe.105    static func from(_ findings: [ShieldFinding], fullyMeasured: Bool = true) -> ShieldLevel {106        if findings.contains(where: { $0.severity == .critical }) { return .critical }107        if findings.contains(where: { $0.severity == .warning }) { return .attention }108        guard fullyMeasured, !findings.isEmpty else { return .unknown }109        return .good110    }111}112113// MARK: - Section 1: vault security114115/// Section 1: how well the local vault protects the secrets at rest. Says nothing about the blockchains.116public struct VaultSecurity: Sendable, Equatable {117    public struct Input: Sendable, Equatable {118        /// nil when no vault exists on this device (watch-only wallet).119        public var report: VaultReport?120        /// Level measured when the password was set; nil when unknown (never the password itself).121        public var passwordQuality: PasswordQuality.Level?122        public var autoLock: AutoLockPolicy123        /// Date of the last encrypted backup, nil when none was made.124        public var lastBackup: Date?125        /// Whether that backup carried a signature; nil when unknown.126        public var lastBackupSigned: Bool?127        /// Whether the user proved they wrote the recovery phrase down.128        public var recoveryPhraseVerified: Bool129        public var isWatchOnly: Bool130        public var now: Date131132        public init(report: VaultReport?, passwordQuality: PasswordQuality.Level?, autoLock: AutoLockPolicy, lastBackup: Date?,133                    lastBackupSigned: Bool?, recoveryPhraseVerified: Bool, isWatchOnly: Bool, now: Date) {134            self.report = report135            self.passwordQuality = passwordQuality136            self.autoLock = autoLock137            self.lastBackup = lastBackup138            self.lastBackupSigned = lastBackupSigned139            self.recoveryPhraseVerified = recoveryPhraseVerified140            self.isWatchOnly = isWatchOnly141            self.now = now142        }143    }144145    public let level: ShieldLevel146    public let findings: [ShieldFinding]147    /// Algorithms in use, for the detail screen (empty without a vault).148    public let algorithms: [String]149}150151// MARK: - Section 2: key exposure152153/// Satoshis by exposure class of the public key guarding them.154public struct BitcoinExposureTotals: Sendable, Equatable, Codable {155    public var hashedUnrevealed: UInt64 = 0156    public var revealedBySpend: UInt64 = 0157    public var revealedByScript: UInt64 = 0158    public var undetermined: UInt64 = 0159160    public var total: UInt64 { hashedUnrevealed + revealedBySpend + revealedByScript + undetermined }161    /// Value whose public key is already on chain.162    public var revealed: UInt64 { revealedBySpend + revealedByScript }163164    public subscript(_ exposure: PublicKeyExposure) -> UInt64 {165        switch exposure {166        case .hashedUnrevealed: return hashedUnrevealed167        case .revealedBySpend: return revealedBySpend168        case .revealedByScript: return revealedByScript169        case .undetermined: return undetermined170        }171    }172}173174/// Section 2, Bitcoin part: which coins sit behind a public key that is already visible on chain.175public struct BitcoinKeyExposure: Sendable, Equatable {176    public struct UTXO: Sendable, Equatable, Identifiable {177        public let outPoint: BitcoinOutPoint178        public let address: String?179        public let value: UInt64180        public let confirmations: UInt32181        public let exposure: PublicKeyExposure182        public let scriptType: BitcoinScriptType183        /// One sentence for the user interface.184        public let explanation: String185        public var id: String { outPoint.description }186    }187188    public struct Address: Sendable, Equatable, Identifiable {189        public let address: String?190        public let scriptPubKey: Bytes191        public let scriptType: BitcoinScriptType192        public let exposure: PublicKeyExposure193        /// Unspent satoshis on the address.194        public let balance: UInt64195        public let utxoCount: Int196        /// Distinct transactions that paid the address.197        public let fundingTransactionCount: Int198        /// Paid by more than one transaction, or paid again after a spend.199        public let isReused: Bool200        /// Paid after its public key had been published by a spend.201        public let fundedAfterSpend: Bool202        public var id: String { address ?? Hex.encode(scriptPubKey) }203    }204205    public let network: BitcoinNetwork206    public let utxos: [UTXO]207    /// Every address seen in the activity or holding coins, sorted by address text.208    public let addresses: [Address]209    public let totals: BitcoinExposureTotals210    public let reusedAddresses: [Address]211    /// Script families that currently hold coins.212    public let scriptTypesInUse: [BitcoinScriptType]213    /// Script families in use that publish the key in the output itself (P2PK, bare multisig, Taproot).214    public let vulnerableScripts: [BitcoinScriptType]215    /// Share of the value on hashed outputs never spent from, in basis points (0…10000); nil when the wallet holds nothing.216    public let hashedUnrevealedShareBasisPoints: Int?217    public let exposedUTXOCount: Int218    public let findings: [ShieldFinding]219    /// Advice for long-term storage, always present.220    public let longTermStorageAdvice: [String]221}222223/// An ERC-20 allowance that lets `spender` move tokens of the account.224public struct TokenApprovalExposure: Sendable, Equatable, Identifiable {225    public let token: TokenInfo226    public let spender: EthereumAddress227    public let allowance: UInt256228    /// The allowance is the "unlimited" value (≥ 2^255).229    public let isUnlimited: Bool230    public var id: String { "\(token.id):\(spender.checksummed)" }231232    public init(token: TokenInfo, spender: EthereumAddress, allowance: UInt256) {233        self.token = token234        self.spender = spender235        self.allowance = allowance236        isUnlimited = ERC20.isUnlimited(allowance)237    }238}239240/// A capability of a chain as registered by the Quantum Migration Engine. The wallet layer copies the registry241/// entries here: this module does not depend on QyvoraMigration.242public struct ProtocolCapability: Sendable, Equatable, Identifiable, Codable {243    public enum Status: String, Sendable, Codable { case available, planned, awaitingProtocol }244245    public let id: String246    public let title: String247    public let detail: String248    public let status: Status249    /// What must happen before the capability can be enabled.250    public let requirement: String?251    public let quantumResistant: Bool252253    public init(id: String, title: String, detail: String, status: Status, requirement: String?, quantumResistant: Bool) {254        self.id = id255        self.title = title256        self.detail = detail257        self.status = status258        self.requirement = requirement259        self.quantumResistant = quantumResistant260    }261}262263/// Section 2, Ethereum part.264public struct EthereumKeyExposure: Sendable, Equatable {265    public enum AccountType: String, Sendable, Codable {266        /// Externally owned account: one secp256k1 key.267        case externallyOwned268    }269270    public let network: EthereumNetwork271    public let address: EthereumAddress272    public let accountType: AccountType273    /// Transactions sent by the account (its nonce); nil when not measured.274    public let outgoingTransactionCount: UInt64?275    /// True as soon as one transaction was sent: the public key is recoverable from its signature. nil when not measured.276    public let publicKeyRecoverable: Bool?277    /// Non-zero allowances; nil when they could not be measured.278    public let openApprovals: [TokenApprovalExposure]?279    /// What Ethereum would need for post-quantum validation, from the migration registry.280    public let compatibilityNotes: [ProtocolCapability]281    public let findings: [ShieldFinding]282}283284/// Section 2, account chains seen as a whole: one key and one address per family, used on one or several networks.285///286/// - EVM: ONE secp256k1 key serves every EVM network. The public key is recoverable from the signature of any287///   outgoing transaction, so it is public as soon as the account has sent one on ANY of them. The evidence is the288///   account nonce (or the history, where there is one).289/// - Solana: the address IS the Ed25519 public key. It is public from the moment the address is shared or funded;290///   nothing needs to be measured. Ed25519 does not resist a large quantum computer.291/// - TRON: like an EVM account, on TRON's own networks. A TRON account has no nonce: the evidence is the history or292///   the account's resource usage.293public struct AccountKeyExposure: Sendable, Equatable, Identifiable {294    public enum Family: String, Sendable, Codable, CaseIterable { case evm, solana, tron }295296    /// What one network says about the key.297    public struct Network: Sendable, Equatable {298        public var name: String299        /// true: an outgoing transaction exists (or, on Solana, the account is on chain). false: measured, none.300        /// nil: not measured (never synchronized, or no history source and no other evidence).301        public var publicKeyExposed: Bool?302        /// Where the answer comes from, as a short phrase ("account nonce", "history", "not synchronized").303        public var evidence: String304305        public init(name: String, publicKeyExposed: Bool?, evidence: String) {306            self.name = name307            self.publicKeyExposed = publicKeyExposed308            self.evidence = evidence309        }310    }311312    /// The open token approvals of the account on one EVM network that has a history source (approvals are found in313    /// the history; a network without one cannot be measured and is not listed).314    public struct NetworkApprovals: Sendable, Equatable, Identifiable {315        public var network: EthereumNetwork316        /// nil when they were not measured (the network was not synchronized, or its lookup failed).317        public var approvals: [TokenApprovalExposure]?318        /// True for the network the Ethereum part of the section reports on: its approvals have their finding there.319        public var isPrimary: Bool320        public var id: String { network.rawValue }321322        public init(network: EthereumNetwork, approvals: [TokenApprovalExposure]?, isPrimary: Bool = false) {323            self.network = network324            self.approvals = approvals325            self.isPrimary = isPrimary326        }327    }328329    public struct Input: Sendable, Equatable {330        public var family: Family331        public var address: String332        /// EVM only: the approvals of each enabled network that has a history source (set after `init`).333        public var approvals: [NetworkApprovals] = []334        /// One entry per enabled network of the family.335        public var networks: [Network]336337        public init(family: Family, address: String, networks: [Network]) {338            self.family = family339            self.address = address340            self.networks = networks341        }342    }343344    public let family: Family345    public let address: String346    public let networks: [Network]347    /// true when the key is public (on Solana always; elsewhere when a network shows an outgoing transaction).348    /// false only when every network was measured and none shows one. nil when no network shows one and at least one349    /// could not be measured: the key may be public there.350    public let publicKeyExposed: Bool?351    /// Networks without measurement.352    public let unmeasuredNetworks: [String]353    public let findings: [ShieldFinding]354    public var id: String { family.rawValue }355    /// EVM only: the open approvals of every enabled network that has a history source, the primary one included.356    public internal(set) var approvals: [NetworkApprovals] = []357    /// Every open approval measured, on any network.358    public var openApprovals: [TokenApprovalExposure] { approvals.flatMap { $0.approvals ?? [] } }359}360361/// Section 2: exposure of the wallet's public keys on chain. A statement about this wallet's history, not about the vault362/// and not about what the networks can do.363public struct KeyExposure: Sendable, Equatable {364    public struct BitcoinInput: Sendable, Equatable {365        public var network: BitcoinNetwork366        public var utxos: [BitcoinUTXO]367        /// Funding and spending events of the wallet's scripts.368        public var activity: [ScriptActivity]369370        public init(network: BitcoinNetwork, utxos: [BitcoinUTXO], activity: [ScriptActivity]) {371            self.network = network372            self.utxos = utxos373            self.activity = activity374        }375    }376377    public struct EthereumInput: Sendable, Equatable {378        public var network: EthereumNetwork379        public var address: EthereumAddress380        /// Nonce of the account at "latest"; nil when unknown.381        public var outgoingTransactionCount: UInt64?382        /// Non-zero allowances found; nil when the lookup was not possible.383        public var openApprovals: [TokenApprovalExposure]?384        /// Registry entries of the Ethereum chain.385        public var capabilities: [ProtocolCapability]386387        public init(network: EthereumNetwork, address: EthereumAddress, outgoingTransactionCount: UInt64?,388                    openApprovals: [TokenApprovalExposure]?, capabilities: [ProtocolCapability]) {389            self.network = network390            self.address = address391            self.outgoingTransactionCount = outgoingTransactionCount392            self.openApprovals = openApprovals393            self.capabilities = capabilities394        }395    }396397    /// nil when no Bitcoin data was measured (never synchronized).398    public let bitcoin: BitcoinKeyExposure?399    /// nil when the wallet has no Ethereum account or nothing was measured.400    public let ethereum: EthereumKeyExposure?401    /// `.unknown` when a chain of the wallet was not measured and nothing measured calls for attention.402    public let level: ShieldLevel403    /// True when part of what this section covers has no measurement: a Bitcoin account never synchronized, an Ethereum404    /// account whose transaction count or whose approvals are not known. The interface says so next to the level.405    public let isPartlyUnmeasured: Bool406    /// Findings of every chain, most severe first.407    public let findings: [ShieldFinding]408    /// The account chains as a whole: the EVM account across every enabled EVM network, the Solana account, the TRON409    /// account. Empty when the wallet layer gave none (QYVORA 1.0 inputs).410    public internal(set) var accounts: [AccountKeyExposure] = []411    /// The other UTXO coins of the wallet (Litecoin, Dogecoin, Bitcoin Cash), each analysed like Bitcoin: a key stays412    /// hashed until its address is spent from. Empty when the wallet layer gave none.413    public internal(set) var otherCoins: [BitcoinKeyExposure] = []414    /// The networks of other UTXO coins the wallet uses that were not measured (never synchronized, or without an415    /// indexer): entries of their own, not sentences. Nothing is known about their keys.416    public internal(set) var unmeasuredCoins: [BitcoinNetwork] = []417}418419// MARK: - Section 3: network resistance420421/// Section 3: what the networks themselves offer. Independent of this wallet and of this device.422public struct NetworkResistance: Sendable, Equatable {423    /// The chain a network belongs to: one case per chain of the wallet. `kind` groups them by what they validate.424    /// (QYVORA 1.0 knew `.bitcoin` and `.ethereum` only and used them for every UTXO coin and every EVM network.)425    public enum Chain: String, Sendable, Codable, CaseIterable {426        case bitcoin, ethereum, solana, tron427        case litecoin, dogecoin, bitcoinCash428        case base, arbitrum, optimism, polygon, bsc, avalanche429430        /// What the chain validates: `.bitcoin` for every UTXO coin, `.ethereum` for every EVM network.431        public var kind: Chain {432            switch self {433            case .bitcoin, .litecoin, .dogecoin, .bitcoinCash: return .bitcoin434            case .ethereum, .base, .arbitrum, .optimism, .polygon, .bsc, .avalanche: return .ethereum435            case .solana: return .solana436            case .tron: return .tron437            }438        }439440        /// The chain of a UTXO network.441        public init(_ network: BitcoinNetwork) {442            switch network.coin {443            case .bitcoin: self = .bitcoin444            case .litecoin: self = .litecoin445            case .dogecoin: self = .dogecoin446            case .bitcoinCash: self = .bitcoinCash447            }448        }449450        /// The chain of an EVM network.451        public init(_ network: EthereumNetwork) {452            switch network.family {453            case .ethereum: self = .ethereum454            case .base: self = .base455            case .arbitrum: self = .arbitrum456            case .optimism: self = .optimism457            case .polygon: self = .polygon458            case .bsc: self = .bsc459            case .avalanche: self = .avalanche460            }461        }462    }463464    public struct Input: Sendable, Equatable {465        public var chain: Chain466        public var networkName: String467        /// `MigrationEngine.chainOffersQuantumResistance` for the chain.468        public var offersQuantumResistance: Bool469        /// Registry entries of the chain.470        public var capabilities: [ProtocolCapability]471        /// Signature algorithms the network validates, when they differ from the default of the kind (a UTXO coin472        /// without Schnorr signatures); nil for the default.473        public var signatureSchemes: [String]?474        /// Identifier of the network in the wallet's registry ("litecoin-testnet", "base-sepolia"), so that the475        /// interface finds the network without comparing names; nil when the caller has none.476        public var networkID: String?477        /// The scheme this wallet signs with on the network, when it is narrower than what the network validates478        /// (Bitcoin validates ECDSA and Schnorr; the wallet spends with ECDSA). Set after `init`; nil when not given.479        public var walletSignatureScheme: String?480481        public init(chain: Chain, networkName: String, offersQuantumResistance: Bool, capabilities: [ProtocolCapability],482                    signatureSchemes: [String]? = nil, networkID: String? = nil) {483            self.chain = chain484            self.networkName = networkName485            self.offersQuantumResistance = offersQuantumResistance486            self.capabilities = capabilities487            self.signatureSchemes = signatureSchemes488            self.networkID = networkID489        }490    }491492    public struct ChainStatus: Sendable, Equatable, Identifiable {493        public let chain: Chain494        public let networkName: String495        /// Signature algorithms the network validates today.496        public let signatureSchemes: [String]497        /// Factual sentence shown as is.498        public let statement: String499        /// False for every chain today.500        public let offersQuantumResistance: Bool501        /// Capabilities that wait for a consensus or protocol change. Disabled in the application.502        public let awaitingProtocol: [ProtocolCapability]503        public var id: String { "\(chain.rawValue):\(networkName)" }504        /// Identifier of the network in the wallet's registry, as given in the input; nil when none was given.505        public internal(set) var networkID: String?506        /// The scheme this wallet signs with on the network, as given in the input. `signatureSchemes` is what the507        /// network validates, which can be more (Bitcoin: ECDSA and Schnorr; the wallet spends with ECDSA only).508        public internal(set) var walletSignatureScheme: String?509        /// A sentence for the case where the wallet uses only part of what the network validates; nil otherwise.510        public var walletSignatureNote: String? {511            guard let scheme = walletSignatureScheme, signatureSchemes.count > 1, signatureSchemes.contains(scheme) else { return nil }512            let others = signatureSchemes.filter { $0 != scheme }.joined(separator: ", ")513            return "QYVORA signs \(networkName) transactions with \(scheme) only. \(others) is validated by the network and implemented in the engine, but not used for spending."514        }515    }516517    public let chains: [ChainStatus]518    public let findings: [ShieldFinding]519}520521// MARK: - Report522523/// The Quantum Shield report: three separate sections. There is deliberately no overall score — a strong vault does not524/// compensate for exposed keys, and neither changes what the networks validate.525public struct ShieldReport: Sendable, Equatable {526    public struct Input: Sendable, Equatable {527        public var vault: VaultSecurity.Input528        public var bitcoin: KeyExposure.BitcoinInput?529        public var ethereum: KeyExposure.EthereumInput?530        public var networks: [NetworkResistance.Input]531        /// The wallet has a Bitcoin account: without `bitcoin` data that chain is then unmeasured, not absent.532        public var hasBitcoinAccount: Bool533        /// The account chains as a whole (EVM across its networks, Solana, TRON).534        public var accounts: [AccountKeyExposure.Input]535        /// The other UTXO coins that were measured (set after `init`).536        public var otherCoins: [KeyExposure.BitcoinInput] = []537        /// Names of the networks of other UTXO coins the wallet uses that were not measured.538        public var unmeasuredCoins: [String] = []539        /// The same networks as values (set after `init`). A network given here needs no entry in `unmeasuredCoins`.540        public var unmeasuredCoinNetworks: [BitcoinNetwork] = []541542        public init(vault: VaultSecurity.Input, bitcoin: KeyExposure.BitcoinInput?, ethereum: KeyExposure.EthereumInput?,543                    networks: [NetworkResistance.Input], hasBitcoinAccount: Bool = true, accounts: [AccountKeyExposure.Input] = []) {544            self.vault = vault545            self.bitcoin = bitcoin546            self.ethereum = ethereum547            self.networks = networks548            self.hasBitcoinAccount = hasBitcoinAccount549            self.accounts = accounts550        }551    }552553    public let generatedAt: Date554    public let vaultSecurity: VaultSecurity555    public let keyExposure: KeyExposure556    public let networkResistance: NetworkResistance557    /// Always `QuantumShield.localCryptographyDisclaimer`; the interface must display it with the report.558    public let disclaimer: String559560    /// Figures a migration plan is built from (`MigrationPlan.make` in QyvoraMigration).561    public struct MigrationFigures: Sendable, Equatable {562        public let exposedBitcoinUTXOs: Int563        public let reusedBitcoinAddresses: Int564        /// The EVM key is public: the primary network, or any enabled EVM network, shows an outgoing transaction.565        public let ethereumKeyExposed: Bool566        public let openApprovals: Int567        /// The wallet has a Solana account (its key is its address).568        public let solanaAccountPublic: Bool569        public let tronKeyExposed: Bool570        /// Exposed outputs and reused addresses of each other UTXO coin that was measured (Litecoin, Dogecoin,571        /// Bitcoin Cash), in the order of the report. `exposedBitcoinUTXOs` counts Bitcoin alone.572        public var otherCoins: [CoinFigures] = []573        /// Exposed outputs of every UTXO coin together.574        public var exposedUTXOsOfEveryCoin: Int { otherCoins.reduce(exposedBitcoinUTXOs) { $0 + $1.exposedUTXOs } }575    }576577    /// The exposure figures of one UTXO coin.578    public struct CoinFigures: Sendable, Equatable {579        public let network: BitcoinNetwork580        public let exposedUTXOs: Int581        public let reusedAddresses: Int582    }583584    public var migrationFigures: MigrationFigures {585        func account(_ family: AccountKeyExposure.Family) -> AccountKeyExposure? { keyExposure.accounts.first { $0.family == family } }586        // approvals of every EVM network that was measured; the primary network is counted once587        var approvals = keyExposure.ethereum?.openApprovals?.count ?? 0588        for network in account(.evm)?.approvals ?? [] where !network.isPrimary || keyExposure.ethereum?.openApprovals == nil {589            approvals += network.approvals?.count ?? 0590        }591        var figures = MigrationFigures(exposedBitcoinUTXOs: keyExposure.bitcoin?.exposedUTXOCount ?? 0,592                                       reusedBitcoinAddresses: keyExposure.bitcoin?.reusedAddresses.count ?? 0,593                                       ethereumKeyExposed: (keyExposure.ethereum?.publicKeyRecoverable ?? false) || account(.evm)?.publicKeyExposed == true,594                                       openApprovals: approvals,595                                       solanaAccountPublic: account(.solana) != nil, tronKeyExposed: account(.tron)?.publicKeyExposed == true)596        figures.otherCoins = keyExposure.otherCoins.map { CoinFigures(network: $0.network, exposedUTXOs: $0.exposedUTXOCount, reusedAddresses: $0.reusedAddresses.count) }597        return figures598    }599}600601/// Pure, synchronous analysis. Nothing here touches the network, the vault content or the clock (dates are inputs).602public enum QuantumShield {603    /// Text the interface must show wherever the report is shown.604    public static let localCryptographyDisclaimer =605        "Local post-quantum cryptography does not make Bitcoin or Ethereum quantum-resistant. QYVORA uses post-quantum "606        + "algorithms to protect what stays on this device and its backups; transactions are still authorized with "607        + "secp256k1 signatures, because that is what the networks validate today."608609    /// The same statement for a wallet that uses more chains than Bitcoin and Ethereum. Shown in addition to the610    /// disclaimer wherever the other chains are listed.611    public static let multiChainDisclaimer =612        "The same holds for every other chain of this wallet: Litecoin, Dogecoin, Bitcoin Cash, the EVM networks and TRON validate secp256k1 signatures, "613        + "Solana validates Ed25519 signatures. None of them resists a large quantum computer, and no "614        + "post-quantum signature is deployed on any of them today."615616    /// Days after which an encrypted backup is reported as old.617    public static let backupFreshnessDays = 90618619    public static func analyze(_ input: ShieldReport.Input) -> ShieldReport {620        // a network given as a value is named by `displayName`; a name given alone is kept as it is621        let names = input.unmeasuredCoinNetworks.map(\.displayName)622        var exposure = keyExposure(bitcoin: input.bitcoin, ethereum: input.ethereum, hasBitcoinAccount: input.hasBitcoinAccount,623                                   accounts: input.accounts, otherCoins: input.otherCoins,624                                   unmeasuredCoins: names + input.unmeasuredCoins.filter { !names.contains($0) })625        exposure.unmeasuredCoins = input.unmeasuredCoinNetworks626        return ShieldReport(generatedAt: input.vault.now, vaultSecurity: vaultSecurity(input.vault), keyExposure: exposure,627                            networkResistance: networkResistance(input.networks), disclaimer: localCryptographyDisclaimer)628    }629630    // MARK: Vault631632    public static func vaultSecurity(_ input: VaultSecurity.Input) -> VaultSecurity {633        var f = [ShieldFinding]()634        guard let report = input.report else {635            if input.isWatchOnly {636                f.append(ShieldFinding(id: "vault.watch-only", title: "Watch-only wallet",637                                       detail: "This device holds no private key: it can show balances and prepare transactions, not sign them.",638                                       severity: .info))639                return VaultSecurity(level: .good, findings: f, algorithms: [])640            }641            f.append(ShieldFinding(id: "vault.missing", title: "No vault on this device",642                                   detail: "No encrypted vault was found, so its protection cannot be assessed.", severity: .info))643            return VaultSecurity(level: .unknown, findings: f, algorithms: [])644        }645646        if report.selfTestPassed {647            f.append(ShieldFinding(id: "vault.self-test.ok", title: "Cryptographic self-test passed",648                                   detail: "The system and the QYVORA implementations of the vault algorithms agree.", severity: .good))649        } else {650            f.append(ShieldFinding(id: "vault.self-test.failed", title: "Cryptographic self-test failed",651                                   detail: "The two implementations of the vault algorithms disagree. The vault refuses to work.",652                                   severity: .critical, recommendation: "Do not use this build. Restore the wallet from the recovery phrase on a healthy installation."))653        }654        f.append(ShieldFinding(id: "vault.encryption", title: "Secrets encrypted at rest",655                               detail: "\(report.recordEncryption) with a \(report.masterKeyBits)-bit master key, file authenticated with \(report.fileAuthentication). A symmetric key of this size keeps a wide margin against Grover's algorithm.",656                               severity: .good))657        if report.recoveredFromPreviousCopy {658            f.append(ShieldFinding(id: "vault.recovered-previous", title: "Vault restored from its previous copy",659                                   detail: "The current vault file was damaged; this session runs on the copy kept from the previous write.",660                                   severity: .warning, recommendation: "Check that recent changes are present and make a fresh encrypted backup."))661        }662663        switch input.passwordQuality {664        case .none:665            f.append(ShieldFinding(id: "vault.password.unknown", title: "Password strength not measured",666                                   detail: "The strength of the vault password was not recorded on this device.", severity: .info,667                                   recommendation: "Changing the password measures it again."))668        case .some(let level) where level <= .weak:669            f.append(ShieldFinding(id: "vault.password.weak", title: "Weak vault password",670                                   detail: "The password protecting the vault would not resist an offline guessing attack on a copy of the vault file.",671                                   severity: .critical, recommendation: "Choose a longer passphrase of several unrelated words."))672        case .some(let level) where level == .fair:673            f.append(ShieldFinding(id: "vault.password.fair", title: "Vault password could be stronger",674                                   detail: "The password is acceptable, but a longer one raises the cost of an offline attack considerably.",675                                   severity: .warning, recommendation: "Lengthen the password."))676        default:677            f.append(ShieldFinding(id: "vault.password.strong", title: "Strong vault password",678                                   detail: "The password was rated strong when it was set.", severity: .good))679        }680        if let slot = report.passwordSlot {681            f.append(ShieldFinding(id: "vault.kdf", title: "Slow key derivation",682                                   detail: "\(slot.construction): Argon2id \(slot.parameters.argon2MemoryKiB / 1024) MiB × \(slot.parameters.argon2Iterations) passes, PBKDF2 \(slot.parameters.pbkdf2Iterations) iterations.",683                                   severity: slot.parameters.argon2MemoryKiB >= 19_456 ? .good : .warning,684                                   recommendation: slot.parameters.argon2MemoryKiB >= 19_456 ? nil : "The key-derivation cost is below the recommended minimum; rotate the vault key on a current build."))685        }686687        if report.deviceSlotEnabled {688            f.append(ShieldFinding(id: "vault.biometric.on", title: "Biometric unlock enabled",689                                   detail: report.deviceSlotUsesSecureEnclave690                                       ? "The device key is wrapped by the Secure Enclave and released only after Face ID or Touch ID."691                                       : "The device key sits in the Keychain behind Face ID or Touch ID.",692                                   severity: .info))693        } else {694            f.append(ShieldFinding(id: "vault.biometric.off", title: "Biometric unlock disabled",695                                   detail: "The vault opens with the password only.", severity: .info))696        }697        if report.pinSlot != nil {698            let failed = report.pinFailedAttempts ?? 0699            if failed >= 3 {700                f.append(ShieldFinding(id: "vault.pin.failures", title: "Repeated wrong PIN entries",701                                       detail: "\(failed) consecutive wrong PINs were recorded on this device.", severity: .warning,702                                       recommendation: "If this was not you, change the PIN and the password."))703            }704            f.append(ShieldFinding(id: "vault.pin.on", title: "PIN unlock enabled",705                                   detail: report.pinWipeAfterFailedAttempts.map { "Wrong PINs are delayed, and the vault is erased from this device after \($0) failures." }706                                       ?? "Wrong PINs are delayed with escalating waiting times. The PIN only works on this device.",707                                   severity: .info))708        }709710        switch input.autoLock {711        case .never:712            f.append(ShieldFinding(id: "vault.autolock.never", title: "Auto-lock disabled",713                                   detail: "The vault stays open until it is locked by hand.", severity: .warning,714                                   recommendation: "Set an auto-lock delay of a few minutes."))715        case .after(let seconds) where seconds > 900:716            f.append(ShieldFinding(id: "vault.autolock.long", title: "Long auto-lock delay",717                                   detail: "The vault locks after \(Int(min(seconds / 60, 1e9))) minutes without activity.", severity: .warning,718                                   recommendation: "A delay of five minutes or less limits what an unattended device exposes."))719        case .after(let seconds):720            f.append(ShieldFinding(id: "vault.autolock.ok", title: "Auto-lock enabled",721                                   detail: "The vault locks after \(max(1, seconds.isFinite ? Int(max(seconds / 60, 0)) : 1)) minute(s) without activity.",722                                   severity: .good))723        case .immediately:724            f.append(ShieldFinding(id: "vault.autolock.ok", title: "Auto-lock enabled",725                                   detail: "The vault locks as soon as the application leaves the foreground.", severity: .good))726        }727728        if !input.recoveryPhraseVerified {729            f.append(ShieldFinding(id: "vault.phrase.unverified", title: "Recovery phrase not verified",730                                   detail: "The recovery phrase has not been confirmed on this device. Without it, losing the device loses the funds.",731                                   severity: .critical, recommendation: "Write the recovery phrase down and complete the verification."))732        } else {733            f.append(ShieldFinding(id: "vault.phrase.verified", title: "Recovery phrase verified",734                                   detail: "The recovery phrase was confirmed word for word.", severity: .good))735        }736        if let last = input.lastBackup {737            let days = Int(min(max(0, input.now.timeIntervalSince(last)) / 86_400, 1e9))738            if days > backupFreshnessDays {739                f.append(ShieldFinding(id: "vault.backup.old", title: "Encrypted backup is old",740                                       detail: "The last encrypted backup was made \(days) days ago.", severity: .warning,741                                       recommendation: "Make a new encrypted backup."))742            } else {743                f.append(ShieldFinding(id: "vault.backup.recent", title: "Encrypted backup available",744                                       detail: days == 0 ? "An encrypted backup was made today." : "The last encrypted backup was made \(days) day(s) ago.",745                                       severity: .good))746            }747            if input.lastBackupSigned == false {748                f.append(ShieldFinding(id: "vault.backup.unsigned", title: "Last backup is not signed",749                                       detail: "The backup is encrypted but carries no signature of this wallet's identity, so a replaced file would only be detected at decryption.",750                                       severity: .warning, recommendation: "Create an identity and make a signed backup."))751            }752        } else {753            f.append(ShieldFinding(id: "vault.backup.none", title: "No encrypted backup",754                                   detail: "No encrypted backup of the vault was recorded. The recovery phrase restores the keys, not labels, tokens or settings.",755                                   severity: .warning, recommendation: "Make an encrypted backup and keep it away from this device."))756        }757758        let algorithms = [report.recordEncryption, report.sealingBackend, report.subkeyDerivation, report.fileAuthentication]759            + (report.passwordSlot.map { [$0.construction] } ?? [])760        return VaultSecurity(level: .from(f), findings: sorted(f), algorithms: algorithms)761    }762763    // MARK: Key exposure764765    public static func bitcoinKeyExposure(_ input: KeyExposure.BitcoinInput) -> BitcoinKeyExposure {766        let assessments = BitcoinPrivacyAnalysis.publicKeyExposure(utxos: input.utxos, activity: input.activity)767        let spentScripts = Set(input.activity.filter { $0.kind == .spent }.map(\.scriptPubKey))768        var totals = BitcoinExposureTotals()769        var utxos = [BitcoinKeyExposure.UTXO]()770        for u in input.utxos {771            let a = assessments[u.outPoint] ?? BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: u.scriptPubKey, hasSpend: spentScripts.contains(u.scriptPubKey))772            let address = u.address ?? (try? BitcoinAddress(scriptPubKey: u.scriptPubKey, network: input.network))?.string773            utxos.append(.init(outPoint: u.outPoint, address: address, value: u.value, confirmations: u.confirmations, exposure: a.exposure,774                               scriptType: a.scriptType, explanation: a.explanation))775            switch a.exposure {776            case .hashedUnrevealed: totals.hashedUnrevealed = add(totals.hashedUnrevealed, u.value)777            case .revealedBySpend: totals.revealedBySpend = add(totals.revealedBySpend, u.value)778            case .revealedByScript: totals.revealedByScript = add(totals.revealedByScript, u.value)779            case .undetermined: totals.undetermined = add(totals.undetermined, u.value)780            }781        }782        utxos.sort { $0.id < $1.id }783784        let reuse = Dictionary(uniqueKeysWithValues: BitcoinPrivacyAnalysis.addressReuse(activity: input.activity).map { ($0.scriptPubKey, $0) })785        var scripts = Set(input.activity.map(\.scriptPubKey))786        for u in input.utxos { scripts.insert(u.scriptPubKey) }787        var fundingCounts = [Bytes: Set<String>]()788        for a in input.activity where a.kind == .funded { fundingCounts[a.scriptPubKey, default: []].insert(a.txid) }789        var addresses = [BitcoinKeyExposure.Address]()790        for script in scripts {791            let assessment = BitcoinPrivacyAnalysis.publicKeyExposure(scriptPubKey: script, hasSpend: spentScripts.contains(script))792            let own = input.utxos.filter { $0.scriptPubKey == script }793            let finding = reuse[script]794            addresses.append(.init(address: (try? BitcoinAddress(scriptPubKey: script, network: input.network))?.string, scriptPubKey: script,795                                   scriptType: assessment.scriptType, exposure: assessment.exposure,796                                   balance: own.reduce(0) { add($0, $1.value) }, utxoCount: own.count,797                                   fundingTransactionCount: finding?.fundingTransactionCount ?? fundingCounts[script]?.count ?? 0,798                                   isReused: finding != nil, fundedAfterSpend: finding?.fundedAfterSpend ?? false))799        }800        addresses.sort { $0.id < $1.id }801        let reused = addresses.filter(\.isReused)802803        let inUse = BitcoinScriptType.allCases.filter { t in utxos.contains { $0.scriptType == t } }804        let vulnerable = inUse.filter { [.p2pk, .multisig, .p2tr].contains($0) }805        let exposedCount = utxos.filter { $0.exposure == .revealedBySpend || $0.exposure == .revealedByScript }.count806        var share: Int?807        if totals.total > 0 {808            let (product, overflow) = totals.hashedUnrevealed.multipliedReportingOverflow(by: 10_000)809            share = overflow ? Int(totals.hashedUnrevealed / (totals.total / 10_000 + 1)) : Int(product / totals.total)810        }811812        var f = [ShieldFinding]()813        if input.utxos.isEmpty {814            f.append(ShieldFinding(id: "btc.exposure.empty", title: "No bitcoin held",815                                   detail: "The wallet holds no unspent output on \(input.network.displayName), so no key guards any value.", severity: .info))816        } else if exposedCount == 0 {817            f.append(ShieldFinding(id: "btc.exposure.none", title: "Bitcoin keys still hidden",818                                   detail: "Every output sits on an address that was never spent from: only hashes of the public keys are on chain.",819                                   severity: .good))820        } else {821            f.append(ShieldFinding(id: "btc.exposure.revealed", title: "Bitcoin behind published keys",822                                   detail: "\(exposedCount) output(s) holding \(totals.revealed) sat sit on addresses whose public key is already on chain.",823                                   severity: .warning, recommendation: "Sweep them to fresh addresses of this wallet: the key is hidden again until the next spend."))824        }825        if !reused.isEmpty {826            f.append(ShieldFinding(id: "btc.reuse", title: "Address reuse",827                                   detail: "\(reused.count) address(es) received more than one payment. Reuse links payments together and, after a spend, leaves new coins behind a published key.",828                                   severity: .warning, recommendation: "Give a new address to each payer."))829        }830        if !vulnerable.isEmpty {831            f.append(ShieldFinding(id: "btc.script.revealing", title: "Outputs that publish their key",832                                   detail: "Script types in use that write the public key in the output itself: \(vulnerable.map(\.rawValue).joined(separator: ", ")).",833                                   severity: .warning, recommendation: "Move these coins to native SegWit (P2WPKH) addresses, which only publish a hash."))834        }835        if totals.undetermined > 0 {836            f.append(ShieldFinding(id: "btc.exposure.undetermined", title: "Outputs that cannot be assessed",837                                   detail: "\(totals.undetermined) sat sit on scripts whose exposure cannot be determined.", severity: .info))838        }839        let advice = [840            "For long-term storage, keep coins on addresses that have never been spent from: only a hash of the public key is on chain.",841            "Spend an address completely: after a spend, anything left or received later on that address is behind a published key.",842            "A hashed address protects coins at rest only. While a spending transaction waits for confirmation its public key is visible.",843            "Never reuse an address; QYVORA hands out a new one for every payment.",844        ]845        return BitcoinKeyExposure(network: input.network, utxos: utxos, addresses: addresses, totals: totals, reusedAddresses: reused,846                                  scriptTypesInUse: inUse, vulnerableScripts: vulnerable, hashedUnrevealedShareBasisPoints: share,847                                  exposedUTXOCount: exposedCount, findings: sorted(f), longTermStorageAdvice: advice)848    }849850    public static func ethereumKeyExposure(_ input: KeyExposure.EthereumInput) -> EthereumKeyExposure {851        var f = [ShieldFinding]()852        let recoverable = input.outgoingTransactionCount.map { $0 >= 1 }853        switch input.outgoingTransactionCount {854        case .none:855            f.append(ShieldFinding(id: "eth.exposure.unknown", title: "Ethereum key exposure not measured",856                                   detail: "The number of transactions sent by the account is not known yet.", severity: .info,857                                   recommendation: "Synchronize the Ethereum account."))858        case .some(0):859            f.append(ShieldFinding(id: "eth.exposure.none", title: "Ethereum key still hidden",860                                   detail: "The account has never sent a transaction: only the hash of its public key (the address) is public.",861                                   severity: .good))862        case .some(let n):863            f.append(ShieldFinding(id: "eth.exposure.revealed", title: "Ethereum public key is public",864                                   detail: "The account sent \(n) transaction(s). Its public key can be recovered from any of their signatures, and an account address cannot be changed.",865                                   severity: .warning, recommendation: "For long-term holdings, use an account that has never sent a transaction."))866        }867        if let approvals = input.openApprovals {868            if approvals.isEmpty {869                f.append(ShieldFinding(id: "eth.approvals.none", title: "No open token approval",870                                       detail: "No spender contract found in the account's history can move its tokens.", severity: .good))871            } else {872                let unlimited = approvals.filter(\.isUnlimited).count873                f.append(ShieldFinding(id: "eth.approvals.open", title: "Open token approvals",874                                       detail: "\(approvals.count) spender contract(s) can move tokens of this account" + (unlimited > 0 ? ", \(unlimited) of them without limit." : "."),875                                       severity: unlimited > 0 ? .critical : .warning,876                                       recommendation: "Revoke the approvals you no longer need."))877            }878        } else {879            f.append(ShieldFinding(id: "eth.approvals.unknown", title: "Token approvals not measured",880                                   detail: "Approvals could not be looked up (no indexer configured, or not synchronized).", severity: .info))881        }882        return EthereumKeyExposure(network: input.network, address: input.address, accountType: .externallyOwned,883                                   outgoingTransactionCount: input.outgoingTransactionCount, publicKeyRecoverable: recoverable,884                                   openApprovals: input.openApprovals,885                                   compatibilityNotes: input.capabilities.filter { $0.status != .available || $0.id == "eth.eoa" },886                                   findings: sorted(f))887    }888889    /// `hasBitcoinAccount`: pass false for a wallet without Bitcoin account, so that the missing `bitcoin` input is not890    /// read as "not measured".891    public static func keyExposure(bitcoin: KeyExposure.BitcoinInput?, ethereum: KeyExposure.EthereumInput?,892                                   hasBitcoinAccount: Bool = true, accounts: [AccountKeyExposure.Input] = [],893                                   otherCoins: [KeyExposure.BitcoinInput] = [], unmeasuredCoins: [String] = []) -> KeyExposure {894        let b = bitcoin.map(bitcoinKeyExposure)895        let e = ethereum.map(ethereumKeyExposure)896        let others = accounts.map(accountKeyExposure)897        let coins = otherCoins.map(coinKeyExposure)898        var coinFindings = coins.flatMap(\.findings)899        for name in unmeasuredCoins {900            coinFindings.append(ShieldFinding(id: "utxo.exposure.unmeasured.\(name.lowercased().replacingOccurrences(of: " ", with: "-"))",901                                              title: "\(name) key exposure not measured", detail: "\(name) was not synchronized, so nothing is known about its keys.",902                                              severity: .info, recommendation: "Synchronize \(name)."))903        }904        let all = (b?.findings ?? []) + (e?.findings ?? []) + others.flatMap(\.findings) + coinFindings905        let bitcoinUnmeasured = b == nil && hasBitcoinAccount906        let ethereumUnmeasured = e.map { $0.outgoingTransactionCount == nil || $0.openApprovals == nil } ?? false907        let unmeasured = bitcoinUnmeasured || ethereumUnmeasured || others.contains { !$0.unmeasuredNetworks.isEmpty } || !unmeasuredCoins.isEmpty908        var result = KeyExposure(bitcoin: b, ethereum: e, level: .from(all, fullyMeasured: !unmeasured), isPartlyUnmeasured: unmeasured,909                                 findings: sorted(all))910        result.accounts = others911        result.otherCoins = coins912        return result913    }914915    /// Another UTXO coin, analysed with Bitcoin's rules; the findings name the coin and carry its ticker in their916    /// identifiers ("ltc.exposure.none", "doge.reuse"…).917    public static func coinKeyExposure(_ input: KeyExposure.BitcoinInput) -> BitcoinKeyExposure {918        let r = bitcoinKeyExposure(input)919        guard input.network.coin != .bitcoin else { return r }920        let name = input.network.mainCounterpart.displayName, prefix = input.network.ticker.lowercased()921        func rename(_ text: String) -> String {922            text.replacingOccurrences(of: "No bitcoin held", with: "No \(name) held").replacingOccurrences(of: "Bitcoin", with: name)923                .replacingOccurrences(of: "bitcoin", with: name).replacingOccurrences(of: " sat ", with: " \(input.network.baseUnitName)s ")924        }925        let findings = r.findings.map { f in926            // the advice to move to native SegWit only holds where SegWit exists927            let advice = f.id == "btc.script.revealing" && !input.network.supportsSegWit ? "Move these coins to ordinary addresses of this wallet, which only publish a hash." : f.recommendation928            return ShieldFinding(id: prefix + String(f.id.dropFirst(3)), title: rename(f.title), detail: rename(f.detail), severity: f.severity, recommendation: advice)929        }930        return BitcoinKeyExposure(network: r.network, utxos: r.utxos, addresses: r.addresses, totals: r.totals, reusedAddresses: r.reusedAddresses,931                                  scriptTypesInUse: r.scriptTypesInUse, vulnerableScripts: r.vulnerableScripts,932                                  hashedUnrevealedShareBasisPoints: r.hashedUnrevealedShareBasisPoints, exposedUTXOCount: r.exposedUTXOCount,933                                  findings: findings, longTermStorageAdvice: r.longTermStorageAdvice)934    }935936    /// One account family across its networks. See `AccountKeyExposure` for the rule of each family.937    public static func accountKeyExposure(_ input: AccountKeyExposure.Input) -> AccountKeyExposure {938        var f = [ShieldFinding]()939        let unmeasured = input.networks.filter { $0.publicKeyExposed == nil }.map(\.name)940        let exposedOn = input.networks.filter { $0.publicKeyExposed == true }941        var exposed: Bool?942        switch input.family {943        case .solana:944            // nothing to measure: the address is the key945            exposed = true946            let onChain = !exposedOn.isEmpty947            f.append(ShieldFinding(id: "sol.exposure.address-is-key", title: "Solana public key is the address",948                                   detail: "A Solana address is the Ed25519 public key of the account itself. It is public from the moment the address is shared or funded"949                                       + (onChain ? ", and this account is on chain (" + exposedOn.map(\.name).joined(separator: ", ") + ")." : ".")950                                       + " Ed25519 does not resist a large quantum computer, and a Solana account cannot hide its key behind a hash.",951                                   severity: onChain ? .warning : .info,952                                   recommendation: onChain ? "Nothing in a wallet can hide a Solana key. Keep on Solana only what you need there." : nil))953        case .evm, .tron:954            let prefix = input.family == .evm ? "evm" : "trx"955            let label = input.family == .evm ? "EVM" : "TRON"956            if !exposedOn.isEmpty {957                exposed = true958                let shared = input.family == .evm ? " The same key controls this address on every EVM network: it is public for all of them." : ""959                f.append(ShieldFinding(id: "\(prefix).exposure.revealed", title: "\(label) public key is public",960                                       detail: "The account has sent transactions on " + exposedOn.map { "\($0.name) (\($0.evidence))" }.joined(separator: ", ")961                                           + ". Its public key can be recovered from any of their signatures, and an account address cannot be changed." + shared,962                                       severity: .warning, recommendation: "For long-term holdings, use an account that has never sent a transaction."))963            } else if unmeasured.isEmpty, !input.networks.isEmpty {964                exposed = false965                f.append(ShieldFinding(id: "\(prefix).exposure.none", title: "\(label) key still hidden",966                                       detail: "No outgoing transaction was found on " + input.networks.map(\.name).joined(separator: ", ")967                                           + ": only the hash of the public key (the address) is public."968                                           + (input.family == .evm ? " One transaction on any EVM network, enabled here or not, publishes the key for all of them." : ""),969                                       severity: .good))970            } else {971                exposed = nil972            }973            if !unmeasured.isEmpty {974                f.append(ShieldFinding(id: "\(prefix).exposure.unmeasured", title: "\(label) key exposure not measured everywhere",975                                       detail: "Not measured on " + unmeasured.joined(separator: ", ")976                                           + (exposedOn.isEmpty ? ": the key may be public there." : "."),977                                       severity: .info, recommendation: "Synchronize these networks."))978            }979        }980        // EVM: the approvals of the networks other than the primary one (which has its finding in the Ethereum part)981        if input.family == .evm {982            for entry in input.approvals where !entry.isPrimary {983                let name = entry.network.displayName, key = entry.network.rawValue.lowercased()984                guard let approvals = entry.approvals else {985                    f.append(ShieldFinding(id: "evm.approvals.unknown.\(key)", title: "Token approvals not measured on \(name)",986                                           detail: "Approvals could not be looked up on \(name) (not synchronized, or its history source did not answer).", severity: .info,987                                           recommendation: "Synchronize \(name)."))988                    continue989                }990                guard !approvals.isEmpty else { continue }991                let unlimited = approvals.filter(\.isUnlimited).count992                f.append(ShieldFinding(id: "evm.approvals.open.\(key)", title: "Open token approvals on \(name)",993                                       detail: "\(approvals.count) spender contract(s) can move tokens of this account on \(name)" + (unlimited > 0 ? ", \(unlimited) of them without limit." : "."),994                                       severity: unlimited > 0 ? .critical : .warning, recommendation: "Revoke the approvals you no longer need."))995            }996        }997        var result = AccountKeyExposure(family: input.family, address: input.address, networks: input.networks, publicKeyExposed: exposed,998                                        unmeasuredNetworks: input.family == .solana ? [] : unmeasured, findings: sorted(f))999        result.approvals = input.family == .evm ? input.approvals : []1000        return result1001    }10021003    // MARK: Network resistance10041005    public static func networkResistance(_ inputs: [NetworkResistance.Input]) -> NetworkResistance {1006        var chains = [NetworkResistance.ChainStatus]()1007        var f = [ShieldFinding]()1008        var seen = Set<NetworkResistance.Chain>()1009        for input in inputs {1010            var schemes: [String]1011            let statement: String1012            // `kind` never returns another case than these four1013            switch input.chain.kind {1014            case .bitcoin, .litecoin, .dogecoin, .bitcoinCash:1015                schemes = input.signatureSchemes ?? ["secp256k1 ECDSA", "secp256k1 Schnorr (BIP-340)"]1016                statement = schemes.count > 11017                    ? "\(input.networkName) validates secp256k1 ECDSA and Schnorr signatures only. Neither resists a large quantum computer, and no post-quantum signature or output type is deployed on the network today."1018                    : "\(input.networkName) validates \(schemes.first ?? "secp256k1 ECDSA") signatures only, which do not resist a large quantum computer. No post-quantum signature or output type is deployed on the network today."1019            case .ethereum, .base, .arbitrum, .optimism, .polygon, .bsc, .avalanche:1020                schemes = input.signatureSchemes ?? ["secp256k1 ECDSA"]1021                statement = "\(input.networkName) accounts are controlled by secp256k1 ECDSA signatures, which do not resist a large quantum computer. No post-quantum transaction validation is deployed on the network today."1022            case .solana:1023                schemes = input.signatureSchemes ?? ["Ed25519"]1024                statement = "\(input.networkName) accounts are controlled by Ed25519 signatures, and an address is the public key itself. Ed25519 does not resist a large quantum computer. No post-quantum transaction validation is deployed on the network today."1025            case .tron:1026                schemes = input.signatureSchemes ?? ["secp256k1 ECDSA"]1027                statement = "\(input.networkName) accounts are controlled by secp256k1 ECDSA signatures, which do not resist a large quantum computer. No post-quantum transaction validation is deployed on the network today."1028            }1029            // the first network of a kind keeps the identifier of QYVORA 1.0; the others add their name1030            let slug = input.networkName.lowercased().map { $0.isLetter || $0.isNumber ? $0 : "-" }1031            // (identifiers are by kind, as before the chains had their own case: they do not change with this version)1032            let kind = input.chain.kind1033            let key = seen.insert(kind).inserted ? kind.rawValue : "\(kind.rawValue).\(String(slug))"1034            let resistant = input.offersQuantumResistance1035            var status = NetworkResistance.ChainStatus(chain: input.chain, networkName: input.networkName, signatureSchemes: schemes,1036                                                       statement: resistant ? statement + " The migration registry reports a quantum-resistant mechanism as available." : statement,1037                                                       offersQuantumResistance: resistant,1038                                                       awaitingProtocol: input.capabilities.filter { $0.status == .awaitingProtocol })1039            status.networkID = input.networkID1040            status.walletSignatureScheme = input.walletSignatureScheme1041            chains.append(status)1042            f.append(ShieldFinding(id: "network.\(key).\(resistant ? "resistant" : "not-resistant")",1043                                   title: resistant ? "\(input.networkName): quantum-resistant mechanism available" : "\(input.networkName) is not quantum-resistant",1044                                   detail: statement, severity: .info,1045                                   recommendation: resistant ? nil : "Nothing in a wallet can change this: it needs a protocol upgrade of the network. QYVORA keeps its migration steps disabled until then."))1046        }1047        return NetworkResistance(chains: chains, findings: f)1048    }10491050    // MARK: Helpers10511052    private static func add(_ a: UInt64, _ b: UInt64) -> UInt64 {1053        let (s, o) = a.addingReportingOverflow(b)1054        return o ? UInt64.max : s1055    }10561057    /// Most severe first, stable otherwise.1058    private static func sorted(_ findings: [ShieldFinding]) -> [ShieldFinding] {1059        findings.enumerated().sorted { a, b in1060            a.element.severity != b.element.severity ? a.element.severity > b.element.severity : a.offset < b.offset1061        }.map(\.element)1062    }1063}1064
Files main
Menu

Theme