Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : App/Sources/Security/ShieldEthereumExposureView.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 QyvoraQuantumShield44import QyvoraWallet45import QyvoraUI4647extension ProtocolCapability.Status {48 var title: String {49 switch self {50 case .available: return "Available"51 case .planned: return "Planned"52 case .awaitingProtocol: return "Awaiting protocol"53 }54 }5556 var systemImage: String {57 switch self {58 case .available: return "checkmark.circle"59 case .planned: return "calendar"60 case .awaitingProtocol: return "lock"61 }62 }6364 var tone: QBadge.Tone {65 switch self {66 case .available: return .positive67 case .planned: return .accent68 case .awaitingProtocol: return .neutral69 }70 }71}7273/// One registry entry as the Shield shows it: title, status, and what the protocol must offer first.74struct ProtocolCapabilityRow: View {75 let capability: ProtocolCapability7677 var body: some View {78 VStack(alignment: .leading, spacing: 4) {79 Text(capability.title).font(QFont.callout.weight(.semibold)).foregroundStyle(QColor.textPrimary)80 QBadge(capability.status.title, systemImage: capability.status.systemImage, tone: capability.status.tone)81 Text(capability.detail).font(QFont.caption).foregroundStyle(QColor.textSecondary)82 if let requirement = capability.requirement {83 Text("Requires: \(requirement)").font(QFont.caption).foregroundStyle(QColor.textSecondary)84 }85 }86 .fixedSize(horizontal: false, vertical: true)87 .frame(maxWidth: .infinity, alignment: .leading)88 .padding(.vertical, QSpace.m)89 .accessibilityElement(children: .combine)90 }91}9293/// One network of an account: its glyph and name, where the answer comes from, and the answer.94struct SecShieldNetworkRow: View {95 let name: String96 let evidence: String97 let state: SecShieldState98 @Environment(\.dynamicTypeSize) private var typeSize99100 var body: some View {101 let network = SecShield.network(named: name)102 Group {103 if typeSize.isAccessibilitySize {104 VStack(alignment: .leading, spacing: 4) {105 HStack(spacing: QSpace.m) { glyph(network); names }106 state107 }108 .frame(maxWidth: .infinity, alignment: .leading)109 } else {110 HStack(spacing: QSpace.m) {111 glyph(network)112 names113 Spacer(minLength: QSpace.s)114 state115 }116 }117 }118 .padding(.vertical, QSpace.s + 2)119 .accessibilityElement(children: .combine)120 .accessibilityLabel("\(network?.spokenName ?? name): \(state.label). Evidence: \(evidence).")121 }122123 @ViewBuilder func glyph(_ network: QNetwork?) -> some View {124 if let network { ChainGlyph(network, size: .small) }125 }126127 var names: some View {128 VStack(alignment: .leading, spacing: 2) {129 Text(name).font(QFont.subheadline).foregroundStyle(QColor.textPrimary)130 Text(evidence).font(QFont.caption).foregroundStyle(QColor.textSecondary)131 }132 .fixedSize(horizontal: false, vertical: true)133 }134}135136/// The address of an account in full, with a copy control.137struct SecShieldAddressRow: View {138 let label: String139 let address: String140141 var body: some View {142 VStack(alignment: .leading, spacing: 4) {143 HStack {144 QEyebrow(label)145 Spacer(minLength: QSpace.s)146 CopyButton(address, title: "Copy \(label.lowercased())")147 }148 ChunkedAddressText(address, font: QFont.mono)149 }150 .padding(.vertical, QSpace.m)151 }152}153154/// Section 2, the EVM account — ONE account for every EVM network: the key is recoverable as soon as one outgoing155/// transaction exists on any of them. Lists the networks measured and those that were not, the open token approvals156/// where the service reads them (with revocation), and what the EVM networks would need for post-quantum validation.157struct ShieldEthereumExposureView: View {158 /// The primary EVM network: account type, nonce, approvals.159 let exposure: EthereumKeyExposure?160 /// The account across every enabled EVM network; nil when a single EVM network is enabled.161 let account: AccountKeyExposure?162 let snapshot: WalletSnapshot163 let synchronizing: Bool164 let synchronize: () -> Void165166 @Environment(WalletStore.self) private var store167 @Environment(\.secSendReviewHandoff) private var reviewHandoff168 @Environment(\.ethereumReviewHandoff) private var ethereumHandoff169 @State private var revoking: TokenApprovalExposure?170 @State private var pendingReview: EthereumSendReview?171 @State private var handoffError: String?172 @State private var showNeeds = SecShield.startsExpanded173174 var address: String? { account?.address ?? exposure?.address.checksummed ?? snapshot.profile.ethereumAddress?.checksummed }175176 /// true as soon as one network shows an outgoing transaction; false only when every network was measured and none177 /// does; nil otherwise.178 var keyExposed: Bool? {179 if account?.publicKeyExposed == true || exposure?.publicKeyRecoverable == true { return true }180 if let account { return account.publicKeyExposed }181 return exposure?.publicKeyRecoverable182 }183184 var networks: [AccountKeyExposure.Network] {185 if let account { return account.networks }186 guard let e = exposure else { return [] }187 return [.init(name: e.network.displayName, publicKeyExposed: e.publicKeyRecoverable,188 evidence: e.outgoingTransactionCount.map { "account nonce \($0)" } ?? "not synchronized")]189 }190191 var unmeasured: [String] { networks.filter { $0.publicKeyExposed == nil }.map(\.name) }192 var evmRunning: Bool { synchronizing || snapshot.chains.contains { $0.chain.family == .evm && $0.isSynchronizing } }193194 var body: some View {195 VStack(alignment: .leading, spacing: QSpace.m) {196 if let address {197 accountCard(address)198 networksCard199 ShieldFindingsCard(findings: (account?.findings ?? []) + (exposure?.findings ?? []))200 if let exposure {201 approvals(exposure).id("approvals")202 }203 // the other EVM networks that have a history source: their approvals, with the same revocation204 ForEach((account?.approvals ?? []).filter { !$0.isPrimary }) { entry in205 otherApprovals(entry).id("approvals-\(entry.id)")206 }207 if let exposure { needs(exposure) }208 } else {209 QListSection {210 header211 SecTextRow(text: "This wallet has no EVM account.")212 }213 }214 SecInlineError(handoffError)215 }216 .sheet(item: $revoking, onDismiss: {217 if let review = pendingReview {218 pendingReview = nil219 hand(review)220 }221 }) { approval in222 RevokeApprovalSheet(approval: approval, handsOff: reviewHandoff != nil || ethereumHandoff != nil) { review in223 pendingReview = review224 revoking = nil225 }226 }227 }228229 /// Gives the revocation to the wallet's review: the multi-chain one when it is installed, else the Ethereum one.230 func hand(_ review: EthereumSendReview) {231 guard let reviewHandoff else {232 ethereumHandoff?.review(review)233 return234 }235 handoffError = nil236 Task {237 do {238 let wrapped = try await store.run { await $0.review(for: review) }239 reviewHandoff.review(wrapped)240 } catch {241 if let ethereumHandoff { ethereumHandoff.review(review) } else { handoffError = SecurityError.text(error) }242 }243 }244 }245246 var header: some View {247 HStack(spacing: QSpace.m) {248 ChainGlyph(.ethereum)249 VStack(alignment: .leading, spacing: 3) {250 Text("EVM account").font(QFont.headline).foregroundStyle(QColor.textPrimary)251 .accessibilityAddTraits(.isHeader)252 Text("One address and one secp256k1 key for every EVM network").font(QFont.caption).foregroundStyle(QColor.textSecondary)253 }254 .fixedSize(horizontal: false, vertical: true)255 Spacer(minLength: 0)256 }257 .padding(.vertical, QSpace.m)258 .frame(minHeight: QMetric.rowMinHeight)259 .accessibilityElement(children: .combine)260 }261262 func accountCard(_ address: String) -> some View {263 QListSection(separatorInset: QMetric.padding) {264 header265 SecShieldAddressRow(label: "Address", address: address)266 HStack(spacing: QSpace.s) {267 Text("Public key").font(QFont.callout).foregroundStyle(QColor.textSecondary)268 Spacer(minLength: QSpace.s)269 SecShieldState(keyExposed, exposedLabel: "Recoverable from a signature on chain", hiddenLabel: "Not on chain (no transaction sent)")270 }271 .padding(.vertical, QSpace.m)272 .accessibilityElement(children: .combine)273 if let exposure {274 SecFactRow(label: "Outgoing transactions on \(exposure.network.displayName)",275 value: exposure.outgoingTransactionCount.map { "\($0)" } ?? "Not measured")276 }277 SecTextRow(text: "The key is recoverable from any signature: one outgoing transaction on any EVM network, enabled here or not, makes it public for all of them. The address cannot be changed.")278 }279 }280281 @ViewBuilder var networksCard: some View {282 if !networks.isEmpty {283 let measured = networks.count - unmeasured.count284 QListSection("Networks measured · \(measured) of \(networks.count)",285 footnote: unmeasured.isEmpty ? nil : "Not measured: \(unmeasured.joined(separator: ", ")). The key may be public there; not measured is not counted as safe.",286 separatorInset: QMetric.padding + 28 + QSpace.m) {287 ForEach(networks, id: \.name) { n in288 SecShieldNetworkRow(name: n.name, evidence: n.evidence,289 state: SecShieldState(n.publicKeyExposed, exposedLabel: "Transaction sent", hiddenLabel: "None sent"))290 }291 if !unmeasured.isEmpty, !snapshot.profile.coldMode {292 LoadingButton("Synchronize to measure", loadingTitle: "Synchronizing", systemImage: "arrow.triangle.2.circlepath",293 state: evmRunning ? .loading : .idle, prominence: .secondary, action: synchronize)294 .padding(.vertical, QSpace.m)295 }296 }297 }298 }299300 // MARK: Approvals301302 /// The enabled EVM networks whose approvals cannot be read: they have no history source.303 var networksWithoutApprovals: [String] {304 let measured = Set((account?.approvals ?? []).map(\.network.displayName) + (exposure.map { [$0.network.displayName] } ?? []))305 return networks.map(\.name).filter { !measured.contains($0) }306 }307308 /// The approvals of an EVM network other than the primary one, as the report measured them.309 @ViewBuilder func otherApprovals(_ entry: AccountKeyExposure.NetworkApprovals) -> some View {310 let name = entry.network.displayName311 QListSection("Open token approvals · \(name)", separatorInset: QMetric.padding) {312 if let list = entry.approvals {313 if list.isEmpty {314 SecTextRow(text: "No open approval found on \(name).", systemImage: QTone.positive.systemImage, tone: .positive)315 }316 ForEach(list) { approvalRow($0) }317 } else {318 HStack { SecShieldState(nil); Spacer(minLength: 0) }.padding(.vertical, QSpace.m)319 SecTextRow(text: snapshot.profile.coldMode320 ? "Cold mode is on: approvals are read from the chain, which this device does not query."321 : "Not measured on \(name): synchronize it. Not measured does not mean there is none.")322 }323 }324 }325326 @ViewBuilder func approvals(_ e: EthereumKeyExposure) -> some View {327 let others = networksWithoutApprovals328 QListSection("Open token approvals · \(e.network.displayName)",329 footnote: others.isEmpty ? nil : "Approvals are found in the history of the account. \(others.joined(separator: ", ")) \(others.count == 1 ? "has" : "have") no history source: approvals cannot be measured there, and there may be some.",330 separatorInset: QMetric.padding) {331 if let list = e.openApprovals {332 if list.isEmpty {333 SecTextRow(text: "No open approval found on \(e.network.displayName).", systemImage: QTone.positive.systemImage, tone: .positive)334 }335 ForEach(list) { approvalRow($0) }336 } else {337 HStack { SecShieldState(nil); Spacer(minLength: 0) }.padding(.vertical, QSpace.m)338 SecTextRow(text: approvalsUnavailableReason)339 }340 }341 }342343 var approvalsUnavailableReason: String {344 if case .available(let eth) = snapshot.ethereum, case .unavailable(let reason) = eth.approvals { return reason }345 if snapshot.profile.coldMode { return "Cold mode is on: approvals are read from the chain, which this device does not query." }346 return "Approvals are read from the chain during a synchronization. Not measured does not mean there is none."347 }348349 func approvalRow(_ approval: TokenApprovalExposure) -> some View {350 VStack(alignment: .leading, spacing: QSpace.s) {351 HStack(alignment: .firstTextBaseline, spacing: QSpace.s) {352 Text(approval.token.symbol).font(QFont.headline).foregroundStyle(QColor.textPrimary)353 if approval.isUnlimited {354 QBadge("Unlimited", systemImage: "exclamationmark.triangle", tone: .warning)355 }356 Spacer(minLength: QSpace.s)357 if !approval.isUnlimited {358 Text(BaseUnits.format(approval.allowance, decimals: approval.token.decimals, maxFractionDigits: 6) + " " + approval.token.symbol)359 .font(QFont.amount)360 .foregroundStyle(QColor.textPrimary)361 }362 }363 HStack {364 Text("Spender").font(QFont.caption).foregroundStyle(QColor.textSecondary)365 AddressText(approval.spender.checksummed, kind: "Spender address")366 }367 if snapshot.profile.kind == .watchOnly {368 Label("Watch-only wallet: revoke from the device that holds the keys.", systemImage: "eye")369 .font(QFont.caption)370 .foregroundStyle(QColor.textSecondary)371 .fixedSize(horizontal: false, vertical: true)372 } else {373 Button {374 revoking = approval375 } label: {376 Label("Revoke", systemImage: "xmark.circle")377 }378 .buttonStyle(.qSecondary)379 .accessibilityLabel("Revoke the \(approval.token.symbol) approval")380 }381 }382 .padding(.vertical, QSpace.m)383 }384385 @ViewBuilder func needs(_ e: EthereumKeyExposure) -> some View {386 if !e.compatibilityNotes.isEmpty {387 QListSection(separatorInset: QMetric.padding) {388 Button {389 showNeeds.toggle()390 } label: {391 SecShieldDisclosureLabel(title: "What the EVM networks would need", count: e.compatibilityNotes.count, isOpen: showNeeds)392 }393 .buttonStyle(.qRow)394 .qHaptic(.selection, trigger: showNeeds)395 if showNeeds {396 ForEach(e.compatibilityNotes) { ProtocolCapabilityRow(capability: $0) }397 }398 }399 }400 }401}402403/// Section 2, an account chain with its own key: Solana (the address IS the public key) or TRON (like an EVM account,404/// on TRON's own networks).405struct SecShieldAccountExposureView: View {406 let account: AccountKeyExposure407 let snapshot: WalletSnapshot408 let synchronizing: Bool409 let synchronize: () -> Void410411 var chain: QChain { account.family == .solana ? .solana : .tron }412 var family: ChainFamily { account.family == .solana ? .solana : .tron }413 var running: Bool { synchronizing || snapshot.chains.contains { $0.chain.family == family && $0.isSynchronizing } }414 /// On Solana a network only says whether the account exists on chain: nothing about the key depends on it.415 var unmeasuredNames: [String] { account.networks.filter { $0.publicKeyExposed == nil }.map(\.name) }416417 var body: some View {418 VStack(alignment: .leading, spacing: QSpace.m) {419 QListSection(separatorInset: QMetric.padding) {420 HStack(spacing: QSpace.m) {421 ChainGlyph(chain)422 VStack(alignment: .leading, spacing: 3) {423 Text(account.family == .solana ? "Solana account" : "TRON account").font(QFont.headline).foregroundStyle(QColor.textPrimary)424 .accessibilityAddTraits(.isHeader)425 Text(account.family == .solana ? "One address: the Ed25519 public key itself" : "One address and one secp256k1 key")426 .font(QFont.caption).foregroundStyle(QColor.textSecondary)427 }428 .fixedSize(horizontal: false, vertical: true)429 Spacer(minLength: 0)430 }431 .padding(.vertical, QSpace.m)432 .frame(minHeight: QMetric.rowMinHeight)433 .accessibilityElement(children: .combine)434 SecShieldAddressRow(label: account.family == .solana ? "Address (the public key)" : "Address", address: account.address)435 HStack(spacing: QSpace.s) {436 Text("Public key").font(QFont.callout).foregroundStyle(QColor.textSecondary)437 Spacer(minLength: QSpace.s)438 SecShieldState(account.publicKeyExposed,439 exposedLabel: account.family == .solana ? "Public: it is the address" : "Recoverable from a signature on chain",440 hiddenLabel: "Not on chain (no transaction sent)")441 }442 .padding(.vertical, QSpace.m)443 .accessibilityElement(children: .combine)444 SecTextRow(text: account.family == .solana445 ? "A Solana address is the public key. It is exposed as soon as the address is shared or funded: nothing needs to be measured, and no wallet can hide it behind a hash."446 : "The key is recoverable from the signature of any outgoing transaction. A TRON account has no nonce: the evidence is its history, or the bandwidth and energy it has used.")447 }448 QListSection(account.family == .solana ? "Account on chain" : "Networks measured · \(account.networks.count - unmeasuredNames.count) of \(account.networks.count)",449 footnote: networksFootnote, separatorInset: QMetric.padding + 28 + QSpace.m) {450 ForEach(account.networks, id: \.name) { n in451 SecShieldNetworkRow(name: n.name, evidence: n.evidence, state: state(n))452 }453 if !unmeasuredNames.isEmpty, !snapshot.profile.coldMode {454 LoadingButton("Synchronize to measure", loadingTitle: "Synchronizing", systemImage: "arrow.triangle.2.circlepath",455 state: running ? .loading : .idle, prominence: .secondary, action: synchronize)456 .padding(.vertical, QSpace.m)457 }458 }459 ShieldFindingsCard(findings: account.findings)460 }461 }462463 var networksFootnote: String? {464 if account.family == .solana {465 return "Whether the account exists on a cluster changes nothing about the key: it is public either way."466 }467 return unmeasuredNames.isEmpty ? nil : "Not measured: \(unmeasuredNames.joined(separator: ", ")). The key may be public there; not measured is not counted as safe."468 }469470 func state(_ n: AccountKeyExposure.Network) -> SecShieldState {471 account.family == .solana472 ? SecShieldState(n.publicKeyExposed, exposedLabel: "On chain", hiddenLabel: "Not on chain yet", hiddenIsNeutral: true)473 : SecShieldState(n.publicKeyExposed, exposedLabel: "Transaction sent", hiddenLabel: "None sent")474 }475}476477/// Section 2 as a whole: every Bitcoin-family coin with its own breakdown, then the EVM account once, then Solana and478/// TRON. A chain the wallet uses that was not measured has its own "not measured" card.479struct SecShieldExposureSection: View {480 let shield: WalletShieldReport481 let snapshot: WalletSnapshot482 let synchronizing: Bool483 let synchronize: () -> Void484485 var exposure: KeyExposure { shield.report.keyExposure }486487 /// The other UTXO coins the wallet shows, in registry order, measured or not.488 var otherCoins: [(chain: ChainSnapshot, network: BitcoinNetwork)] {489 snapshot.chains.compactMap { chain in490 guard chain.chain.family == .utxo, let network = SecShield.bitcoinNetwork(chain.chain), network.coin != .bitcoin else { return nil }491 return (chain, network)492 }493 }494495 var showsBitcoin: Bool {496 exposure.bitcoin != nil || SecShield.chain(snapshot.profile.bitcoinNetwork, in: snapshot) != nil497 }498499 var showsEVM: Bool {500 exposure.ethereum != nil || account(.evm) != nil || snapshot.chains.contains { $0.chain.family == .evm }501 }502503 func account(_ family: AccountKeyExposure.Family) -> AccountKeyExposure? {504 exposure.accounts.first { $0.family == family }505 }506507 var body: some View {508 if showsBitcoin {509 let network = exposure.bitcoin?.network ?? snapshot.profile.bitcoinNetwork510 ShieldBitcoinExposureView(exposure: exposure.bitcoin, network: network, chain: SecShield.chain(network, in: snapshot), snapshot: snapshot,511 measuredAt: shield.bitcoinMeasuredAt, supportsSweep: true, synchronizing: synchronizing, synchronize: synchronize)512 .id("bitcoin")513 }514 ForEach(otherCoins, id: \.chain.id) { coin in515 ShieldBitcoinExposureView(exposure: exposure.otherCoins.first { $0.network == coin.network }, network: coin.network, chain: coin.chain,516 snapshot: snapshot, measuredAt: shield.measuredAt[coin.chain.id], supportsSweep: true,517 synchronizing: synchronizing, synchronize: synchronize)518 .id(coin.chain.chain.mainCounterpart.rawValue)519 }520 if showsEVM {521 ShieldEthereumExposureView(exposure: exposure.ethereum, account: account(.evm), snapshot: snapshot, synchronizing: synchronizing, synchronize: synchronize)522 .id("ethereum")523 }524 if let solana = account(.solana) {525 SecShieldAccountExposureView(account: solana, snapshot: snapshot, synchronizing: synchronizing, synchronize: synchronize)526 .id("solana")527 }528 if let tron = account(.tron) {529 SecShieldAccountExposureView(account: tron, snapshot: snapshot, synchronizing: synchronizing, synchronize: synchronize)530 .id("tron")531 }532 }533}534