SPB Git

Repository Public

RecoverySheetView.swift 18.0 KB 363 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/RecoverySheetView.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 UIKit43import QyvoraCore44import QyvoraRecovery45import QyvoraWallet46import QyvoraUI4748/// Renders text as a paginated A4 PDF, in memory.49enum TextPDF {50    static func render(title: String, body: String) -> Data {51        let page = CGRect(x: 0, y: 0, width: 595, height: 842)52        let margin: CGFloat = 4853        let content = page.insetBy(dx: margin, dy: margin)54        let titleAttributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 16, weight: .semibold), .foregroundColor: UIColor.black]55        let paragraph = NSMutableParagraphStyle()56        paragraph.lineBreakMode = .byCharWrapping57        let bodyAttributes: [NSAttributedString.Key: Any] = [.font: UIFont.monospacedSystemFont(ofSize: 9, weight: .regular),58                                                             .foregroundColor: UIColor.black, .paragraphStyle: paragraph]59        return UIGraphicsPDFRenderer(bounds: page).pdfData { context in60            var y = content.minY61            func newPage() {62                context.beginPage()63                y = content.minY64            }65            newPage()66            (title as NSString).draw(at: CGPoint(x: content.minX, y: y), withAttributes: titleAttributes)67            y += 3068            for line in body.components(separatedBy: "\n") {69                let text = (line.isEmpty ? " " : line) as NSString70                let height = ceil(text.boundingRect(with: CGSize(width: content.width, height: .greatestFiniteMagnitude),71                                                    options: [.usesLineFragmentOrigin], attributes: bodyAttributes, context: nil).height)72                if y + height > content.maxY { newPage() }73                text.draw(with: CGRect(x: content.minX, y: y, width: content.width, height: height), options: [.usesLineFragmentOrigin],74                          attributes: bodyAttributes, context: nil)75                y += height + 276            }77        }78    }79}8081/// What another wallet needs to find the funds of each chain from the recovery phrase. The paths come from the82/// registry of the wallet service (`ChainDescriptor.derivationPath`); the sentences say what to choose elsewhere.83enum SecRecoveryGuide {84    struct Entry: Identifiable {85        let chain: ChainDescriptor86        let standard: String87        let advice: String88        var id: ChainID { chain.id }89    }9091    static func entries(_ group: ChainGroup) -> [Entry] {92        // one entry for the whole EVM family: one address, one path93        let chains = group.family == .evm ? Array(group.chains.prefix(1)) : group.chains94        return chains.map { Entry(chain: $0, standard: standard($0), advice: advice($0, group: group)) }95    }9697    static func standard(_ chain: ChainDescriptor) -> String {98        switch chain.family {99        case .utxo:100            if chain.derivationPath.hasPrefix("m/84'") { return "BIP-84, native SegWit addresses" }101            if chain.derivationPath.hasPrefix("m/44'") { return chain.id == .bitcoinCash ? "BIP-44, CashAddr addresses" : "BIP-44, legacy addresses" }102            return "BIP-32 account"103        case .evm: return "BIP-44, secp256k1"104        case .solana: return "SLIP-0010, Ed25519"105        case .tron: return "BIP-44, secp256k1"106        }107    }108109    static func advice(_ chain: ChainDescriptor, group: ChainGroup) -> String {110        switch chain.id {111        case .bitcoin:112            return "Choose a BIP-39 wallet and the native SegWit (BIP-84) account type. The descriptor of this sheet imports the same account in a descriptor wallet without the phrase, to watch only."113        case .litecoin:114            return chain.derivationPath.hasPrefix("m/84'")115                ? "Choose native SegWit (BIP-84) for Litecoin: addresses start with ltc1q."116                : "Choose the legacy (BIP-44) account type for Litecoin."117        case .dogecoin:118            return "Dogecoin has no SegWit: choose the standard BIP-44 account. Addresses start with D."119        case .bitcoinCash:120            return "Choose the standard BIP-44 account of Bitcoin Cash (coin type 145). Addresses are shown in CashAddr form (bitcoincash:q…); the legacy form of the same address is the same key."121        case .solana:122            return "Phantom and Solflare use this path for the first account. If a wallet shows several derivation styles, choose m/44'/501'/0'/0'. The address is the public key itself."123        case .tron:124            return "TronLink and Ledger use this path for the first account. The same address serves mainnet, Nile and Shasta."125        default:126            if chain.family == .evm {127                let names = group.chains.map(\.displayName).joined(separator: ", ")128                return "One address for every EVM network (\(names)). MetaMask, Rabby and Ledger use this path for the first account; add each network in that wallet to see its balance."129            }130            return "Use the account path above."131        }132    }133}134135/// The recovery sheet: derivation paths, extended public keys, descriptors and first addresses of every chain. Public136/// material by default; the recovery phrase is added only through a separate, re-authenticated action with its own137/// warning, and is removed again when the screen is left.138struct RecoverySheetView: View {139    @Environment(WalletStore.self) private var store140    @Environment(\.scenePhase) private var scenePhase141    @State private var sheet: RecoverySheet?142    @State private var privateSheet: RecoverySheet?143    @State private var loadError: String?144    @State private var error: String?145    @State private var busy = false146    @State private var acknowledged = false147    @State private var reauthenticate = false148    @State private var screenshotTaken = false149150    var body: some View {151        SecurityScroll {152            if let sheet {153                WarningBanner(.info, title: "Public material",154                              message: "This sheet lets anyone who reads it see every address and balance of the wallet, on every chain. It cannot spend. Keep it with the recovery phrase, not on a shared drive.")155                summary(sheet).id("summary")156                ForEach(sheet.bitcoin, id: \.derivationPath) { bitcoin($0) }157                ethereum(sheet).id("ethereum")158                ForEach(Array(sheet.otherChains.enumerated()), id: \.offset) { index, account in159                    other(account).id("chain-\(index)")160                }161                if sheet.otherChains.isEmpty {162                    WarningBanner(.warning, message: "This sheet lists Bitcoin and Ethereum only: the service returned no account for the other chains.")163                }164                share(sheet, isPrivate: false).id("share")165                guide(sheet).id("guide")166                privateSection167            } else if let loadError {168                UnavailableDataView(reason: loadError, title: "Recovery sheet unavailable") { Task { await load() } }169            } else {170                SecSkeletonSection(rows: 4)171                SecSkeletonSection(title: "Bitcoin", rows: 3)172            }173        }174        .debugScroll()175        .navigationTitle("Recovery sheet")176        .navigationBarTitleDisplayMode(.inline)177        .task { await load() }178        .requiresReauthentication(isPresented: $reauthenticate, reason: "Add the recovery phrase to the sheet") { loadPrivate() }179        .warnsAboutScreenshots(of: privateSheet?.privateMaterial != nil, taken: $screenshotTaken)180        .onDisappear { clearPrivate() }181        #if DEBUG182        .task {183            if SecurityDebug.action == "private" {184                acknowledged = true185                reauthenticate = true186            }187        }188        #endif189        .onChange(of: scenePhase) { _, phase in190            if phase != .active { clearPrivate() }191        }192    }193194    private func summary(_ sheet: RecoverySheet) -> some View {195        QListSection {196            SecFactRow(label: "Created", value: SecurityFormat.date(sheet.createdAt))197            SecFactRow(label: "Master fingerprint", value: sheet.masterFingerprint)198            SecFactRow(label: "Recovery phrase", value: "\(sheet.mnemonicWordCount) words (BIP-39)")199            SecFactRow(label: "BIP-39 passphrase", value: sheet.usesPassphrase ? "In use" : "None", tone: sheet.usesPassphrase ? .warning : nil)200            SecFactRow(label: "Sheet format", value: "Version \(sheet.formatVersion)")201        }202    }203204    private func value(_ label: String, _ value: String) -> some View {205        MonoValue(label: label, value: value).padding(.vertical, QSpace.m)206    }207208    private func bitcoin(_ account: RecoverySheet.BitcoinAccount) -> some View {209        QListSection {210            SecChainHeader(network: account.network.qNetwork, detail: "BIP-84 native SegWit, secp256k1")211            SecFactRow(label: "Account path", value: account.derivationPath)212            value("Extended public key", account.extendedPublicKey)213            value("SLIP-132 form", account.slip132PublicKey)214            value("Receive descriptor", account.receiveDescriptor)215            value("Change descriptor", account.changeDescriptor)216            value("First receive address", account.firstReceiveAddress)217        }218    }219220    private func ethereum(_ sheet: RecoverySheet) -> some View {221        QListSection(footnote: "The same addresses on every EVM network. The wallet uses the first one.") {222            SecChainHeader(network: .mainnet(.ethereum), detail: "Ethereum and EVM networks · BIP-44, secp256k1")223            ForEach(sheet.ethereum, id: \.index) { account in224                value(account.derivationPath, account.address)225            }226        }227    }228229    /// An account of another chain, exactly as the service describes it.230    private func other(_ account: RecoverySheet.ChainAccount) -> some View {231        QListSection(footnote: account.note) {232            // by the identifier the sheet carries; a sheet written before it existed is matched by its name233            if let descriptor = account.chainDescriptor ?? ChainRegistry.all.first(where: { $0.displayName == account.chain }) {234                SecChainHeader(network: descriptor.qNetwork, detail: account.scheme)235            } else {236                SecRowLabel(title: account.chain, subtitle: account.scheme)237            }238            SecFactRow(label: "Networks", value: account.networks)239            SecFactRow(label: "Derivation path", value: account.derivationPath)240            if let address = account.address { value(account.extendedPublicKey == nil ? "Address" : "First receive address", address) }241            if let key = account.extendedPublicKey { value("Extended public key", key) }242            if let descriptor = account.descriptor { value("Receive descriptor", descriptor) }243        }244    }245246    private func share(_ sheet: RecoverySheet, isPrivate: Bool) -> some View {247        let text = sheet.plainText()248        let title = isPrivate ? "QYVORA recovery sheet (PRIVATE: contains the recovery phrase)" : "QYVORA recovery sheet (public material)"249        return ViewThatFits(in: .horizontal) {250            HStack(spacing: QSpace.m) { shareButtons(text, title) }251            VStack(spacing: QSpace.m) { shareButtons(text, title) }252        }253    }254255    @ViewBuilder private func shareButtons(_ text: String, _ title: String) -> some View {256        ShareLink(item: text) {257            Label("Share as text", systemImage: "doc.plaintext").frame(maxWidth: .infinity)258        }259        .buttonStyle(.qSecondary)260        ShareLink(item: SharedPDF(title: title, text: text), preview: SharePreview(title)) {261            Label("Share as PDF", systemImage: "doc.richtext").frame(maxWidth: .infinity)262        }263        .buttonStyle(.qSecondary)264    }265266    // MARK: Recovering elsewhere267268    @ViewBuilder private func guide(_ sheet: RecoverySheet) -> some View {269        SectionHeader("Recovering in another wallet", subtitle: "What each chain needs besides the \(sheet.mnemonicWordCount) words.")270            .padding(.top, QSpace.s)271        if sheet.usesPassphrase {272            WarningBanner(.warning, title: "This wallet uses a BIP-39 passphrase",273                          message: "Every chain below also needs the passphrase, typed exactly. Without it the same words open a different, empty wallet.")274        }275        ForEach(ChainRegistry.groups) { group in276            QListSection(group.title, footnote: group.accountNote) {277                ForEach(SecRecoveryGuide.entries(group)) { entry in278                    VStack(alignment: .leading, spacing: QSpace.s) {279                        HStack(spacing: QSpace.s) {280                            ChainGlyph(entry.chain.qNetwork, size: .small)281                            Text(group.family == .evm ? "Every EVM network" : entry.chain.displayName).font(QFont.headline).foregroundStyle(QColor.textPrimary)282                        }283                        Text(entry.chain.derivationPath).font(QFont.monoLarge).foregroundStyle(QColor.textPrimary)284                        Text(entry.standard).font(QFont.caption).foregroundStyle(QColor.textSecondary)285                        Text(entry.advice).font(QFont.callout).foregroundStyle(QColor.textSecondary).fixedSize(horizontal: false, vertical: true)286                    }287                    .frame(maxWidth: .infinity, alignment: .leading)288                    .padding(.vertical, QSpace.m)289                    .accessibilityElement(children: .combine)290                }291            }292        }293        Explanation("The recovery phrase restores the keys of every chain above. It does not restore the post-quantum identity or the other vault records: those travel in an encrypted backup, in QYVORA only.")294    }295296    // MARK: Private sheet297298    @ViewBuilder private var privateSection: some View {299        SectionHeader("Sheet with the recovery phrase", subtitle: "A separate document, for a safe or a sealed envelope.")300            .padding(.top, QSpace.s)301            .id("private")302        if let privateSheet, let material = privateSheet.privateMaterial {303            WarningBanner(.critical, title: "This version contains the recovery phrase",304                          message: "Whoever obtains it controls the funds on every chain. Print it on a printer you trust, or save it only to storage that is itself encrypted. Do not send it by e-mail or message.")305            if screenshotTaken {306                WarningBanner(.critical, title: ScreenshotWarning.title, message: ScreenshotWarning.message)307            }308            SeedPhraseGrid(words: material.mnemonic.split(separator: " ").map(String.init), masked: false, protected: true)309            if material.passphrase != nil {310                Explanation("The BIP-39 passphrase is included in the shared document.")311            }312            share(privateSheet, isPrivate: true)313                .privacySensitive()314            Button { clearPrivate() } label: { Label("Remove the phrase from this screen", systemImage: "eye.slash") }315                .buttonStyle(.qSecondary)316        } else {317            QListSection(footnote: "By default the sheet holds nothing that can spend. Adding the recovery phrase turns it into a full copy of the wallet in clear text.") {318                Toggle(isOn: $acknowledged) {319                    Text("I understand that this document alone gives control of the funds")320                        .font(QFont.callout)321                        .foregroundStyle(QColor.textPrimary)322                        .fixedSize(horizontal: false, vertical: true)323                }324                .tint(QColor.violet)325                .padding(.vertical, QSpace.m)326            }327            SecInlineError(error)328            LoadingButton("Include the recovery phrase", loadingTitle: "Reading the vault", systemImage: "exclamationmark.lock",329                          state: busy ? .loading : .idle, prominence: .secondary) { reauthenticate = true }330                .disabled(!acknowledged)331        }332    }333334    private func clearPrivate() {335        privateSheet = nil336        acknowledged = false337    }338339    private func load() async {340        guard sheet == nil else { return }341        do {342            sheet = try await store.run { try await $0.recoverySheet() }343            loadError = nil344        } catch {345            loadError = SecurityError.text(error)346        }347    }348349    private func loadPrivate() {350        guard !busy else { return }351        busy = true352        error = nil353        Task {354            do {355                privateSheet = try await store.run { try await $0.recoverySheet(includePrivateMaterial: true) }356            } catch {357                self.error = SecurityError.text(error)358            }359            busy = false360        }361    }362}363
Files main
Menu

Theme