SPB Git

Repository Public

SecurityDebug.swift 20.4 KB 351 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : App/Sources/Security/SecurityDebug.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// =============================================================================4041#if DEBUG42import SwiftUI43import QyvoraCore44import QyvoraBitcoin45import QyvoraEthereum46import QyvoraStorage47import QyvoraWallet48import notify4950/// DEBUG-only launch arguments of the security screens (screenshots, UI review). Not compiled in Release.51/// They complement `DebugLaunch`: select the tab with `-QYScreen shield` or `-QYScreen settings`, then the arguments52/// below. `-QYScreen settings` always shows the main shell, and the preparation runs there. `-QYScreen shield` follows53/// the real wallet state (onboarding without wallet, lock screen while locked): prepare the wallet with54/// `-QYDebugWallet watch` or `-QYDebugWallet create,unlock` (DebugWalletLaunch) so that the Shield is reachable.55///56///   -QYSecScreen <name>   vault | identity | identity-sign | identity-verify | identity-contact | recovery57///                         | reveal-phrase | verify-phrase | recovery-sheet | backup-create | backup-inspect58///                         | restore-backup | transfer-send | transfer-receive | cold | watch-only-export59///                         | cold-psbt | cold-ethereum | migration-plan | mainnet-warning60///                         The screen is pushed on the stack of the selected tab (Shield or Settings).61///   -QYSecSheet <name>    on the vault screen: changePassword | pinSetup | rotate | delete | reauth62///   -QYSecWallet <mode>   create : when the device has no wallet, creates a REAL one through the service, protected by63///                                  the throwaway password below, and unlocks it (the recovery phrase is discarded:64///                                  never send funds to such a wallet)65///                         watch  : when the device has no wallet, imports a REAL watch-only wallet: the BIP-8466///                                  account of the public test vector "abandon … about" on Signet and the public67///                                  address 0xf39F…2266 (Sepolia, Base Sepolia…), a public Solana devnet address and68///                                  a public TRON Nile address, so that the Shield shows measured exposure69///                         vector : when the device has no wallet, imports the same public test vector as a FULL70///                                  wallet (real `importWallet`), protected by the throwaway password71///   -QYSecChains <a,b>    chains to enable after the wallet exists (main-network identifiers of the registry:72///                         bitcoin,litecoin,dogecoin,bitcoin-cash,ethereum,base,…,solana,tron; "all" for every chain).73///                         A watch-only wallet can only enable the chains it has an account for.74///   -QYSecTestNet <a,b>   test networks to choose (bitcoin-testnet, solana-testnet, tron-shasta…)75///   -QYSecPrep <a,b>      identity : creates the wallet identity when there is none (real key generation)76///                         sync     : synchronizes every active chain once (real network requests)77///                         cold     : switches cold mode on78///                         psbt     : after "sync", builds a REAL unsigned payment of 1 500 sat from the synchronized79///                                    wallet to an address outside it and writes its PSBT (never broadcast) to80///                                    tmp/qy-security-debug-psbt.txt, to feed `-QYSecPayload` on the cold side81///   Networks and endpoints: `-QYSecScreen networks` (tour anchors mode, limits, chains-utxo, chains-evm, chains-solana,82///                         chains-tron, endpoints); `-QYSecScreen mainnet-warning` opens the warning over it;83///                         `-QYScreen endpoints` with `-QYSecAction endpoints-chain -QYSecEndpointChain <main id>`,84///                         `-QYSecAction endpoints-tron-key`; `-QYScreen endpoint-list -QYEndpointKind <kind> -QYNetwork85///                         <key>` with `-QYSecSheet endpoint-add`86///   -QYSecAuto YES        the re-authentication sheet submits the throwaway password by itself (a real unlock call)87///   -QYSecAction <name>   starts the main action of the pushed screen: go | export | rotate | private | integrity | sign88///   -QYSecPayload <text>  input of the cold-signing screens (PSBT, unsigned transaction); "sample-transfer" and89///                         "sample-unknown" build an unsigned Sepolia transaction for this wallet with the engine;90///                         "sample-psbt" builds a PSBT for the test-vector wallet (`-QYSecWallet vector`) that spends91///                         an output which does not exist on any chain: it can be reviewed and signed, never broadcast92///   -QYSecTour <a,b,c>    scroll anchors visited one by one, each time the Darwin notification93///                         "ai.spboucher.qyvora.debug.advance" is posted94///                         (`xcrun simctl spawn <device> notifyutil -p ai.spboucher.qyvora.debug.advance`)95///96/// Hooks for `DebugLaunch` (optional, one line each): `SecurityDebug.route` gives the `SecurityRoute` to append to a97/// navigation path, and `await SecurityDebug.prepare(store)` performs the wallet preparation.98enum SecurityDebug {99    enum Host { case shield, settings }100101    static var defaults: UserDefaults { .standard }102    /// Why the last debug preparation failed, for the debugger (nothing is written to the console).103    nonisolated(unsafe) static var lastFailure: String?104    static var screen: String? { defaults.string(forKey: "QYSecScreen") }105    static var sheet: String? { defaults.string(forKey: "QYSecSheet") }106    static var walletMode: String? { defaults.string(forKey: "QYSecWallet") }107    static var autoAuthenticate: Bool { defaults.bool(forKey: "QYSecAuto") }108    static var action: String? { defaults.string(forKey: "QYSecAction") }109    static var payload: String? { defaults.string(forKey: "QYSecPayload") }110    static var tour: [String] { (defaults.string(forKey: "QYSecTour") ?? "").split(separator: ",").map(String.init) }111    static let advanceNotification = "ai.spboucher.qyvora.debug.advance"112    static var preparation: Set<String> { Set((defaults.string(forKey: "QYSecPrep") ?? "").split(separator: ",").map(String.init)) }113114    /// Password of the wallets created here: the same throwaway value as `-QYDebugWallet` (DebugWalletLaunch), so that115    /// both sets of launch arguments work on the same simulator wallet.116    static var throwawayPassword: String { DebugLaunch.throwawayPassword }117    /// BIP-39 test vector published with the standard; public by definition.118    static let testVectorPhrase = Array(repeating: "abandon", count: 11) + ["about"]119    static let sepoliaTestAddress = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"120    /// A public account of Solana devnet (it holds SOL there; read on 2026-12-05).121    static let solanaDevnetAddress = "9B5XszUGdMaxCZ7uSQhPzdks5ZQSmWxrmzCSvtJ6Ns6g"122    /// A public account of TRON Nile.123    static let tronNileAddress = "TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs"124    static var chains: [String] { (defaults.string(forKey: "QYSecChains") ?? "").split(separator: ",").map(String.init) }125    static var testNetworks: [String] { (defaults.string(forKey: "QYSecTestNet") ?? "").split(separator: ",").map(String.init) }126127    /// The tab whose stack receives the debug screen.128    static var host: Host { DebugLaunch.screen == "shield" ? .shield : .settings }129130    static var route: SecurityRoute? {131        switch screen {132        case "vault": return .vault133        case "identity": return .identity134        case "identity-sign": return .identitySign135        case "identity-verify": return .identityVerify136        case "identity-contact": return .identityContact137        case "recovery": return .recovery138        case "reveal-phrase": return .revealPhrase139        case "verify-phrase": return .verifyPhrase140        case "recovery-sheet": return .recoverySheet141        case "backup-create": return .backupCreate142        case "backup-inspect": return .backupInspect143        case "restore-backup": return .restoreBackup144        case "transfer-send": return .transferSend(receiver: nil)145        case "transfer-receive": return .transferReceive146        case "cold": return .coldMode147        case "watch-only-export": return .watchOnlyExport148        case "cold-psbt": return .coldSign149        case "cold-ethereum": return .coldSign150        case "migration-plan": return .migrationPlan151        case "cold-sign": return .coldSign152        case "networks": return .networks153        default: return nil154        }155    }156157    @MainActor @ViewBuilder static func destination(_ route: SecurityRoute) -> some View {158        route.destination159    }160161    @MainActor private static var preparationTask: Task<Void, Never>?162163    /// Performs the wallet preparation asked on the command line, once per launch. Every step is a real service call.164    @MainActor static func prepare(_ store: WalletStore) async {165        if let running = preparationTask {166            await running.value167            return168        }169        let task = Task { await run(store) }170        preparationTask = task171        await task.value172    }173174    @MainActor private static func run(_ store: WalletStore) async {175        guard let service = store.service else { return }176        try? FileManager.default.removeItem(at: FileManager.default.temporaryDirectory.appendingPathComponent(markerName))177        let steps = preparation178        do {179            if await !service.snapshot().hasWallet {180                switch walletMode {181                case "create":182                    _ = try await service.createWallet(password: throwawayPassword)183                case "vector":184                    try await service.importWallet(words: testVectorPhrase, password: throwawayPassword)185                case "watch":186                    let account = try testVectorAccount()187                    try await service.importWatchOnly(bitcoinExtendedPublicKey: account.key, ethereumAddress: sepoliaTestAddress,188                                                      masterFingerprint: account.fingerprint, solanaAddress: solanaDevnetAddress,189                                                      tronAddress: tronNileAddress)190                default:191                    break192                }193            }194            let vault = await service.vaultStatus()195            if vault.exists, !vault.isUnlocked, walletMode == "create" || walletMode == "vector" {196                try await service.unlock(password: throwawayPassword)197            }198            if steps.contains("identity"), await service.vaultStatus().isUnlocked, try await service.identity() == nil {199                _ = try await service.createIdentity()200            }201            if await service.snapshot().hasWallet {202                let wanted = chains203                if wanted == ["all"] {204                    try await service.setEnabledChains(ChainRegistry.mainChains.map(\.id))205                } else if !wanted.isEmpty {206                    try await service.setEnabledChains(wanted.map { ChainID($0) })207                }208                for test in testNetworks { try await service.setTestNetwork(ChainID(test)) }209            }210            if steps.contains("cold") { try await service.setColdMode(true) }211        } catch {212            lastFailure = "preparation failed: \(SecurityError.text(error))"213        }214        await store.refresh()215        if steps.contains("sync"), await service.snapshot().hasWallet {216            await store.synchronize()217        }218        if steps.contains("psbt") { await writeSamplePSBT(service) }219        await writeMarker(service)220    }221222    static let markerName = "qy-security-debug-ready.txt"223    static let psbtName = "qy-security-debug-psbt.txt"224225    /// Builds an unsigned payment with the service and stores its PSBT text for the cold-signing screen.226    /// The destination is the first address of account 1 of the test vector: valid, and not part of the wallet.227    private static func writeSamplePSBT(_ service: WalletService) async {228        do {229            let master = try ExtendedKey.master(seed: try BIP39.seed(mnemonic: testVectorPhrase))230            let other = try master.derive(StandardPaths.bip84Account(.signet, account: 1)).neutered.serialized(.tpub)231            guard let destination = try BIP84Account(extendedKey: other, network: .signet, accountIndex: 1).addresses(chain: .receive, range: 0..<1).first?.string else { return }232            let plan = try await service.prepareBitcoinSend(to: destination, amount: 1_500, feeRate: FeeRate(satPerVByte: 2))233            writeDebugFile(try await service.exportPSBT(plan).text, name: psbtName)234        } catch {235            writeDebugFile("error: \(error)", name: psbtName)236        }237    }238239    /// Writes a file of this debug helper through `FileStore`, like every file the application writes: data240    /// protection and exclusion from backups apply to it too (it was written directly before, which the rule241    /// `qyvora-file-write-without-protection` reports). The name and the directory are unchanged.242    private static func writeDebugFile(_ text: String, name: String) {243        try? FileStore(root: FileManager.default.temporaryDirectory).write(Array(text.utf8), to: name, keepPrevious: false)244    }245246    /// Leaves a line in the temporary directory once the preparation is over, so that a screenshot script knows when247    /// to capture. It holds the state of the two chains (no secret, no address).248    private static func writeMarker(_ service: WalletService) async {249        let snapshot = await service.snapshot()250        func describe<T>(_ state: Availability<T>) -> String {251            switch state {252            case .available: return "available"253            case .unavailable(let reason): return "unavailable (\(reason))"254            case .notLoaded: return "not loaded"255            }256        }257        let chains = snapshot.chains.map { "\($0.id.rawValue)=\(describe($0.data))" }.joined(separator: " ")258        let text = "wallet=\(snapshot.hasWallet) unlocked=\(snapshot.vault.isUnlocked) mode=\(snapshot.networkMode.rawValue) \(chains) failure=\(lastFailure ?? "none")\n"259        writeDebugFile(text, name: markerName)260    }261262    /// One event per posted advance notification.263    static func advances() -> AsyncStream<Void> {264        AsyncStream { continuation in265            var token: Int32 = 0266            notify_register_dispatch(advanceNotification, &token, .main) { _ in continuation.yield() }267            let registered = token268            continuation.onTermination = { _ in notify_cancel(registered) }269        }270    }271272    /// An unsigned EIP-1559 transaction of the wallet's account on Sepolia, as "0x02…" text, built with the engine:273    /// a plain transfer of 0.001 ETH, or a call whose data is not an ERC-20 call (blind-signing review).274    static func sampleEthereumPayload(unknownCall: Bool) -> String? {275        guard let to = EthereumAddress("0x70997970C51812dc3A010C7d01b50e0d17dc79C8") else { return nil }276        let transaction = EIP1559Transaction(chainID: EthereumNetwork.sepolia.chainID, nonce: 0, maxPriorityFeePerGas: UInt256(1_500_000_000),277                                             maxFeePerGas: UInt256(30_000_000_000), gasLimit: unknownCall ? 90_000 : 21_000, to: to,278                                             value: unknownCall ? .zero : UInt256(1_000_000_000_000_000),279                                             data: unknownCall ? [0xde, 0xad, 0xbe, 0xef] + [UInt8](repeating: 0, count: 31) + [0x01] : [])280        return "0x" + transaction.unsignedPayload.map { String(format: "%02x", $0) }.joined()281    }282283    /// A syntactically valid PSBT for the test-vector account: one input paying the wallet's first receive script284    /// (100 000 sat, from a transaction identifier that exists nowhere), one output outside the wallet (60 000 sat)285    /// and one change output (39 000 sat). Test input for the review screen; it cannot be broadcast.286    static func samplePSBT() -> String? {287        do {288            let master = try ExtendedKey.master(seed: try BIP39.seed(mnemonic: testVectorPhrase))289            let account = try BIP84Account(master: master, network: .signet)290            let outside = try BIP84Account(master: master, network: .signet, accountIndex: 1)291            guard let outPoint = BitcoinOutPoint(hash: [UInt8](repeating: 0x11, count: 32), index: 0) else { return nil }292            let transaction = BitcoinTransaction(inputs: [.init(previousOutput: outPoint, sequence: 0xffff_fffd)], outputs: [293                .init(value: 60_000, scriptPubKey: try outside.scriptPubKey(chain: .receive, index: 0)),294                .init(value: 39_000, scriptPubKey: try account.scriptPubKey(chain: .change, index: 0)),295            ])296            var psbt = try PSBT(unsignedTransaction: transaction)297            psbt.inputs[0].witnessUTXO = .init(value: 100_000, scriptPubKey: try account.scriptPubKey(chain: .receive, index: 0))298            psbt.inputs[0].derivations = [.init(publicKey: try account.publicKey(chain: .receive, index: 0), fingerprint: master.fingerprint,299                                                path: account.path(chain: .receive, index: 0))]300            psbt.outputs[1].derivations = [.init(publicKey: try account.publicKey(chain: .change, index: 0), fingerprint: master.fingerprint,301                                                 path: account.path(chain: .change, index: 0))]302            return psbt.base64303        } catch {304            lastFailure = "sample PSBT failed: \(error)"305            return nil306        }307    }308309    /// Resolves `-QYSecPayload` for the Bitcoin cold-signing screen.310    static var bitcoinPayload: String? {311        payload == "sample-psbt" ? samplePSBT() : payload312    }313314    /// Resolves `-QYSecPayload` for the Ethereum cold-signing screen.315    static var ethereumPayload: String? {316        switch payload {317        case "sample-transfer": return sampleEthereumPayload(unknownCall: false)318        case "sample-unknown": return sampleEthereumPayload(unknownCall: true)319        default: return payload320        }321    }322323    /// Account public key (tpub) and master fingerprint of the test vector, derived with the engine.324    static func testVectorAccount() throws -> (key: String, fingerprint: String) {325        let master = try ExtendedKey.master(seed: try BIP39.seed(mnemonic: testVectorPhrase))326        let account = try master.derive(StandardPaths.bip84Account(.signet))327        return (try account.neutered.serialized(.tpub), master.fingerprint.map { String(format: "%02x", $0) }.joined())328    }329}330331/// Scrolls its content to the anchors of `-QYSecTour`, one per advance notification, in a loop.332struct SecurityDebugTour<Content: View>: View {333    @ViewBuilder let content: Content334335    var body: some View {336        ScrollViewReader { proxy in337            content.task {338                let anchors = SecurityDebug.tour339                guard !anchors.isEmpty else { return }340                var index = 0341                for await _ in SecurityDebug.advances() {342                    // the tour loops, so that every stop can be captured again at another appearance or text size343                    proxy.scrollTo(anchors[index % anchors.count], anchor: .top)344                    index += 1345                }346            }347        }348    }349}350#endif351
Files main
Menu

Theme