SPB Git

Repository Public

DevSelfTest.swift 7.8 KB 99 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/DevSelfTest.swift3// Description: DEVELOPMENT VARIANT ONLY: scripted end-to-end checks of the SIGNED app against the local throwaway stack (real API, real isolated signer process, test keys, no real funds). Results: <container>/Library/Application Support/SPWallet/selftest.json.4#if SPW_DEV5import Foundation6import SPWalletCore78@MainActor enum DevSelfTest {9    struct Result: Codable { let name: String; let ok: Bool; let detail: String }10    static var results: [Result] = []11    static func check(_ name: String, _ ok: Bool, _ detail: String = "") { results.append(Result(name: name, ok: ok, detail: detail)); log.info("selftest \(ok ? "PASS" : "FAIL", privacy: .public) \(name, privacy: .public) \(detail, privacy: .public)") }1213    static func run(model: AppModel) async {14        results = []15        check("session.signed-in", model.phase == .signedIn, "\(model.phase)")16        await model.refreshAll()17        check("networks.loaded", (model.networks?.value.count ?? 0) >= 20, "\(model.networks?.value.count ?? 0) networks")18        check("accounts.from-signer", model.accounts?.value.signerReachable == true && !(model.accounts?.value.accounts.isEmpty ?? true), "\(model.accounts?.value.accounts.count ?? 0) addresses")19        check("portfolio.loaded", model.portfolio != nil && model.portfolio?.fromCache == false)20        check("portfolio.no-invented-balance", model.portfolio?.value.balances.allSatisfy { $0.amount != nil || $0.error != nil } ?? false)21        check("security.signer-reachable", model.security?.value.signer.reachable == true)22        check("security.not-halted", model.security?.value.signer.halted == false)23        // the session token is in the keychain, not in defaults or files24        check("session.token-in-keychain", KeychainTokenStore(service: AppEnvironment.keychainService).load() != nil)2526        // --- transfer: wrong inputs are refused before anything is prepared27        let flow = SendFlow(model: model)28        flow.network = "base"; flow.asset = "native"; flow.to = "0x70997970C51812dc3A010C7d01b50e0d17dc79C9"; flow.amount = "0.001"29        check("send.bad-checksum-refused-locally", flow.formProblem != nil, flow.formProblem ?? "")30        flow.to = model.address(on: "base") ?? ""31        check("send.own-address-refused", flow.formProblem != nil, flow.formProblem ?? "")32        flow.to = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8"; flow.amount = "0.0000000000000000001"33        check("send.too-many-decimals-refused", flow.formProblem != nil, flow.formProblem ?? "")3435        // --- transfer on the local fork (only when the stack was started with `up-fork`: 1 fake ETH on a local Base fork)36        let funded = model.portfolio?.value.balances.first { $0.network == "base" && $0.asset == "native" }?.isNonZero == true37        if funded {38            // a fresh random destination: well-known test addresses carry code on mainnet and are refused as contracts39            flow.to = "0x" + (0..<20).map { _ in String(format: "%02x", UInt8.random(in: 0...255)) }.joined()40            flow.amount = "0.001"41            await flow.prepare()42            check("send.prepared-and-verified", flow.step == .review && flow.approval != nil, flow.error ?? "")43            if let a = flow.approval {44                check("send.intent-matches-form", a.intent.to == flow.addressCheck?.normalized && a.intent.amount == "1000000000000000" && a.intent.network == "base" && a.intent.kind == .transfer)45                check("send.challenge-is-intent-hash", a.approval.options.challengeData == a.approval.digest)46                // a tampered intent must not verify against the same challenge47                var j = a.intent.served; if case .object(var o) = j { o["to"] = .string("0x000000000000000000000000000000000000dEaD"); j = .object(o) }48                let forged = try? Intent(served: j)49                let rejected: Bool = { guard let forged else { return true }; do { _ = try ApprovalBinding.verify(forged, options: a.approval.options, rpId: model.configuration.rpId); return false } catch { return true } }()50                check("send.tampered-intent-refused", rejected)51                // the owner dismisses the passkey sheet: nothing is signed, the proposal stays pending52                DevPasskey.refuse = true; await flow.approve(); DevPasskey.refuse = false53                let still = try? await model.transfers.proposal(a.proposal.id)54                check("send.cancelled-passkey-signs-nothing", flow.step == .review && still?.state == .pendingApproval, "\(String(describing: still?.state))")55                await flow.approve()56                check("send.approved-tracking", flow.step == .tracking, flow.error ?? "")57                var last: ProposalState?58                for _ in 0..<150 { last = flow.tracked?.state; if last?.isTerminal == true { break }; try? await Task.sleep(for: .seconds(1)) }59                check("send.terminal-state-from-chain", last == .finalized || last == .notBroadcast, "\(String(describing: last)) history=\(flow.history.map { $0.1.rawValue })")60                check("send.never-success-before-finalized", flow.history.filter { $0.1.isSuccess }.count <= 1 && flow.history.last?.1 == last)61                // replaying the same assertion-bearing approval is refused by the server62                do { _ = try await model.transfers.approve(a, with: model.authenticator); check("send.replay-refused", false) } catch { check("send.replay-refused", true, model.describe(error)) }63            }64        } else {65            flow.amount = "0.001"66            check("send.over-balance-refused-locally", flow.formProblem != nil, flow.formProblem ?? "")67            // and by the server, when asked directly68            do { _ = try await model.transfers.draft(TransferRequest(network: "base", asset: "native", to: "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", amount: "0.001"), idempotencyKey: APIClient.newIdempotencyKey()); check("send.unfunded-refused-by-server", false, "a draft was created") }69            catch { check("send.unfunded-refused-by-server", true, model.describe(error)) }70        }7172        // --- emergency halt is NOT exercised here on purpose when other tests follow; run with -spwSelfTestHalt YES73        if UserDefaults.standard.bool(forKey: "spwSelfTestHalt") {74            do { try await model.wallet.emergencyHalt(); await model.refreshAll()75                check("halt.engaged", model.security?.value.signer.halted == true && model.portfolio?.value.halted == true)76                let f2 = SendFlow(model: model); f2.network = "base"; f2.asset = "native"; f2.to = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8"; f2.amount = "0.0001"77                await f2.prepare()78                check("halt.blocks-transfers", f2.step == .form && f2.error != nil, f2.error ?? "")79            } catch { check("halt.engaged", false, model.describe(error)) }80        }8182        // --- offline: snapshots exist and survive a sign-out without erase83        let snap: Snapshot<Portfolio>? = await SnapshotStore.shared.load("portfolio")84        check("offline.snapshot-written", snap != nil)85        await model.signOut(eraseLocalData: false)86        check("signout.session-closed", model.phase == .signedOut && KeychainTokenStore(service: AppEnvironment.keychainService).load() == nil)87        check("offline.data-kept-for-consultation", model.hasSnapshots && model.portfolio != nil)88        do { _ = try await model.wallet.portfolio(); check("signout.api-refuses", false) } catch { check("signout.api-refuses", true) }89        await model.signIn()90        check("signin.again", model.phase == .signedIn)9192        let url = AppEnvironment.supportDirectory.appendingPathComponent("selftest.json")93        let enc = JSONEncoder(); enc.outputFormatting = [.prettyPrinted]94        try? enc.encode(results).write(to: url)95        log.info("selftest done: \(results.filter(\.ok).count)/\(results.count)")96    }97}98#endif99
Files main
Menu

Theme