SPB Git

Repository Public

Migration.swift 25.0 KB 335 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraMigration/Migration.swift8// Module           : Qyvora Migration9// 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 QyvoraCore4344/// Quantum Migration Engine: the crypto-agile registry of everything QYVORA could sign with or migrate to.45///46/// A capability is only `available` when the corresponding blockchain rule is live on the network and47/// implemented here. Everything that depends on a future protocol change is registered as `awaitingProtocol`48/// and cannot be enabled from the application: the registry is the single place where that decision lives.49public enum MigrationEngine {50    /// `.ethereum` stands for every EVM network (one account, one signature scheme); `.bitcoin` for Bitcoin itself.51    public enum Chain: String, Sendable, Codable, CaseIterable { case bitcoin, ethereum, solana, tron, litecoin, dogecoin, bitcoinCash }5253    public enum Status: String, Sendable, Codable {54        /// Usable today.55        case available56        /// Specified and implementable today, not shipped in this version.57        case planned58        /// Depends on a consensus or protocol change that is not deployed. Disabled.59        case awaitingProtocol60    }6162    public enum Family: String, Sendable, Codable {63        case addressType, script, signature, hybridSignature, account, assetMigration, keyRotation64    }6566    public struct Capability: Sendable, Identifiable, Equatable, Codable {67        public let id: String68        public let chain: Chain69        public let family: Family70        public let title: String71        public let detail: String72        public let status: Status73        /// What must happen before the capability can be enabled.74        public let requirement: String?75        /// Whether the mechanism resists a quantum adversary once in use.76        public let quantumResistant: Bool77    }7879    public static let capabilities: [Capability] = [80        Capability(id: "btc.p2wpkh", chain: .bitcoin, family: .addressType, title: "Native SegWit (P2WPKH)",81                   detail: "BIP-84 single-key outputs. The public key stays hashed until the first spend.",82                   status: .available, requirement: nil, quantumResistant: false),83        Capability(id: "btc.p2wsh", chain: .bitcoin, family: .script, title: "P2WSH scripts and multisig",84                   detail: "Witness-script outputs; keys stay hashed until the first spend.",85                   status: .available, requirement: nil, quantumResistant: false),86        Capability(id: "btc.psbt", chain: .bitcoin, family: .script, title: "PSBT (BIP-174)",87                   detail: "Offline signing and watch-only coordination.",88                   status: .available, requirement: nil, quantumResistant: false),89        Capability(id: "btc.rotation", chain: .bitcoin, family: .keyRotation, title: "Sweep to fresh addresses",90                   detail: "Moves funds from addresses whose public key is exposed to never-used addresses of the same wallet.",91                   status: .available, requirement: nil, quantumResistant: false),92        Capability(id: "btc.p2tr", chain: .bitcoin, family: .addressType, title: "Taproot (P2TR) receiving",93                   detail: "BIP-340 signing exists in the engine. Taproot outputs publish a public key on chain, which is the opposite of what long-term quantum caution recommends, so QYVORA does not create them by default.",94                   status: .planned, requirement: "Explicit user opt-in and BIP-86 / BIP-341 support in the Bitcoin module.", quantumResistant: false),95        Capability(id: "btc.pq-output", chain: .bitcoin, family: .addressType, title: "Post-quantum output type",96                   detail: "A new output type committing to post-quantum public keys (proposals such as BIP-360 are drafts).",97                   status: .awaitingProtocol, requirement: "A Bitcoin soft fork defining post-quantum outputs and signature opcodes.", quantumResistant: true),98        Capability(id: "btc.pq-signature", chain: .bitcoin, family: .signature, title: "Native post-quantum signatures",99                   detail: "ML-DSA or SLH-DSA signatures validated by Bitcoin consensus. The engine already implements both algorithms.",100                   status: .awaitingProtocol, requirement: "Consensus support for a post-quantum signature scheme.", quantumResistant: true),101        Capability(id: "btc.hybrid-signature", chain: .bitcoin, family: .hybridSignature, title: "Hybrid secp256k1 + post-quantum spending",102                   detail: "Outputs that require both a classical and a post-quantum signature during a transition period.",103                   status: .awaitingProtocol, requirement: "Consensus support for post-quantum signature checks in script.", quantumResistant: true),104        Capability(id: "btc.utxo-migration", chain: .bitcoin, family: .assetMigration, title: "UTXO migration to post-quantum outputs",105                   detail: "Planned sweep of every UTXO to a post-quantum output type, most exposed first.",106                   status: .awaitingProtocol, requirement: "Availability of a post-quantum output type on the network.", quantumResistant: true),107        Capability(id: "eth.eoa", chain: .ethereum, family: .account, title: "Externally owned account (secp256k1)",108                   detail: "Standard account. Its public key becomes recoverable from the first outgoing transaction.",109                   status: .available, requirement: nil, quantumResistant: false),110        Capability(id: "eth.eip1559", chain: .ethereum, family: .signature, title: "EIP-1559 transactions",111                   detail: "Type-2 transactions signed locally.", status: .available, requirement: nil, quantumResistant: false),112        Capability(id: "eth.rotation", chain: .ethereum, family: .keyRotation, title: "Move assets to a fresh account",113                   detail: "Transfers ETH and tokens to a new address derived from the same phrase whose public key has never been revealed.",114                   status: .planned, requirement: "Guided multi-asset transfer flow.", quantumResistant: false),115        Capability(id: "eth.smart-account", chain: .ethereum, family: .account, title: "Smart contract wallet (ERC-4337)",116                   detail: "Account whose validation logic is a contract, which is the route by which post-quantum signature checks can reach Ethereum accounts.",117                   status: .planned, requirement: "An audited account contract and bundler support in the Ethereum module.", quantumResistant: false),118        Capability(id: "eth.pq-validation", chain: .ethereum, family: .signature, title: "Post-quantum transaction validation",119                   detail: "Account validation with ML-DSA or hash-based signatures, on chain. Verification in contract code is possible in principle but costly without precompiles.",120                   status: .awaitingProtocol, requirement: "An audited post-quantum verifier (precompile or contract) and account-abstraction support on the network.", quantumResistant: true),121        Capability(id: "eth.asset-migration", chain: .ethereum, family: .assetMigration, title: "Asset migration to a post-quantum account",122                   detail: "Moves ETH, tokens and revokes approvals from the classical account to a post-quantum-validated account.",123                   status: .awaitingProtocol, requirement: "Availability of post-quantum account validation.", quantumResistant: true),124        Capability(id: "ltc.p2wpkh", chain: .litecoin, family: .addressType, title: "Native SegWit (P2WPKH)",125                   detail: "BIP-84 single-key outputs (coin type 2). The public key stays hashed until the first spend.",126                   status: .available, requirement: nil, quantumResistant: false),127        Capability(id: "ltc.rotation", chain: .litecoin, family: .keyRotation, title: "Move coins to fresh addresses",128                   detail: "A payment to a never-used address of the same wallet hides the key again until the next spend. The guided sweep moves every exposed output in one transaction, signed on this device.",129                   status: .available, requirement: nil, quantumResistant: false),130        Capability(id: "ltc.pq-output", chain: .litecoin, family: .addressType, title: "Post-quantum output type",131                   detail: "An output type committing to post-quantum public keys. Nothing of the kind is specified for Litecoin.",132                   status: .awaitingProtocol, requirement: "A Litecoin soft fork defining post-quantum outputs and signature checks.", quantumResistant: true),133        Capability(id: "ltc.utxo-migration", chain: .litecoin, family: .assetMigration, title: "UTXO migration to post-quantum outputs",134                   detail: "Sweep of every output to a post-quantum output type, most exposed first.",135                   status: .awaitingProtocol, requirement: "Availability of a post-quantum output type on the network.", quantumResistant: true),136        Capability(id: "doge.p2pkh", chain: .dogecoin, family: .addressType, title: "Legacy addresses (P2PKH)",137                   detail: "BIP-44 single-key outputs (coin type 3); Dogecoin has no SegWit. The public key stays hashed until the first spend.",138                   status: .available, requirement: nil, quantumResistant: false),139        Capability(id: "doge.rotation", chain: .dogecoin, family: .keyRotation, title: "Move coins to fresh addresses",140                   detail: "A payment to a never-used address of the same wallet hides the key again until the next spend. The guided sweep moves every exposed output in one transaction, signed on this device.",141                   status: .available, requirement: nil, quantumResistant: false),142        Capability(id: "doge.pq-output", chain: .dogecoin, family: .addressType, title: "Post-quantum output type",143                   detail: "An output type committing to post-quantum public keys. Nothing of the kind is specified for Dogecoin.",144                   status: .awaitingProtocol, requirement: "A Dogecoin consensus change defining post-quantum outputs and signature checks.", quantumResistant: true),145        Capability(id: "doge.utxo-migration", chain: .dogecoin, family: .assetMigration, title: "UTXO migration to post-quantum outputs",146                   detail: "Sweep of every output to a post-quantum output type, most exposed first.",147                   status: .awaitingProtocol, requirement: "Availability of a post-quantum output type on the network.", quantumResistant: true),148        Capability(id: "bch.p2pkh", chain: .bitcoinCash, family: .addressType, title: "CashAddr addresses (P2PKH)",149                   detail: "BIP-44 single-key outputs (coin type 145), signed with the fork-id digest. The public key stays hashed until the first spend.",150                   status: .available, requirement: nil, quantumResistant: false),151        Capability(id: "bch.rotation", chain: .bitcoinCash, family: .keyRotation, title: "Move coins to fresh addresses",152                   detail: "A payment to a never-used address of the same wallet hides the key again until the next spend. The guided sweep moves every exposed output in one transaction, signed on this device.",153                   status: .available, requirement: nil, quantumResistant: false),154        Capability(id: "bch.pq-output", chain: .bitcoinCash, family: .addressType, title: "Post-quantum output type",155                   detail: "An output type committing to post-quantum public keys. Nothing of the kind is deployed on Bitcoin Cash.",156                   status: .awaitingProtocol, requirement: "A Bitcoin Cash network upgrade defining post-quantum outputs and signature checks.", quantumResistant: true),157        Capability(id: "bch.utxo-migration", chain: .bitcoinCash, family: .assetMigration, title: "UTXO migration to post-quantum outputs",158                   detail: "Sweep of every output to a post-quantum output type, most exposed first.",159                   status: .awaitingProtocol, requirement: "Availability of a post-quantum output type on the network.", quantumResistant: true),160        Capability(id: "sol.account", chain: .solana, family: .account, title: "Solana account (Ed25519)",161                   detail: "Standard account. Its address is the Ed25519 public key itself: the key is public from the moment the address is shared, and no hashed address form exists.",162                   status: .available, requirement: nil, quantumResistant: false),163        Capability(id: "sol.transfers", chain: .solana, family: .signature, title: "SOL and SPL token transfers",164                   detail: "Legacy-message transactions signed locally with Ed25519 (written from scratch in the engine), simulated by the cluster before they are sent.",165                   status: .available, requirement: nil, quantumResistant: false),166        Capability(id: "sol.pq-signature", chain: .solana, family: .signature, title: "Post-quantum transaction signatures",167                   detail: "Transactions authorized by ML-DSA or hash-based signatures validated by the cluster. Nothing of the kind is deployed; hash-based vaults built as on-chain programs exist as experiments and are not what a wallet account is.",168                   status: .awaitingProtocol, requirement: "A Solana protocol upgrade that validates a post-quantum signature scheme for transaction signers.", quantumResistant: true),169        Capability(id: "sol.asset-migration", chain: .solana, family: .assetMigration, title: "Asset migration to a post-quantum account",170                   detail: "Moves SOL and tokens from the Ed25519 account to an account controlled by a post-quantum key.",171                   status: .awaitingProtocol, requirement: "Availability of post-quantum signers on the network.", quantumResistant: true),172        Capability(id: "trx.account", chain: .tron, family: .account, title: "TRON account (secp256k1)",173                   detail: "Standard account. Its public key becomes recoverable from the first outgoing transaction.",174                   status: .available, requirement: nil, quantumResistant: false),175        Capability(id: "trx.transfers", chain: .tron, family: .signature, title: "TRX and TRC-20 transfers",176                   detail: "Transactions encoded and signed locally with secp256k1 ECDSA.", status: .available, requirement: nil, quantumResistant: false),177        Capability(id: "trx.rotation", chain: .tron, family: .keyRotation, title: "Move assets to a fresh account",178                   detail: "Transfers TRX and tokens to a new address derived from the same phrase whose public key has never been revealed.",179                   status: .planned, requirement: "Guided multi-asset transfer flow.", quantumResistant: false),180        Capability(id: "trx.pq-validation", chain: .tron, family: .signature, title: "Post-quantum transaction validation",181                   detail: "Account permissions validated with a post-quantum signature scheme. TRON's account permissions accept secp256k1 keys only.",182                   status: .awaitingProtocol, requirement: "A TRON protocol upgrade that accepts post-quantum keys in account permissions.", quantumResistant: true),183        Capability(id: "trx.asset-migration", chain: .tron, family: .assetMigration, title: "Asset migration to a post-quantum account",184                   detail: "Moves TRX and tokens from the classical account to an account controlled by a post-quantum key.",185                   status: .awaitingProtocol, requirement: "Availability of post-quantum account permissions.", quantumResistant: true),186    ]187188    public static func capabilities(for chain: Chain) -> [Capability] { capabilities.filter { $0.chain == chain } }189190    public static func capability(_ id: String) -> Capability? { capabilities.first { $0.id == id } }191192    /// The only gate the application consults before offering a feature.193    public static func isEnabled(_ id: String) -> Bool { capability(id)?.status == .available }194195    /// True when some deployed mechanism on the chain resists a quantum adversary. False for both chains today.196    public static func chainOffersQuantumResistance(_ chain: Chain) -> Bool {197        capabilities(for: chain).contains { $0.status == .available && $0.quantumResistant }198    }199}200201/// A signature scheme the wallet can be asked to use. New schemes are added here and nowhere else.202public protocol TransactionSignatureScheme: Sendable {203    static var identifier: String { get }204    /// The registry entry that must be `available` for the scheme to sign anything.205    static var capabilityID: String { get }206    static var publicKeySize: Int { get }207    static var signatureSize: Int { get }208}209210public enum SignatureSchemes {211    public enum Secp256k1ECDSA: TransactionSignatureScheme {212        public static let identifier = "secp256k1-ecdsa"213        public static let capabilityID = "btc.p2wpkh"214        public static let publicKeySize = 33215        public static let signatureSize = 72216    }217218    /// Registered for sizing and planning only: no network validates it yet.219    public enum MLDSA65Native: TransactionSignatureScheme {220        public static let identifier = "ml-dsa-65"221        public static let capabilityID = "btc.pq-signature"222        public static let publicKeySize = 1952223        public static let signatureSize = 3309224    }225226    /// Registered for sizing and planning only: no network validates it yet.227    public enum SLHDSASHA2128sNative: TransactionSignatureScheme {228        public static let identifier = "slh-dsa-sha2-128s"229        public static let capabilityID = "btc.pq-signature"230        public static let publicKeySize = 32231        public static let signatureSize = 7856232    }233234    /// Size planning: how much larger one input's authorization data becomes with a post-quantum scheme.235    public static func witnessGrowth<S: TransactionSignatureScheme>(_ scheme: S.Type) -> Double {236        Double(scheme.publicKeySize + scheme.signatureSize) / Double(Secp256k1ECDSA.publicKeySize + Secp256k1ECDSA.signatureSize)237    }238}239240/// An ordered list of steps the wallet proposes; steps that depend on unavailable capabilities are listed but blocked.241public struct MigrationPlan: Sendable, Equatable {242    /// The measured exposure of one UTXO coin other than Bitcoin.243    public struct CoinExposure: Sendable, Equatable {244        public let chain: MigrationEngine.Chain245        /// The name of the coin as shown ("Litecoin").246        public let name: String247        public let exposedUTXOs: Int248        public let reusedAddresses: Int249250        public init(chain: MigrationEngine.Chain, name: String, exposedUTXOs: Int, reusedAddresses: Int) {251            self.chain = chain252            self.name = name253            self.exposedUTXOs = exposedUTXOs254            self.reusedAddresses = reusedAddresses255        }256257        /// Prefix of the coin's entries in the capability registry; nil for a chain that is not another UTXO coin.258        var capabilityPrefix: String? {259            switch chain {260            case .litecoin: return "ltc"261            case .dogecoin: return "doge"262            case .bitcoinCash: return "bch"263            default: return nil264            }265        }266    }267268    public struct Step: Sendable, Equatable, Identifiable {269        public let id: String270        public let title: String271        public let detail: String272        public let capabilityID: String273        public var isActionable: Bool { MigrationEngine.isEnabled(capabilityID) }274        public var blockedBy: String? { isActionable ? nil : MigrationEngine.capability(capabilityID)?.requirement }275    }276277    public let steps: [Step]278    public var actionable: [Step] { steps.filter(\.isActionable) }279    public var blocked: [Step] { steps.filter { !$0.isActionable } }280281    /// Builds the plan from the exposure the Quantum Shield measured.282    /// `solanaAccount` and `tronAccount` say whether the wallet uses those chains (their steps are listed only then);283    /// `tronKeyExposed` adds the step that moves TRON assets to a fresh account.284    /// `otherCoins` gives the same figures for the other UTXO coins (Litecoin, Dogecoin, Bitcoin Cash): each one with285    /// exposed outputs or reused addresses gets its own sweep step, after Bitcoin's.286    public static func make(exposedBitcoinUTXOs: Int, reusedBitcoinAddresses: Int, ethereumKeyExposed: Bool, openApprovals: Int,287                            solanaAccount: Bool = false, tronAccount: Bool = false, tronKeyExposed: Bool = false,288                            otherCoins: [CoinExposure] = []) -> MigrationPlan {289        var steps = [Step]()290        if exposedBitcoinUTXOs > 0 || reusedBitcoinAddresses > 0 {291            steps.append(Step(id: "sweep-btc", title: "Sweep exposed bitcoin to fresh addresses",292                              detail: "\(exposedBitcoinUTXOs) output(s) sit on addresses whose public key is already on chain. Moving them to never-used addresses hides the key again until the next spend.",293                              capabilityID: "btc.rotation"))294        }295        for coin in otherCoins where coin.exposedUTXOs > 0 || coin.reusedAddresses > 0 {296            guard let prefix = coin.capabilityPrefix else { continue }297            steps.append(Step(id: "sweep-\(prefix)", title: "Sweep exposed \(coin.name) to fresh addresses",298                              detail: "\(coin.exposedUTXOs) \(coin.name) output(s) sit on addresses whose public key is already on chain. Moving them to never-used addresses hides the key again until the next spend.",299                              capabilityID: "\(prefix).rotation"))300        }301        if ethereumKeyExposed {302            steps.append(Step(id: "rotate-eth", title: "Move Ethereum assets to a fresh account",303                              detail: "This account has sent transactions, so its public key is public. A new account from the same phrase starts unexposed.",304                              capabilityID: "eth.rotation"))305        }306        if openApprovals > 0 {307            steps.append(Step(id: "revoke-approvals", title: "Review and revoke token approvals",308                              detail: "\(openApprovals) spender contract(s) can move tokens from this account.",309                              capabilityID: "eth.eip1559"))310        }311        steps.append(Step(id: "btc-pq", title: "Migrate bitcoin to post-quantum outputs",312                          detail: "When Bitcoin defines a post-quantum output type, QYVORA will move every output to it, most exposed first.",313                          capabilityID: "btc.utxo-migration"))314        steps.append(Step(id: "eth-pq", title: "Migrate to a post-quantum Ethereum account",315                          detail: "When post-quantum account validation is available, QYVORA will move assets and revoke approvals on the old account.",316                          capabilityID: "eth.asset-migration"))317        if tronKeyExposed {318            steps.append(Step(id: "rotate-trx", title: "Move TRON assets to a fresh account",319                              detail: "This account has sent transactions, so its public key is public. A new account from the same phrase starts unexposed.",320                              capabilityID: "trx.rotation"))321        }322        if solanaAccount {323            steps.append(Step(id: "sol-pq", title: "Migrate to a post-quantum Solana account",324                              detail: "A Solana address is the public key itself, so nothing can hide it today. When Solana validates post-quantum signers, QYVORA will move SOL and tokens to such an account.",325                              capabilityID: "sol.asset-migration"))326        }327        if tronAccount {328            steps.append(Step(id: "trx-pq", title: "Migrate to a post-quantum TRON account",329                              detail: "When TRON accepts post-quantum keys in account permissions, QYVORA will move TRX and tokens to such an account.",330                              capabilityID: "trx.asset-migration"))331        }332        return MigrationPlan(steps: steps)333    }334}335
Files main
Menu

Theme