SPB Git

Repository Public

RecoverySheet.swift 17.8 KB 331 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraRecovery/RecoverySheet.swift8// Module           : Qyvora Recovery9// 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 QyvoraCore43import QyvoraEthereum44import QyvoraMath45import QyvoraSymmetric4647public enum RecoverySheetError: Error, Equatable, Sendable {48    /// The words are not a valid BIP-39 sentence (unknown word, wrong count or bad checksum).49    case invalidMnemonic50    /// A key derivation failed (probability below 2^-127 for a valid seed).51    case derivationFailed52    /// More than 1 000 Ethereum addresses were requested.53    case invalidParameters54}5556/// Everything needed to find the wallet's funds again with any standard wallet, should QYVORA disappear.57///58/// By default the sheet holds public data only: extended public keys, descriptors and addresses. They let anyone who59/// reads the sheet watch the wallet (balances and history) but never spend. The recovery phrase is included only when60/// `includePrivateMaterial` is requested explicitly.61///62/// Standards used: BIP-39 (phrase to seed), BIP-32 (derivation), BIP-84 (native SegWit accounts m/84'/coin'/0'),63/// SLIP-132 (zpub / vpub prefixes), BIP-380 output descriptors, BIP-44 for Ethereum (m/44'/60'/0'/0/i).64public struct RecoverySheet: Codable, Sendable, Equatable {65    public struct BitcoinAccount: Codable, Sendable, Equatable {66        public let network: BitcoinNetwork67        /// For example "m/84'/0'/0'".68        public let derivationPath: String69        /// BIP-32 form of the account key: xpub (mainnet) or tpub (test networks). This is what descriptors use.70        public let extendedPublicKey: String71        /// SLIP-132 form of the same key: zpub (mainnet) or vpub (test networks), as shown by many wallets.72        public let slip132PublicKey: String73        /// `wpkh([fingerprint/84h/coinh/0h]xpub…/0/*)` — receiving addresses. No checksum: QyvoraBitcoin (or74        /// `bitcoin-cli getdescriptorinfo`) appends the `#checksum` suffix.75        public let receiveDescriptor: String76        /// `wpkh([fingerprint/84h/coinh/0h]xpub…/1/*)` — change addresses.77        public let changeDescriptor: String78        /// The address at …/0/0, to check an import in another wallet at a glance.79        public let firstReceiveAddress: String80    }8182    public struct EthereumAccount: Codable, Sendable, Equatable {83        public let index: UInt3284        /// For example "m/44'/60'/0'/0/0" (the same path on test networks).85        public let derivationPath: String86        /// EIP-55 checksummed address.87        public let address: String88    }8990    public struct PrivateMaterial: Codable, Sendable, Equatable {91        /// The BIP-39 recovery phrase. Whoever reads it controls the funds.92        public let mnemonic: String93        /// The BIP-39 passphrase, when one is used.94        public let passphrase: String?95    }9697    /// The account of a chain other than Bitcoin and the EVM networks: Solana, TRON, another UTXO coin.98    public struct ChainAccount: Codable, Sendable, Equatable {99        /// "Solana", "TRON", "Litecoin"…100        public let chain: String101        /// Which networks the entry holds for ("mainnet-beta, devnet and testnet: the same address").102        public let networks: String103        /// For example "m/44'/501'/0'/0'".104        public let derivationPath: String105        /// How the key is derived and what signs ("SLIP-0010 Ed25519", "BIP-32 secp256k1").106        public let scheme: String107        /// The account address (account chains), or the first receive address (UTXO coins).108        public let address: String?109        /// Account extended public key (UTXO coins).110        public let extendedPublicKey: String?111        /// Output descriptor of the receive chain, without checksum (UTXO coins).112        public let descriptor: String?113        /// What to know to recover the account in another wallet.114        public let note: String?115        /// Identifier of the network in the wallet's chain registry ("solana", "tron", "litecoin", "litecoin-testnet"),116        /// so that a reader finds the chain without comparing display names. nil in a sheet written before this field117        /// existed, and for an account whose caller gave none; `chain` stays the name to display.118        public let chainID: String?119120        public init(chain: String, networks: String, derivationPath: String, scheme: String, address: String?, extendedPublicKey: String? = nil,121                    descriptor: String? = nil, note: String? = nil, chainID: String? = nil) {122            self.chainID = chainID123            self.chain = chain124            self.networks = networks125            self.derivationPath = derivationPath126            self.scheme = scheme127            self.address = address128            self.extendedPublicKey = extendedPublicKey129            self.descriptor = descriptor130            self.note = note131        }132    }133134    /// 1: Bitcoin and Ethereum. 2: adds `otherChains`. A sheet of format 1 is still read (its `otherChains` is empty).135    public static let currentFormatVersion = 2136137    public let formatVersion: Int138    public let createdAt: Date139    /// BIP-32 fingerprint of the master key (8 hexadecimal digits).140    public let masterFingerprint: String141    public let mnemonicWordCount: Int142    /// True when a BIP-39 passphrase is part of the seed: the phrase alone does not restore this wallet.143    public let usesPassphrase: Bool144    public let bitcoin: [BitcoinAccount]145    /// The EVM account: the same addresses on Ethereum and on every other EVM network (Base, Arbitrum One, OP Mainnet,146    /// Polygon PoS, BNB Smart Chain, Avalanche C-Chain) and on their test networks.147    public let ethereum: [EthereumAccount]148    public let privateMaterial: PrivateMaterial?149    /// Accounts of the other chains, as the caller derived them (see `make(extraAccounts:)`). Empty in a sheet made150    /// without them.151    public let otherChains: [ChainAccount]152153    init(formatVersion: Int, createdAt: Date, masterFingerprint: String, mnemonicWordCount: Int, usesPassphrase: Bool, bitcoin: [BitcoinAccount],154         ethereum: [EthereumAccount], privateMaterial: PrivateMaterial?, otherChains: [ChainAccount] = []) {155        self.formatVersion = formatVersion156        self.createdAt = createdAt157        self.masterFingerprint = masterFingerprint158        self.mnemonicWordCount = mnemonicWordCount159        self.usesPassphrase = usesPassphrase160        self.bitcoin = bitcoin161        self.ethereum = ethereum162        self.privateMaterial = privateMaterial163        self.otherChains = otherChains164    }165166    /// Tolerant decoding: a sheet written before the multi-chain upgrade has no `otherChains`.167    public init(from decoder: any Decoder) throws {168        let c = try decoder.container(keyedBy: CodingKeys.self)169        formatVersion = try c.decode(Int.self, forKey: .formatVersion)170        createdAt = try c.decode(Date.self, forKey: .createdAt)171        masterFingerprint = try c.decode(String.self, forKey: .masterFingerprint)172        mnemonicWordCount = try c.decode(Int.self, forKey: .mnemonicWordCount)173        usesPassphrase = try c.decode(Bool.self, forKey: .usesPassphrase)174        bitcoin = try c.decode([BitcoinAccount].self, forKey: .bitcoin)175        ethereum = try c.decode([EthereumAccount].self, forKey: .ethereum)176        privateMaterial = try c.decodeIfPresent(PrivateMaterial.self, forKey: .privateMaterial)177        otherChains = try c.decodeIfPresent([ChainAccount].self, forKey: .otherChains) ?? []178    }179180    /// Derives the sheet from the recovery phrase. `mnemonic` holds the words in order (`BIP39.words(from:)` splits text).181    ///182    /// `extraAccounts` derives the accounts of the chains this module does not know (it depends on neither the Solana183    /// nor the TRON module): it receives the BIP-39 seed and the BIP-32 master key for the duration of the call and184    /// returns public data only. The wallet service passes the derivation of every chain it supports; without it the185    /// sheet lists Bitcoin and the EVM account only. A failure of the closure is a `derivationFailed`.186    public static func make(187        mnemonic: [String], passphrase: String = "", ethereumAddressCount: Int = 5, includePrivateMaterial: Bool = false,188        createdAt: Date = Date(), extraAccounts: ((_ bip39Seed: Bytes, _ master: ExtendedKey) throws -> [ChainAccount])? = nil189    ) throws(RecoverySheetError) -> RecoverySheet {190        guard (0...1000).contains(ethereumAddressCount) else { throw .invalidParameters }191        guard var seed = try? BIP39.seed(mnemonic: mnemonic, passphrase: passphrase) else { throw .invalidMnemonic }192        defer { SecureMemory.zero(&seed) }193        do {194            let master = try ExtendedKey.master(seed: seed)195            let fingerprint = master.fingerprint.hex196197            var bitcoin: [BitcoinAccount] = []198            // Bitcoin's networks only: the sheet documents BIP-84 accounts, and the other UTXO coins are not on it yet199            for network in BitcoinNetwork.networks(of: .bitcoin) {200                let account = try master.derive(StandardPaths.bip84Account(network)).neutered201                let xpub = try account.serialized(network == .mainnet ? .xpub : .tpub)202                let slip132 = try account.serialized(network == .mainnet ? .zpub : .vpub)203                let origin = "[\(fingerprint)/84h/\(network.coinType)h/0h]"204                let first = try account.derive(.normal(0)).derive(.normal(0))205                guard let address = SegWitAddress.encode(hrp: network.hrp, version: 0, program: Hash160.hash(first.publicKey)) else {206                    throw RecoverySheetError.derivationFailed207                }208                bitcoin.append(209                    BitcoinAccount(210                        network: network, derivationPath: StandardPaths.bip84Account(network).description, extendedPublicKey: xpub,211                        slip132PublicKey: slip132, receiveDescriptor: "wpkh(\(origin)\(xpub)/0/*)", changeDescriptor: "wpkh(\(origin)\(xpub)/1/*)",212                        firstReceiveAddress: address))213            }214215            var ethereum: [EthereumAccount] = []216            for i in 0..<UInt32(ethereumAddressCount) {217                let path = StandardPaths.ethereum(index: i)218                let key = try master.derive(path)219                ethereum.append(EthereumAccount(index: i, derivationPath: path.description, address: try EthereumAddress(publicKey: key.publicKey).checksummed))220            }221222            let others = try extraAccounts?(seed, master) ?? []223            return RecoverySheet(224                formatVersion: currentFormatVersion, createdAt: Date(timeIntervalSince1970: createdAt.timeIntervalSince1970.rounded(.down)),225                masterFingerprint: fingerprint, mnemonicWordCount: mnemonic.count, usesPassphrase: !passphrase.isEmpty, bitcoin: bitcoin,226                ethereum: ethereum,227                privateMaterial: includePrivateMaterial228                    ? PrivateMaterial(mnemonic: mnemonic.joined(separator: " "), passphrase: passphrase.isEmpty ? nil : passphrase) : nil,229                otherChains: others)230        } catch let error as RecoverySheetError {231            throw error232        } catch {233            throw .derivationFailed234        }235    }236237    /// The same sheet without the recovery phrase and passphrase.238    public var withoutPrivateMaterial: RecoverySheet {239        RecoverySheet(240            formatVersion: formatVersion, createdAt: createdAt, masterFingerprint: masterFingerprint, mnemonicWordCount: mnemonicWordCount,241            usesPassphrase: usesPassphrase, bitcoin: bitcoin, ethereum: ethereum, privateMaterial: nil, otherChains: otherChains)242    }243244    /// JSON with sorted keys and ISO-8601 dates.245    public func json() throws -> Data {246        let encoder = JSONEncoder()247        encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]248        encoder.dateEncodingStrategy = .iso8601249        return try encoder.encode(self)250    }251252    public static func fromJSON(_ data: Data) throws -> RecoverySheet {253        let decoder = JSONDecoder()254        decoder.dateDecodingStrategy = .iso8601255        return try decoder.decode(RecoverySheet.self, from: data)256    }257258    /// A printable plain-text rendering (English, ASCII).259    public func plainText() -> String {260        let formatter = ISO8601DateFormatter()261        formatter.formatOptions = [.withInternetDateTime]262        var lines: [String] = []263        lines.append("QYVORA RECOVERY SHEET (format \(formatVersion))")264        lines.append("Created: \(formatter.string(from: createdAt))")265        lines.append("")266        lines.append("This sheet lets you find your funds again with any standard wallet,")267        lines.append("even if QYVORA no longer exists.")268        lines.append("")269        lines.append("Master key fingerprint: \(masterFingerprint)")270        lines.append("Recovery phrase: \(mnemonicWordCount) words (BIP-39, English)")271        lines.append(272            usesPassphrase273                ? "BIP-39 passphrase: YES. The phrase alone does NOT restore this wallet; the passphrase is required too."274                : "BIP-39 passphrase: none")275        lines.append("")276        if let privateMaterial {277            lines.append("=== PRIVATE: whoever reads this section controls the funds ===")278            lines.append("Recovery phrase: \(privateMaterial.mnemonic)")279            if let passphrase = privateMaterial.passphrase { lines.append("Passphrase: \(passphrase)") }280            lines.append("=== END OF PRIVATE SECTION ===")281        } else {282            lines.append("This sheet contains NO private key and NO recovery phrase.")283            lines.append("It allows watching the wallet, never spending. Keep the recovery phrase separately.")284        }285        lines.append("")286        lines.append("BITCOIN (BIP-84 native SegWit, addresses starting with bc1q / tb1q)")287        for account in bitcoin {288            lines.append("")289            lines.append("  Network: \(account.network.displayName)")290            lines.append("  Account path: \(account.derivationPath)")291            lines.append("  Extended public key: \(account.extendedPublicKey)")292            lines.append("  Same key, SLIP-132 form: \(account.slip132PublicKey)")293            lines.append("  Receive descriptor: \(account.receiveDescriptor)")294            lines.append("  Change descriptor:  \(account.changeDescriptor)")295            lines.append("  First receive address (path /0/0): \(account.firstReceiveAddress)")296        }297        lines.append("")298        lines.append("  Descriptors are given without checksum; Bitcoin Core computes it with getdescriptorinfo.")299        lines.append("")300        lines.append("ETHEREUM AND EVM NETWORKS (BIP-44, same addresses on mainnet and test networks)")301        for account in ethereum {302            lines.append("  \(account.derivationPath)  \(account.address)")303        }304        lines.append("")305        lines.append("  The same addresses hold on every EVM network: Ethereum, Base, Arbitrum One, OP Mainnet, Polygon PoS,")306        lines.append("  BNB Smart Chain, Avalanche C-Chain, and their test networks. QYVORA uses the first one.")307        lines.append("")308        if !otherChains.isEmpty {309            lines.append("OTHER CHAINS")310            for account in otherChains {311                lines.append("")312                lines.append("  \(account.chain) (\(account.networks))")313                lines.append("  Path: \(account.derivationPath)  [\(account.scheme)]")314                if let address = account.address { lines.append("  Address: \(address)") }315                if let key = account.extendedPublicKey { lines.append("  Extended public key: \(key)") }316                if let descriptor = account.descriptor { lines.append("  Receive descriptor: \(descriptor)") }317                if let note = account.note { lines.append("  \(note)") }318            }319            lines.append("")320        }321        lines.append("HOW TO RECOVER")322        lines.append("  1. Install a wallet that supports BIP-39 recovery phrases (Sparrow, Electrum, BlueWallet, MetaMask, Ledger...).")323        lines.append("  2. Choose \"restore from recovery phrase\" and enter the \(mnemonicWordCount) words in order\(usesPassphrase ? ", then the passphrase" : "").")324        lines.append("  3. Bitcoin: select native SegWit (BIP-84). Ethereum and EVM networks: the default path m/44'/60'/0'/0.")325        if !otherChains.isEmpty { lines.append("     Other chains: the path printed next to each one above.") }326        lines.append("  4. Check that the first addresses match the ones printed above.")327        lines.append("")328        return lines.joined(separator: "\n")329    }330}331
Files main
Menu

Theme