SPB Git

Repository Public

Transaction.swift 20.4 KB 429 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraBitcoin/Transaction.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/// Reference to a transaction output. `hash` is in wire order (the reverse of the hexadecimal txid shown by explorers).47public struct BitcoinOutPoint: Equatable, Hashable, Sendable, CustomStringConvertible {48    /// 32 bytes, wire (internal) byte order.49    public let hash: Bytes50    public let index: UInt325152    /// `hash` must be 32 bytes in wire order.53    public init?(hash: Bytes, index: UInt32) {54        guard hash.count == 32 else { return nil }55        self.hash = hash56        self.index = index57    }5859    /// From the 64-character hexadecimal txid as displayed by explorers and returned by Esplora.60    public init?(txid: String, vout: UInt32) {61        guard txid.utf8.count == 64, let b = Hex.decode(txid) else { return nil }62        hash = b.reversed()63        index = vout64    }6566    /// Hexadecimal txid in display order.67    public var txid: String { Hex.encode(hash.reversed()) }68    public var description: String { "\(txid):\(index)" }6970    var serialized: Bytes { hash + Wire.u32(index) }71    var isNull: Bool { index == 0xffff_ffff && hash.allSatisfy { $0 == 0 } }72}7374/// SIGHASH flags (one base type, optionally combined with ANYONECANPAY).75public struct BitcoinSighashType: Equatable, Hashable, Sendable {76    public let rawValue: UInt3277    public init(rawValue: UInt32) { self.rawValue = rawValue }7879    public static let all = BitcoinSighashType(rawValue: 0x01)80    public static let none = BitcoinSighashType(rawValue: 0x02)81    public static let single = BitcoinSighashType(rawValue: 0x03)82    public static let allAnyoneCanPay = BitcoinSighashType(rawValue: 0x81)83    public static let noneAnyoneCanPay = BitcoinSighashType(rawValue: 0x82)84    public static let singleAnyoneCanPay = BitcoinSighashType(rawValue: 0x83)8586    public var anyoneCanPay: Bool { rawValue & 0x80 != 0 }87    var base: UInt32 { rawValue & 0x1f }88    /// One of the six defined values (the only ones standardness accepts on Bitcoin, Litecoin and Dogecoin).89    public var isStandard: Bool { [0x01, 0x02, 0x03, 0x81, 0x82, 0x83].contains(rawValue) }9091    /// SIGHASH_FORKID, the replay-protection flag of Bitcoin Cash (the fork id itself, in the upper 24 bits, is 0).92    public static let forkIDFlag: UInt32 = 0x4093    /// SIGHASH_ALL | SIGHASH_FORKID: the type of every signature QYVORA makes on Bitcoin Cash (signature byte 0x41).94    public static let allForkID = BitcoinSighashType(rawValue: 0x41)95    public var hasForkID: Bool { rawValue & Self.forkIDFlag != 0 }96    public var withForkID: BitcoinSighashType { BitcoinSighashType(rawValue: rawValue | Self.forkIDFlag) }97    public var withoutForkID: BitcoinSighashType { BitcoinSighashType(rawValue: rawValue & ~Self.forkIDFlag) }9899    /// The type as a network writes it: with the fork-id flag on Bitcoin Cash, without it elsewhere.100    public func adapted(to scheme: UTXOSighashScheme) -> BitcoinSighashType { scheme == .bip143ForkID ? withForkID : withoutForkID }101102    /// Whether a signature of this type is acceptable under a scheme: one of the six base values, with the fork-id103    /// flag exactly when the scheme is Bitcoin Cash's (a signature without it is replayable on Bitcoin, one with it is104    /// invalid everywhere else).105    public func isStandard(for scheme: UTXOSighashScheme) -> Bool {106        scheme == .bip143ForkID ? hasForkID && withoutForkID.isStandard : isStandard107    }108}109110/// A Bitcoin transaction with BIP-144 witness data.111public struct BitcoinTransaction: Equatable, Hashable, Sendable {112    public struct Input: Equatable, Hashable, Sendable {113        public var previousOutput: BitcoinOutPoint114        public var scriptSig: Bytes115        public var sequence: UInt32116        /// Witness stack; empty for a non-witness input.117        public var witness: [Bytes]118119        public init(previousOutput: BitcoinOutPoint, scriptSig: Bytes = [], sequence: UInt32 = Input.sequenceFinal, witness: [Bytes] = []) {120            self.previousOutput = previousOutput121            self.scriptSig = scriptSig122            self.sequence = sequence123            self.witness = witness124        }125126        public static let sequenceFinal: UInt32 = 0xffff_ffff127        /// Highest sequence that still enables nLockTime without signalling replaceability.128        public static let sequenceLockTimeOnly: UInt32 = 0xffff_fffe129        /// BIP-125 opt-in replace-by-fee signal used by QYVORA (and Bitcoin Core).130        public static let sequenceRBF: UInt32 = 0xffff_fffd131    }132133    public struct Output: Equatable, Hashable, Sendable {134        /// Satoshis.135        public var value: UInt64136        public var scriptPubKey: Bytes137138        public init(value: UInt64, scriptPubKey: Bytes) {139            self.value = value140            self.scriptPubKey = scriptPubKey141        }142143        var serialized: Bytes { Wire.u64(value) + Wire.varBytes(scriptPubKey) }144    }145146    public var version: Int32147    public var inputs: [Input]148    public var outputs: [Output]149    public var lockTime: UInt32150151    public init(version: Int32 = 2, inputs: [Input], outputs: [Output], lockTime: UInt32 = 0) {152        self.version = version153        self.inputs = inputs154        self.outputs = outputs155        self.lockTime = lockTime156    }157158    public var hasWitness: Bool { inputs.contains { !$0.witness.isEmpty } }159    /// True when at least one input signals BIP-125 replaceability.160    public var signalsRBF: Bool { inputs.contains { $0.sequence <= Input.sequenceRBF } }161162    // MARK: Serialization163164    /// Network serialization. With `includeWitness` (the default) the BIP-144 form is used when a witness exists;165    /// without it, the legacy form that defines the txid.166    public func serialized(includeWitness: Bool = true) -> Bytes {167        let witness = includeWitness && hasWitness168        var out = Wire.u32(UInt32(bitPattern: version))169        if witness { out += [0x00, 0x01] }170        out += Wire.varInt(inputs.count)171        for i in inputs {172            out += i.previousOutput.serialized173            out += Wire.varBytes(i.scriptSig)174            out += Wire.u32(i.sequence)175        }176        out += Wire.varInt(outputs.count)177        for o in outputs { out += o.serialized }178        if witness {179            for i in inputs {180                out += Wire.varInt(i.witness.count)181                for item in i.witness { out += Wire.varBytes(item) }182            }183        }184        out += Wire.u32(lockTime)185        return out186    }187188    public var hex: String { Hex.encode(serialized()) }189190    /// Strict parser: canonical CompactSize, counts bounded by the data, a witness flag only with a non-empty witness,191    /// no trailing byte. With `allowWitness` false the data is read as the legacy form only (PSBT unsigned transactions).192    public init(parsing data: Bytes, allowWitness: Bool = true) throws {193        guard data.count <= BitcoinLimits.maxWeight else { throw BitcoinSerializationError.oversized }194        var r = ByteReader(data)195        self = try BitcoinTransaction(reader: &r, allowWitness: allowWitness)196        guard r.isAtEnd else { throw BitcoinSerializationError.trailingBytes }197    }198199    public init(hex: String, allowWitness: Bool = true) throws {200        guard let data = Hex.decode(hex) else { throw BitcoinSerializationError.malformed("hexadecimal") }201        try self.init(parsing: data, allowWitness: allowWitness)202    }203204    init(reader r: inout ByteReader, allowWitness: Bool) throws {205        version = Int32(bitPattern: try r.u32())206        func readInputs(_ r: inout ByteReader) throws -> [Input] {207            let n = try r.count(minimumItemSize: 41)208            var list = [Input]()209            list.reserveCapacity(n)210            for _ in 0..<n {211                let hash = try r.take(32)212                let index = try r.u32()213                let script = try r.varBytes()214                let sequence = try r.u32()215                list.append(Input(previousOutput: BitcoinOutPoint(hash: hash, index: index)!, scriptSig: script, sequence: sequence))216            }217            return list218        }219        func readOutputs(_ r: inout ByteReader) throws -> [Output] {220            let n = try r.count(minimumItemSize: 9)221            var list = [Output]()222            list.reserveCapacity(n)223            for _ in 0..<n {224                let value = try r.u64()225                list.append(Output(value: value, scriptPubKey: try r.varBytes()))226            }227            return list228        }229        var ins = try readInputs(&r)230        var outs = [Output]()231        var flags: UInt8 = 0232        if ins.isEmpty && allowWitness {233            // BIP-144: an empty input vector is the marker; the next byte is the flag.234            flags = try r.u8()235            if flags != 0 {236                ins = try readInputs(&r)237                outs = try readOutputs(&r)238            }239        } else {240            outs = try readOutputs(&r)241        }242        if flags & 1 != 0 {243            flags ^= 1244            for i in ins.indices {245                let n = try r.count(minimumItemSize: 1)246                var stack = [Bytes]()247                stack.reserveCapacity(n)248                for _ in 0..<n { stack.append(try r.varBytes()) }249                ins[i].witness = stack250            }251            guard ins.contains(where: { !$0.witness.isEmpty }) else { throw BitcoinSerializationError.malformed("superfluous witness record") }252        }253        guard flags == 0 else { throw BitcoinSerializationError.malformed("unknown transaction optional data") }254        inputs = ins255        outputs = outs256        lockTime = try r.u32()257    }258259    // MARK: Identity and size260261    /// Double SHA-256 of the legacy serialization, wire byte order.262    public var txidBytes: Bytes { SHA256.double(serialized(includeWitness: false)) }263    /// Transaction identifier as displayed (hexadecimal, reversed).264    public var txid: String { Hex.encode(txidBytes.reversed()) }265    /// Witness transaction identifier (BIP-141), displayed form; equals `txid` without witness.266    public var wtxid: String { Hex.encode(SHA256.double(serialized()).reversed()) }267268    /// BIP-141 weight: 3 × base size + total size.269    public var weight: Int { serialized(includeWitness: false).count * 3 + serialized().count }270    /// Virtual size in vbytes: weight / 4 rounded up.271    public var vsize: Int { (weight + 3) / 4 }272273    /// Sum of the output values, nil on overflow of Bitcoin's monetary range.274    public var outputValue: UInt64? { outputValue(maximumMoney: BitcoinLimits.maxMoney) }275276    /// Sum of the output values, nil when an output or the sum exceeds `maximumMoney` (`BitcoinNetwork.maximumMoney`).277    public func outputValue(maximumMoney: UInt64) -> UInt64? {278        var total: UInt64 = 0279        for o in outputs {280            guard o.value <= maximumMoney else { return nil }281            let (sum, overflow) = total.addingReportingOverflow(o.value)282            guard !overflow, sum <= maximumMoney else { return nil }283            total = sum284        }285        return total286    }287288    public enum SanityError: Swift.Error, Equatable, Sendable {289        case noInputs, noOutputs, valueOutOfRange, duplicateInput, nullInput, oversized290    }291292    /// Context-free checks of Bitcoin Core's `CheckTransaction` (for a non-coinbase transaction).293    /// `maximumMoney` is the monetary range of the network (`BitcoinNetwork.maximumMoney`), Bitcoin's by default.294    public func checkSanity(maximumMoney: UInt64 = BitcoinLimits.maxMoney) throws {295        guard !inputs.isEmpty else { throw SanityError.noInputs }296        guard !outputs.isEmpty else { throw SanityError.noOutputs }297        guard serialized(includeWitness: false).count * 4 <= BitcoinLimits.maxWeight else { throw SanityError.oversized }298        guard outputValue(maximumMoney: maximumMoney) != nil else { throw SanityError.valueOutOfRange }299        guard Set(inputs.map(\.previousOutput)).count == inputs.count else { throw SanityError.duplicateInput }300        guard !inputs.contains(where: { $0.previousOutput.isNull }) else { throw SanityError.nullInput }301    }302}303304/// Signature hashes: BIP-143 for witness version 0, the original algorithm for legacy inputs, and the fork-id variant305/// of BIP-143 that Bitcoin Cash applies to every input.306public enum BitcoinSighash {307    public enum Error: Swift.Error, Equatable, Sendable {308        case inputIndexOutOfRange309        /// The hash type does not fit the scheme (fork-id flag missing on Bitcoin Cash, or present elsewhere).310        case sighashTypeMismatch311    }312313    /// Bitcoin Cash digest of input `inputIndex` ("replay protected sighash", UAHF): the BIP-143 preimage with the314    /// amount of the spent output, for every kind of input, with SIGHASH_FORKID in the hash type and fork id 0.315    /// `scriptCode` is the script being executed: the scriptPubKey for P2PKH, the redeem script for P2SH.316    public static func forkID(transaction tx: BitcoinTransaction, inputIndex: Int, scriptCode: Bytes, value: UInt64,317                              type: BitcoinSighashType = .allForkID) throws -> Bytes {318        guard type.hasForkID, type.rawValue >> 8 == 0 else { throw Error.sighashTypeMismatch }319        return SHA256.double(try segwitV0Preimage(transaction: tx, inputIndex: inputIndex, scriptCode: scriptCode, value: value, type: type))320    }321322    /// The digest an input signs under a network's scheme. `isWitness` says whether the script being satisfied is a323    /// witness version 0 program (ignored where the scheme leaves no choice); `value` is the amount of the spent324    /// output, which the legacy algorithm does not use.325    public static func digest(scheme: UTXOSighashScheme, isWitness: Bool, transaction tx: BitcoinTransaction, inputIndex: Int,326                              scriptCode: Bytes, value: UInt64, type: BitcoinSighashType) throws -> Bytes {327        guard type.isStandard(for: scheme) else { throw Error.sighashTypeMismatch }328        switch scheme {329        case .bip143ForkID:330            return try forkID(transaction: tx, inputIndex: inputIndex, scriptCode: scriptCode, value: value, type: type)331        case .legacy:332            return try legacy(transaction: tx, inputIndex: inputIndex, scriptCode: scriptCode, type: type)333        case .bip143:334            return isWitness335                ? try segwitV0(transaction: tx, inputIndex: inputIndex, scriptCode: scriptCode, value: value, type: type)336                : try legacy(transaction: tx, inputIndex: inputIndex, scriptCode: scriptCode, type: type)337        }338    }339340    /// BIP-143 digest of input `inputIndex`. `scriptCode` is the script being executed (for P2WPKH the P2PKH-style script of341    /// the key hash; for P2WSH the witness script, after the last executed OP_CODESEPARATOR), `value` the amount of the342    /// spent output in satoshis.343    public static func segwitV0(transaction tx: BitcoinTransaction, inputIndex: Int, scriptCode: Bytes, value: UInt64,344                                type: BitcoinSighashType = .all) throws -> Bytes {345        SHA256.double(try segwitV0Preimage(transaction: tx, inputIndex: inputIndex, scriptCode: scriptCode, value: value, type: type))346    }347348    /// The BIP-143 preimage (before the double SHA-256), exposed for the official vectors.349    public static func segwitV0Preimage(transaction tx: BitcoinTransaction, inputIndex: Int, scriptCode: Bytes, value: UInt64,350                                        type: BitcoinSighashType = .all) throws -> Bytes {351        guard tx.inputs.indices.contains(inputIndex) else { throw Error.inputIndexOutOfRange }352        let zero = Bytes(repeating: 0, count: 32)353        let base = type.base354        var hashPrevouts = zero, hashSequence = zero, hashOutputs = zero355        if !type.anyoneCanPay {356            hashPrevouts = SHA256.double(tx.inputs.flatMap { $0.previousOutput.serialized })357        }358        if !type.anyoneCanPay && base != 2 && base != 3 {359            hashSequence = SHA256.double(tx.inputs.flatMap { Wire.u32($0.sequence) })360        }361        if base != 2 && base != 3 {362            hashOutputs = SHA256.double(tx.outputs.flatMap { $0.serialized })363        } else if base == 3 && inputIndex < tx.outputs.count {364            hashOutputs = SHA256.double(tx.outputs[inputIndex].serialized)365        }366        let input = tx.inputs[inputIndex]367        var pre = Wire.u32(UInt32(bitPattern: tx.version))368        pre += hashPrevouts369        pre += hashSequence370        pre += input.previousOutput.serialized371        pre += Wire.varBytes(scriptCode)372        pre += Wire.u64(value)373        pre += Wire.u32(input.sequence)374        pre += hashOutputs375        pre += Wire.u32(tx.lockTime)376        pre += Wire.u32(type.rawValue)377        return pre378    }379380    /// Original (pre-SegWit) digest. `scriptCode` is the scriptPubKey or the redeem script being executed; OP_CODESEPARATOR381    /// bytes are removed as consensus does. Signature removal (FindAndDelete) is not performed: QYVORA never signs scripts382    /// that embed their own signatures.383    public static func legacy(transaction tx: BitcoinTransaction, inputIndex: Int, scriptCode: Bytes,384                              type: BitcoinSighashType = .all) throws -> Bytes {385        guard tx.inputs.indices.contains(inputIndex) else { throw Error.inputIndexOutOfRange }386        let base = type.base387        if base == 3 && inputIndex >= tx.outputs.count {388            // Historical consensus quirk: the digest is the number one.389            return [1] + Bytes(repeating: 0, count: 31)390        }391        var copy = tx392        for i in copy.inputs.indices {393            copy.inputs[i].scriptSig = []394            copy.inputs[i].witness = []395        }396        copy.inputs[inputIndex].scriptSig = removingCodeSeparators(scriptCode)397        if base == 2 || base == 3 {398            if base == 2 {399                copy.outputs = []400            } else {401                copy.outputs = Array(copy.outputs[...inputIndex])402                for i in 0..<inputIndex { copy.outputs[i] = BitcoinTransaction.Output(value: UInt64.max, scriptPubKey: []) }403            }404            for i in copy.inputs.indices where i != inputIndex { copy.inputs[i].sequence = 0 }405        }406        if type.anyoneCanPay { copy.inputs = [copy.inputs[inputIndex]] }407        return SHA256.double(copy.serialized(includeWitness: false) + Wire.u32(type.rawValue))408    }409410    private static func removingCodeSeparators(_ script: Bytes) -> Bytes {411        guard script.contains(BitcoinOpcode.opCodeSeparator), let elements = try? BitcoinScript.decode(script) else { return script }412        var out = Bytes()413        for e in elements {414            switch e {415            case .op(let op): if op != BitcoinOpcode.opCodeSeparator { out.append(op) }416            case .push(let data, let opcode):417                // Re-emit the push exactly as it was encoded.418                switch opcode {419                case BitcoinOpcode.pushData1: out += [opcode, UInt8(data.count)] + data420                case BitcoinOpcode.pushData2: out += [opcode] + Wire.u16(UInt16(data.count)) + data421                case BitcoinOpcode.pushData4: out += [opcode] + Wire.u32(UInt32(data.count)) + data422                default: out += [opcode] + data423                }424            }425        }426        return out427    }428}429
Files main
Menu

Theme