SPB Git

Repository Public

WatchOnlyFlow.swift 24.5 KB 468 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Onboarding/WatchOnlyFlow.swift8// Module           : Onboarding9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0513//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 QyvoraEthereum44import QyvoraWallet45import QyvoraUI4647/// Creates a watch-only wallet from public data: account public keys of the UTXO coins, the EVM address, the Solana48/// and TRON addresses — typed, pasted or scanned — or the watch-only package shown by a cold device (version 249/// carries every chain). No secret is involved; the chains of the families given are the ones the wallet shows.50struct WatchOnlyFlow: View {51    enum Scan: Identifiable, Hashable {52        case key, address, solana, tron, coin(String), package53        var id: String {54            switch self {55            case .key: return "key"56            case .address: return "address"57            case .solana: return "solana"58            case .tron: return "tron"59            case .coin(let name): return "coin-" + name60            case .package: return "package"61            }62        }63    }6465    /// The other UTXO coins a key can be given for: the name shown and the chain it belongs to.66    private static let coins: [(name: String, main: ChainID)] = [("Litecoin", .litecoin), ("Dogecoin", .dogecoin), ("Bitcoin Cash", .bitcoinCash)]6768    let onClose: () -> Void6970    @Environment(WalletStore.self) private var wallet71    @State private var extendedKey = ""72    @State private var fingerprint = ""73    @State private var address = ""74    @State private var solana = ""75    @State private var tron = ""76    @State private var coinKeys: [String: String] = [:]77    @State private var showsCoins = false78    @State private var solanaValidity: FieldValidity = .empty79    @State private var tronValidity: FieldValidity = .empty80    @State private var scan: Scan?81    @State private var collector = FrameCollector()82    @State private var busy = false83    @State private var error: String?84    @State private var done = false85    /// A scanned package waiting for the comparison of its code with the signing device (QYV-APP-080).86    @State private var pending: PendingPackage?8788    struct PendingPackage: Equatable {89        let frames: [String]90        let preview: WatchOnlyPreview91    }9293    var body: some View {94        if let pending, !done {95            WatchOnlyPackageConfirmation(pending: pending, busy: busy, error: error,96                                         onImport: { code in importPackage(pending, code: code) },97                                         onDiscard: {98                                             self.pending = nil99                                             error = nil100                                         })101        } else if done {102            OnboardingDoneStep(title: "Watch-only wallet ready", lines: [103                "This device holds public data only: it shows balances and history and prepares transactions, but it cannot sign.",104                "To spend, export a prepared transaction as QR codes to the device that holds the keys.",105                "The networks of the accounts you gave are enabled. A network of another family needs its own address or key.",106            ], step: 1, stepCount: 2, onFinish: onClose)107        } else {108            form109        }110    }111112    var trimmedKey: String { extendedKey.trimmingCharacters(in: .whitespacesAndNewlines) }113    var trimmedAddress: String { address.trimmingCharacters(in: .whitespacesAndNewlines) }114    var trimmedSolana: String { solana.trimmingCharacters(in: .whitespacesAndNewlines) }115    var trimmedTron: String { tron.trimmingCharacters(in: .whitespacesAndNewlines) }116    var trimmedFingerprint: String { fingerprint.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }117    var filledCoinKeys: [String: String] { coinKeys.mapValues { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.value.isEmpty } }118119    var addressValidity: FieldValidity {120        if trimmedAddress.isEmpty { return .empty }121        guard EthereumAddress(trimmedAddress) != nil else { return .invalid("Not a valid EVM address, or its checksum does not verify.") }122        let digits = trimmedAddress.dropFirst(2)123        let mixed = digits.contains(where: \.isLowercase) && digits.contains(where: \.isUppercase)124        return .valid(mixed ? "Checksum verified" : "No checksum in this address: compare it carefully.")125    }126127    var fingerprintProblem: String? {128        guard !trimmedFingerprint.isEmpty else { return nil }129        return trimmedFingerprint.count == 8 && trimmedFingerprint.allSatisfy(\.isHexDigit) ? nil : "Eight hexadecimal digits, for example 73c5da0a."130    }131132    var canSubmit: Bool {133        guard !busy, fingerprintProblem == nil else { return false }134        for validity in [addressValidity, solanaValidity, tronValidity] {135            if case .invalid = validity { return false }136        }137        return !trimmedKey.isEmpty || !trimmedAddress.isEmpty || !trimmedSolana.isEmpty || !trimmedTron.isEmpty || !filledCoinKeys.isEmpty138    }139140    var form: some View {141        OnboardingScaffold(title: "Watch-only wallet", step: 0, stepCount: 2, onClose: busy ? nil : onClose) {142            WarningBanner(.info, message: "Enter public data only. Never paste a recovery phrase or a private key (xprv, tprv) here. Give what you want to watch: every section is optional, at least one is needed.")143            VStack(alignment: .leading, spacing: QSpace.m) {144                SectionHeader("From a cold device", subtitle: "QYVORA on the signing device shows a watch-only package as QR codes. It carries every account at once.")145                Button { collector.reset(); scan = .package } label: { Label("Scan a watch-only package", systemImage: "qrcode.viewfinder").frame(maxWidth: .infinity) }146                    .buttonStyle(.qSecondary)147                    .disabled(busy)148            }149            section(.bitcoin, title: "Bitcoin", subtitle: "Account public key (BIP-84): tpub or vpub on test networks; xpub or zpub need main networks switched on.") {150                keyField("tpub… / vpub…", text: $extendedKey, label: "Bitcoin account public key", scan: .key)151                TextField("Master fingerprint (optional)", text: $fingerprint)152                    .font(QFont.mono)153                    .textInputAutocapitalization(.never)154                    .autocorrectionDisabled()155                    .modifier(OnboardingFieldChrome())156                Text("The fingerprint lets the signing device recognise its own inputs in a transaction prepared here.")157                    .font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)158                InlineError(message: fingerprintProblem)159            }160            section(.ethereum, title: "Ethereum and EVM networks", subtitle: "One address for Ethereum, Base, Arbitrum, Optimism, Polygon, BNB Chain and Avalanche.") {161                AddressField(text: $address, placeholder: "0x…", validity: addressValidity) { scan = .address }162            }163            section(.solana, title: "Solana", subtitle: "The address of the account (it is its public key).") {164                AddressField(text: $solana, placeholder: "Solana address", validity: solanaValidity) { scan = .solana }165            }166            section(.tron, title: "TRON", subtitle: "The address of the account: 34 characters starting with T.") {167                AddressField(text: $tron, placeholder: "T…", validity: tronValidity) { scan = .tron }168            }169            VStack(alignment: .leading, spacing: QSpace.m) {170                Button { showsCoins.toggle() } label: {171                    HStack {172                        VStack(alignment: .leading, spacing: 2) {173                            Text("Litecoin, Dogecoin, Bitcoin Cash").font(QFont.headline).foregroundStyle(QColor.textPrimary)174                            Text("One account public key per coin").font(QFont.caption).foregroundStyle(QColor.textSecondary)175                        }176                        Spacer()177                        Image(systemName: "chevron.down").font(.footnote.weight(.semibold)).foregroundStyle(QColor.textTertiary)178                            .rotationEffect(.degrees(showsCoins ? 180 : 0))179                    }180                    .frame(minHeight: QMetric.minTap)181                    .contentShape(Rectangle())182                }183                .buttonStyle(.plain)184                .accessibilityHint(showsCoins ? "Hides the fields" : "Shows one field per coin")185                if showsCoins {186                    ForEach(Self.coins, id: \.name) { coin in187                        VStack(alignment: .leading, spacing: QSpace.s) {188                            HStack(spacing: QSpace.s) {189                                if let descriptor = coin.main.descriptor { ChainGlyph(descriptor.qNetwork, size: .small) }190                                Text(coin.name).font(QFont.subheadline).foregroundStyle(QColor.textPrimary)191                            }192                            keyField("Account public key of the test network (tpub…)", text: Binding(get: { coinKeys[coin.name] ?? "" }, set: { coinKeys[coin.name] = $0 }),193                                     label: "\(coin.name) account public key", scan: .coin(coin.name))194                        }195                    }196                    Text("A key written for a test network (tpub, vpub) is watched on the coin's test network; a main-network key needs main networks switched on. The signing device shows these keys in its watch-only export.")197                        .font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)198                }199            }200            .qAnimation(value: showsCoins)201            InlineError(message: error)202        } footer: {203            LoadingButton("Create the watch-only wallet", loadingTitle: "Checking the keys", state: busy ? .loading : .idle) { submit() }204                .disabled(!canSubmit)205        }206        .sheet(item: $scan) { kind in207            scanner(kind).presentedPrivacyCover()208        }209        .task(id: trimmedSolana) { solanaValidity = await validity(trimmedSolana, chain: .solanaDevnet) }210        .task(id: trimmedTron) { tronValidity = await validity(trimmedTron, chain: .tronNile) }211        #if DEBUG212        .task {213            if DebugLaunch.onboardingStep == "package" || DebugLaunch.onboardingStep == "package-typed" {214                submitPackage([DebugLaunch.publicWatchOnlyPackage])215                return216            }217            guard DebugLaunch.onboardingStep == "filled" else { return }218            extendedKey = DebugLaunch.testVectorAccountKey219            address = DebugLaunch.testVectorEthereumAddress220            solana = DebugLaunch.publicSolanaAddress221            tron = DebugLaunch.publicTronAddress222        }223        #endif224    }225226    /// The form of a Solana or TRON address is the same on every network of the chain: the service checks it227    /// (no network request) and its refusal is shown as given.228    func validity(_ text: String, chain: ChainID) async -> FieldValidity {229        guard !text.isEmpty else { return .empty }230        guard let service = wallet.service else { return .empty }231        do {232            let check = try await service.checkAddress(text, chain: chain)233            return .valid(check.notes.first)234        } catch {235            return .invalid(WalletStore.message(for: error))236        }237    }238239    func section<Content: View>(_ chain: ChainID, title: String, subtitle: String, @ViewBuilder content: () -> Content) -> some View {240        VStack(alignment: .leading, spacing: QSpace.m) {241            HStack(alignment: .top, spacing: QSpace.m) {242                if let descriptor = chain.descriptor { ChainGlyph(descriptor.qNetwork.chain, size: .small) }243                VStack(alignment: .leading, spacing: 2) {244                    Text(title).font(QFont.headline).foregroundStyle(QColor.textPrimary)245                    Text(subtitle).font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)246                }247            }248            .accessibilityElement(children: .combine)249            .accessibilityAddTraits(.isHeader)250            content()251        }252    }253254    func keyField(_ placeholder: String, text: Binding<String>, label: String, scan kind: Scan) -> some View {255        VStack(alignment: .leading, spacing: QSpace.s) {256            TextField(placeholder, text: text, axis: .vertical)257                .font(QFont.mono)258                .lineLimit(2...4)259                .textInputAutocapitalization(.never)260                .autocorrectionDisabled()261                .modifier(OnboardingFieldChrome())262                .accessibilityLabel(label)263            HStack(spacing: QSpace.m) {264                PasteButton(payloadType: String.self) { strings in265                    if let first = strings.first { text.wrappedValue = first.trimmingCharacters(in: .whitespacesAndNewlines) }266                }267                .labelStyle(.titleAndIcon)268                .tint(QColor.violet)269                Button { scan = kind } label: { Label("Scan", systemImage: "qrcode.viewfinder") }270                    .buttonStyle(.bordered)271                    .tint(QColor.violet)272            }273        }274    }275276    @ViewBuilder277    func scanner(_ kind: Scan) -> some View {278        VStack(spacing: QSpace.l) {279            SheetHeader(kind == .package ? "Scan the watch-only package" : "Scan a QR code") { scan = nil }280            switch kind {281            case .package:282                QRScannerView(collect: { collector.collect($0) }, onComplete: {283                    scan = nil284                    submitPackage(collector.payload)285                })286            default:287                QRScannerView { text in288                    apply(text.trimmingCharacters(in: .whitespacesAndNewlines), to: kind)289                    scan = nil290                }291            }292        }293        .padding(QMetric.screenPadding)294        .qScreen()295    }296297    func apply(_ value: String, to kind: Scan) {298        /// A payment request names the address after its scheme: only the address is kept.299        func bare(_ scheme: String) -> String {300            guard value.lowercased().hasPrefix(scheme + ":") else { return value }301            return String(value.dropFirst(scheme.count + 1).prefix { $0 != "?" && $0 != "@" })302        }303        switch kind {304        case .key: extendedKey = value305        case .address: address = bare("ethereum")306        case .solana: solana = bare("solana")307        case .tron: tron = bare("tron")308        case .coin(let name): coinKeys[name] = value309        case .package: break310        }311    }312313    /// The network a coin key is for, by the raw value the service expects: the test network of the coin for a314    /// test-network key, its main network otherwise.315    func accounts() -> [String: String] {316        var out = [String: String]()317        for (name, key) in filledCoinKeys {318            let isTest = key.hasPrefix("tpub") || key.hasPrefix("vpub")319            switch name {320            case "Litecoin": out[isTest ? BitcoinNetwork.litecoinTestnet.rawValue : BitcoinNetwork.litecoin.rawValue] = key321            case "Dogecoin": out[isTest ? BitcoinNetwork.dogecoinTestnet.rawValue : BitcoinNetwork.dogecoin.rawValue] = key322            case "Bitcoin Cash": out[isTest ? BitcoinNetwork.bitcoinCashTestnet.rawValue : BitcoinNetwork.bitcoinCash.rawValue] = key323            default: break324            }325        }326        return out327    }328329    func submit() {330        let key = trimmedKey.isEmpty ? nil : trimmedKey, eth = trimmedAddress.isEmpty ? nil : trimmedAddress331        let fp = trimmedFingerprint.isEmpty ? nil : trimmedFingerprint332        let sol = trimmedSolana.isEmpty ? nil : trimmedSolana, trx = trimmedTron.isEmpty ? nil : trimmedTron333        let others = accounts()334        run {335            try await $0.importWatchOnly(bitcoinExtendedPublicKey: key, ethereumAddress: eth, masterFingerprint: fp, solanaAddress: sol, tronAddress: trx, accounts: others)336        }337    }338339    /// A scanned package is never imported from the scanner: its code and first addresses are shown first, and the340    /// import needs the code confirmed against the signing device.341    func submitPackage(_ frames: [String]) {342        error = nil343        do {344            pending = PendingPackage(frames: frames, preview: try WalletService.watchOnlyPreview(package: frames))345        } catch {346            self.error = WalletStore.message(for: error)347        }348    }349350    func importPackage(_ pending: PendingPackage, code: String) {351        let frames = pending.frames352        run { try await $0.importWatchOnly(package: frames, comparedFingerprint: code) }353    }354355    func run(_ operation: @escaping @Sendable (WalletService) async throws -> Void) {356        guard !busy else { return }357        busy = true358        error = nil359        Task {360            defer { busy = false }361            do {362                try await wallet.run(operation)363                done = true364            } catch {365                self.error = WalletStore.message(for: error)366            }367        }368    }369}370371/// The comparison step of a watch-only package (QYV-APP-080): what was scanned is shown — its code without the last372/// group, the first address of every account — and nothing is imported until the user has typed the last group as373/// the signing device displays it and confirmed the comparison. The service checks the code against the package.374struct WatchOnlyPackageConfirmation: View {375    let pending: WatchOnlyFlow.PendingPackage376    let busy: Bool377    let error: String?378    let onImport: (String) -> Void379    let onDiscard: () -> Void380381    @State private var lastGroup = ""382    @State private var compared = false383    @FocusState private var focused: Bool384385    private var preview: WatchOnlyPreview { pending.preview }386    private var typed: String { String(lastGroup.uppercased().filter { $0.isASCII && $0.isHexDigit }.prefix(4)) }387    private var expected: String { preview.fingerprintGroups.last ?? "" }388    /// The code as the user states it: the four groups shown here and the group typed from the other device.389    private var statedCode: String { (preview.fingerprintGroups.dropLast() + [typed]).joined(separator: "-") }390    private var groupProblem: String? {391        guard typed.count == 4 else { return nil }392        return typed == expected ? nil : "This is not the last group of the package scanned here. If the signing device really shows \(typed), the package was replaced on its way: do not import it."393    }394    private var canImport: Bool { !busy && compared && typed.count == 4 && typed == expected }395396    var body: some View {397        OnboardingScaffold(title: "Compare with the signing device", step: 0, stepCount: 2, onClose: busy ? nil : onDiscard) {398            WarningBanner(.warning, title: "Nothing is imported yet",399                          message: "A watch-only package is public data and nothing signs it. If someone replaced it on its way, this device would show their addresses as yours, and what you receive on them would be lost. The code below is computed from what this device scanned: it must be the one the signing device shows.")400            WatchOnlyFingerprintCard(preview: preview, hidesLastGroup: true).id("code")401            VStack(alignment: .leading, spacing: QSpace.s) {402                QEyebrow("Last group, as the signing device shows it")403                TextField("4 characters", text: $lastGroup)404                    .font(Font.system(.title3, design: .monospaced).weight(.semibold))405                    .textInputAutocapitalization(.characters)406                    .autocorrectionDisabled()407                    .keyboardType(.asciiCapable)408                    .focused($focused)409                    .padding(14)410                    .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))411                    .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous)412                        .strokeBorder(groupProblem != nil ? QColor.negative : (typed == expected && typed.count == 4 ? QColor.positive : QColor.stroke), lineWidth: 1))413                    .accessibilityLabel("Last group of the package code, as shown on the signing device")414                    .onChange(of: lastGroup) { _, new in415                        let clean = String(new.uppercased().filter { $0.isASCII && $0.isHexDigit }.prefix(4))416                        if clean != new { lastGroup = clean }417                    }418                if let groupProblem {419                    Label(groupProblem, systemImage: "exclamationmark.octagon").font(QFont.caption).foregroundStyle(QColor.negative)420                        .fixedSize(horizontal: false, vertical: true)421                } else {422                    Text("On the signing device: Shield, Cold mode, Watch-only package. Its code has five groups; type the fifth.")423                        .font(QFont.caption).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)424                }425            }426            .id("group")427            WatchOnlyAccountsSection(preview: preview, title: "Accounts this device would watch",428                                     footnote: "The first address of each account, derived here from the package. The signing device lists the same ones under its code. A main-network account is imported only when main networks are switched on.")429                .id("addresses")430            QListSection("If something differs") {431                SecTextRow(text: "A different group, or an address the signing device does not show, means this is not the package of your wallet. Discard it and scan again, directly from the screen of the signing device.",432                           systemImage: "xmark.octagon", tone: .critical)433                SecTextRow(text: "A wallet created from a wrong package cannot spend anything, but every address it shows belongs to someone else.",434                           systemImage: "info.circle", tone: .info)435            }436            .id("mismatch")437            AcknowledgementCheck(text: "I compared the four groups and the addresses above with the screen of the signing device, and they are the same.", isOn: $compared)438                .id("compared")439            InlineError(message: error)440        } footer: {441            LoadingButton("Import this watch-only wallet", loadingTitle: "Checking the package", state: busy ? .loading : .idle) { onImport(statedCode) }442                .disabled(!canImport)443            Button("Discard: the codes differ") { onDiscard() }444                .buttonStyle(.qSecondary)445                .disabled(busy)446        }447        #if DEBUG448        .task {449            // screenshots only: the state a user reaches by typing and ticking (never in a Release build)450            if DebugLaunch.onboardingStep == "package-typed" {451                lastGroup = expected452                compared = true453            }454        }455        #endif456    }457}458459/// The surface of a plain text field of the onboarding forms.460private struct OnboardingFieldChrome: ViewModifier {461    func body(content: Content) -> some View {462        content463            .padding(14)464            .background(QColor.surface, in: RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous))465            .overlay(RoundedRectangle(cornerRadius: QMetric.radiusSmall, style: .continuous).strokeBorder(QColor.stroke, lineWidth: 1))466    }467}468
Files main
Menu

Theme