SPB Git

Repository Public

Descriptor.swift 26.6 KB 569 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraBitcoin/Descriptor.swift8// Module           : Qyvora Bitcoin9// 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 QyvoraSecp256k145import QyvoraCore4647/// Errors of the output descriptor language (BIP-380 and following).48public enum DescriptorError: Swift.Error, Equatable, Sendable {49    case invalidCharacter50    case missingChecksum51    case invalidChecksum52    /// Not one of `wpkh(KEY)`, `wsh(multi(k,KEY,…))`, `wsh(sortedmulti(k,KEY,…))`.53    case unsupportedDescriptor54    case malformed(String)55    case invalidKey56    /// BIP-382: only compressed keys inside wpkh() and wsh().57    case uncompressedKeyNotAllowed58    /// QYVORA descriptors are public: xprv / WIF keys are refused so that a descriptor can never leak a secret.59    case privateKeyNotSupported60    /// A hardened step after an extended public key cannot be derived without the private key.61    case hardenedDerivationUnsupported62    case invalidThreshold63    case tooManyKeys64    case duplicateKey65    /// Keys of both mainnet and test networks in one descriptor, or an address requested for the other kind of network.66    case networkMismatch67    case multipathMismatch68    case indexOutOfRange69    case derivationFailed70}7172/// A key expression: optional origin, then a raw compressed public key or an extended public key with a derivation suffix.73public struct DescriptorKey: Equatable, Sendable {74    /// `[fingerprint/path]`: where the key comes from in its master's tree.75    public struct Origin: Equatable, Sendable {76        /// 4-byte fingerprint of the master key.77        public let fingerprint: Bytes78        public let path: DerivationPath7980        public init?(fingerprint: Bytes, path: DerivationPath) {81            guard fingerprint.count == 4 else { return nil }82            self.fingerprint = fingerprint83            self.path = path84        }85    }8687    public enum Step: Equatable, Sendable {88        /// Unhardened child index.89        case index(UInt32)90        /// BIP-389 `<a;b;…>`: one alternative per derived descriptor (receive / change).91        case multipath([UInt32])92    }9394    public enum Source: Equatable, Sendable {95        /// 33-byte compressed public key.96        case publicKey(Bytes)97        /// Extended public key in its BIP-32 form (`xpub…` / `tpub…`), whatever prefix it was given with.98        case extended(String)99    }100101    public let origin: Origin?102    public let source: Source103    /// Steps after the extended key, before the wildcard.104    public let steps: [Step]105    /// True when the expression ends with `/*`.106    public let wildcard: Bool107    /// Parsed extended key (nil for a raw public key).108    let extendedKey: ExtendedKey?109    /// True for tpub / vpub keys, false for xpub / zpub, nil for raw public keys.110    public let isTestKey: Bool?111112    public static func == (a: DescriptorKey, b: DescriptorKey) -> Bool {113        a.origin == b.origin && a.source == b.source && a.steps == b.steps && a.wildcard == b.wildcard114    }115116    /// A raw compressed public key.117    public init(publicKey: Bytes, origin: Origin? = nil) throws {118        guard publicKey.count == 33 else { throw publicKey.count == 65 ? DescriptorError.uncompressedKeyNotAllowed : DescriptorError.invalidKey }119        guard Secp256k1.isValidPublicKey(publicKey) else { throw DescriptorError.invalidKey }120        self.origin = origin121        source = .publicKey(publicKey)122        steps = []123        wildcard = false124        extendedKey = nil125        isTestKey = nil126    }127128    /// An extended public key (a private one is neutered first) followed by `steps` and an optional `/*`.129    public init(extendedKey key: ExtendedKey, testNetwork: Bool, origin: Origin? = nil, steps: [Step] = [], wildcard: Bool = true) throws {130        for s in steps {131            switch s {132            case .index(let i): guard i < ChildIndex.hardenedBit else { throw DescriptorError.hardenedDerivationUnsupported }133            case .multipath(let list):134                guard list.count >= 2, Set(list).count == list.count, list.allSatisfy({ $0 < ChildIndex.hardenedBit }) else {135                    throw DescriptorError.malformed("multipath")136                }137            }138        }139        guard steps.filter({ if case .multipath = $0 { return true } else { return false } }).count <= 1 else {140            throw DescriptorError.malformed("more than one multipath step")141        }142        let pub = key.neutered143        guard let text = try? pub.serialized(testNetwork ? .tpub : .xpub) else { throw DescriptorError.invalidKey }144        self.origin = origin145        source = .extended(text)146        self.steps = steps147        self.wildcard = wildcard148        extendedKey = pub149        isTestKey = testNetwork150    }151152    /// Number of alternatives of the multipath step, 1 without one.153    public var multipathCount: Int {154        for s in steps { if case .multipath(let list) = s { return list.count } }155        return 1156    }157158    /// The public key at `index` (ignored without wildcard) on multipath alternative `branch`.159    public func publicKey(index: UInt32, branch: Int = 0) throws -> Bytes {160        switch source {161        case .publicKey(let k):162            return k163        case .extended:164            guard var key = extendedKey else { throw DescriptorError.invalidKey }165            do {166                for s in steps {167                    switch s {168                    case .index(let i): key = try key.derive(.normal(i))169                    case .multipath(let list):170                        guard list.indices.contains(branch) else { throw DescriptorError.indexOutOfRange }171                        key = try key.derive(.normal(list[branch]))172                    }173                }174                if wildcard {175                    guard index < ChildIndex.hardenedBit else { throw DescriptorError.indexOutOfRange }176                    key = try key.derive(.normal(index))177                }178            } catch let e as DescriptorError {179                throw e180            } catch {181                throw DescriptorError.derivationFailed182            }183            return key.publicKey184        }185    }186187    /// Full derivation path from the master key (origin path + steps + index), nil without origin.188    public func fullPath(index: UInt32, branch: Int = 0) -> DerivationPath? {189        guard let origin else { return nil }190        var indices = origin.path.indices191        for s in steps {192            switch s {193            case .index(let i): indices.append(.normal(i))194            case .multipath(let list):195                guard list.indices.contains(branch) else { return nil }196                indices.append(.normal(list[branch]))197            }198        }199        if wildcard { indices.append(.normal(index)) }200        return DerivationPath(indices)201    }202203    /// The same key with its multipath step replaced by alternative `branch`.204    func resolving(branch: Int) throws -> DescriptorKey {205        guard multipathCount > 1 else { return self }206        guard let key = extendedKey, let test = isTestKey else { throw DescriptorError.invalidKey }207        var out = [Step]()208        for s in steps {209            if case .multipath(let list) = s {210                guard list.indices.contains(branch) else { throw DescriptorError.indexOutOfRange }211                out.append(.index(list[branch]))212            } else {213                out.append(s)214            }215        }216        return try DescriptorKey(extendedKey: key, testNetwork: test, origin: origin, steps: out, wildcard: wildcard)217    }218219    /// Text form; hardened origin steps are written with `h` (no shell quoting, as recent Bitcoin Core does).220    public var string: String {221        var out = ""222        if let origin {223            out += "[" + Hex.encode(origin.fingerprint)224            for c in origin.path.indices { out += "/\(c.index)" + (c.isHardened ? "h" : "") }225            out += "]"226        }227        switch source {228        case .publicKey(let k): out += Hex.encode(k)229        case .extended(let text): out += text230        }231        for s in steps {232            switch s {233            case .index(let i): out += "/\(i)"234            case .multipath(let list): out += "/<" + list.map(String.init).joined(separator: ";") + ">"235            }236        }237        if wildcard { out += "/*" }238        return out239    }240241    private static func number(_ text: Substring) -> UInt32? {242        guard !text.isEmpty, text.utf8.count <= 10, text.utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }),243              let v = UInt32(text), v < ChildIndex.hardenedBit else { return nil }244        return v245    }246247    /// Parses a key expression.248    public init(parsing text: String) throws {249        var rest = Substring(text)250        var origin: Origin?251        if rest.first == "[" {252            guard let close = rest.firstIndex(of: "]") else { throw DescriptorError.malformed("unterminated key origin") }253            let inner = rest[rest.index(after: rest.startIndex)..<close]254            let parts = inner.split(separator: "/", omittingEmptySubsequences: false)255            guard let fp = parts.first, fp.utf8.count == 8, let fingerprint = Hex.decode(String(fp)) else {256                throw DescriptorError.malformed("key origin fingerprint")257            }258            var indices = [ChildIndex]()259            for p in parts.dropFirst() {260                let hardened = p.hasSuffix("'") || p.hasSuffix("h")261                guard let v = Self.number(hardened ? p.dropLast() : p) else { throw DescriptorError.malformed("key origin path") }262                indices.append(hardened ? .hardened(v) : .normal(v))263            }264            origin = Origin(fingerprint: fingerprint, path: DerivationPath(indices))265            rest = rest[rest.index(after: close)...]266        }267        let parts = rest.split(separator: "/", omittingEmptySubsequences: false)268        guard let keyText = parts.first, !keyText.isEmpty else { throw DescriptorError.invalidKey }269        let isHex = keyText.utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x61 && $0 <= 0x66) || ($0 >= 0x41 && $0 <= 0x46) }270        if isHex, keyText.utf8.count == 66 || keyText.utf8.count == 130 {271            guard parts.count == 1 else { throw DescriptorError.malformed("derivation after a raw public key") }272            guard let bytes = Hex.decode(String(keyText)) else { throw DescriptorError.invalidKey }273            try self.init(publicKey: bytes, origin: origin)274            return275        }276        guard let parsed = try? ExtendedKey.parse(String(keyText)) else { throw DescriptorError.invalidKey }277        guard !parsed.version.isPrivate else { throw DescriptorError.privateKeyNotSupported }278        let test = parsed.version == .tpub || parsed.version == .vpub279        var steps = [Step]()280        var wildcard = false281        for (n, p) in parts.dropFirst().enumerated() {282            let last = n == parts.count - 2283            if p == "*" {284                guard last else { throw DescriptorError.malformed("wildcard must be the last step") }285                wildcard = true286            } else if p == "*'" || p == "*h" {287                throw DescriptorError.hardenedDerivationUnsupported288            } else if p.first == "<" {289                guard p.last == ">" else { throw DescriptorError.malformed("multipath") }290                var list = [UInt32]()291                for item in p.dropFirst().dropLast().split(separator: ";", omittingEmptySubsequences: false) {292                    if item.hasSuffix("'") || item.hasSuffix("h") { throw DescriptorError.hardenedDerivationUnsupported }293                    guard let v = Self.number(item) else { throw DescriptorError.malformed("multipath") }294                    list.append(v)295                }296                steps.append(.multipath(list))297            } else {298                if p.hasSuffix("'") || p.hasSuffix("h") { throw DescriptorError.hardenedDerivationUnsupported }299                guard let v = Self.number(p) else { throw DescriptorError.malformed("derivation step") }300                steps.append(.index(v))301            }302        }303        try self.init(extendedKey: parsed.key, testNetwork: test, origin: origin, steps: steps, wildcard: wildcard)304    }305}306307/// Output descriptors supported by QYVORA: `pkh(KEY)`, `wpkh(KEY)`, `wsh(multi(k,KEY,…))` and `wsh(sortedmulti(k,KEY,…))`308/// (BIP-380 key expressions and checksum, BIP-381, BIP-382, BIP-383, BIP-389 multipath).309public struct OutputDescriptor: Equatable, Sendable, CustomStringConvertible {310    public enum Kind: Equatable, Sendable {311        /// Legacy P2PKH (BIP-381): the accounts of Dogecoin and Bitcoin Cash.312        case pkh313        case wpkh314        /// Keys in the order written.315        case wshMulti(required: Int)316        /// Keys sorted lexicographically at each derivation (BIP-67).317        case wshSortedMulti(required: Int)318    }319320    public let kind: Kind321    public let keys: [DescriptorKey]322323    // MARK: Construction324325    public static func wpkh(_ key: DescriptorKey) throws -> OutputDescriptor {326        try OutputDescriptor(kind: .wpkh, keys: [key])327    }328329    public static func pkh(_ key: DescriptorKey) throws -> OutputDescriptor {330        try OutputDescriptor(kind: .pkh, keys: [key])331    }332333    public static func wshMultisig(required: Int, keys: [DescriptorKey], sorted: Bool) throws -> OutputDescriptor {334        try OutputDescriptor(kind: sorted ? .wshSortedMulti(required: required) : .wshMulti(required: required), keys: keys)335    }336337    init(kind: Kind, keys: [DescriptorKey]) throws {338        switch kind {339        case .wpkh, .pkh:340            guard keys.count == 1 else { throw DescriptorError.malformed("wpkh and pkh take one key") }341        case .wshMulti(let k), .wshSortedMulti(let k):342            guard !keys.isEmpty else { throw DescriptorError.malformed("multisig without key") }343            guard keys.count <= BitcoinLimits.maxMultisigKeys else { throw DescriptorError.tooManyKeys }344            guard k >= 1, k <= keys.count else { throw DescriptorError.invalidThreshold }345        }346        let kinds = Set(keys.compactMap(\.isTestKey))347        guard kinds.count <= 1 else { throw DescriptorError.networkMismatch }348        let multi = Set(keys.map(\.multipathCount).filter { $0 > 1 })349        guard multi.count <= 1 else { throw DescriptorError.multipathMismatch }350        for (i, a) in keys.enumerated() {351            for b in keys[(i + 1)...] where a.source == b.source && a.steps == b.steps && a.wildcard == b.wildcard {352                throw DescriptorError.duplicateKey353            }354        }355        self.kind = kind356        self.keys = keys357    }358359    // MARK: Checksum (BIP-380)360361    private static let inputCharset = Array("0123456789()[],'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ".utf8)362    private static let checksumCharset = Array("qpzry9x8gf2tvdw0s3jn54khce6mua7l".utf8)363364    private static func polymod(_ c: UInt64, _ value: UInt64) -> UInt64 {365        let c0 = c >> 35366        var c = ((c & 0x7_ffff_ffff) << 5) ^ value367        if c0 & 1 != 0 { c ^= 0xf5_dee5_1989 }368        if c0 & 2 != 0 { c ^= 0xa9_fdca_3312 }369        if c0 & 4 != 0 { c ^= 0x1b_ab10_e32d }370        if c0 & 8 != 0 { c ^= 0x37_06b1_677a }371        if c0 & 16 != 0 { c ^= 0x64_4d62_6ffd }372        return c373    }374375    /// The 8-character checksum of a descriptor body (without `#…`); nil when the body holds a character outside the376    /// descriptor character set.377    public static func checksum(_ body: String) -> String? {378        var c: UInt64 = 1379        var cls: UInt64 = 0380        var clsCount = 0381        for ch in body.utf8 {382            guard let pos = inputCharset.firstIndex(of: ch) else { return nil }383            c = polymod(c, UInt64(pos & 31))384            cls = cls * 3 + UInt64(pos >> 5)385            clsCount += 1386            if clsCount == 3 {387                c = polymod(c, cls)388                cls = 0389                clsCount = 0390            }391        }392        if clsCount > 0 { c = polymod(c, cls) }393        for _ in 0..<8 { c = polymod(c, 0) }394        c ^= 1395        let chars = (0..<8).map { checksumCharset[Int((c >> UInt64(5 * (7 - $0))) & 31)] }396        return String(decoding: chars, as: UTF8.self)397    }398399    // MARK: Text400401    /// Descriptor without checksum.402    public var body: String {403        let list = keys.map(\.string).joined(separator: ",")404        switch kind {405        case .pkh: return "pkh(\(list))"406        case .wpkh: return "wpkh(\(list))"407        case .wshMulti(let k): return "wsh(multi(\(k),\(list)))"408        case .wshSortedMulti(let k): return "wsh(sortedmulti(\(k),\(list)))"409        }410    }411412    /// Descriptor with its checksum: `body#checksum`.413    public var string: String { body + "#" + (Self.checksum(body) ?? "") }414    public var description: String { string }415416    /// Parses a descriptor. A checksum, when present, must verify; `requireChecksum` refuses a descriptor without one.417    /// Extended keys may be written xpub / tpub or SLIP-132 zpub / vpub; they are kept and re-serialized as xpub / tpub.418    public init(parsing text: String, requireChecksum: Bool = false) throws {419        guard text.utf8.count <= 8192 else { throw DescriptorError.malformed("too long") }420        var body = text421        if let hash = text.lastIndex(of: "#") {422            body = String(text[..<hash])423            let given = String(text[text.index(after: hash)...])424            guard given.utf8.count == 8 else { throw DescriptorError.invalidChecksum }425            guard let expected = Self.checksum(body) else { throw DescriptorError.invalidCharacter }426            guard expected == given else { throw DescriptorError.invalidChecksum }427        } else {428            guard !requireChecksum else { throw DescriptorError.missingChecksum }429            guard Self.checksum(body) != nil else { throw DescriptorError.invalidCharacter }430        }431        guard !body.contains("#") else { throw DescriptorError.malformed("several checksum separators") }432433        func unwrap(_ s: Substring, _ name: String) -> Substring? {434            guard s.hasPrefix(name + "("), s.hasSuffix(")") else { return nil }435            return s.dropFirst(name.count + 1).dropLast()436        }437        let whole = Substring(body)438        if let inner = unwrap(whole, "wpkh") {439            guard !inner.contains("("), !inner.contains(",") else { throw DescriptorError.malformed("wpkh argument") }440            try self.init(kind: .wpkh, keys: [try DescriptorKey(parsing: String(inner))])441            return442        }443        if let inner = unwrap(whole, "pkh") {444            guard !inner.contains("("), !inner.contains(",") else { throw DescriptorError.malformed("pkh argument") }445            try self.init(kind: .pkh, keys: [try DescriptorKey(parsing: String(inner))])446            return447        }448        guard let script = unwrap(whole, "wsh") else { throw DescriptorError.unsupportedDescriptor }449        let sorted: Bool450        let arguments: Substring451        if let a = unwrap(script, "sortedmulti") {452            sorted = true453            arguments = a454        } else if let a = unwrap(script, "multi") {455            sorted = false456            arguments = a457        } else {458            throw DescriptorError.unsupportedDescriptor459        }460        guard !arguments.contains("("), !arguments.contains(")") else { throw DescriptorError.malformed("multisig arguments") }461        let parts = arguments.split(separator: ",", omittingEmptySubsequences: false)462        guard parts.count >= 2 else { throw DescriptorError.malformed("multisig arguments") }463        guard parts[0].utf8.count <= 2, !parts[0].isEmpty, parts[0].utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }), let k = Int(parts[0]) else {464            throw DescriptorError.invalidThreshold465        }466        guard parts.count - 1 <= BitcoinLimits.maxMultisigKeys else { throw DescriptorError.tooManyKeys }467        let keys = try parts.dropFirst().map { try DescriptorKey(parsing: String($0)) }468        try self.init(kind: sorted ? .wshSortedMulti(required: k) : .wshMulti(required: k), keys: keys)469    }470471    // MARK: Derivation472473    /// True when at least one key ends with a wildcard: the descriptor describes a family of scripts.474    public var isRanged: Bool { keys.contains { $0.wildcard } }475    /// Number of BIP-389 alternatives (2 for `<0;1>`), 1 for an ordinary descriptor.476    public var multipathCount: Int { keys.map(\.multipathCount).max() ?? 1 }477    /// True for tpub keys, false for xpub keys, nil when the descriptor only holds raw public keys.478    public var isTestNetwork: Bool? { keys.compactMap(\.isTestKey).first }479480    /// The ordinary descriptor of multipath alternative `branch` (0 = first, usually receive; 1 = change).481    public func singlePath(_ branch: Int) throws -> OutputDescriptor {482        guard branch >= 0, branch < multipathCount else { throw DescriptorError.indexOutOfRange }483        return try OutputDescriptor(kind: kind, keys: try keys.map { try $0.resolving(branch: branch) })484    }485486    /// Public keys at `index`, in script order (sorted for sortedmulti).487    public func publicKeys(index: UInt32 = 0, branch: Int = 0) throws -> [Bytes] {488        guard branch >= 0, branch < multipathCount else { throw DescriptorError.indexOutOfRange }489        let derived = try keys.map { try $0.publicKey(index: index, branch: branch) }490        if case .wshSortedMulti = kind { return derived.sorted(by: lexicographicallyPrecedes) }491        return derived492    }493494    /// The multisig witness script at `index`; nil for wpkh and pkh.495    public func witnessScript(index: UInt32 = 0, branch: Int = 0) throws -> Bytes? {496        switch kind {497        case .wpkh, .pkh:498            return nil499        case .wshMulti(let k), .wshSortedMulti(let k):500            do {501                return try BitcoinScript.multisig(required: k, publicKeys: try publicKeys(index: index, branch: branch), sorted: false)502            } catch let e as DescriptorError {503                throw e504            } catch {505                throw DescriptorError.duplicateKey506            }507        }508    }509510    public func scriptPubKey(index: UInt32 = 0, branch: Int = 0) throws -> Bytes {511        do {512            if let script = try witnessScript(index: index, branch: branch) { return try BitcoinScript.p2wsh(witnessScript: script) }513            let key = try publicKeys(index: index, branch: branch)[0]514            return kind == .pkh ? try BitcoinScript.p2pkh(publicKey: key) : try BitcoinScript.p2wpkh(publicKey: key)515        } catch let e as DescriptorError {516            throw e517        } catch {518            throw DescriptorError.derivationFailed519        }520    }521522    /// Address at `index`. Throws `networkMismatch` when the keys belong to the other kind of network (xpub on testnet…).523    public func address(index: UInt32 = 0, branch: Int = 0, network: BitcoinNetwork) throws -> BitcoinAddress {524        if let test = isTestNetwork, test != network.isTest { throw DescriptorError.networkMismatch }525        let script = try scriptPubKey(index: index, branch: branch)526        guard let address = try? BitcoinAddress(scriptPubKey: script, network: network) else { throw DescriptorError.derivationFailed }527        return address528    }529530    // MARK: BIP-84531532    /// Descriptors of a BIP-84 account, for recovery sheets and watch-only import in another wallet.533    public struct AccountDescriptors: Equatable, Sendable {534        /// `wpkh([fp/84h/ch/ah]xpub/0/*)#…`535        public let receive: OutputDescriptor536        /// `wpkh([fp/84h/ch/ah]xpub/1/*)#…`537        public let change: OutputDescriptor538        /// `wpkh([fp/84h/ch/ah]xpub/<0;1>/*)#…` (BIP-389)539        public let combined: OutputDescriptor540    }541542    /// `accountKey` is the key at m/84'/coin'/account' (private or public; only its public part is used).543    /// `masterFingerprint` is the fingerprint of the master key; without it the descriptors carry no origin.544    public static func bip84(accountKey: ExtendedKey, network: BitcoinNetwork, account: UInt32 = 0,545                             masterFingerprint: Bytes? = nil) throws -> AccountDescriptors {546        try self.account(.bip84, accountKey: accountKey, network: network, account: account, masterFingerprint: masterFingerprint)547    }548549    /// Descriptors of a single-key account of either purpose: `wpkh(…)` for BIP-84, `pkh(…)` for BIP-44. The origin550    /// path is m/purpose'/coin'/account' with the coin type of `network`; extended keys are written xpub / tpub on551    /// every coin (the version bytes of Bitcoin, as descriptors require).552    public static func account(_ purpose: UTXOAccountPurpose, accountKey: ExtendedKey, network: BitcoinNetwork, account: UInt32 = 0,553                               masterFingerprint: Bytes? = nil) throws -> AccountDescriptors {554        guard network.supports(purpose) else { throw DescriptorError.unsupportedDescriptor }555        var origin: DescriptorKey.Origin?556        if let fp = masterFingerprint {557            guard let o = DescriptorKey.Origin(fingerprint: fp, path: StandardPaths.account(purpose, network, account: account)) else {558                throw DescriptorError.malformed("fingerprint")559            }560            origin = o561        }562        func make(_ step: DescriptorKey.Step) throws -> OutputDescriptor {563            let key = try DescriptorKey(extendedKey: accountKey, testNetwork: network.isTest, origin: origin, steps: [step], wildcard: true)564            return purpose == .bip84 ? try .wpkh(key) : try .pkh(key)565        }566        return AccountDescriptors(receive: try make(.index(0)), change: try make(.index(1)), combined: try make(.multipath([0, 1])))567    }568}569
Files main
Menu

Theme