Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Security/ColdModeView.swift8// Module : Security9// 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 QyvoraCore43import QyvoraWallet44import QyvoraUI4546/// Cold mode: the two-device setup, the switch that stops every network request, the single offline signing flow47/// (every chain) and the watch-only package for the online device. Everything on this screen works without network.48struct ColdModeView: View {49 @Environment(WalletStore.self) private var store50 @State private var requestCount: Int?51 @State private var error: String?52 @State private var busy = false53 @State private var failures = 05455 private var snapshot: WalletSnapshot? { store.snapshot }56 private var isOn: Bool { snapshot?.profile.coldMode == true }57 private var hasWallet: Bool { snapshot?.hasWallet == true }58 private var isWatchOnly: Bool { snapshot?.profile.kind == .watchOnly }5960 /// The chains enabled in this wallet (main-network descriptors, registry order).61 private var enabledChains: [ChainDescriptor] {62 let enabled = snapshot?.profile.enabledChains ?? ChainRegistry.defaultEnabled63 return ChainRegistry.mainChains.filter { enabled.contains($0.id) }64 }6566 var body: some View {67 SecurityScroll {68 VStack(alignment: .leading, spacing: QSpace.s) {69 Explanation("Two devices share one wallet. This one keeps the keys and stays offline. A second device, set up as watch-only, is online: it shows balances and prepares transactions but cannot sign.")70 Explanation("Unsigned transactions travel to this device as QR codes, are reviewed and signed here, and travel back as QR codes to be broadcast.")71 }72 SecInlineError(error)73 if snapshot == nil {74 SecSkeletonSection(rows: 2)75 } else {76 switchSection.id("switch")77 signSection.id("sign")78 supportSection.id("support")79 setupSection.id("setup")80 }81 }82 .navigationTitle("Cold mode")83 .navigationBarTitleDisplayMode(.inline)84 .task(id: isOn) { requestCount = await store.service?.networkRequestCount() }85 .qHaptic(.failed, trigger: failures)86 }8788 private var switchSection: some View {89 QListSection(footnote: "While cold mode is on, QYVORA sends no network request at all: every request is refused inside the app before it leaves the device. No balance, price or history is fetched; creating, importing, showing addresses and signing keep working. The guarantee covers this app only: also turn on Airplane Mode, so that the device itself stays off every network.") {90 SecToggleRow(title: "Cold mode", subtitle: isOn ? "On: no network request" : "Off", systemImage: "snowflake",91 isOn: Binding(get: { isOn }, set: { setColdMode($0) }))92 .disabled(busy)93 SecFactRow(label: "Network requests since launch", value: requestCount.map { "\($0)" } ?? "Not read")94 }95 }9697 private var signSection: some View {98 QListSection("Sign offline", footnote: isWatchOnly99 ? "This is a watch-only wallet: it can review but not sign. Signing happens on the device that holds the keys."100 : "One flow for every chain: scan or paste, read what the bytes do, authenticate, sign. Signing needs the vault unlocked and a fresh authentication. It uses no network.") {101 SecLinkRow(title: "Sign a transaction", subtitle: "Scan, review the decoded transaction, sign", systemImage: "signature", value: SecurityRoute.coldSign)102 .disabled(!hasWallet)103 }104 }105106 /// Which chains can be cold-signed today: the registry's capability for each enabled chain, then the limits the107 /// service states for an unaudited build.108 private var supportSection: some View {109 VStack(alignment: .leading, spacing: QSpace.m) {110 QListSection("Cold signing today", footnote: "Listed: the chains enabled in this wallet. A transaction of another chain is refused until that chain is enabled here.") {111 ForEach(enabledChains) { chain in112 let supported = chain.capabilities.coldSigning113 HStack(spacing: QSpace.m) {114 ChainGlyph(chain.qNetwork, size: .small)115 Text(chain.displayName).font(QFont.headline).foregroundStyle(QColor.textPrimary)116 Spacer(minLength: QSpace.s)117 StatusDot(supported ? .positive : .neutral, label: supported ? Self.format(chain) : "Not available yet")118 }119 .padding(.vertical, QSpace.m)120 .accessibilityElement(children: .combine)121 .accessibilityLabel("\(chain.displayName): \(supported ? "cold signing with \(Self.format(chain))" : "cold signing not available yet")")122 }123 }124 QListSection("Limits") {125 if enabledChains.contains(where: { !$0.capabilities.coldSigning }) {126 SecTextRow(text: "Litecoin, Dogecoin and Bitcoin Cash cannot be cold-signed yet: their payments are signed on the device that holds the keys while it is online.", systemImage: "minus.circle")127 }128 if enabledChains.contains(where: { $0.family == .solana }) {129 SecTextRow(text: "A Solana transaction is valid for about a minute after it was prepared (its blockhash expires): prepare, sign and broadcast without delay.", systemImage: "clock")130 }131 if !MainnetPolicy.auditCompleted, enabledChains.contains(where: { $0.family == .solana || $0.family == .tron }) {132 SecTextRow(text: "This unaudited build does not sign Solana or TRON transactions on an offline device. Their bytes do not name a network and the account is the same key on every one: offline, nothing can check that a transaction labelled as a test network is not valid on the main network, where it would pass the mainnet switch and the limits. A device that is online asks the main-network nodes before it signs. On a main network their limits also need fresh prices, which an offline device does not have.", systemImage: "exclamationmark.triangle", tone: .warning)133 }134 SecTextRow(text: "Whatever the chain, a transaction that cannot be decoded entirely is signed only after an explicit extra confirmation, and never on a main network while the build is unaudited.", systemImage: "eye.slash")135 SecTextRow(text: "Figures that depend on chain state cannot be verified offline, and the review says so: the L1 data fee of Base and OP Mainnet, the rent of a new Solana token account, the energy and bandwidth a TRON transaction burns.", systemImage: "wifi.slash")136 }137 }138 }139140 private var setupSection: some View {141 QListSection("Set up the online device", footnote: "The package holds the Bitcoin descriptors, the account keys of the other coins and the EVM, Solana and TRON addresses of this wallet, with the list of enabled chains. It can watch, never spend.") {142 SecLinkRow(title: "Export watch-only package", subtitle: "Public keys and addresses for the online device", systemImage: "eye", value: SecurityRoute.watchOnlyExport)143 .disabled(!hasWallet)144 }145 }146147 static func format(_ chain: ChainDescriptor) -> String {148 switch chain.family {149 case .utxo: return "PSBT"150 case .evm: return "EIP-1559 payload"151 case .solana, .tron: return "QYVORA envelope"152 }153 }154155 private func setColdMode(_ enabled: Bool) {156 guard !busy else { return }157 busy = true158 error = nil159 Task {160 do {161 try await store.run { try await $0.setColdMode(enabled) }162 await store.refresh()163 // Back online: bring balances up to date.164 if !enabled { Task { await store.synchronize() } }165 } catch {166 self.error = SecurityError.text(error)167 failures += 1168 }169 busy = false170 }171 }172}173174/// Input of the offline signing flow: scanned frames or pasted text.175struct PayloadInputCard: View {176 let title: String177 let placeholder: String178 @Binding var text: String179 let onScan: () -> Void180181 var body: some View {182 VStack(alignment: .leading, spacing: QSpace.s) {183 QEyebrow(title).padding(.leading, 2)184 TextEditor(text: $text)185 .font(QFont.mono)186 .textInputAutocapitalization(.never)187 .autocorrectionDisabled()188 .frame(minHeight: 110)189 .scrollContentBackground(.hidden)190 .padding(QSpace.s)191 .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous))192 .overlay(RoundedRectangle(cornerRadius: QMetric.radius, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))193 .overlay(alignment: .topLeading) {194 if text.isEmpty {195 Text(placeholder).font(QFont.mono).foregroundStyle(QColor.textTertiary).padding(QSpace.l).allowsHitTesting(false)196 .accessibilityHidden(true)197 }198 }199 .accessibilityLabel(title)200 HStack(spacing: QSpace.m) {201 Button(action: onScan) { Label("Scan QR codes", systemImage: "qrcode.viewfinder").frame(maxWidth: .infinity) }202 .buttonStyle(.qSecondary)203 PasteButton(payloadType: String.self) { strings in204 if let first = strings.first { text = first }205 }206 .labelStyle(.iconOnly)207 .tint(QColor.violet)208 .accessibilityLabel("Paste")209 }210 }211 }212}213