SPB Git

Repository Public

TransactionBuilder.swift 26.6 KB 453 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraBitcoin/TransactionBuilder.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/// Reasons a spend cannot be built.47public enum BitcoinBuildError: Swift.Error, Equatable, Sendable {48    case noRecipients49    /// Recipient `index` is below its dust threshold or outside the monetary range.50    case dustOutput(index: Int)51    case invalidAmount52    case duplicateUTXO53    /// A UTXO required by coin control is missing from the candidates, frozen, immature or not confirmed enough.54    case requiredInputUnavailable(BitcoinOutPoint)55    /// The spending input of this UTXO cannot be sized (unknown script without `inputWeightOverride`).56    case unknownInputSize(BitcoinOutPoint)57    /// `required` is the amount to send plus the fee of the cheapest transaction that was attempted.58    case insufficientFunds(available: UInt64, required: UInt64)59    /// Change would be needed and no change script was supplied.60    case changeScriptRequired61    /// "Send max": what remains after the fee is below the dust threshold of the destination.62    case sendMaxBelowDust63    case feeRateOutOfRange64    case feeExceedsCap(fee: UInt64, cap: UInt64)65    /// Internal guard: the fee exceeds what the target rate and the changeless tolerance explain.66    case absurdFee(fee: UInt64, expected: UInt64)67    case transactionTooLarge68    /// A recipient, change or send-max script is a witness program and the network has no SegWit (Dogecoin, Bitcoin69    /// Cash): there, such an output could be spent by anyone.70    case witnessScriptNotSupported71}7273/// A payment to build.74public struct BitcoinSpendRequest: Sendable {75    /// Explicit control over the inputs.76    public struct CoinControl: Sendable {77        /// UTXOs that must be spent, whatever the algorithm would choose.78        public var required: [BitcoinOutPoint] = []79        /// Spend exactly `required` and nothing else.80        public var useOnlyRequired = false81        /// Frozen UTXOs: never selected.82        public var excluded: Set<BitcoinOutPoint> = []83        /// Minimum confirmations of automatically selected UTXOs (0 allows unconfirmed coins).84        public var minimumConfirmations: UInt32 = 18586        public init(required: [BitcoinOutPoint] = [], useOnlyRequired: Bool = false, excluded: Set<BitcoinOutPoint> = [],87                    minimumConfirmations: UInt32 = 1) {88            self.required = required89            self.useOnlyRequired = useOnlyRequired90            self.excluded = excluded91            self.minimumConfirmations = minimumConfirmations92        }93    }9495    /// Fixed payments (value in satoshis and scriptPubKey).96    public var recipients: [BitcoinTransaction.Output]97    /// "Send max": when set, every selected coin is spent and what remains after `recipients` and the fee goes to this98    /// script; there is no change output.99    public var sendMaxScript: Bytes?100    /// Spendable candidates.101    public var utxos: [BitcoinUTXO]102    /// Target fee rate.103    public var feeRate: FeeRate104    /// Where change goes (a script of the caller's change chain). Without it only changeless solutions are accepted.105    public var changeScript: Bytes?106    public var coinControl = CoinControl()107    /// BIP-125 signalling: sequence 0xfffffffd on every input (0xfffffffe otherwise).108    public var enableRBF = true109    /// Anti-fee-sniping: the current chain tip height; the lock time is set to it (with Bitcoin Core's occasional small110    /// random back-off). nil gives lock time 0.111    public var currentHeight: UInt32?112    /// Hard cap on the absolute fee, in satoshis.113    public var maximumFee: UInt64 = 1_000_000114    /// Bounds on the target fee rate.115    public var minimumFeeRate: FeeRate = .minimumRelay116    public var maximumFeeRate = FeeRate(satPerVByte: 5_000)117    /// Rate at which change is expected to be spent later (waste metric and cost of change). Defaults to `feeRate`.118    public var longTermFeeRate: FeeRate?119    /// Seed of the input / output shuffles and of the lock-time back-off. nil draws one from the system generator;120    /// a fixed seed makes the build reproducible.121    public var seed: UInt64?122    public var version: Int32 = 2123    /// How dust is decided (`BitcoinNetwork.feePolicy.dust`); Bitcoin's rule by default.124    public var dustRule: UTXODustRule = .relayFee(perKiloVByte: 3_000)125    /// False on a network without SegWit: witness programs are refused as outputs and as inputs, and sizes are plain126    /// byte counts.127    public var allowWitness = true128    /// Monetary range of the network, in base units.129    public var maximumMoney: UInt64 = BitcoinLimits.maxMoney130    /// The network the request was prepared for, when it was built with `init(network:…)`.131    public private(set) var network: BitcoinNetwork?132133    /// A request with Bitcoin's rules (1 sat/vB floor, Bitcoin's dust formula, replace-by-fee signalled, SegWit).134    public init(recipients: [BitcoinTransaction.Output], utxos: [BitcoinUTXO], feeRate: FeeRate, changeScript: Bytes?,135                sendMaxScript: Bytes? = nil) {136        self.recipients = recipients137        self.utxos = utxos138        self.feeRate = feeRate139        self.changeScript = changeScript140        self.sendMaxScript = sendMaxScript141    }142143    /// A request with the rules of `network`: its fee floor and ceiling, its dust rule, its monetary range, no witness144    /// scripts where SegWit does not exist, and no replace-by-fee signal where the network has none (Bitcoin Cash).145    /// On Bitcoin the result is the same as the other initialiser's.146    public init(network: BitcoinNetwork, recipients: [BitcoinTransaction.Output], utxos: [BitcoinUTXO], feeRate: FeeRate,147                changeScript: Bytes?, sendMaxScript: Bytes? = nil) {148        self.init(recipients: recipients, utxos: utxos, feeRate: feeRate, changeScript: changeScript, sendMaxScript: sendMaxScript)149        self.network = network150        minimumFeeRate = .minimum(for: network)151        maximumFeeRate = .maximum(for: network)152        enableRBF = network.supportsRBF153        dustRule = network.feePolicy.dust154        allowWitness = network.supportsSegWit155        maximumMoney = network.maximumMoney156        // the default cap of 0.01 BTC is expressed in satoshis: on Dogecoin the same number of koinu is 0.01 DOGE,157        // less than the fee of a large transaction at the recommended rate158        if network.coin == .dogecoin { maximumFee = 1_000_000_000 }159    }160}161162/// The outcome of a build: an unsigned transaction and everything needed to review and sign it.163public struct BitcoinTransactionPlan: Equatable, Sendable {164    public enum Algorithm: String, Sendable {165        /// Changeless exact match found by Branch and Bound.166        case branchAndBound167        /// Largest effective value first, with change (or changeless when the remainder is dust).168        case largestFirst169        /// Every eligible coin, remainder to the destination.170        case sendMax171        /// Exactly the inputs imposed by coin control.172        case manual173    }174175    /// Unsigned transaction (empty scriptSigs and witnesses).176    public let transaction: BitcoinTransaction177    /// Spent UTXOs, in the order of the transaction inputs.178    public let inputs: [BitcoinUTXO]179    /// Position of the change output, nil for a changeless transaction.180    public let changeIndex: Int?181    /// Position of the "send max" output, nil otherwise.182    public let sendMaxIndex: Int?183    /// Satoshis paid to miners: inputs minus outputs.184    public let fee: UInt64185    /// Upper estimate of the signed weight and virtual size.186    public let estimatedWeight: Int187    public var estimatedVSize: Int { (estimatedWeight + 3) / 4 }188    public let targetFeeRate: FeeRate189    public let algorithm: Algorithm190    /// The network of the request, when it named one.191    public let network: BitcoinNetwork?192193    public var inputValue: UInt64 { inputs.reduce(0) { $0 + $1.value } }194    public var changeValue: UInt64 { changeIndex.map { transaction.outputs[$0].value } ?? 0 }195    /// Lower bound of the fee rate actually paid, in millisatoshis per vbyte (fee over the estimated size, rounded down).196    public var effectiveFeeRate: FeeRate { FeeRate(milliSatPerVByte: fee * 1000 / UInt64(max(1, estimatedVSize))) }197198    /// Creator + Updater: the PSBT of the plan, each input with its UTXO and its scripts.199    ///200    /// `previousTransactions` maps a txid (display hexadecimal) to the transaction that created the coin. A SegWit input201    /// carries its witness UTXO, and its previous transaction too when one is given. An input that is not SegWit (every202    /// input on Dogecoin and Bitcoin Cash) can only be signed from its previous transaction: it must be supplied, and it203    /// must match the coin (`PSBTError.nonWitnessUTXORequired`, `nonWitnessUTXOMismatch`).204    public func psbt(previousTransactions: [String: BitcoinTransaction] = [:]) throws -> PSBT {205        var psbt = try PSBT(unsignedTransaction: transaction)206        psbt.sighashScheme = network?.sighashScheme ?? .bip143207        for (i, utxo) in inputs.enumerated() {208            let previous = previousTransactions[utxo.outPoint.txid]209            if let previous, !utxo.isAuthenticated(by: previous) { throw PSBTError.nonWitnessUTXOMismatch }210            var program = utxo.scriptPubKey211            if case .p2sh = BitcoinScript.classify(program), let redeem = utxo.redeemScript { program = redeem }212            if BitcoinScript.witnessProgram(of: program) != nil {213                psbt.inputs[i].witnessUTXO = utxo.output214            } else if previous == nil {215                throw PSBTError.nonWitnessUTXORequired216            }217            psbt.inputs[i].nonWitnessUTXO = previous218            psbt.inputs[i].redeemScript = utxo.redeemScript219            psbt.inputs[i].witnessScript = utxo.witnessScript220        }221        return psbt222    }223}224225/// Builds unsigned transactions: validation, coin selection, change, fee limits, ordering.226///227/// Ordering choice (documented): BIP-69 lexicographic ordering is *not* used, because a fixed order that only some228/// wallets follow is itself a fingerprint and it reveals nothing less about change. Inputs and outputs are instead229/// shuffled uniformly (Fisher–Yates) so that the change position carries no information, as Bitcoin Core does.230/// The shuffle is driven by `seed`: reproducible in tests, unpredictable in production (system generator).231public enum BitcoinTransactionBuilder {232    public static func build(_ request: BitcoinSpendRequest) throws -> BitcoinTransactionPlan {233        // 1. Request validation234        let rate = request.feeRate235        guard rate >= request.minimumFeeRate, rate <= request.maximumFeeRate, rate.milliSatPerVByte > 0 else { throw BitcoinBuildError.feeRateOutOfRange }236        guard !request.recipients.isEmpty || request.sendMaxScript != nil else { throw BitcoinBuildError.noRecipients }237        // The monetary range is the network's, and never above 2^62: every sum below stays far from 64-bit overflow.238        let maxMoney = min(request.maximumMoney, 1 << 62)239        let segwit = request.allowWitness240        func witnessAllowed(_ script: Bytes) -> Bool { segwit || BitcoinScript.witnessProgram(of: script) == nil }241        var outputTotal: UInt64 = 0242        for (i, r) in request.recipients.enumerated() {243            guard r.value <= maxMoney, r.scriptPubKey.count <= BitcoinLimits.maxScriptSize else { throw BitcoinBuildError.dustOutput(index: i) }244            guard witnessAllowed(r.scriptPubKey) else { throw BitcoinBuildError.witnessScriptNotSupported }245            let unspendable = BitcoinScript.isUnspendable(r.scriptPubKey)246            guard unspendable || (r.value > 0 && !BitcoinSizeEstimator.isDust(r, rule: request.dustRule)) else { throw BitcoinBuildError.dustOutput(index: i) }247            outputTotal += r.value248            guard outputTotal <= maxMoney else { throw BitcoinBuildError.invalidAmount }249        }250        for script in [request.changeScript, request.sendMaxScript].compactMap({ $0 }) {251            guard witnessAllowed(script) else { throw BitcoinBuildError.witnessScriptNotSupported }252        }253        guard Set(request.utxos.map(\.outPoint)).count == request.utxos.count else { throw BitcoinBuildError.duplicateUTXO }254        // The candidates come from an indexer. Their total is bounded here once, so that no sum over any subset of255        // them (input totals, effective values, waste) can overflow further down.256        var candidateTotal: UInt64 = 0257        for u in request.utxos {258            guard u.value <= maxMoney else { throw BitcoinBuildError.invalidAmount }259            candidateTotal += u.value260            guard candidateTotal <= maxMoney else { throw BitcoinBuildError.invalidAmount }261        }262        guard Set(request.coinControl.required).count == request.coinControl.required.count else { throw BitcoinBuildError.duplicateUTXO }263264        // 2. Candidates265        let longTerm = request.longTermFeeRate ?? rate266        func candidate(_ u: BitcoinUTXO) throws -> BitcoinCoinSelection.Candidate {267            // on a network without SegWit a witness program is not a coin the wallet can spend268            guard witnessAllowed(u.scriptPubKey), u.redeemScript.map(witnessAllowed) ?? true else { throw BitcoinBuildError.unknownInputSize(u.outPoint) }269            let estimated = u.inputWeightOverride ?? BitcoinSizeEstimator.inputWeight(scriptPubKey: u.scriptPubKey, witnessScript: u.witnessScript,270                                                                                    redeemScript: u.redeemScript, inWitnessTransaction: segwit)271            guard let w = estimated, w > 0 else { throw BitcoinBuildError.unknownInputSize(u.outPoint) }272            guard u.value <= maxMoney else { throw BitcoinBuildError.invalidAmount }273            return BitcoinCoinSelection.Candidate(utxo: u, weight: w, fee: rate.fee(weight: w), longTermFee: longTerm.fee(weight: w))274        }275        func spendable(_ u: BitcoinUTXO) -> Bool { !u.isCoinbase || u.confirmations >= 100 }276        let byOutPoint = Dictionary(uniqueKeysWithValues: request.utxos.map { ($0.outPoint, $0) })277        var forced = [BitcoinCoinSelection.Candidate]()278        for op in request.coinControl.required {279            guard let u = byOutPoint[op], !request.coinControl.excluded.contains(op), spendable(u) else {280                throw BitcoinBuildError.requiredInputUnavailable(op)281            }282            forced.append(try candidate(u))283        }284        let forcedSet = Set(request.coinControl.required)285        var pool = [BitcoinCoinSelection.Candidate]()286        if !request.coinControl.useOnlyRequired {287            for u in request.utxos where !forcedSet.contains(u.outPoint) && !request.coinControl.excluded.contains(u.outPoint)288                && u.confirmations >= request.coinControl.minimumConfirmations && spendable(u) {289                // Coins the wallet cannot size, or that cost more than they are worth at this rate, are left out.290                guard let c = try? candidate(u), c.effectiveValue > 0 else { continue }291                pool.append(c)292            }293        }294        // Deterministic base order, independent of the order the caller listed the UTXOs in.295        func key(_ c: BitcoinCoinSelection.Candidate) -> Bytes { c.utxo.outPoint.hash + Wire.u32(c.utxo.outPoint.index) }296        pool.sort {297            if $0.effectiveValue != $1.effectiveValue { return $0.effectiveValue > $1.effectiveValue }298            return key($0).lexicographicallyPrecedes(key($1))299        }300301        // 3. Sizes302        let recipientScripts = request.recipients.map(\.scriptPubKey)303        func weight(_ selected: [BitcoinCoinSelection.Candidate], extraOutput: Bytes?) -> Int {304            BitcoinSizeEstimator.transactionWeight(inputWeights: selected.map(\.weight), outputScripts: recipientScripts + (extraOutput.map { [$0] } ?? []),305                                                   hasWitness: segwit)306        }307        func total(_ selected: [BitcoinCoinSelection.Candidate]) -> UInt64 { selected.reduce(0) { $0 + $1.utxo.value } }308309        var selected: [BitcoinCoinSelection.Candidate]310        var extra: BitcoinTransaction.Output?   // change or send-max output311        var algorithm: BitcoinTransactionPlan.Algorithm312        var tolerance: UInt64 = 0               // fee above the requirement that a changeless result may carry313314        if let maxScript = request.sendMaxScript {315            // 4a. Send max: everything eligible, remainder to the destination316            guard maxScript.count <= BitcoinLimits.maxScriptSize, !BitcoinScript.isUnspendable(maxScript) else { throw BitcoinBuildError.sendMaxBelowDust }317            selected = forced + pool318            guard !selected.isEmpty else { throw BitcoinBuildError.insufficientFunds(available: 0, required: outputTotal) }319            let fee = rate.fee(weight: weight(selected, extraOutput: maxScript))320            let inputTotal = total(selected)321            guard inputTotal >= outputTotal + fee else { throw BitcoinBuildError.insufficientFunds(available: inputTotal, required: outputTotal + fee) }322            let remainder = BitcoinTransaction.Output(value: inputTotal - outputTotal - fee, scriptPubKey: maxScript)323            guard remainder.value > 0, !BitcoinSizeEstimator.isDust(remainder, rule: request.dustRule) else { throw BitcoinBuildError.sendMaxBelowDust }324            extra = remainder325            algorithm = request.coinControl.useOnlyRequired ? .manual : .sendMax326        } else {327            let changeScript = request.changeScript328            if let c = changeScript {329                guard c.count <= BitcoinLimits.maxScriptSize, !BitcoinScript.isUnspendable(c) else { throw BitcoinBuildError.changeScriptRequired }330            }331            let changeDust = changeScript.map { BitcoinSizeEstimator.dustThreshold(scriptPubKey: $0, rule: request.dustRule) } ?? 0332            // Cost of change: creating the output now and spending it later.333            let changeOutputFee = changeScript.map { rate.fee(weight: BitcoinSizeEstimator.outputWeight(scriptPubKey: $0)) } ?? rate.fee(vsize: 31)334            let changeSpendWeight = changeScript.flatMap { BitcoinSizeEstimator.inputWeight(scriptPubKey: $0, inWitnessTransaction: segwit) } ?? 272335            let costOfChange = changeOutputFee + longTerm.fee(weight: changeSpendWeight)336            // A remainder too small to be worth a change output is left to the fee; it never exceeds this bound.337            tolerance = changeOutputFee + max(changeDust, longTerm.fee(weight: changeSpendWeight))338339            /// Completes a selection: change when it is worth an output, otherwise changeless if the remainder is within340            /// the tolerance. nil when the selection does not cover the payment.341            func complete(_ s: [BitcoinCoinSelection.Candidate], allowChange: Bool) -> BitcoinTransaction.Output?? {342                let inputTotal = total(s)343                if allowChange, let c = changeScript {344                    let fee = rate.fee(weight: weight(s, extraOutput: c))345                    if inputTotal >= outputTotal + fee + max(changeDust, 1) {346                        return .some(BitcoinTransaction.Output(value: inputTotal - outputTotal - fee, scriptPubKey: c))347                    }348                }349                let fee = rate.fee(weight: weight(s, extraOutput: nil))350                if inputTotal >= outputTotal + fee, inputTotal - outputTotal - fee <= tolerance { return .some(nil) }351                return nil352            }353354            if request.coinControl.useOnlyRequired {355                guard !forced.isEmpty else { throw BitcoinBuildError.insufficientFunds(available: 0, required: outputTotal) }356                selected = forced357                algorithm = .manual358                guard let result = complete(selected, allowChange: true) else {359                    let need = outputTotal + rate.fee(weight: weight(selected, extraOutput: nil))360                    if total(selected) < need { throw BitcoinBuildError.insufficientFunds(available: total(selected), required: need) }361                    throw BitcoinBuildError.changeScriptRequired362                }363                extra = result364            } else {365                // 4b. Branch and Bound for a changeless transaction366                var found: (selection: [BitcoinCoinSelection.Candidate], output: BitcoinTransaction.Output?)?367                let fixedFee = rate.fee(weight: weight([], extraOutput: nil) + (forced.count + pool.count > 252 ? 8 : 0))368                let forcedEffective = forced.reduce(Int64(0)) { $0 + $1.effectiveValue }369                let target = Int64(outputTotal) + Int64(fixedFee) - forcedEffective370                if let picked = BitcoinCoinSelection.branchAndBound(candidates: pool, target: target, costOfChange: Int64(costOfChange)) {371                    let s = forced + picked.map { pool[$0] }372                    // By construction the excess is at most the cost of change, plus the per-input rounding of the fees.373                    let fee = rate.fee(weight: weight(s, extraOutput: nil))374                    if total(s) >= outputTotal + fee {375                        found = (s, nil)376                        tolerance = max(tolerance, total(s) - outputTotal - fee)377                    }378                }379                algorithm = .branchAndBound380                // 4c. Largest first, with change381                if found == nil {382                    algorithm = .largestFirst383                    var s = forced384                    var next = 0385                    while true {386                        if !s.isEmpty {387                            if let result = complete(s, allowChange: true) {388                                found = (s, result)389                                break390                            }391                        }392                        guard next < pool.count else { break }393                        s.append(pool[next])394                        next += 1395                    }396                }397                guard let found else {398                    let all = forced + pool399                    let need = outputTotal + rate.fee(weight: weight(all, extraOutput: nil))400                    let have = total(all)401                    if have >= need, changeScript == nil { throw BitcoinBuildError.changeScriptRequired }402                    throw BitcoinBuildError.insufficientFunds(available: have, required: need)403                }404                selected = found.selection405                extra = found.output406            }407        }408409        // 5. Fee checks410        let inputTotal = total(selected)411        let finalOutputs = request.recipients + (extra.map { [$0] } ?? [])412        let finalTotal = finalOutputs.reduce(UInt64(0)) { $0 + $1.value }413        guard inputTotal >= finalTotal else { throw BitcoinBuildError.invalidAmount }414        let fee = inputTotal - finalTotal415        let estimatedWeight = BitcoinSizeEstimator.transactionWeight(inputWeights: selected.map(\.weight), outputScripts: finalOutputs.map(\.scriptPubKey),416                                                                     hasWitness: segwit)417        guard estimatedWeight <= BitcoinLimits.maxStandardWeight else { throw BitcoinBuildError.transactionTooLarge }418        let requiredFee = rate.fee(weight: estimatedWeight)419        guard fee >= requiredFee else { throw BitcoinBuildError.absurdFee(fee: fee, expected: requiredFee) }420        guard fee <= request.maximumFee else { throw BitcoinBuildError.feeExceedsCap(fee: fee, cap: request.maximumFee) }421        let ceiling = requiredFee + (extra == nil ? tolerance : 0)422        guard fee <= ceiling else { throw BitcoinBuildError.absurdFee(fee: fee, expected: ceiling) }423424        // 6. Ordering, sequence, lock time425        var seedValue = request.seed426        if seedValue == nil {427            let b = SystemRandom.bytes(8)428            seedValue = b.reduce(UInt64(0)) { $0 << 8 | UInt64($1) }429        }430        var rng = SeededGenerator(seed: seedValue ?? 0)431        var orderedInputs = selected.map(\.utxo)432        rng.shuffle(&orderedInputs)433        var tagged = finalOutputs.enumerated().map { (isExtra: extra != nil && $0.offset == finalOutputs.count - 1, output: $0.element) }434        rng.shuffle(&tagged)435        let extraIndex = tagged.firstIndex { $0.isExtra }436        var lockTime: UInt32 = 0437        if let height = request.currentHeight, height < 500_000_000 {438            lockTime = height439            // Bitcoin Core: one time in ten, pick a lock time up to 99 blocks back, for the privacy of delayed signers.440            if rng.below(10) == 0 { lockTime = height - min(height, UInt32(rng.below(100))) }441        }442        let sequence = request.enableRBF ? BitcoinTransaction.Input.sequenceRBF : BitcoinTransaction.Input.sequenceLockTimeOnly443        let tx = BitcoinTransaction(version: request.version,444                                    inputs: orderedInputs.map { BitcoinTransaction.Input(previousOutput: $0.outPoint, sequence: sequence) },445                                    outputs: tagged.map(\.output), lockTime: lockTime)446        do { try tx.checkSanity(maximumMoney: maxMoney) } catch { throw BitcoinBuildError.invalidAmount }447        let isSendMax = request.sendMaxScript != nil448        return BitcoinTransactionPlan(transaction: tx, inputs: orderedInputs, changeIndex: isSendMax ? nil : extraIndex,449                                      sendMaxIndex: isSendMax ? extraIndex : nil, fee: fee, estimatedWeight: estimatedWeight,450                                      targetFeeRate: rate, algorithm: algorithm, network: request.network)451    }452}453
Files main
Menu

Theme