SPB Git

Repository Public

ShieldBitcoinExposureView.swift 17.6 KB 411 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/ShieldBitcoinExposureView.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 QyvoraBitcoin44import QyvoraQuantumShield45import QyvoraWallet46import QyvoraUI4748extension PublicKeyExposure {49    var title: String {50        switch self {51        case .hashedUnrevealed: return "Key still hashed"52        case .revealedBySpend: return "Key revealed by a spend"53        case .revealedByScript: return "Key in the script itself"54        case .undetermined: return "Undetermined"55        }56    }5758    var color: Color {59        switch self {60        case .hashedUnrevealed: return QColor.positive61        case .revealedBySpend: return QColor.warning62        case .revealedByScript: return QColor.negative63        case .undetermined: return QColor.textSecondary64        }65    }6667    var pattern: SegmentedSummaryBar.Pattern {68        switch self {69        case .hashedUnrevealed: return .solid70        case .revealedBySpend: return .striped71        case .revealedByScript: return .dotted72        case .undetermined: return .hollow73        }74    }7576    var badgeTone: QBadge.Tone {77        switch self {78        case .hashedUnrevealed: return .positive79        case .revealedBySpend: return .warning80        case .revealedByScript: return .negative81        case .undetermined: return .neutral82        }83    }84}8586extension BitcoinScriptType {87    var title: String {88        switch self {89        case .p2pkh: return "P2PKH (legacy)"90        case .p2sh: return "P2SH"91        case .p2wpkh: return "P2WPKH (native SegWit)"92        case .p2wsh: return "P2WSH"93        case .p2tr: return "P2TR (Taproot)"94        case .p2pk: return "P2PK"95        case .multisig: return "Bare multisig"96        case .nullData: return "OP_RETURN"97        case .witnessUnknown: return "Unknown witness program"98        case .unknown: return "Non-standard"99        }100    }101}102103/// Section 2, one Bitcoin-family coin (Bitcoin, Litecoin, Dogecoin, Bitcoin Cash): value by exposure class, reused104/// addresses, exposed outputs, script types, storage advice, and the sweep where the service has one. Each coin has105/// its own account and its own breakdown. "Not measured" is shown as such, never as zero or as safe.106struct ShieldBitcoinExposureView: View {107    /// nil when the coin was not measured.108    let exposure: BitcoinKeyExposure?109    let network: BitcoinNetwork110    /// The coin's entry among the active chains; nil when its chain is not shown by the wallet.111    let chain: ChainSnapshot?112    let snapshot: WalletSnapshot113    /// When the coin was read, from the report.114    let measuredAt: Date?115    /// True for the coin whose exposed outputs the service can sweep in one transaction.116    let supportsSweep: Bool117    let synchronizing: Bool118    let synchronize: () -> Void119120    @Environment(WalletStore.self) private var store121    @Environment(\.secSendReviewHandoff) private var reviewHandoff122    @Environment(\.bitcoinPlanHandoff) private var planHandoff123    @State private var showSweep = false124    @State private var pendingPlan: BitcoinSendPlan?125    @State private var handoffError: String?126    @State private var showAllUTXOs = false127    @State private var showAllReused = false128    @State private var showAdvice = SecShield.startsExpanded129130    static let listLimit = 5131132    var qNetwork: QNetwork { network.qNetwork }133    var coinName: String { network.mainCounterpart.displayName }134    var isRunning: Bool { synchronizing || chain?.isSynchronizing == true }135    /// A coin shown by the wallet has an account; Bitcoin itself is always stated, with or without one.136    var hasAccount: Bool { network.coin == .bitcoin ? !snapshot.profile.bitcoinAccounts.isEmpty : true }137138    var body: some View {139        VStack(alignment: .leading, spacing: QSpace.m) {140            if let exposure {141                measured(exposure)142            } else {143                notMeasured144            }145            SecInlineError(handoffError)146        }147        .sheet(isPresented: $showSweep, onDismiss: {148            if let plan = pendingPlan {149                pendingPlan = nil150                hand(plan)151            }152        }) {153            SweepExposedSheet(network: network, handsOff: reviewHandoff != nil || (planHandoff != nil && network.coin == .bitcoin)) { plan in154                pendingPlan = plan155                showSweep = false156            }157        }158    }159160    /// Gives the sweep plan to the wallet's review: the multi-chain one when it is installed, else the Bitcoin one.161    func hand(_ plan: BitcoinSendPlan) {162        guard let reviewHandoff else {163            // the older handoff reviews Bitcoin plans only164            if network.coin == .bitcoin { planHandoff?.review(plan) }165            return166        }167        handoffError = nil168        Task {169            do {170                let review = try await store.run { await $0.review(for: plan) }171                reviewHandoff.review(review)172            } catch {173                if let planHandoff, network.coin == .bitcoin { planHandoff.review(plan) } else { handoffError = SecurityError.text(error) }174            }175        }176    }177178    // MARK: Not measured179180    var notMeasured: some View {181        QListSection {182            SecChainHeader(network: qNetwork, detail: "Own account · a new address for every payment")183            HStack(spacing: QSpace.s) {184                SecShieldState(nil)185                Spacer(minLength: 0)186            }187            .padding(.vertical, QSpace.m)188            SecTextRow(text: notMeasuredReason)189            if hasAccount, !snapshot.profile.coldMode, chain?.chain.capabilities.historyAvailable != false {190                if let error = chain?.syncError ?? chain.flatMap({ SecShield.failure($0.data) }), !isRunning {191                    UnavailableDataView(reason: error, title: "Synchronization failed", compact: true, retry: synchronize)192                        .padding(.vertical, QSpace.m)193                } else {194                    LoadingButton("Synchronize to measure", loadingTitle: "Synchronizing", systemImage: "arrow.triangle.2.circlepath",195                                  state: isRunning ? .loading : .idle, prominence: .secondary, action: synchronize)196                        .padding(.vertical, QSpace.m)197                }198            }199        }200    }201202    var notMeasuredReason: String {203        if !hasAccount { return "This wallet has no \(coinName) account." }204        if snapshot.profile.coldMode {205            return "Cold mode is on. Exposure is measured from the chain, which this device does not query. Measure it on the online companion device."206        }207        if chain?.chain.capabilities.historyAvailable == false {208            return "No indexer is available for \(network.displayName): its coins and history cannot be read, so the exposure of its keys cannot be measured. Not measured does not mean safe."209        }210        return "The \(coinName) account has not been synchronized on this network yet, so nothing is known about its public keys on chain. Not measured does not mean safe."211    }212213    // MARK: Measured214215    @ViewBuilder func measured(_ e: BitcoinKeyExposure) -> some View {216        if let error = chain?.syncError {217            WarningBanner(.warning, title: "Showing the last successful measurement of \(network.displayName)", message: error)218        }219        QListSection(footnote: measuredAt.map { "Measured \(SecurityFormat.date($0))." }, separatorInset: QMetric.padding) {220            SecChainHeader(network: qNetwork, detail: "Own account · a new address for every payment")221            VStack(alignment: .leading, spacing: QSpace.m) {222                QEyebrow("Value by exposure of the key")223                SegmentedSummaryBar(segments: PublicKeyExposure.allCases.map { c in224                    .init(id: c.rawValue, label: c.title, value: Double(e.totals[c]), detail: SecChain.amount(e.totals[c], on: network), color: c.color, pattern: c.pattern)225                }, emptyLabel: "No coins on this network")226            }227            .padding(.vertical, QSpace.l)228            SecFactRow(label: "Total measured", value: SecChain.amount(e.totals.total, on: network))229            SecFactRow(label: "Share on never-spent hashed outputs", value: e.hashedUnrevealedShareBasisPoints.map(Self.percent) ?? "Not applicable (no coins)")230            SecFactRow(label: "Outputs with an exposed key", value: "\(e.exposedUTXOCount)", tone: e.exposedUTXOCount > 0 ? .warning : nil)231            SecFactRow(label: "Reused addresses", value: "\(e.reusedAddresses.count)", tone: e.reusedAddresses.isEmpty ? nil : .warning)232            SecFactRow(label: "Script types holding coins", value: e.scriptTypesInUse.isEmpty ? "None" : e.scriptTypesInUse.map(\.title).joined(separator: ", "))233            if !e.vulnerableScripts.isEmpty {234                SecFactRow(label: "Types that publish the key", value: e.vulnerableScripts.map(\.title).joined(separator: ", "), tone: .warning)235            }236        }237        ShieldFindingsCard(findings: e.findings)238        exposedList(e)239        reusedList(e)240        if !e.longTermStorageAdvice.isEmpty {241            QListSection(separatorInset: QMetric.padding) {242                Button {243                    showAdvice.toggle()244                } label: {245                    SecShieldDisclosureLabel(title: "Long-term storage of \(coinName)", count: e.longTermStorageAdvice.count, isOpen: showAdvice)246                }247                .buttonStyle(.qRow)248                .qHaptic(.selection, trigger: showAdvice)249                if showAdvice {250                    ForEach(e.longTermStorageAdvice, id: \.self) { SecTextRow(text: $0) }251                }252            }253        }254    }255256    @ViewBuilder func exposedList(_ e: BitcoinKeyExposure) -> some View {257        let exposed = e.utxos.filter { $0.exposure == .revealedBySpend || $0.exposure == .revealedByScript }258        if !exposed.isEmpty {259            QListSection("Outputs with an exposed key · \(exposed.count)", separatorInset: QMetric.padding) {260                ForEach(showAllUTXOs ? exposed : Array(exposed.prefix(Self.listLimit))) { utxo in261                    VStack(alignment: .leading, spacing: 6) {262                        SecShieldAddressAmount(address: utxo.address, amount: SecChain.amount(utxo.value, on: network))263                        ViewThatFits(in: .horizontal) {264                            HStack(spacing: 6) { badges(utxo) }265                            VStack(alignment: .leading, spacing: 6) { badges(utxo) }266                        }267                        Text(utxo.explanation).font(QFont.caption).foregroundStyle(QColor.textSecondary)268                            .fixedSize(horizontal: false, vertical: true)269                    }270                    .padding(.vertical, QSpace.m)271                    .accessibilityElement(children: .combine)272                }273                if exposed.count > Self.listLimit {274                    SecShieldShowAll(isOpen: $showAllUTXOs, count: exposed.count)275                }276                if supportsSweep { sweepAction }277            }278            .id("exposed-\(network.rawValue)")279        }280    }281282    @ViewBuilder func badges(_ utxo: BitcoinKeyExposure.UTXO) -> some View {283        QBadge(utxo.exposure.title, tone: utxo.exposure.badgeTone)284        QBadge(utxo.scriptType.title, tone: .neutral)285    }286287    @ViewBuilder var sweepAction: some View {288        if snapshot.profile.kind == .watchOnly {289            SecTextRow(text: "Watch-only wallet: the sweep is prepared and signed on the device that holds the keys.", systemImage: "eye")290        } else {291            VStack(alignment: .leading, spacing: QSpace.s) {292                Button {293                    showSweep = true294                } label: {295                    Label("Sweep exposed coins to fresh addresses", systemImage: "arrow.right.arrow.left")296                }297                .buttonStyle(.qPrimary)298                Text("Moves these outputs to a never-used address of this wallet. It pays a network fee and links the swept addresses together. It does not make \(coinName) quantum-resistant: the new output is protected by a hash until it is spent.")299                    .font(QFont.caption)300                    .foregroundStyle(QColor.textSecondary)301                    .fixedSize(horizontal: false, vertical: true)302            }303            .padding(.vertical, QSpace.m)304        }305    }306307    @ViewBuilder func reusedList(_ e: BitcoinKeyExposure) -> some View {308        if !e.reusedAddresses.isEmpty {309            QListSection("Reused addresses · \(e.reusedAddresses.count)", separatorInset: QMetric.padding) {310                ForEach(showAllReused ? e.reusedAddresses : Array(e.reusedAddresses.prefix(Self.listLimit))) { a in311                    VStack(alignment: .leading, spacing: 4) {312                        SecShieldAddressAmount(address: a.address, amount: SecChain.amount(a.balance, on: network))313                        Text("Paid by \(a.fundingTransactionCount) transaction(s)" + (a.fundedAfterSpend ? " · paid again after its key was published" : ""))314                            .font(QFont.caption)315                            .foregroundStyle(QColor.textSecondary)316                            .fixedSize(horizontal: false, vertical: true)317                    }318                    .padding(.vertical, QSpace.m)319                    .accessibilityElement(children: .combine)320                }321                if e.reusedAddresses.count > Self.listLimit {322                    SecShieldShowAll(isOpen: $showAllReused, count: e.reusedAddresses.count)323                }324            }325            .id("reused-\(network.rawValue)")326        }327    }328329    static func percent(_ basisPoints: Int) -> String {330        "\(basisPoints / 100).\(String(format: "%02d", basisPoints % 100)) %"331    }332}333334/// An address (or the mention that the script has none) with the amount it holds; stacked at accessibility sizes.335struct SecShieldAddressAmount: View {336    let address: String?337    let amount: String338    @Environment(\.dynamicTypeSize) private var typeSize339340    var body: some View {341        if typeSize.isAccessibilitySize {342            VStack(alignment: .leading, spacing: 4) {343                addressText344                amountText345            }346        } else {347            HStack(alignment: .firstTextBaseline) {348                addressText349                Spacer(minLength: QSpace.s)350                amountText351            }352        }353    }354355    @ViewBuilder var addressText: some View {356        if let address {357            AddressText(address)358        } else {359            Text("Script without address form").font(QFont.callout).foregroundStyle(QColor.textSecondary)360        }361    }362363    var amountText: some View {364        Text(amount).font(QFont.amount).foregroundStyle(QColor.textPrimary)365    }366}367368/// "Show all 12" / "Show fewer" at the end of a shortened list.369struct SecShieldShowAll: View {370    @Binding var isOpen: Bool371    let count: Int372373    var body: some View {374        Button(isOpen ? "Show fewer" : "Show all \(count)") { isOpen.toggle() }375            .font(.callout.weight(.medium))376            .foregroundStyle(QColor.violet)377            .frame(maxWidth: .infinity, minHeight: QMetric.minTap, alignment: .leading)378            .buttonStyle(.qRow)379            .qHaptic(.selection, trigger: isOpen)380    }381}382383/// The label of a row that opens and closes a part of a card.384struct SecShieldDisclosureLabel: View {385    let title: String386    var count: Int?387    let isOpen: Bool388389    var body: some View {390        HStack(spacing: QSpace.s) {391            Text(title).font(QFont.subheadline).foregroundStyle(QColor.textPrimary)392                .fixedSize(horizontal: false, vertical: true)393            if let count {394                Text("\(count)").font(QFont.figure).foregroundStyle(QColor.textSecondary)395            }396            Spacer(minLength: QSpace.s)397            Image(systemName: "chevron.down")398                .font(.footnote.weight(.semibold))399                .foregroundStyle(QColor.textTertiary)400                .rotationEffect(.degrees(isOpen ? 180 : 0))401                .qAnimation(value: isOpen)402                .accessibilityHidden(true)403        }404        .padding(.vertical, QSpace.m)405        .frame(minHeight: QMetric.minTap)406        .accessibilityElement(children: .combine)407        .accessibilityValue(isOpen ? "Expanded" : "Collapsed")408        .accessibilityAddTraits(.isButton)409    }410}411
Files main
Menu

Theme