Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBitcoin/Script.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 QyvoraSecp256k14546/// Opcodes used by the standard scripts QYVORA builds and recognises.47public enum BitcoinOpcode {48 public static let op0: UInt8 = 0x0049 public static let pushData1: UInt8 = 0x4c50 public static let pushData2: UInt8 = 0x4d51 public static let pushData4: UInt8 = 0x4e52 public static let op1Negate: UInt8 = 0x4f53 public static let op1: UInt8 = 0x5154 public static let op16: UInt8 = 0x6055 public static let opReturn: UInt8 = 0x6a56 public static let opDup: UInt8 = 0x7657 public static let opEqual: UInt8 = 0x8758 public static let opEqualVerify: UInt8 = 0x8859 public static let opHash160: UInt8 = 0xa960 public static let opCodeSeparator: UInt8 = 0xab61 public static let opCheckSig: UInt8 = 0xac62 public static let opCheckSigVerify: UInt8 = 0xad63 public static let opCheckMultisig: UInt8 = 0xae64 public static let opCheckMultisigVerify: UInt8 = 0xaf65}6667/// Family of a scriptPubKey.68public enum BitcoinScriptType: String, Codable, Sendable, CaseIterable {69 case p2pkh, p2sh, p2wpkh, p2wsh, p2tr, p2pk, multisig, nullData, witnessUnknown, unknown70}7172/// Result of the scriptPubKey classifier, with the data each template carries.73public enum BitcoinScriptClass: Equatable, Sendable {74 /// OP_DUP OP_HASH160 <20> OP_EQUALVERIFY OP_CHECKSIG75 case p2pkh(publicKeyHash: Bytes)76 /// OP_HASH160 <20> OP_EQUAL77 case p2sh(scriptHash: Bytes)78 /// OP_0 <20>79 case p2wpkh(publicKeyHash: Bytes)80 /// OP_0 <32>81 case p2wsh(scriptHash: Bytes)82 /// OP_1 <32>: the x-only output key is in the script itself.83 case p2tr(outputKey: Bytes)84 /// <33 or 65-byte public key> OP_CHECKSIG85 case p2pk(publicKey: Bytes)86 /// OP_k <keys…> OP_n OP_CHECKMULTISIG, outside any script hash.87 case multisig(required: Int, publicKeys: [Bytes])88 /// OP_RETURN followed by pushes only; `data` is the concatenated pushed bytes.89 case nullData(data: Bytes)90 /// A witness program of a version or a size without assigned meaning.91 case witnessUnknown(version: UInt8, program: Bytes)92 case unknown9394 public var type: BitcoinScriptType {95 switch self {96 case .p2pkh: return .p2pkh97 case .p2sh: return .p2sh98 case .p2wpkh: return .p2wpkh99 case .p2wsh: return .p2wsh100 case .p2tr: return .p2tr101 case .p2pk: return .p2pk102 case .multisig: return .multisig103 case .nullData: return .nullData104 case .witnessUnknown: return .witnessUnknown105 case .unknown: return .unknown106 }107 }108}109110/// Script construction, decoding and classification.111public enum BitcoinScript {112 public enum Error: Swift.Error, Equatable, Sendable {113 case invalidLength114 case invalidPublicKey115 case invalidMultisig116 case dataTooLarge117 case malformedScript118 }119120 /// One decoded script item.121 public enum Element: Equatable, Sendable {122 /// A data push (OP_0 is the empty push); `opcode` is the opcode that introduced it.123 case push(Bytes, opcode: UInt8)124 case op(UInt8)125 }126127 // MARK: Pushes128129 /// Minimal push of arbitrary data (BIP-62 rule 3): OP_0, OP_1…OP_16 and OP_1NEGATE for the one-byte values they cover.130 public static func push(_ data: Bytes) -> Bytes {131 if data.isEmpty { return [BitcoinOpcode.op0] }132 if data.count == 1 {133 if (1...16).contains(data[0]) { return [BitcoinOpcode.op1 + data[0] - 1] }134 if data[0] == 0x81 { return [BitcoinOpcode.op1Negate] }135 }136 return pushRaw(data)137 }138139 /// Push with the shortest length prefix but without replacing small values by OP_n (signatures, keys, scripts).140 static func pushRaw(_ data: Bytes) -> Bytes {141 switch data.count {142 case 0: return [BitcoinOpcode.op0]143 case 1...75: return [UInt8(data.count)] + data144 case 76...255: return [BitcoinOpcode.pushData1, UInt8(data.count)] + data145 case 256...65535: return [BitcoinOpcode.pushData2] + Wire.u16(UInt16(data.count)) + data146 default: return [BitcoinOpcode.pushData4] + Wire.u32(UInt32(data.count)) + data147 }148 }149150 /// Minimal push of a small non-negative script number (OP_0, OP_1…OP_16, then little-endian sign-magnitude).151 static func pushNumber(_ n: Int) -> Bytes {152 precondition(n >= 0 && n <= 0x7fff_ffff)153 if n == 0 { return [BitcoinOpcode.op0] }154 if n <= 16 { return [BitcoinOpcode.op1 + UInt8(n) - 1] }155 var v = n156 var out = Bytes()157 while v > 0 {158 out.append(UInt8(v & 0xff))159 v >>= 8160 }161 if out[out.count - 1] & 0x80 != 0 { out.append(0) }162 return pushRaw(out)163 }164165 // MARK: Decoding166167 /// Decodes a script into pushes and opcodes; throws on a push that runs past the end.168 public static func decode(_ script: Bytes) throws -> [Element] {169 var out = [Element]()170 var i = 0171 while i < script.count {172 let op = script[i]173 i += 1174 var length = -1175 switch op {176 case 0x00: length = 0177 case 0x01...0x4b: length = Int(op)178 case BitcoinOpcode.pushData1:179 guard i + 1 <= script.count else { throw Error.malformedScript }180 length = Int(script[i])181 i += 1182 case BitcoinOpcode.pushData2:183 guard i + 2 <= script.count else { throw Error.malformedScript }184 length = Int(script[i]) | Int(script[i + 1]) << 8185 i += 2186 case BitcoinOpcode.pushData4:187 guard i + 4 <= script.count else { throw Error.malformedScript }188 length = Int(script[i]) | Int(script[i + 1]) << 8 | Int(script[i + 2]) << 16 | Int(script[i + 3]) << 24189 i += 4190 default: break191 }192 if length >= 0 {193 guard length <= script.count - i else { throw Error.malformedScript }194 out.append(.push(Bytes(script[i..<(i + length)]), opcode: op))195 i += length196 } else {197 out.append(.op(op))198 }199 }200 return out201 }202203 /// Value of a small-integer element: OP_1…OP_16, or a minimal one-byte number push of 17…127.204 private static func smallInteger(_ e: Element) -> Int? {205 switch e {206 case .op(let op) where (BitcoinOpcode.op1...BitcoinOpcode.op16).contains(op):207 return Int(op - BitcoinOpcode.op1) + 1208 case .push(let data, let opcode) where opcode == 0x01 && data[0] > 16 && data[0] < 0x80:209 return Int(data[0])210 default:211 return nil212 }213 }214215 // MARK: scriptPubKey builders216217 public static func p2pkh(publicKeyHash h: Bytes) throws -> Bytes {218 guard h.count == 20 else { throw Error.invalidLength }219 return [BitcoinOpcode.opDup, BitcoinOpcode.opHash160, 20] + h + [BitcoinOpcode.opEqualVerify, BitcoinOpcode.opCheckSig]220 }221222 public static func p2pkh(publicKey: Bytes) throws -> Bytes {223 guard Secp256k1.isValidPublicKey(publicKey) else { throw Error.invalidPublicKey }224 return try p2pkh(publicKeyHash: Hash160.hash(publicKey))225 }226227 public static func p2sh(scriptHash h: Bytes) throws -> Bytes {228 guard h.count == 20 else { throw Error.invalidLength }229 return [BitcoinOpcode.opHash160, 20] + h + [BitcoinOpcode.opEqual]230 }231232 public static func p2sh(redeemScript: Bytes) throws -> Bytes {233 guard redeemScript.count <= BitcoinLimits.maxScriptElementSize else { throw Error.dataTooLarge }234 return try p2sh(scriptHash: Hash160.hash(redeemScript))235 }236237 public static func p2wpkh(publicKeyHash h: Bytes) throws -> Bytes {238 guard h.count == 20 else { throw Error.invalidLength }239 return [BitcoinOpcode.op0, 20] + h240 }241242 /// P2WPKH of a compressed public key (BIP-141 forbids uncompressed keys in witness programs by policy; QYVORA refuses them).243 public static func p2wpkh(publicKey: Bytes) throws -> Bytes {244 guard publicKey.count == 33, Secp256k1.isValidPublicKey(publicKey) else { throw Error.invalidPublicKey }245 return try p2wpkh(publicKeyHash: Hash160.hash(publicKey))246 }247248 public static func p2wsh(scriptHash h: Bytes) throws -> Bytes {249 guard h.count == 32 else { throw Error.invalidLength }250 return [BitcoinOpcode.op0, 32] + h251 }252253 /// P2WSH of a witness script: OP_0 <SHA256(script)> (single SHA-256).254 public static func p2wsh(witnessScript: Bytes) throws -> Bytes {255 guard witnessScript.count <= BitcoinLimits.maxScriptSize else { throw Error.dataTooLarge }256 return try p2wsh(scriptHash: SHA256.hash(witnessScript))257 }258259 /// P2TR from the 32-byte x-only *output* key (already tweaked).260 public static func p2tr(outputKey k: Bytes) throws -> Bytes {261 guard k.count == 32 else { throw Error.invalidLength }262 return [BitcoinOpcode.op1, 32] + k263 }264265 public static func p2pk(publicKey: Bytes) throws -> Bytes {266 guard Secp256k1.isValidPublicKey(publicKey) else { throw Error.invalidPublicKey }267 return pushRaw(publicKey) + [BitcoinOpcode.opCheckSig]268 }269270 /// Any witness program: OP_n <program>, version 0…16, program 2…40 bytes (20 or 32 for version 0).271 public static func witnessProgram(version: UInt8, program: Bytes) throws -> Bytes {272 guard version <= 16, (2...40).contains(program.count), version != 0 || program.count == 20 || program.count == 32 else {273 throw Error.invalidLength274 }275 return [version == 0 ? BitcoinOpcode.op0 : BitcoinOpcode.op1 + version - 1, UInt8(program.count)] + program276 }277278 /// OP_k <key 1> … <key n> OP_n OP_CHECKMULTISIG. With `sorted`, keys are put in lexicographic order (BIP-67, `sortedmulti`).279 /// 1 ≤ k ≤ n ≤ 20; keys must be valid and distinct. `compressedOnly` (the default) is required inside P2WSH.280 public static func multisig(required k: Int, publicKeys: [Bytes], sorted: Bool, compressedOnly: Bool = true) throws -> Bytes {281 guard k >= 1, k <= publicKeys.count, publicKeys.count <= BitcoinLimits.maxMultisigKeys else { throw Error.invalidMultisig }282 guard Set(publicKeys).count == publicKeys.count else { throw Error.invalidMultisig }283 for key in publicKeys {284 guard Secp256k1.isValidPublicKey(key), !compressedOnly || key.count == 33 else { throw Error.invalidPublicKey }285 }286 let keys = sorted ? publicKeys.sorted(by: lexicographicallyPrecedes) : publicKeys287 var script = pushNumber(k)288 for key in keys { script += pushRaw(key) }289 script += pushNumber(keys.count)290 script.append(BitcoinOpcode.opCheckMultisig)291 return script292 }293294 /// OP_RETURN <data>: at most 80 bytes of payload (the historical standardness bound, kept as QYVORA's limit).295 public static func nullData(_ data: Bytes) throws -> Bytes {296 guard data.count <= 80 else { throw Error.dataTooLarge }297 return [BitcoinOpcode.opReturn] + (data.isEmpty ? [] : pushRaw(data))298 }299300 // MARK: Classification301302 /// Parses OP_k <keys> OP_n OP_CHECKMULTISIG; nil when the script is anything else or the keys are not valid points.303 public static func parseMultisig(_ script: Bytes) -> (required: Int, publicKeys: [Bytes])? {304 guard script.last == BitcoinOpcode.opCheckMultisig, let elements = try? decode(script), elements.count >= 4,305 let k = smallInteger(elements[0]), let n = smallInteger(elements[elements.count - 2]),306 n == elements.count - 3, k >= 1, k <= n, n <= BitcoinLimits.maxMultisigKeys else { return nil }307 var keys = [Bytes]()308 for e in elements[1..<(elements.count - 2)] {309 guard case .push(let key, let opcode) = e, key.count == 33 || key.count == 65, Int(opcode) == key.count,310 Secp256k1.isValidPublicKey(key) else { return nil }311 keys.append(key)312 }313 return (k, keys)314 }315316 /// Witness version and program of a scriptPubKey (BIP-141), nil when it is not a witness program.317 public static func witnessProgram(of script: Bytes) -> (version: UInt8, program: Bytes)? {318 guard script.count >= 4, script.count <= 42, Int(script[1]) == script.count - 2,319 script[0] == BitcoinOpcode.op0 || (BitcoinOpcode.op1...BitcoinOpcode.op16).contains(script[0]) else { return nil }320 let version = script[0] == 0 ? 0 : script[0] - BitcoinOpcode.op1 + 1321 return (version, Bytes(script[2...]))322 }323324 public static func classify(_ script: Bytes) -> BitcoinScriptClass {325 if script.count == 25, script[0] == BitcoinOpcode.opDup, script[1] == BitcoinOpcode.opHash160, script[2] == 20,326 script[23] == BitcoinOpcode.opEqualVerify, script[24] == BitcoinOpcode.opCheckSig {327 return .p2pkh(publicKeyHash: Bytes(script[3..<23]))328 }329 if script.count == 23, script[0] == BitcoinOpcode.opHash160, script[1] == 20, script[22] == BitcoinOpcode.opEqual {330 return .p2sh(scriptHash: Bytes(script[2..<22]))331 }332 if let (version, program) = witnessProgram(of: script) {333 if version == 0 {334 if program.count == 20 { return .p2wpkh(publicKeyHash: program) }335 if program.count == 32 { return .p2wsh(scriptHash: program) }336 return .unknown // version 0 with another size is invalid under BIP-141337 }338 if version == 1, program.count == 32 { return .p2tr(outputKey: program) }339 return .witnessUnknown(version: version, program: program)340 }341 if script.count == 35 || script.count == 67, Int(script[0]) == script.count - 2, script[script.count - 1] == BitcoinOpcode.opCheckSig {342 let key = Bytes(script[1..<(script.count - 1)])343 if Secp256k1.isValidPublicKey(key) { return .p2pk(publicKey: key) }344 }345 if let m = parseMultisig(script) { return .multisig(required: m.required, publicKeys: m.publicKeys) }346 if script.first == BitcoinOpcode.opReturn, let elements = try? decode(Bytes(script.dropFirst())) {347 var data = Bytes()348 for e in elements {349 switch e {350 case .push(let d, _): data += d351 case .op(let op) where op == BitcoinOpcode.op1Negate || (BitcoinOpcode.op1...BitcoinOpcode.op16).contains(op):352 data.append(op == BitcoinOpcode.op1Negate ? 0x81 : op - BitcoinOpcode.op1 + 1)353 default: return .unknown354 }355 }356 return .nullData(data: data)357 }358 return .unknown359 }360361 /// True for scripts that can never be spent (OP_RETURN outputs or scripts above the consensus size).362 public static func isUnspendable(_ script: Bytes) -> Bool {363 script.first == BitcoinOpcode.opReturn || script.count > BitcoinLimits.maxScriptSize364 }365}366