SPB Git

Repository Public

CoinSelection.swift 18.9 KB 381 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraBitcoin/CoinSelection.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 QyvoraCore4546/// Fee rate as an exact integer: millisatoshis per virtual byte (equivalently satoshis per 1000 vbytes).47/// No floating point enters fee arithmetic; `fromEstimate` is the single, rounding-up entry point for estimator output.48public struct FeeRate: Equatable, Comparable, Hashable, Sendable, CustomStringConvertible {49    public let milliSatPerVByte: UInt645051    public init(milliSatPerVByte: UInt64) { self.milliSatPerVByte = milliSatPerVByte }52    public init(satPerVByte: UInt64) { milliSatPerVByte = satPerVByte.multipliedReportingOverflow(by: 1000).overflow ? UInt64.max / 2 : satPerVByte * 1000 }53    public init(satPerKiloVByte: UInt64) { milliSatPerVByte = satPerKiloVByte }5455    /// Converts an estimator figure in sat/vB (Esplora, mempool.space) by rounding up to the next millisatoshi.56    /// nil for a value that is not finite, negative or above 1 000 000 sat/vB.57    public static func fromEstimate(satPerVByte value: Double) -> FeeRate? {58        guard value.isFinite, value >= 0, value <= 1_000_000 else { return nil }59        return FeeRate(milliSatPerVByte: UInt64((value * 1000).rounded(.up)))60    }6162    /// Dust relay fee of Bitcoin Core: 3 sat/vB.63    public static let dustRelay = FeeRate(satPerVByte: 3)64    /// Default minimum relay fee: 1 sat/vB.65    public static let minimumRelay = FeeRate(satPerVByte: 1)6667    /// The lowest rate QYVORA builds with on a network (`BitcoinNetwork.feePolicy`): 1 sat/vB on Bitcoin, Litecoin and68    /// Bitcoin Cash, 0.01 DOGE per 1000 bytes on Dogecoin.69    public static func minimum(for network: BitcoinNetwork) -> FeeRate { FeeRate(satPerKiloVByte: network.feePolicy.minimumFeeRatePerKiloVByte) }70    /// The rate above which a build is refused on a network, whatever the caller asks.71    public static func maximum(for network: BitcoinNetwork) -> FeeRate { FeeRate(satPerKiloVByte: network.feePolicy.maximumFeeRatePerKiloVByte) }7273    /// Converts an estimate expressed in whole coins per 1000 bytes (Blockbook `estimatefee`, Bitcore `fee`, the unit74    /// of the node's RPC) by rounding up to the next base unit per 1000 bytes. nil when the value is not finite, not75    /// positive or above 1000 coins per 1000 bytes.76    public static func fromEstimate(coinsPerKiloByte value: Double) -> FeeRate? {77        guard value.isFinite, value > 0, value <= 1_000 else { return nil }78        // 0.00001 × 10^8 is 1000.0000000000001 in binary floating point: a product within a millionth of a whole79        // number is that number, anything else is rounded up80        let scaled = value * 100_000_000, nearest = scaled.rounded()81        return FeeRate(milliSatPerVByte: UInt64(abs(scaled - nearest) < 1e-6 ? nearest : scaled.rounded(.up)))82    }8384    /// The rate brought inside the bounds of a network: an estimate below the floor is raised to it, one above the85    /// ceiling is lowered to it (Dogecoin nodes commonly estimate far above the recommended 0.01 DOGE/kB).86    public func clamped(to network: BitcoinNetwork) -> FeeRate { min(max(self, .minimum(for: network)), .maximum(for: network)) }8788    /// Fee in satoshis for `vsize` virtual bytes, rounded up.89    public func fee(vsize: Int) -> UInt64 {90        let (product, overflow) = milliSatPerVByte.multipliedReportingOverflow(by: UInt64(max(0, vsize)))91        if overflow { return UInt64.max / 2 }92        return product / 1000 + (product % 1000 == 0 ? 0 : 1)93    }9495    /// Fee for a weight: the weight is first rounded up to whole vbytes, as relay policy does.96    public func fee(weight: Int) -> UInt64 { fee(vsize: (max(0, weight) + 3) / 4) }9798    public static func < (a: FeeRate, b: FeeRate) -> Bool { a.milliSatPerVByte < b.milliSatPerVByte }99100    public var description: String {101        let whole = milliSatPerVByte / 1000, frac = milliSatPerVByte % 1000102        return frac == 0 ? "\(whole) sat/vB" : "\(whole)." + String(repeating: "0", count: 3 - String(frac).count) + "\(frac) sat/vB"103    }104}105106/// An unspent output the wallet may spend, with what is needed to size and sign its input.107public struct BitcoinUTXO: Equatable, Hashable, Sendable {108    /// Position in an HD account: chain 0 = receive, 1 = change.109    public struct Derivation: Equatable, Hashable, Sendable {110        public let chain: UInt32111        public let index: UInt32112        public init(chain: UInt32, index: UInt32) {113            self.chain = chain114            self.index = index115        }116    }117118    public let outPoint: BitcoinOutPoint119    /// Satoshis.120    public let value: UInt64121    public let scriptPubKey: Bytes122    /// 0 for an unconfirmed output.123    public let confirmations: UInt32124    public let address: String?125    public let derivation: Derivation?126    /// Witness script of a P2WSH (or P2SH-P2WSH) output.127    public let witnessScript: Bytes?128    /// Redeem script of a P2SH output.129    public let redeemScript: Bytes?130    /// Coinbase outputs need 100 confirmations before they can be spent.131    public let isCoinbase: Bool132    /// Weight of the spending input when the script is one the estimator does not know.133    public let inputWeightOverride: Int?134135    public init(outPoint: BitcoinOutPoint, value: UInt64, scriptPubKey: Bytes, confirmations: UInt32, address: String? = nil,136                derivation: Derivation? = nil, witnessScript: Bytes? = nil, redeemScript: Bytes? = nil, isCoinbase: Bool = false,137                inputWeightOverride: Int? = nil) {138        self.outPoint = outPoint139        self.value = value140        self.scriptPubKey = scriptPubKey141        self.confirmations = confirmations142        self.address = address143        self.derivation = derivation144        self.witnessScript = witnessScript145        self.redeemScript = redeemScript146        self.isCoinbase = isCoinbase147        self.inputWeightOverride = inputWeightOverride148    }149150    public var output: BitcoinTransaction.Output { BitcoinTransaction.Output(value: value, scriptPubKey: scriptPubKey) }151152    /// True when `previous` is the transaction that created this output and it shows exactly this amount and script:153    /// its txid is recomputed and compared with the outpoint. On a network whose signatures do not commit to the154    /// amounts (`BitcoinNetwork.signatureCommitsToAmounts` false: Dogecoin), a coin must pass this check before it is155    /// spent, or an indexer understating its value would turn the difference into fee.156    public func isAuthenticated(by previous: BitcoinTransaction) -> Bool {157        previous.txidBytes == outPoint.hash && Int(outPoint.index) < previous.outputs.count158            && previous.outputs[Int(outPoint.index)] == output159    }160    /// Weight of the input that spends this output, nil when it cannot be determined.161    public var inputWeight: Int? {162        inputWeightOverride ?? BitcoinSizeEstimator.inputWeight(scriptPubKey: scriptPubKey, witnessScript: witnessScript, redeemScript: redeemScript)163    }164}165166/// Sizes of inputs, outputs and transactions in weight units, and dust thresholds.167///168/// Signatures are counted at 72 bytes (71-byte DER maximum for low-s plus the SIGHASH byte): an estimate is never below169/// the real size, so the paid fee rate is never below the target.170public enum BitcoinSizeEstimator {171    /// Signature element with its length prefix.172    static let signatureElement = 1 + 72173    /// outpoint (36) + empty scriptSig length (1) + sequence (4), in weight units.174    static let baseInputWeight = 41 * 4175176    /// Version, lock time, input and output counts (non-witness), plus marker and flag when the transaction has a witness.177    public static func overheadWeight(inputCount: Int, outputCount: Int, hasWitness: Bool) -> Int {178        (4 + 4 + Wire.varIntSize(inputCount) + Wire.varIntSize(outputCount)) * 4 + (hasWitness ? 2 : 0)179    }180181    public static func outputWeight(scriptPubKey: Bytes) -> Int {182        (8 + Wire.varIntSize(scriptPubKey.count) + scriptPubKey.count) * 4183    }184185    private static func multisigWitnessWeight(_ script: Bytes) -> Int? {186        guard let m = BitcoinScript.parseMultisig(script) else { return nil }187        return 1 + 1 + m.required * signatureElement + Wire.varIntSize(script.count) + script.count188    }189190    /// Weight of the input spending a script, including its witness stack; nil for scripts QYVORA cannot size.191    /// A non-witness input costs one more unit in a SegWit transaction (its empty witness count); it is included here192    /// unless `inWitnessTransaction` is false (networks without SegWit: the weight is then exactly four times the size).193    public static func inputWeight(scriptPubKey: Bytes, witnessScript: Bytes? = nil, redeemScript: Bytes? = nil,194                                   inWitnessTransaction: Bool = true) -> Int? {195        let p2wpkhWitness = 1 + signatureElement + 1 + 33196        let emptyWitness = inWitnessTransaction ? 1 : 0197        switch BitcoinScript.classify(scriptPubKey) {198        case .p2wpkh:199            return baseInputWeight + p2wpkhWitness200        case .p2wsh:201            guard let ws = witnessScript, let w = multisigWitnessWeight(ws) else { return nil }202            return baseInputWeight + w203        case .p2tr:204            return baseInputWeight + 1 + 1 + 64205        case .p2pkh:206            return (40 + 1 + signatureElement + 1 + 33) * 4 + emptyWitness207        case .p2pk:208            return (40 + 1 + signatureElement) * 4 + emptyWitness209        case .p2sh:210            guard let redeem = redeemScript else { return nil }211            switch BitcoinScript.classify(redeem) {212            case .p2wpkh:213                return (40 + 1 + 1 + redeem.count) * 4 + p2wpkhWitness214            case .p2wsh:215                guard let ws = witnessScript, let w = multisigWitnessWeight(ws) else { return nil }216                return (40 + 1 + 1 + redeem.count) * 4 + w217            case .multisig(let k, _):218                let scriptSig = 1 + k * signatureElement + BitcoinScript.pushRaw(redeem).count219                return (40 + Wire.varIntSize(scriptSig) + scriptSig) * 4 + emptyWitness220            default:221                return nil222            }223        default:224            return nil225        }226    }227228    /// Estimated weight of a transaction from its inputs' weights and its output scripts.229    /// `hasWitness` false is for networks without SegWit (no marker and flag bytes).230    public static func transactionWeight(inputWeights: [Int], outputScripts: [Bytes], hasWitness: Bool = true) -> Int {231        overheadWeight(inputCount: inputWeights.count, outputCount: outputScripts.count, hasWitness: hasWitness)232            + inputWeights.reduce(0, +) + outputScripts.reduce(0) { $0 + outputWeight(scriptPubKey: $1) }233    }234235    /// Bitcoin Core's dust threshold (`GetDustThreshold`): the output size plus the size of the input that would spend it236    /// (67 bytes for a witness program, 148 otherwise), priced at the dust relay fee. An output whose value is below the237    /// threshold is dust. 294 sat for P2WPKH, 330 for P2WSH and P2TR, 546 for P2PKH, 540 for P2SH; 0 for OP_RETURN.238    public static func dustThreshold(scriptPubKey: Bytes, dustRelayFee: FeeRate = .dustRelay) -> UInt64 {239        if BitcoinScript.isUnspendable(scriptPubKey) { return 0 }240        let outputSize = 8 + Wire.varIntSize(scriptPubKey.count) + scriptPubKey.count241        let spendSize = BitcoinScript.witnessProgram(of: scriptPubKey) != nil ? 32 + 4 + 1 + 107 / 4 + 4 : 32 + 4 + 1 + 107 + 4242        // CFeeRate::GetFee truncates.243        return dustRelayFee.milliSatPerVByte * UInt64(outputSize + spendSize) / 1000244    }245246    public static func isDust(_ output: BitcoinTransaction.Output, dustRelayFee: FeeRate = .dustRelay) -> Bool {247        output.value < dustThreshold(scriptPubKey: output.scriptPubKey, dustRelayFee: dustRelayFee)248    }249250    /// Dust threshold under a network's rule: Bitcoin Core's formula at the network's dust relay rate (Bitcoin 3 sat/vB,251    /// Litecoin 30: 2940 litoshi for P2WPKH, 5460 for P2PKH), or one fixed value for every spendable script (Dogecoin252    /// 0.01 DOGE, Bitcoin Cash 546 sat). 0 for a provably unspendable output.253    public static func dustThreshold(scriptPubKey: Bytes, rule: UTXODustRule) -> UInt64 {254        switch rule {255        case .relayFee(let perKiloVByte):256            return dustThreshold(scriptPubKey: scriptPubKey, dustRelayFee: FeeRate(satPerKiloVByte: perKiloVByte))257        case .fixed(let threshold):258            return BitcoinScript.isUnspendable(scriptPubKey) ? 0 : threshold259        }260    }261262    public static func isDust(_ output: BitcoinTransaction.Output, rule: UTXODustRule) -> Bool {263        output.value < dustThreshold(scriptPubKey: output.scriptPubKey, rule: rule)264    }265266    public static func dustThreshold(scriptPubKey: Bytes, network: BitcoinNetwork) -> UInt64 {267        dustThreshold(scriptPubKey: scriptPubKey, rule: network.feePolicy.dust)268    }269270    public static func isDust(_ output: BitcoinTransaction.Output, network: BitcoinNetwork) -> Bool {271        isDust(output, rule: network.feePolicy.dust)272    }273}274275/// Deterministic generator (SplitMix64) for the shuffles of the builder: the same seed gives the same transaction.276struct SeededGenerator {277    private var state: UInt64278    init(seed: UInt64) { state = seed }279280    mutating func next() -> UInt64 {281        state &+= 0x9e37_79b9_7f4a_7c15282        var z = state283        z = (z ^ (z >> 30)) &* 0xbf58_476d_1ce4_e5b9284        z = (z ^ (z >> 27)) &* 0x94d0_49bb_1331_11eb285        return z ^ (z >> 31)286    }287288    /// Uniform integer in 0..<bound (rejection sampling, no modulo bias).289    mutating func below(_ bound: UInt64) -> UInt64 {290        precondition(bound > 0)291        let limit = UInt64.max - UInt64.max % bound292        while true {293            let v = next()294            if v < limit { return v % bound }295        }296    }297298    mutating func shuffle<T>(_ items: inout [T]) {299        guard items.count > 1 else { return }300        for i in stride(from: items.count - 1, to: 0, by: -1) {301            items.swapAt(i, Int(below(UInt64(i + 1))))302        }303    }304}305306/// Coin selection algorithms over effective values (value minus the fee to spend the coin at the target rate).307public enum BitcoinCoinSelection {308    /// A candidate with its input size and its cost at the current and long-term fee rates.309    struct Candidate {310        let utxo: BitcoinUTXO311        let weight: Int312        let fee: UInt64313        let longTermFee: UInt64314        var effectiveValue: Int64 { Int64(utxo.value) - Int64(fee) }315    }316317    static let branchAndBoundTries = 100_000318319    /// Branch and Bound (Murch; Bitcoin Core `SelectCoinsBnB`): an input set whose effective value lies in320    /// [target, target + costOfChange], minimising waste, explored depth-first on candidates sorted by decreasing321    /// effective value, within 100 000 steps. nil when no such set exists (or was found in the budget).322    /// `candidates` must have positive effective values. Returns indices into `candidates`.323    static func branchAndBound(candidates: [Candidate], target: Int64, costOfChange: Int64) -> [Int]? {324        guard target > 0 else { return nil }325        let order = candidates.indices.sorted {326            let a = candidates[$0], b = candidates[$1]327            if a.effectiveValue != b.effectiveValue { return a.effectiveValue > b.effectiveValue }328            if a.fee != b.fee { return a.fee < b.fee }329            return (a.utxo.outPoint.hash + Wire.u32(a.utxo.outPoint.index)).lexicographicallyPrecedes(b.utxo.outPoint.hash + Wire.u32(b.utxo.outPoint.index))330        }331        let pool = order.map { candidates[$0] }332        var available = pool.reduce(Int64(0)) { $0 + $1.effectiveValue }333        guard available >= target, let first = pool.first else { return nil }334        let feeRateHigh = first.fee > first.longTermFee335        var selection = [Bool]()336        var best: [Bool]?337        var bestWaste = Int64.max338        var value: Int64 = 0339        var waste: Int64 = 0340        for _ in 0..<branchAndBoundTries {341            var backtrack = false342            if value + available < target || value > target + costOfChange || (waste > bestWaste && feeRateHigh) {343                backtrack = true344            } else if value >= target {345                waste += value - target346                if waste <= bestWaste {347                    best = selection348                    bestWaste = waste349                    if bestWaste == 0 { break }350                }351                waste -= value - target352                backtrack = true353            }354            if backtrack {355                while let last = selection.last, !last {356                    selection.removeLast()357                    available += pool[selection.count].effectiveValue358                }359                if selection.isEmpty { break }360                selection[selection.count - 1] = false361                let c = pool[selection.count - 1]362                value -= c.effectiveValue363                waste -= Int64(c.fee) - Int64(c.longTermFee)364            } else {365                let c = pool[selection.count]366                available -= c.effectiveValue367                if let last = selection.last, !last,368                   c.effectiveValue == pool[selection.count - 1].effectiveValue, c.fee == pool[selection.count - 1].fee {369                    selection.append(false)370                } else {371                    selection.append(true)372                    value += c.effectiveValue373                    waste += Int64(c.fee) - Int64(c.longTermFee)374                }375            }376        }377        guard let best else { return nil }378        return best.indices.filter { best[$0] }.map { order[$0] }379    }380}381
Files main
Menu

Theme