SPB Git

Repository Public

CryptoInfoView.swift 14.9 KB 342 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/CryptoInfoView.swift8// Module           : Sources9// 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 SwiftUI42import QyvoraCrypto43import QyvoraWallet44import QyvoraUI4546/// Presentation helpers for the engine catalogue.47extension QyvoraEngine.Algorithm {48    /// True when QYVORA uses the algorithm in a product feature (the catalogue says "Available" otherwise).49    var isInUse: Bool { !use.hasPrefix("Available") }5051    var isPostQuantumStandard: Bool { ["FIPS 203", "FIPS 204", "FIPS 205"].contains(standard) }5253    /// What `outputSize` measures for this kind of algorithm.54    var outputLabel: String {55        switch kind {56        case .keyEncapsulation: return "Ciphertext"57        case .signature, .curve: return "Signature"58        case .hash: return "Digest"59        case .mac, .aead: return "Output"60        }61    }6263    var privateKeyLabel: String { kind == .aead ? "Key" : "Private key" }64}6566extension QyvoraEngine.Kind {67    var systemImage: String {68        switch self {69        case .keyEncapsulation: return "key.horizontal"70        case .signature: return "signature"71        case .hash: return "number"72        case .mac: return "lock.rectangle"73        case .aead: return "lock.doc"74        case .curve: return "point.topleft.down.to.point.bottomright.curvepath"75        }76    }77}7879struct AlgorithmRoute: Hashable {80    let name: String81}8283/// The signature scheme each chain of the wallet validates, from the chain registry, and whether the engine catalogue84/// has an entry of that name. Nothing is added to the catalogue here.85private struct SecSignatureScheme: Identifiable {86    let name: String87    let chains: [ChainDescriptor]88    var id: String { name }89    var catalogueEntry: QyvoraEngine.Algorithm? { QyvoraEngine.algorithms.first { $0.name == name } }9091    static var all: [SecSignatureScheme] {92        var order = [String]()93        var byName = [String: [ChainDescriptor]]()94        for chain in ChainRegistry.mainChains {95            if byName[chain.signatureScheme] == nil { order.append(chain.signatureScheme) }96            byName[chain.signatureScheme, default: []].append(chain)97        }98        return order.map { SecSignatureScheme(name: $0, chains: byName[$0] ?? []) }99    }100}101102/// The engine catalogue grouped by kind, the self-test, the audit statement, what post-quantum cryptography covers and103/// the signature scheme of every chain.104struct CryptoInfoView: View {105    @Environment(AppModel.self) private var model106    @Namespace private var zoom107    @State private var runFeedback = 0108109    private var schemes: [SecSignatureScheme] { SecSignatureScheme.all }110111    var body: some View {112        ScrollView {113            VStack(alignment: .leading, spacing: QSpace.xl) {114                selfTestSection115                QListSection("Audit status",116                             footnote: "The engine is written from scratch in Swift, without external dependency. Passing test vectors shows that the implementation computes the right values; it is not a security certification.",117                             separatorInset: QMetric.padding) {118                    SecTextRow(text: QyvoraEngine.auditStatus, systemImage: "exclamationmark.triangle", tone: .warning)119                }120                .id("audit")121                scopeSection122                chainSection123                ForEach(QyvoraEngine.Kind.allCases, id: \.self) { kind in124                    // the engine's own implementations; what comes from the system is listed apart, below125                    let algorithms = QyvoraEngine.engineAlgorithms.filter { $0.kind == kind }126                    if !algorithms.isEmpty {127                        QListSection(kind.rawValue, separatorInset: QMetric.padding) {128                            ForEach(algorithms) { algorithm in129                                NavigationLink(value: AlgorithmRoute(name: algorithm.name)) {130                                    AlgorithmRow(algorithm: algorithm)131                                }132                                .buttonStyle(.qRow)133                                .qMatchedSource(id: algorithm.name, in: zoom)134                            }135                        }136                        .id("kind-\(kind.rawValue)")137                    }138                }139                let system = QyvoraEngine.algorithms.filter { !$0.isFromScratch }140                if !system.isEmpty {141                    QListSection("System primitives", footnote: "Provided by the operating system (CryptoKit), not written from scratch in this engine: its test vectors and its self-test do not cover them.",142                                 separatorInset: QMetric.padding) {143                        ForEach(system) { algorithm in144                            NavigationLink(value: AlgorithmRoute(name: algorithm.name)) {145                                AlgorithmRow(algorithm: algorithm)146                            }147                            .buttonStyle(.qRow)148                            .qMatchedSource(id: algorithm.name, in: zoom)149                        }150                    }151                    .id("kind-system")152                }153            }154            .padding(.horizontal, QMetric.screenPadding)155            .padding(.top, QSpace.m)156            .padding(.bottom, QSpace.xxl)157            .frame(maxWidth: 640, alignment: .leading)158            .frame(maxWidth: .infinity)159        }160        .debugScroll()161        .qScreen()162        .navigationTitle("Cryptography")163        .navigationBarTitleDisplayMode(.inline)164        .navigationDestination(for: AlgorithmRoute.self) { route in165            AlgorithmDetailView(name: route.name)166                .qMatchedDestination(id: route.name, in: zoom)167        }168        .sensoryFeedback(trigger: runFeedback) { _, _ in169            model.selfTest?.passed == true ? .success : .error170        }171    }172173    // MARK: Self-test174175    var selfTestSection: some View {176        QListSection("Self-test",177                     footnote: "Known answers are recomputed for SHA-256, SHA3-256, secp256k1, ML-KEM-768, ML-DSA-44, SLH-DSA-SHAKE-128f and AES-256-GCM. The test also runs at every launch; a wrong result blocks the application.",178                     separatorInset: QMetric.padding) {179            if let record = model.selfTest {180                HStack {181                    QBadge(record.passed ? "Passed" : "Failed", systemImage: record.passed ? "checkmark.seal" : "xmark.octagon",182                           tone: record.passed ? .positive : .negative)183                    Spacer(minLength: 0)184                }185                .padding(.vertical, QSpace.m)186                SecFactRow(label: "Last run", value: record.date.formatted(date: .abbreviated, time: .standard))187                SecFactRow(label: "Duration", value: Self.durationText(record.duration))188            } else {189                HStack {190                    QBadge("Not run in this session", systemImage: "circle.dashed", tone: .neutral)191                    Spacer(minLength: 0)192                }193                .padding(.vertical, QSpace.m)194            }195            SecFactRow(label: "Engine version", value: QyvoraEngine.version)196            Button {197                Task {198                    await model.runSelfTest()199                    runFeedback += 1200                }201            } label: {202                HStack(spacing: QSpace.s) {203                    if model.selfTestRunning {204                        ProgressView().controlSize(.small)205                        Text("Running")206                    } else {207                        Image(systemName: "arrow.clockwise")208                        Text("Run again")209                    }210                }211                .font(.body.weight(.medium))212                .foregroundStyle(QColor.violet)213                .frame(minHeight: QMetric.minTap)214            }215            .buttonStyle(.qRow)216            .disabled(model.selfTestRunning)217        }218        .id("self-test")219    }220221    static func durationText(_ duration: Duration) -> String {222        let seconds = Double(duration.components.seconds) + Double(duration.components.attoseconds) / 1e18223        return seconds >= 1 ? String(format: "%.2f s", seconds) : String(format: "%.0f ms", seconds * 1000)224    }225226    // MARK: Scope227228    var scopeSection: some View {229        QListSection("Scope", separatorInset: QMetric.padding) {230            scope("checkmark.shield", QColor.positive, "Post-quantum algorithms protect",231                  "the local vault, backups, device-to-device transfers and the wallet identity.")232            scope("xmark.shield", QColor.negative, "They do not protect",233                  "transactions on any chain. Each network requires its own signature scheme (\(schemes.map(\.name).joined(separator: ", "))), and none of them resists a large quantum computer.")234        }235        .id("scope")236    }237238    func scope(_ systemImage: String, _ tint: Color, _ title: String, _ text: String) -> some View {239        HStack(alignment: .firstTextBaseline, spacing: QSpace.m) {240            Image(systemName: systemImage).foregroundStyle(tint).accessibilityHidden(true)241            Text("\(Text(title).fontWeight(.semibold)) \(text)")242                .font(QFont.callout)243                .foregroundStyle(QColor.textPrimary)244                .fixedSize(horizontal: false, vertical: true)245        }246        .frame(maxWidth: .infinity, alignment: .leading)247        .padding(.vertical, QSpace.m)248        .accessibilityElement(children: .combine)249    }250251    // MARK: Chains252253    /// What every chain validates, from the registry. A scheme is linked to its catalogue entry when the catalogue has254    /// one of that name; otherwise the row says that the catalogue has none.255    var chainSection: some View {256        QListSection("Transaction signatures by chain",257                     footnote: "From the chain registry of the wallet service. Transactions are signed with what each network validates; no post-quantum signature is deployed on any of them.",258                     separatorInset: QMetric.padding) {259            ForEach(schemes) { scheme in260                if let entry = scheme.catalogueEntry {261                    NavigationLink(value: AlgorithmRoute(name: entry.name)) { schemeRow(scheme, inCatalogue: true) }262                        .buttonStyle(.qRow)263                } else {264                    schemeRow(scheme, inCatalogue: false)265                }266            }267        }268        .id("chains")269    }270271    private func schemeRow(_ scheme: SecSignatureScheme, inCatalogue: Bool) -> some View {272        VStack(alignment: .leading, spacing: QSpace.s) {273            HStack(alignment: .firstTextBaseline, spacing: QSpace.s) {274                Text(scheme.name)275                    .font(Font.system(.body, design: .monospaced).weight(.medium))276                    .foregroundStyle(QColor.textPrimary)277                Spacer(minLength: QSpace.s)278                if inCatalogue {279                    Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary).accessibilityHidden(true)280                }281            }282            FlowLayout(spacing: 6) {283                ForEach(scheme.chains) { chain in284                    HStack(spacing: 5) {285                        ChainGlyph(chain.qNetwork, size: .mini)286                        Text(chain.displayName).font(QFont.caption).foregroundStyle(QColor.textSecondary)287                    }288                }289            }290            .accessibilityElement(children: .ignore)291            .accessibilityLabel("Used by \(scheme.chains.map(\.displayName).joined(separator: ", "))")292            if !inCatalogue {293                Label("The engine catalogue of this version has no entry named \(scheme.name): sizes and standard are not listed here.", systemImage: "circle.dashed")294                    .font(QFont.caption)295                    .foregroundStyle(QColor.textSecondary)296                    .fixedSize(horizontal: false, vertical: true)297            }298        }299        .frame(maxWidth: .infinity, alignment: .leading)300        .padding(.vertical, QSpace.m)301        .accessibilityElement(children: .combine)302    }303}304305struct AlgorithmRow: View {306    let algorithm: QyvoraEngine.Algorithm307308    var body: some View {309        HStack(spacing: QSpace.s) {310            VStack(alignment: .leading, spacing: 6) {311                Text(algorithm.name)312                    .font(Font.system(.body, design: .monospaced).weight(.medium))313                    .foregroundStyle(QColor.textPrimary)314                Text(algorithm.standard).font(QFont.caption).foregroundStyle(QColor.textSecondary)315                if algorithm.isInUse {316                    Text(algorithm.use).font(QFont.callout).foregroundStyle(QColor.textPrimary)317                }318                ViewThatFits(in: .horizontal) {319                    HStack(spacing: 6) { badges }320                    VStack(alignment: .leading, spacing: 6) { badges }321                }322            }323            .fixedSize(horizontal: false, vertical: true)324            Spacer(minLength: QSpace.s)325            Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary).accessibilityHidden(true)326        }327        .padding(.vertical, QSpace.m)328        .accessibilityElement(children: .combine)329    }330331    @ViewBuilder var badges: some View {332        if algorithm.isInUse {333            QBadge("Used by QYVORA", systemImage: "checkmark", tone: .accent)334        } else {335            QBadge("Available, not used yet", systemImage: "circle.dashed", tone: .neutral)336        }337        if let category = algorithm.category {338            QBadge("NIST category \(category)", systemImage: "shield", tone: .neutral)339        }340    }341}342
Files main
Menu

Theme