SPB Git

Repository Public

BIP32.swift 10.8 KB 239 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraCore/HD/BIP32.swift8// Module           : Qyvora Core9// 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 QyvoraSymmetric44import QyvoraSecp256k14546/// One step of a derivation path.47public struct ChildIndex: Equatable, Hashable, Sendable {48    public let raw: UInt3249    public static let hardenedBit: UInt32 = 0x8000_00005051    public init(raw: UInt32) { self.raw = raw }52    public static func normal(_ i: UInt32) -> ChildIndex { ChildIndex(raw: i & ~hardenedBit) }53    public static func hardened(_ i: UInt32) -> ChildIndex { ChildIndex(raw: i | hardenedBit) }54    public var isHardened: Bool { raw & Self.hardenedBit != 0 }55    public var index: UInt32 { raw & ~Self.hardenedBit }56}5758/// A BIP-32 path such as m/84'/0'/0'/0/5.59public struct DerivationPath: Equatable, Hashable, Sendable, CustomStringConvertible {60    public let indices: [ChildIndex]6162    public init(_ indices: [ChildIndex]) { self.indices = indices }6364    /// Accepts "m/…" or a relative path, with ' or h for hardened steps.65    public init?(_ text: String) {66        var parts = text.split(separator: "/", omittingEmptySubsequences: false).map(String.init)67        if parts.first == "m" || parts.first == "M" { parts.removeFirst() }68        var out = [ChildIndex]()69        for p in parts {70            if p.isEmpty { return nil }71            let hardened = p.hasSuffix("'") || p.hasSuffix("h") || p.hasSuffix("H")72            let digits = hardened ? String(p.dropLast()) : p73            guard !digits.isEmpty, digits.allSatisfy({ $0.isASCII && $0.isNumber }),74                  let v = UInt32(digits), v < ChildIndex.hardenedBit else { return nil }75            out.append(hardened ? .hardened(v) : .normal(v))76        }77        indices = out78    }7980    public var description: String {81        "m" + indices.map { "/\($0.index)" + ($0.isHardened ? "'" : "") }.joined()82    }8384    public func appending(_ child: ChildIndex) -> DerivationPath { DerivationPath(indices + [child]) }85}8687/// BIP-32 extended key (private or public) on secp256k1.88public struct ExtendedKey: Sendable {89    public enum Error: Swift.Error, Equatable {90        case invalidSeed91        case invalidChild92        case hardenedFromPublic93        case invalidEncoding94    }9596    /// 32-byte private key, or nil for a public-only key.97    public private(set) var privateKey: Bytes?98    /// 33-byte compressed public key.99    public let publicKey: Bytes100    public private(set) var chainCode: Bytes101    public let depth: UInt8102    public let parentFingerprint: Bytes103    public let childNumber: UInt32104105    public var isPrivate: Bool { privateKey != nil }106107    /// First four bytes of HASH160(public key).108    public var fingerprint: Bytes { Bytes(Hash160.hash(publicKey).prefix(4)) }109110    /// Master key from a seed of 16 to 64 bytes.111    public static func master(seed: Bytes) throws -> ExtendedKey {112        let dit = DataIndependentTiming.enable()113        defer { DataIndependentTiming.restore(dit) }114        guard (16...64).contains(seed.count) else { throw Error.invalidSeed }115        var i = HMAC<SHA512>.authenticate(key: Bytes("Bitcoin seed".utf8), message: seed)116        defer { SecureMemory.zero(&i) }117        let key = Bytes(i[0..<32])118        guard Secp256k1.isValidPrivateKey(key) else { throw Error.invalidSeed }119        return ExtendedKey(privateKey: key, publicKey: try Secp256k1.publicKey(privateKey: key), chainCode: Bytes(i[32..<64]),120                           depth: 0, parentFingerprint: [0, 0, 0, 0], childNumber: 0)121    }122123    public func derive(_ child: ChildIndex) throws -> ExtendedKey {124        let dit = DataIndependentTiming.enable()125        defer { DataIndependentTiming.restore(dit) }126        guard depth < 255 else { throw Error.invalidChild }127        var data: Bytes128        if child.isHardened {129            guard let k = privateKey else { throw Error.hardenedFromPublic }130            data = [0] + k131        } else {132            data = publicKey133        }134        data += Endian.be32(child.raw)135        var i = HMAC<SHA512>.authenticate(key: chainCode, message: data)136        defer {137            SecureMemory.zero(&i)138            SecureMemory.zero(&data)139        }140        var il = Bytes(i[0..<32])141        let ir = Bytes(i[32..<64])142        // IL is the tweak between the parent and the child private key143        defer { SecureMemory.zero(&il) }144        if let k = privateKey {145            // BIP-32: when IL ≥ n or the child key is zero the index is invalid (probability below 2^-127)146            guard let childKey = try? Secp256k1.privateKeyAdd(k, tweak: il) else { throw Error.invalidChild }147            return ExtendedKey(privateKey: childKey, publicKey: try Secp256k1.publicKey(privateKey: childKey), chainCode: ir,148                               depth: depth + 1, parentFingerprint: fingerprint, childNumber: child.raw)149        }150        guard let childPub = try? Secp256k1.publicKeyAdd(publicKey, tweak: il) else { throw Error.invalidChild }151        return ExtendedKey(privateKey: nil, publicKey: childPub, chainCode: ir,152                           depth: depth + 1, parentFingerprint: fingerprint, childNumber: child.raw)153    }154155    /// The key at `path` below this one. The intermediate keys of the walk are erased as soon as the next one exists156    /// (QYV-CRY-003): only the result holds key material when the function returns.157    public func derive(_ path: DerivationPath) throws -> ExtendedKey {158        var k = self159        for (step, c) in path.indices.enumerated() {160            let next = try k.derive(c)161            if step > 0 { k.wipe() }162            k = next163        }164        return k165    }166167    /// Erases the private key and the chain code of this value in place (QYV-CRY-003): 32 zero bytes remain where the168    /// private key was. The key must not be used afterwards (a signature with it fails: zero is not a valid key).169    ///170    /// Swift arrays are copy-on-write: the bytes are overwritten where they are only when this value is the sole171    /// owner of its buffers. A copy that is still alive keeps the key (and this call then erases a private copy):172    /// call it when the copies handed out have gone, as `WalletService.withMasterKey` does.173    public mutating func wipe() {174        if var key = privateKey {175            // take the buffer out of the optional so that this variable is its only owner, erase, put it back176            privateKey = nil177            SecureMemory.zero(&key)178            privateKey = key179        }180        SecureMemory.zero(&chainCode)181    }182183    /// The same key without its private part.184    public var neutered: ExtendedKey {185        ExtendedKey(privateKey: nil, publicKey: publicKey, chainCode: chainCode, depth: depth,186                    parentFingerprint: parentFingerprint, childNumber: childNumber)187    }188189    /// Version bytes of the serialized forms (SLIP-132 for the SegWit variants).190    public enum Version: UInt32, Sendable, CaseIterable {191        case xprv = 0x0488ADE4, xpub = 0x0488B21E192        case zprv = 0x04B2430C, zpub = 0x04B24746193        case tprv = 0x04358394, tpub = 0x043587CF194        case vprv = 0x045F18BC, vpub = 0x045F1CF6195196        public var isPrivate: Bool {197            switch self {198            case .xprv, .zprv, .tprv, .vprv: return true199            default: return false200            }201        }202    }203204    /// Base58Check serialization (78-byte payload).205    public func serialized(_ version: Version) throws -> String {206        var payload = Endian.be32(version.rawValue) + [depth] + parentFingerprint + Endian.be32(childNumber) + chainCode207        if version.isPrivate {208            guard let k = privateKey else { throw Error.invalidEncoding }209            payload += [0] + k210        } else {211            payload += publicKey212        }213        defer { SecureMemory.zero(&payload) }214        return Base58Check.encode(payload)215    }216217    public static func parse(_ text: String) throws -> (key: ExtendedKey, version: Version) {218        // A serialized key is 111 or 112 characters. Base58 decoding is quadratic in the length: text of another219        // size is refused before it is decoded, so that an oversized paste or QR payload cannot stall the caller.220        guard text.utf8.count <= 120, let payload = Base58Check.decode(text), payload.count == 78,221              let version = Version(rawValue: payload[0..<4].reduce(0) { $0 << 8 | UInt32($1) }) else { throw Error.invalidEncoding }222        let depth = payload[4]223        let parent = Bytes(payload[5..<9])224        let child = payload[9..<13].reduce(UInt32(0)) { $0 << 8 | UInt32($1) }225        let chain = Bytes(payload[13..<45])226        let keyData = Bytes(payload[45..<78])227        if depth == 0, parent != [0, 0, 0, 0] || child != 0 { throw Error.invalidEncoding }228        if version.isPrivate {229            let k = Bytes(keyData[1...])230            guard keyData[0] == 0, Secp256k1.isValidPrivateKey(k) else { throw Error.invalidEncoding }231            return (ExtendedKey(privateKey: k, publicKey: try Secp256k1.publicKey(privateKey: k), chainCode: chain,232                                depth: depth, parentFingerprint: parent, childNumber: child), version)233        }234        guard keyData[0] == 2 || keyData[0] == 3, Secp256k1.isValidPublicKey(keyData) else { throw Error.invalidEncoding }235        return (ExtendedKey(privateKey: nil, publicKey: keyData, chainCode: chain,236                            depth: depth, parentFingerprint: parent, childNumber: child), version)237    }238}239
Files main
Menu

Theme