Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraWallet/WalletService+Shield.swift8// Module : Qyvora Wallet9// 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 QyvoraMath43import QyvoraCore44import QyvoraBitcoin45import QyvoraEthereum46import QyvoraVault47import QyvoraQuantumShield48import QyvoraMigration49import QyvoraIdentity50import QyvoraRecovery51import QyvoraSolana52import QyvoraTron5354/// The Quantum Shield report together with the migration plan built from what it measured.55public struct WalletShieldReport: Sendable, Equatable {56 /// Three separate sections (vault security, key exposure, network resistance). There is no overall score.57 public let report: ShieldReport58 public let migrationPlan: MigrationPlan59 /// When the Bitcoin data of the key-exposure section was read; nil when that chain was not measured.60 public let bitcoinMeasuredAt: Date?61 /// When the Ethereum data of the key-exposure section was read; nil when that chain was not measured.62 public let ethereumMeasuredAt: Date?63 /// True when a chain of the key-exposure section rests on a snapshot restored from the previous session: what is64 /// reported is the last known exposure as of the dates above, to be shown as such until a synchronization completes.65 public let isFromPreviousSession: Bool66 /// `QuantumShield.localCryptographyDisclaimer`: must be displayed with the report.67 public var disclaimer: String { report.disclaimer }68 /// When each active chain of the key-exposure section was read; a chain without entry was not measured.69 public internal(set) var measuredAt: [ChainID: Date] = [:]70 /// `QuantumShield.multiChainDisclaimer` when the wallet uses other chains than Bitcoin and Ethereum: must be71 /// displayed with the report too. nil otherwise.72 public internal(set) var additionalDisclaimer: String?73}7475/// Public description of the wallet's post-quantum identity.76public struct IdentitySummary: Sendable, Equatable {77 /// "qyvora-id:…" text form of the public identity.78 public let text: String79 /// 16 groups of four hexadecimal digits, to compare by eye or by voice.80 public let fingerprintText: String81 public let createdAt: Date82 /// Number of rotations recorded in the chain.83 public let rotationCount: Int84}8586public struct IdentityRotationResult: Sendable, Equatable {87 public let identity: IdentitySummary88 /// Binary `RotationCertificate` linking the previous identity to the new one; give it to peers who trusted the old one.89 public let certificate: Bytes90}9192/// What a transfer package says about itself once its envelope was opened and its signature verified, before anything93/// is restored.94public struct TransferPackageInspection: Sendable, Equatable {95 /// The identity that signed the package. Its fingerprint must be compared with the one the old device shows.96 public let sender: IdentitySummary97 /// Header of the encrypted backup carried by the package (date, record count, signer); still locked by its password.98 public let backup: BackupHeader99}100101/// A device-to-device transfer package: binary form and QR frames.102public struct TransferExport: Sendable, Equatable {103 public let package: Bytes104 public let frames: [String]105}106107extension WalletService {108 // MARK: Quantum Shield109110 static func isMigrationEnabled(_ capability: String) -> Bool { MigrationEngine.isEnabled(capability) }111112 static func capabilities(_ chain: MigrationEngine.Chain) -> [ProtocolCapability] {113 MigrationEngine.capabilities(for: chain).map {114 ProtocolCapability(id: $0.id, title: $0.title, detail: $0.detail,115 status: $0.status == .available ? .available : ($0.status == .planned ? .planned : .awaitingProtocol),116 requirement: $0.requirement, quantumResistant: $0.quantumResistant)117 }118 }119120 /// The registry chain of a UTXO network.121 static func migrationChain(_ network: BitcoinNetwork) -> MigrationEngine.Chain {122 switch network.coin {123 case .bitcoin: return .bitcoin124 case .litecoin: return .litecoin125 case .dogecoin: return .dogecoin126 case .bitcoinCash: return .bitcoinCash127 }128 }129130 /// The Quantum Shield report from the latest snapshots and the vault report, with the migration plan. No network.131 /// Sections that were not measured (never synchronized) say so instead of assuming anything.132 public func shieldReport() async -> WalletShieldReport {133 let vaultReport = try? await vault.report()134 let vaultInput = VaultSecurity.Input(135 report: vaultReport, passwordQuality: profile.passwordQuality, autoLock: profile.autoLock, lastBackup: profile.lastBackupDate,136 lastBackupSigned: profile.lastBackupSigned, recoveryPhraseVerified: profile.recoveryPhraseVerified,137 isWatchOnly: profile.kind == .watchOnly, now: now())138 var bitcoin: KeyExposure.BitcoinInput?139 if let b = bitcoinSnapshot {140 bitcoin = .init(network: b.network, utxos: b.utxos.map(\.utxo), activity: b.activity)141 }142 var ethereum: KeyExposure.EthereumInput?143 if let address = profile.ethereumAddress {144 let e = ethereumSnapshot145 ethereum = .init(network: profile.ethereumNetwork, address: address, outgoingTransactionCount: e?.latestNonce,146 openApprovals: e?.approvals.value.map { $0.map { TokenApprovalExposure(token: $0.token, spender: $0.spender, allowance: $0.allowance) } },147 capabilities: Self.capabilities(.ethereum))148 }149 // Section 3 lists every active chain with what it validates150 let active = Self.activeKinds(profile)151 var networks = [NetworkResistance.Input]()152 for kind in active {153 let descriptor = ChainRegistry.descriptor(kind)154 switch kind {155 case .utxo(let network):156 let registry = Self.migrationChain(network)157 networks.append(.init(chain: .init(network), networkName: descriptor.displayName,158 offersQuantumResistance: MigrationEngine.chainOffersQuantumResistance(registry), capabilities: Self.capabilities(registry),159 signatureSchemes: network.supportsTaproot ? nil : ["secp256k1 ECDSA"], networkID: descriptor.id.rawValue))160 case .evm(let network):161 networks.append(.init(chain: .init(network), networkName: descriptor.displayName,162 offersQuantumResistance: MigrationEngine.chainOffersQuantumResistance(.ethereum), capabilities: Self.capabilities(.ethereum),163 networkID: descriptor.id.rawValue))164 case .solana:165 networks.append(.init(chain: .solana, networkName: descriptor.displayName,166 offersQuantumResistance: MigrationEngine.chainOffersQuantumResistance(.solana), capabilities: Self.capabilities(.solana),167 networkID: descriptor.id.rawValue))168 case .tron:169 networks.append(.init(chain: .tron, networkName: descriptor.displayName,170 offersQuantumResistance: MigrationEngine.chainOffersQuantumResistance(.tron), capabilities: Self.capabilities(.tron),171 networkID: descriptor.id.rawValue))172 }173 }174 // what the wallet signs with, next to what each network validates (the registry's scheme: ECDSA on Bitcoin)175 for i in networks.indices {176 networks[i].walletSignatureScheme = networks[i].networkID.flatMap { ChainRegistry.descriptor(ChainID($0))?.signatureScheme }177 }178 // the two primary chains are always stated, as in QYVORA 1.0, even when their chain is not in the enabled list179 if !active.contains(.evm(profile.ethereumNetwork)) {180 networks.insert(.init(chain: .init(profile.ethereumNetwork), networkName: profile.ethereumNetwork.displayName,181 offersQuantumResistance: MigrationEngine.chainOffersQuantumResistance(.ethereum), capabilities: Self.capabilities(.ethereum),182 networkID: ChainRegistry.id(profile.ethereumNetwork).rawValue), at: 0)183 networks[0].walletSignatureScheme = "secp256k1 ECDSA"184 }185 if !active.contains(.utxo(profile.bitcoinNetwork)) {186 networks.insert(.init(chain: .bitcoin, networkName: profile.bitcoinNetwork.displayName,187 offersQuantumResistance: MigrationEngine.chainOffersQuantumResistance(.bitcoin), capabilities: Self.capabilities(.bitcoin),188 networkID: ChainRegistry.id(profile.bitcoinNetwork).rawValue), at: 0)189 networks[0].walletSignatureScheme = "secp256k1 ECDSA"190 }191192 // Section 2, account chains as a whole193 var accounts = [AccountKeyExposure.Input]()194 var measuredAt = [ChainID: Date]()195 var previous = bitcoinSnapshot?.isFromPreviousSession == true || ethereumSnapshot?.isFromPreviousSession == true196 if let b = bitcoinSnapshot { measuredAt[ChainRegistry.id(b.network)] = b.synchronizedAt }197 var otherCoins = [KeyExposure.BitcoinInput]()198 var unmeasuredCoins = [BitcoinNetwork]()199 var evmNetworks = [AccountKeyExposure.Network]()200 var evmApprovals = [AccountKeyExposure.NetworkApprovals]()201 var solanaNetworks = [AccountKeyExposure.Network]()202 var tronNetworks = [AccountKeyExposure.Network]()203 for kind in active {204 let descriptor = ChainRegistry.descriptor(kind)205 switch kind {206 case .utxo(let network):207 guard !Self.isPrimaryUTXO(network) else { break }208 guard let s = utxoCoinStates[network]?.snapshot else {209 unmeasuredCoins.append(network)210 continue211 }212 measuredAt[descriptor.id] = s.synchronizedAt213 previous = previous || s.isFromPreviousSession214 otherCoins.append(.init(network: network, utxos: s.utxos.map(\.utxo), activity: s.activity))215 case .evm(let network):216 // approvals are found in the history: a network without a history source cannot be measured, and is217 // not listed; the others are, measured or not (bounded: the enabled networks, read at synchronization)218 let hasHistorySource = !(profile.endpoints.ethereumIndexer[network.rawValue] ?? []).isEmpty219 let isPrimary = network == profile.ethereumNetwork220 guard let s = evmSnapshots[network] else {221 evmNetworks.append(.init(name: descriptor.displayName, publicKeyExposed: nil, evidence: "not synchronized"))222 if hasHistorySource { evmApprovals.append(.init(network: network, approvals: nil, isPrimary: isPrimary)) }223 continue224 }225 if hasHistorySource {226 evmApprovals.append(.init(network: network, approvals: s.approvals.value.map {227 $0.map { TokenApprovalExposure(token: $0.token, spender: $0.spender, allowance: $0.allowance) }228 }, isPrimary: isPrimary))229 }230 measuredAt[descriptor.id] = s.synchronizedAt231 previous = previous || s.isFromPreviousSession232 // the nonce is the evidence on every network, with or without history233 evmNetworks.append(.init(name: descriptor.displayName, publicKeyExposed: s.latestNonce > 0,234 evidence: s.latestNonce > 0 ? "account nonce \(s.latestNonce)" : "account nonce 0"))235 case .solana(let network):236 guard let r = solanaRecords[network] else {237 solanaNetworks.append(.init(name: descriptor.displayName, publicKeyExposed: nil, evidence: "not synchronized"))238 continue239 }240 measuredAt[descriptor.id] = r.synchronizedAt241 previous = previous || (r.isFromPreviousSession ?? false)242 solanaNetworks.append(.init(name: descriptor.displayName, publicKeyExposed: r.extras.accountExists, evidence: "account on chain"))243 case .tron(let network):244 guard let r = tronRecords[network] else {245 tronNetworks.append(.init(name: descriptor.displayName, publicKeyExposed: nil, evidence: "not synchronized"))246 continue247 }248 measuredAt[descriptor.id] = r.synchronizedAt249 previous = previous || (r.isFromPreviousSession ?? false)250 let sentInHistory = r.history?.contains { $0.direction == .sent || $0.direction == .selfTransfer } ?? false251 // "no history source" only when there is none: a history that could not be read, or that is longer252 // than what was read, says so253 let evidence = r.hasOutgoing == nil ? Self.tronUnmeasuredReason(r) : (r.hasOutgoing == true && !sentInHistory ? "transactions sent by the account, outside the history shown" : "history")254 tronNetworks.append(.init(name: descriptor.displayName, publicKeyExposed: r.hasOutgoing, evidence: evidence))255 }256 }257 // the EVM account has its entry as soon as one EVM network is enabled: one key for all of them258 if let address = profile.ethereumAddress, !evmNetworks.isEmpty {259 var account = AccountKeyExposure.Input(family: .evm, address: address.checksummed, networks: evmNetworks)260 account.approvals = evmApprovals261 accounts.append(account)262 }263 if let address = profile.solanaAddress, !solanaNetworks.isEmpty { accounts.append(.init(family: .solana, address: address, networks: solanaNetworks)) }264 if let address = profile.tronAddress, !tronNetworks.isEmpty { accounts.append(.init(family: .tron, address: address, networks: tronNetworks)) }265266 var shieldInput = ShieldReport.Input(vault: vaultInput, bitcoin: bitcoin, ethereum: ethereum, networks: networks,267 hasBitcoinAccount: !profile.bitcoinAccounts.isEmpty, accounts: accounts)268 shieldInput.otherCoins = otherCoins269 shieldInput.unmeasuredCoinNetworks = unmeasuredCoins270 let report = QuantumShield.analyze(shieldInput)271 let figures = report.migrationFigures272 // every UTXO coin with exposed outputs has its sweep step, not Bitcoin alone273 let coinFigures = figures.otherCoins.map {274 MigrationPlan.CoinExposure(chain: Self.migrationChain($0.network), name: $0.network.mainCounterpart.displayName, exposedUTXOs: $0.exposedUTXOs,275 reusedAddresses: $0.reusedAddresses)276 }277 var result = WalletShieldReport(report: report, migrationPlan: MigrationPlan.make(278 exposedBitcoinUTXOs: figures.exposedBitcoinUTXOs, reusedBitcoinAddresses: figures.reusedBitcoinAddresses,279 ethereumKeyExposed: figures.ethereumKeyExposed, openApprovals: figures.openApprovals, solanaAccount: figures.solanaAccountPublic,280 tronAccount: !tronNetworks.isEmpty && profile.tronAddress != nil, tronKeyExposed: figures.tronKeyExposed, otherCoins: coinFigures),281 bitcoinMeasuredAt: bitcoinSnapshot?.synchronizedAt, ethereumMeasuredAt: ethereumSnapshot?.synchronizedAt, isFromPreviousSession: previous)282 result.measuredAt = measuredAt283 if active.contains(where: { $0 != .utxo(profile.bitcoinNetwork) && $0 != .evm(profile.ethereumNetwork) }) {284 result.additionalDisclaimer = QuantumShield.multiChainDisclaimer285 }286 return result287 }288289 /// Why the exposure of a TRON account could not be measured, in a few words: there is no history index, the index290 /// did not answer, or the history is longer than what was read and its recent part shows nothing sent.291 static func tronUnmeasuredReason(_ r: TronChainRecord) -> String {292 if r.history != nil { return "history longer than what was read" }293 if let reason = r.historyReason, reason.hasPrefix("No history index") { return "no history source" }294 return "the history could not be read"295 }296297 /// The migration plan alone: actionable steps (sweep, revoke) and steps blocked until the networks change.298 public func migrationPlan() async -> MigrationPlan {299 await shieldReport().migrationPlan300 }301302 // MARK: Identity303304 static let chainMagic = RotationChain.magic305306 private func identityRecords() async throws -> (identity: (UUID, Identity)?, chain: (UUID, RotationChain)?) {307 guard await vault.isUnlocked else { throw WalletError.vaultLocked }308 var current: (UUID, Identity, Date)?309 for r in try await vault.records(ofType: .identityKeys) {310 guard let id = try? Identity(privateEncoding: r.payload) else { continue }311 if current == nil || r.createdAt >= current!.2 { current = (r.id, id, r.createdAt) }312 }313 var chain: (UUID, RotationChain)?314 for r in try await vault.records(ofType: .custom) where Array(r.payload.prefix(4)) == Self.chainMagic {315 if let c = try? RotationChain(encoded: r.payload) { chain = (r.id, c) }316 }317 return (current.map { ($0.0, $0.1) }, chain)318 }319320 private func summary(_ identity: PublicIdentity, rotations: Int) -> IdentitySummary {321 IdentitySummary(text: identity.text, fingerprintText: identity.fingerprintText,322 createdAt: Date(timeIntervalSince1970: TimeInterval(identity.createdAt)), rotationCount: rotations)323 }324325 private func mapIdentity<T>(_ body: () async throws -> T) async throws -> T {326 do {327 return try await body()328 } catch let e as IdentityError {329 if case .vault(let v) = e { throw WalletError.from(v, now: now()) }330 throw WalletError.invalidPayload(WalletMessages.identity(e))331 } catch let e as BackupError {332 switch e {333 case .vault(let v): throw WalletError.from(v, now: now())334 case .authenticationFailed: throw WalletError.wrongPassword335 default: throw WalletError.invalidPayload(WalletMessages.backup(e))336 }337 } catch let e as RecoverySheetError {338 throw WalletError.invalidInput(WalletMessages.recoverySheet(e))339 }340 }341342 /// Creates the wallet's post-quantum identity (ML-DSA-87 + SLH-DSA, ML-KEM-1024 + X25519) and stores it in the vault.343 /// **Needs an unlocked vault.** Throws `invalidInput` when an identity already exists (use `rotateIdentity`).344 /// The identity signs backups and messages; it does not sign blockchain transactions.345 public func createIdentity() async throws(WalletError) -> IdentitySummary {346 try await run {347 try await mapIdentity {348 guard try await identityRecords().identity == nil else { throw WalletError.invalidInput("This wallet already has an identity.") }349 let identity = Identity.generate(createdAt: now())350 try await identity.store(in: vault)351 return summary(identity.publicIdentity, rotations: 0)352 }353 }354 }355356 /// The current identity, nil when none was created. **Needs an unlocked vault.**357 public func identity() async throws(WalletError) -> IdentitySummary? {358 try await run {359 try await mapIdentity {360 let records = try await identityRecords()361 return records.identity.map { summary($0.1.publicIdentity, rotations: records.chain?.1.certificates.count ?? 0) }362 }363 }364 }365366 /// The public identity as text ("qyvora-id:…") and QR frames, to show to a peer or to a new device.367 /// **Needs an unlocked vault.**368 public func exportPublicIdentity() async throws(WalletError) -> QRExport {369 try await run {370 try await mapIdentity {371 guard let current = try await identityRecords().identity else { throw WalletError.featureUnavailable("No identity has been created.") }372 return try QRExport.make(text: current.1.publicIdentity.text)373 }374 }375 }376377 /// Signs a message with the identity (binary `IdentitySignature`). `dual` adds the SLH-DSA signature (large and slow).378 /// **Needs an unlocked vault.**379 public func signMessage(_ message: Bytes, dual: Bool = false) async throws(WalletError) -> Bytes {380 try await run {381 try await mapIdentity {382 guard let current = try await identityRecords().identity else { throw WalletError.featureUnavailable("No identity has been created.") }383 try await requireFreshAuthentication()384 return try current.1.sign(message, purpose: .message, dual: dual).encoded()385 }386 }387 }388389 /// Verifies a message signature against a public identity given in text form. Pure; no vault, no network.390 public nonisolated func verifyMessage(_ message: Bytes, signature: Bytes, signer text: String, requireDual: Bool = false) -> Bool {391 guard let signer = try? PublicIdentity(text: text), let parsed = try? IdentitySignature(encoded: signature) else { return false }392 return parsed.verify(message: message, signer: signer, purpose: .message, requireDual: requireDual)393 }394395 /// Replaces the identity by a new one and records the rotation certificate (signed by both) in the vault; the old396 /// private keys are deleted. **Needs an unlocked vault.** `dual` adds SLH-DSA signatures to the certificate (slow).397 public func rotateIdentity(dual: Bool = true) async throws(WalletError) -> IdentityRotationResult {398 try await run {399 try await mapIdentity {400 let records = try await identityRecords()401 guard let current = records.identity else { throw WalletError.featureUnavailable("No identity has been created.") }402 try await requireFreshAuthentication()403 let next = try current.1.rotate(at: now(), dual: dual)404 var chain = records.chain?.1 ?? RotationChain()405 chain.append(next.certificate)406 try await next.identity.store(in: vault)407 if let existing = records.chain {408 try await vault.updateRecord(existing.0, payload: chain.encoded())409 } else {410 try await vault.addRecord(type: .custom, payload: chain.encoded())411 }412 try await vault.deleteRecord(current.0)413 return IdentityRotationResult(identity: summary(next.identity.publicIdentity, rotations: chain.certificates.count),414 certificate: next.certificate.encoded())415 }416 }417 }418419 /// The rotation chain (binary `RotationChain`), nil when the identity was never rotated. **Needs an unlocked vault.**420 public func identityRotationChain() async throws(WalletError) -> Bytes? {421 try await run { try await mapIdentity { try await identityRecords().chain?.1.encoded() } }422 }423424 // MARK: Recovery425426 /// The recovery sheet: accounts, extended public keys, descriptors, first addresses — and, only when427 /// `includePrivateMaterial` is true, the recovery phrase itself. **Needs an unlocked vault (full wallet).**428 public func recoverySheet(includePrivateMaterial: Bool = false, ethereumAddressCount: Int = 5) async throws(WalletError) -> RecoverySheet {429 try await run {430 try await mapIdentity {431 guard try requireWallet() == .full else { throw WalletError.watchOnly }432 guard await vault.isUnlocked else { throw WalletError.vaultLocked }433 // the sheet with the recovery phrase is a copy of the wallet in clear text434 if includePrivateMaterial { try await requireFreshAuthentication() }435 guard let record = try await vault.records(ofType: .recoveryPhrase).first else { throw WalletError.noWallet }436 let passphrase = try await vault.records(ofType: .bip39Passphrase).first.map { String(decoding: $0.payload, as: UTF8.self) } ?? ""437 return try RecoverySheet.make(mnemonic: PhraseCodec.words(record.payload), passphrase: passphrase,438 ethereumAddressCount: ethereumAddressCount, includePrivateMaterial: includePrivateMaterial, createdAt: now(),439 extraAccounts: Self.recoveryAccounts)440 }441 }442 }443444 /// The accounts of the chains the Recovery module does not derive itself: Solana and TRON. Public data only.445 /// Pass it as `extraAccounts` to `RecoverySheet.make` to get the complete sheet outside the service.446 public static let recoveryAccounts: @Sendable (_ bip39Seed: Bytes, _ master: ExtendedKey) throws -> [RecoverySheet.ChainAccount] = { seed, master in447 var tron = try master.derive(TronPaths.account())448 defer { tron.wipe() }449 // every network of the other UTXO coins: account path, account key, receive descriptor, first address450 let fingerprint = Hex.encode(master.fingerprint)451 var coins = [RecoverySheet.ChainAccount]()452 for network in BitcoinNetwork.allCases where !WalletService.isPrimaryUTXO(network) {453 var account = try UTXOAccount(master: master, network: network)454 defer { account.wipe() }455 let xpub = account.extendedPublicKey(slip132: false)456 let bip84 = account.purpose == .bip84457 let origin = "[\(fingerprint)/\(account.purpose.rawValue)h/\(network.coinType)h/0h]"458 coins.append(RecoverySheet.ChainAccount(459 chain: network.displayName, networks: network.isTest ? "test network" : "main network", derivationPath: account.accountPath.description,460 scheme: bip84 ? "BIP-84 native SegWit, secp256k1" : "BIP-44 legacy addresses, secp256k1",461 address: try account.address(chain: .receive, index: 0).string, extendedPublicKey: xpub,462 descriptor: "\(bip84 ? "wpkh" : "pkh")(\(origin)\(xpub)/0/*)",463 note: "The key is written with Bitcoin's version bytes (xpub / tpub); the address is the first receive address (…/0/0).",464 chainID: ChainRegistry.id(network).rawValue))465 }466 return coins + [467 RecoverySheet.ChainAccount(468 chain: "Solana", networks: "mainnet-beta, devnet and testnet: the same address", derivationPath: SolanaKeys.derivationPath().description,469 scheme: "SLIP-0010 Ed25519", address: try SolanaKeys.address(bip39Seed: seed).base58,470 note: "The address is the public key. In another wallet (Phantom, Solflare, Ledger) choose the path m/44'/501'/0'/0' if it asks.",471 chainID: ChainID.solana.rawValue),472 RecoverySheet.ChainAccount(473 chain: "TRON", networks: "mainnet, Nile and Shasta: the same address", derivationPath: TronPaths.account().description,474 scheme: "BIP-32 secp256k1", address: try TronAddress(publicKey: tron.publicKey).base58,475 note: "The path TronLink and Ledger use.", chainID: ChainID.tron.rawValue),476 ]477 }478479 private func backupBytes(password: String, sign: Bool) async throws -> (Bytes, Bool) {480 guard try requireWallet() == .full else { throw WalletError.watchOnly }481 // a backup file is stored wherever the user chose: its password is held to the same floor as the vault's482 try Self.requireAcceptablePassword(password)483 guard await vault.isUnlocked else { throw WalletError.vaultLocked }484 // a backup or a transfer package carries every secret of the vault out of the device485 try await requireFreshAuthentication()486 var signer: IdentityDetachedSigner?487 if sign {488 guard let current = try await identityRecords().identity else { throw WalletError.featureUnavailable("Create an identity before making a signed backup.") }489 signer = IdentityDetachedSigner(current.1)490 }491 return (try await BackupFile.export(from: vault, password: password, kdf: backupKDF, signer: signer, createdAt: now()), signer != nil)492 }493494 /// Writes an encrypted backup of every vault record ("QYVORA Backup v1", extension `.qyvora`) to `url`, protected by495 /// its own `password`. With `sign`, the backup is signed by the wallet's identity. **Needs an unlocked vault.**496 ///497 /// Nothing is recorded: the file written here is usually a temporary one that the user still has to save somewhere498 /// (and may not). Call `recordBackupSaved(signed:)` once the copy the user keeps really exists.499 @discardableResult500 public func createBackup(to url: URL, password: String, sign: Bool = false) async throws(WalletError) -> BackupHeader {501 try await run {502 try await mapIdentity {503 let (bytes, _) = try await backupBytes(password: password, sign: sign)504 do {505 try Data(bytes).write(to: url, options: [.atomic])506 } catch {507 throw WalletError.storage("The backup file cannot be written.")508 }509 return try BackupFile.inspect(bytes)510 }511 }512 }513514 /// Records that a backup created with `createBackup` was stored where the user chose (the file exporter reported515 /// success): the date of the last backup, shown in the vault screens and used by the Quantum Shield, is set to now.516 /// `signed` is `BackupHeader.isSigned` of that backup.517 public func recordBackupSaved(signed: Bool) async throws(WalletError) {518 try await run {519 guard try requireWallet() == .full else { throw WalletError.watchOnly }520 profile.lastBackupDate = now()521 profile.lastBackupSigned = signed522 try saveProfile()523 }524 }525526 /// A backup or a transfer package comes from outside, and its header says what the key derivation costs before527 /// the password can be checked (QYV-SVC-012): above `KDFParameters.deviceCeiling` it is refused, with the figures.528 static func requireAffordableKDF(_ kdf: KDFParameters) throws {529 let ceiling = KDFParameters.deviceCeiling530 guard kdf.isWithin(ceiling) else {531 throw WalletError.invalidPayload("This backup asks for a key derivation beyond what this device accepts "532 + "(\(kdf.argon2MemoryKiB / 1024) MiB of memory, \(kdf.argon2Iterations) passes, \(kdf.pbkdf2Iterations) PBKDF2 iterations; "533 + "the limits are \(ceiling.argon2MemoryKiB / 1024) MiB, \(ceiling.argon2Iterations) passes and \(ceiling.pbkdf2Iterations) iterations). "534 + "A backup made by QYVORA never does: the file was not made by QYVORA or was altered.")535 }536 }537538 private func readBackup(_ url: URL) throws -> Bytes {539 guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize, size > 0, size <= BackupFile.maximumFileSize,540 let data = try? Data(contentsOf: url) else { throw WalletError.storage("The backup file cannot be read.") }541 return Bytes(data)542 }543544 /// Header of a backup file (date, vault identifier, record count, signer) without the password.545 public func inspectBackup(at url: URL) async throws(WalletError) -> BackupHeader {546 try await run { try await mapIdentity { try BackupFile.inspect(try readBackup(url)) } }547 }548549 /// Restores a wallet on a device that has none: creates a vault protected by `newPassword`, imports every record of550 /// the backup, and rebuilds the public profile from the recovery phrase. The vault is left unlocked.551 /// A signed backup is verified; `expectedSignerFingerprint` (32 bytes) pins the signer. `wrongPassword` means the backup552 /// password is wrong or the file was modified.553 public func restoreBackup(from url: URL, backupPassword: String, newPassword: String, expectedSignerFingerprint: Bytes? = nil) async throws(WalletError) {554 try await run { try await mapIdentity { try await restore(try readBackup(url), backupPassword: backupPassword, newPassword: newPassword,555 expectedSignerFingerprint: expectedSignerFingerprint) } }556 }557558 private func restore(_ bytes: Bytes, backupPassword: String, newPassword: String, expectedSignerFingerprint: Bytes?) async throws {559 guard profile.kind == nil else { throw WalletError.walletAlreadyExists }560 guard await !vault.exists else { throw WalletError.walletAlreadyExists }561 try Self.requireAcceptablePassword(newPassword)562 try Self.requireAffordableKDF(try BackupFile.inspect(bytes).kdf)563 // everything is verified before the vault is created564 let contents = try BackupFile.open(bytes, password: backupPassword, verifier: IdentityDetachedVerifier(),565 expectedSignerFingerprint: expectedSignerFingerprint)566 guard let phrase = contents.records.first(where: { $0.type == .recoveryPhrase }) else {567 throw WalletError.invalidPayload("The backup holds no recovery phrase.")568 }569 let words = PhraseCodec.words(phrase.payload)570 let passphrase = contents.records.first { $0.type == .bip39Passphrase }.map { String(decoding: $0.payload, as: UTF8.self) }571 var seed = try BIP39.seed(mnemonic: words, passphrase: passphrase ?? "")572 defer { SecureMemory.zero(&seed) }573 let publicData = try Self.publicData(seed: seed)574 try await vault.create(password: newPassword)575 do {576 try await BackupFile.restore(bytes, password: backupPassword, into: vault, verifier: IdentityDetachedVerifier(),577 expectedSignerFingerprint: expectedSignerFingerprint)578 // the binding is what the phrase of the backup derives, whatever record the backup carried (QYV-SVC-011)579 try await storeAccountBinding(publicData)580 var fresh = profile581 fresh.kind = .full582 fresh.apply(publicData)583 fresh.usedReceiveIndices = [:]584 fresh.usedChangeIndices = [:]585 fresh.passwordQuality = PasswordQuality.estimate(newPassword).level586 fresh.recoveryPhraseVerified = true587 fresh.usesPassphrase = passphrase != nil588 fresh.lastBackupDate = contents.header.createdAt589 fresh.lastBackupSigned = contents.header.isSigned590 profile = fresh591 try saveProfile()592 } catch {593 try? await vault.destroy()594 profile.kind = nil595 throw error596 }597 resetSessionState()598 // the new password was typed a moment ago599 noteAuthentication()600 emit(.walletCreated)601 emit(.vaultUnlocked)602 }603604 // MARK: Device-to-device transfer605606 /// Old device: wraps a fresh encrypted backup (still protected by `backupPassword`) for the identity shown by the new607 /// device (`receiver`: its "qyvora-id:…" text or QR frames), signed by this wallet's identity.608 /// **Needs an unlocked vault and an identity.** Compare the receiver's fingerprint with the new device before sending.609 public func createTransferPackage(to receiver: [String], backupPassword: String) async throws(WalletError) -> TransferExport {610 try await run {611 try await mapIdentity {612 let text = try QRExport.text(from: receiver)613 let target = try PublicIdentity(text: text)614 guard let current = try await identityRecords().identity else { throw WalletError.featureUnavailable("Create an identity before transferring.") }615 let (backup, _) = try await backupBytes(password: backupPassword, sign: true)616 let package = try TransferPackage.create(backup: backup, to: target, from: current.1)617 do {618 return TransferExport(package: package, frames: try QRChunker.split(package, chunkSize: 1_200))619 } catch {620 // too large for QR codes: the binary package can still travel by file or AirDrop621 return TransferExport(package: package, frames: [])622 }623 }624 }625 }626627 /// New device, step 1: generates a temporary receiving identity (kept in memory only) and returns its public form as628 /// text and QR frames for the old device to scan. Requires that no wallet exists on this device.629 public func beginTransferReception() async throws(WalletError) -> (identity: IdentitySummary, export: QRExport) {630 try await run {631 guard profile.kind == nil else { throw WalletError.walletAlreadyExists }632 let identity = Identity.generate(createdAt: now())633 transferIdentity = identity634 return (summary(identity.publicIdentity, rotations: 0), try QRExport.make(text: identity.publicIdentity.text))635 }636 }637638 /// New device, step 2: opens the envelope of the package (binary) with the temporary identity, verifies the sender's639 /// signature over it, and reports who sent it and what backup it carries. **Restores nothing**: no vault is created,640 /// the profile is not touched and the backup inside stays locked by its password.641 /// Show `sender.fingerprintText` and have the user compare it with the old device before step 3.642 public func inspectTransferPackage(package: Bytes) async throws(WalletError) -> TransferPackageInspection {643 try await run {644 try await mapIdentity {645 guard let receiver = transferIdentity else { throw WalletError.invalidInput("Call beginTransferReception first.") }646 let opened = try TransferPackage.open(package, receiver: receiver)647 return TransferPackageInspection(sender: summary(opened.sender, rotations: 0), backup: try BackupFile.inspect(opened.backup))648 }649 }650 }651652 /// New device, step 3: opens the package again, requires that it is signed by `expectedSender` (the653 /// `sender.text` returned by `inspectTransferPackage`, whose fingerprint the user compared with the old device) and654 /// that the backup inside is signed by the same identity, then restores the wallet as `restoreBackup` does.655 /// Returns the sender's fingerprint text.656 @discardableResult657 public func completeTransferReception(package: Bytes, backupPassword: String, newPassword: String,658 expectedSender: String) async throws(WalletError) -> String {659 try await run {660 try await mapIdentity {661 guard let receiver = transferIdentity else { throw WalletError.invalidInput("Call beginTransferReception first.") }662 let expected = try PublicIdentity(text: expectedSender)663 let opened = try TransferPackage.open(package, receiver: receiver, expectedSender: expected)664 try await restore(opened.backup, backupPassword: backupPassword, newPassword: newPassword, expectedSignerFingerprint: opened.sender.fingerprint)665 transferIdentity = nil666 return opened.sender.fingerprintText667 }668 }669 }670671 /// Reassembles the QR frames of a transfer package into its binary form.672 public nonisolated func assembleTransferPackage(frames: [String]) throws(WalletError) -> Bytes {673 do {674 return try QRAssembler.assemble(frames)675 } catch {676 throw WalletError.invalidPayload("The QR frames do not form a complete package. Scan every frame of the animated code again.")677 }678 }679}680