Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/OnboardingTests.swift8// Module : Tests9// 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 Foundation42import Testing43import QyvoraMath44import QyvoraCore45import QyvoraBitcoin46import QyvoraEthereum47import QyvoraNetworking48import QyvoraStorage49import QyvoraVault50@testable import QyvoraWallet5152@Suite(.readsMainnetPolicy) struct OnboardingTests {53 @Test func createWalletStoresPhraseAndPublicData() async throws {54 let h = try await Harness.make()55 defer { h.cleanup() }56 #expect(await h.service.snapshot().hasWallet == false)57 #expect(await walletError { try await h.service.syncBitcoin() } == .noWallet)5859 let words = try await h.service.createWallet(password: Harness.password)60 #expect(words.count == 24)61 #expect(BIP39.isValid(words))62 let profile = await h.service.currentProfile()63 #expect(profile.kind == .full)64 #expect(profile.bitcoinNetwork == .signet && profile.ethereumNetwork == .sepolia)65 #expect(profile.bitcoinAccounts["test"]?.extendedPublicKey.hasPrefix("tpub") == true)66 #expect(profile.bitcoinAccounts["test"]?.masterFingerprint?.count == 8)67 #expect(profile.ethereumAddress != nil)68 #expect(profile.passwordQuality != nil)69 #expect(profile.recoveryPhraseVerified == false)7071 // the public data matches an independent derivation from the words72 let master = try ExtendedKey.master(seed: try BIP39.seed(mnemonic: words))73 let account = try BIP84Account(master: master, network: .signet)74 #expect(try await h.receive(0) == account.address(chain: .receive, index: 0).string)75 #expect(profile.ethereumAddress == (try EthereumAddress(publicKey: try master.derive(StandardPaths.ethereum()).publicKey)))7677 // vault content and state78 #expect(await h.vault.isUnlocked)79 #expect(try await h.vault.report().recordCounts == ["recoveryPhrase": 1, "watchOnlyAccount": 1])80 #expect(try await h.service.revealRecoveryPhrase() == words)81 var shuffled = words82 shuffled.swapAt(0, 23)83 if shuffled != words { #expect(try await h.service.verifyPhraseBackup(words: shuffled) == false) }84 #expect(await h.service.currentProfile().recoveryPhraseVerified == false)85 #expect(try await h.service.verifyPhraseBackup(words: words))86 #expect(await h.service.currentProfile().recoveryPhraseVerified)8788 #expect(await walletError { try await h.service.createWallet(password: "x") } == .walletAlreadyExists)89 #expect(await walletError { try await h.service.importWallet(words: Harness.abandon, password: "x") } == .walletAlreadyExists)9091 // lock / unlock92 await h.service.lock()93 #expect(await walletError { try await h.service.revealRecoveryPhrase() } == .vaultLocked)94 #expect(await walletError { try await h.service.unlock(password: "wrong") } == .wrongPassword)95 try await h.service.unlock(password: Harness.password)96 #expect(await h.service.vaultStatus() == VaultStatus(exists: true, isUnlocked: true, biometricEnabled: false, pinEnabled: false))9798 // the profile survives a restart; secrets stay in the vault file only99 let again = try await Harness.make(directory: h.directory, configure: false)100 #expect(await again.service.currentProfile() == h.service.currentProfile())101 let stored = String(decoding: try Data(contentsOf: h.directory.appendingPathComponent("wallet-profile.json")), as: UTF8.self)102 for w in Set(words) where w.count > 4 { #expect(!stored.contains("\"\(w)\"") && !stored.contains(" \(w) ")) }103104 try await h.service.deleteWallet()105 #expect(await h.service.snapshot().hasWallet == false)106 #expect(await h.vault.exists == false)107 #expect(!FileManager.default.fileExists(atPath: h.directory.appendingPathComponent("wallet-profile.json").path))108 }109110 @Test func importWalletMatchesPublishedVectors() async throws {111 let h = try await Harness.abandonWallet()112 defer { h.cleanup() }113 #expect(try await h.receive(0) == Harness.abandonFirstTestAddress)114 #expect(await h.service.currentProfile().ethereumAddress?.checksummed == Harness.abandonEthereumAddress)115 #expect(await h.service.currentProfile().recoveryPhraseVerified)116 #expect(try await h.service.nextReceiveAddress().address == Harness.abandonFirstTestAddress)117 #expect(try await h.service.nextReceiveAddress().path == "m/84'/1'/0'/0/0")118 #expect(await h.service.snapshot().bitcoinReceiveAddress == Harness.abandonFirstTestAddress)119 #expect(await h.service.snapshot().bitcoin == .notLoaded)120121 // sloppy input is normalized122 let other = try await Harness.make()123 defer { other.cleanup() }124 try await other.service.importWallet(words: [" ABANDON abandon "] + Array(Harness.abandon.dropFirst(2)), password: Harness.password)125 #expect(try await other.receive(0) == Harness.abandonFirstTestAddress)126127 // a passphrase gives another wallet and is kept in the vault128 let third = try await Harness.make()129 defer { third.cleanup() }130 try await third.service.importWallet(words: Harness.abandon, passphrase: "TREZOR", password: Harness.password)131 #expect(try await third.receive(0) != Harness.abandonFirstTestAddress)132 #expect(await third.service.currentProfile().usesPassphrase)133 #expect(try await third.vault.report().recordCounts == ["recoveryPhrase": 1, "bip39Passphrase": 1, "watchOnlyAccount": 1])134 }135136 @Test func importRejectsInvalidPhrases() async throws {137 let h = try await Harness.make()138 defer { h.cleanup() }139 var bad = Harness.abandon140 bad[11] = "abandon"141 guard case .invalidRecoveryPhrase(let text)? = await walletError({ try await h.service.importWallet(words: bad, password: Harness.password) }) else {142 Issue.record("expected invalidRecoveryPhrase")143 return144 }145 #expect(text.contains("checksum"))146 bad[3] = "qyvora"147 guard case .invalidRecoveryPhrase(let unknown)? = await walletError({ try await h.service.importWallet(words: bad, password: Harness.password) }) else {148 Issue.record("expected invalidRecoveryPhrase")149 return150 }151 #expect(unknown.contains("Word 4"))152 guard case .invalidRecoveryPhrase? = await walletError({ try await h.service.importWallet(words: ["abandon"], password: Harness.password) }) else {153 Issue.record("expected invalidRecoveryPhrase")154 return155 }156 guard case .weakPassword? = await walletError({ try await h.service.importWallet(words: Harness.abandon, password: "") }) else {157 Issue.record("expected weakPassword")158 return159 }160 // nothing was created by the failed attempts161 #expect(await h.vault.exists == false)162 #expect(await h.service.currentProfile().kind == nil)163 }164165 @Test func watchOnlyWalletHasNoSecrets() async throws {166 let full = try await Harness.abandonWallet()167 defer { full.cleanup() }168 let tpub = try #require(await full.service.currentProfile().bitcoinAccounts["test"]?.extendedPublicKey)169170 let h = try await Harness.make()171 defer { h.cleanup() }172 try await h.service.importWatchOnly(bitcoinExtendedPublicKey: tpub, ethereumAddress: Harness.abandonEthereumAddress)173 #expect(await h.service.currentProfile().kind == .watchOnly)174 #expect(await h.vault.exists == false)175 #expect(try await h.receive(0) == Harness.abandonFirstTestAddress)176 #expect(await walletError { try await h.service.revealRecoveryPhrase() } == .watchOnly)177 #expect(await walletError { try await h.service.recoverySheet() } == .watchOnly)178 #expect(await walletError { try await h.service.unlock(password: "x") } == .noWallet)179 #expect(await walletError { try await h.service.importWatchOnly(bitcoinExtendedPublicKey: tpub, ethereumAddress: nil) } == .walletAlreadyExists)180 let shield = await h.service.shieldReport()181 #expect(shield.report.vaultSecurity.findings.map(\.id) == ["vault.watch-only"])182183 // input validation184 let fresh = try await Harness.make()185 defer { fresh.cleanup() }186 guard case .invalidInput? = await walletError({ try await fresh.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: nil) }) else {187 Issue.record("expected invalidInput")188 return189 }190 guard case .invalidInput? = await walletError({ try await fresh.service.importWatchOnly(bitcoinExtendedPublicKey: "tpubnonsense", ethereumAddress: nil) }) else {191 Issue.record("expected invalidInput")192 return193 }194 // a private key is refused with an explicit message195 let master = try ExtendedKey.master(seed: try BIP39.seed(mnemonic: Harness.abandon))196 let tprv = try master.derive(StandardPaths.bip84Account(.signet)).serialized(.tprv)197 guard case .invalidInput(let message)? = await walletError({ try await fresh.service.importWatchOnly(bitcoinExtendedPublicKey: tprv, ethereumAddress: nil) }) else {198 Issue.record("expected invalidInput")199 return200 }201 #expect(message.contains("private"))202 // wrong EIP-55 checksum203 guard case .invalidAddress? = await walletError({204 try await fresh.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: "0x9858EfFD232B4033E47d90003D41EC34EcaEda95")205 }) else {206 Issue.record("expected invalidAddress")207 return208 }209 #expect(await fresh.service.currentProfile().kind == nil)210 // Ethereum only211 try await fresh.service.importWatchOnly(bitcoinExtendedPublicKey: nil, ethereumAddress: Harness.abandonEthereumAddress)212 guard case .featureUnavailable? = await walletError({ try await fresh.service.syncBitcoin() }) else {213 Issue.record("expected featureUnavailable")214 return215 }216 }217218 @Test func pinLockoutBiometricsAndAutoLock() async throws {219 let h = try await Harness.abandonWallet()220 defer { h.cleanup() }221 // one rule everywhere: a PIN is exactly six digits, which is what the PIN pad of the lock screen can enter222 #expect(WalletService.pinLength == 6)223 for bad in ["123", "12345", "1234567", "12345678", "", "12345a", "abcdef", "12 456", "123456", "123456\n"] {224 guard case .invalidInput(let reason)? = await walletError({ try await h.service.enablePIN(bad) }) else {225 Issue.record("\(bad.debugDescription) must be refused as a PIN")226 return227 }228 #expect(reason == WalletService.pinRejection(bad) && reason.contains("PIN") && reason.contains("digits"))229 #expect(await h.service.vaultStatus().pinEnabled == false)230 }231 #expect(WalletService.pinRejection("1234567") == "A PIN is exactly 6 digits.")232 #expect(WalletService.pinRejection("12345a") == "A PIN is made of digits only (0 to 9).")233 #expect(WalletService.pinRejection("481516") == nil)234 try await h.service.enablePIN("481516")235 #expect(await h.service.vaultStatus().pinEnabled)236 await h.service.lock()237 #expect(await walletError { try await h.service.unlock(pin: "000000") } == .wrongPIN(retryAllowedAt: nil))238 #expect(await walletError { try await h.service.unlock(pin: "000001") } == .wrongPIN(retryAllowedAt: nil))239 guard case .wrongPIN(let retry?)? = await walletError({ try await h.service.unlock(pin: "000002") }) else {240 Issue.record("expected a delay after the third wrong PIN")241 return242 }243 #expect(retry.timeIntervalSince(h.clock.now) == 60)244 h.clock.advance(20)245 // even the right PIN is refused during the delay, with the remaining time246 guard case .pinLocked(let until, let remaining)? = await walletError({ try await h.service.unlock(pin: "481516") }) else {247 Issue.record("expected pinLocked")248 return249 }250 #expect(until == retry)251 #expect(remaining == 40)252 h.clock.advance(41)253 try await h.service.unlock(pin: "481516")254 #expect(await h.vault.isUnlocked)255256 // biometrics257 await h.service.lock()258 guard case .biometricUnavailable? = await walletError({ try await h.service.unlockWithBiometrics() }) else {259 Issue.record("expected biometricUnavailable")260 return261 }262 try await h.service.unlock(password: Harness.password)263 try await h.service.enableBiometrics(useSecureEnclave: false)264 await h.service.lock()265 try await h.service.unlockWithBiometrics(prompt: "Unlock")266 #expect(await h.service.vaultStatus() == VaultStatus(exists: true, isUnlocked: true, biometricEnabled: true, pinEnabled: true))267268 // auto-lock269 try await h.service.setAutoLockPolicy(.after(seconds: 120))270 await h.service.noteActivity()271 h.clock.advance(100)272 #expect(await h.service.autoLockIfNeeded() == false)273 h.clock.advance(30)274 #expect(await h.service.autoLockIfNeeded())275 #expect(await h.vault.isUnlocked == false)276 guard case .invalidInput? = await walletError({ try await h.service.setAutoLockPolicy(.after(seconds: 0)) }) else {277 Issue.record("expected invalidInput")278 return279 }280281 // vault management282 try await h.service.unlock(password: Harness.password)283 #expect(await walletError { try await h.service.changePassword(current: "nope", new: "quiet lantern 58 marsh") } == .wrongPassword)284 // QYV-APP-001: a weak new password is refused by the service, whatever the form did285 guard case .weakPassword? = await walletError({ try await h.service.changePassword(current: Harness.password, new: "password") }) else {286 Issue.record("a weak password must be refused")287 return288 }289 try await h.service.changePassword(current: Harness.password, new: "quiet lantern 58 marsh")290 #expect(try #require(await h.service.currentProfile().passwordQuality) >= .fair)291 let rotation = try await h.service.rotateMasterKey(password: "quiet lantern 58 marsh", pin: "481516")292 // the recovery phrase and the account binding (QYV-SVC-011)293 #expect(rotation.recordsReencrypted == 2 && rotation.pinSlotKept)294 #expect(try await h.service.verifyVaultIntegrity().recordsVerified == 2)295 #expect(try await h.service.vaultReport().keyEpoch == 2)296 try await h.service.disablePIN()297 try await h.service.disableBiometrics()298 #expect(await h.service.vaultStatus() == VaultStatus(exists: true, isUnlocked: true, biometricEnabled: false, pinEnabled: false))299 #expect(h.backend.requests.isEmpty)300 }301302 @Test func settingsAreValidatedAndPersisted() async throws {303 let h = try await Harness.abandonWallet()304 defer { h.cleanup() }305 var endpoints = FakeBackend.endpoints306 endpoints.esplora["signet"] = ["http://example.com/api"]307 guard case .invalidInput? = await walletError({ try await h.service.setEndpoints(endpoints) }) else {308 Issue.record("expected invalidInput")309 return310 }311 endpoints.esplora["signet"] = ["http://192.168.1.20:3000/api", "https://esplora.test/api"]312 try await h.service.setEndpoints(endpoints)313 // (a name that is no network at all: "dogecoin" is one since the UTXO upgrade)314 endpoints.esplora["dogecoin2"] = ["https://x.test"]315 guard case .invalidInput? = await walletError({ try await h.service.setEndpoints(endpoints) }) else {316 Issue.record("expected invalidInput")317 return318 }319 try await h.service.setDisplayCurrency(.cad)320 try await h.service.setAddressLabel(" Rent ", for: Harness.abandonFirstTestAddress)321 let op = try #require(BitcoinOutPoint(txid: String(repeating: "ab", count: 32), vout: 1))322 try await h.service.setFrozen(true, outPoint: op)323 let reopened = try await Harness.make(directory: h.directory, configure: false)324 let p = await reopened.service.currentProfile()325 #expect(p.displayCurrency == .cad)326 #expect(p.addressLabels == [Harness.abandonFirstTestAddress: "Rent"])327 #expect(p.frozenUTXOs == [op.description])328 #expect(p.endpoints == endpoints.with { $0.esplora["dogecoin2"] = nil })329 try await h.service.setAddressLabel(nil, for: Harness.abandonFirstTestAddress)330 try await h.service.setFrozen(false, outPoint: op)331 #expect(await h.service.currentProfile().addressLabels.isEmpty)332 #expect(await h.service.currentProfile().frozenUTXOs.isEmpty)333 try await h.service.resetEndpoints()334 #expect(await h.service.currentProfile().endpoints == .default)335 }336}337338extension EndpointConfiguration {339 func with(_ change: (inout EndpointConfiguration) -> Void) -> EndpointConfiguration {340 var copy = self341 change(©)342 return copy343 }344}345