Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBitcoin/Encoding.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/// Errors of the Bitcoin wire formats (transactions, scripts, PSBT payloads).47public enum BitcoinSerializationError: Swift.Error, Equatable, Sendable {48 /// The data ends before the announced structure does.49 case truncated50 /// A CompactSize integer is not in its shortest form.51 case nonCanonicalVarInt52 /// A count or a length exceeds what the remaining data (or the protocol) allows.53 case oversized54 /// Bytes remain after the structure.55 case trailingBytes56 /// The structure is malformed (the text says where).57 case malformed(String)58}5960/// Bounds of the protocol used as hard limits by the parsers and the builders.61public enum BitcoinLimits {62 /// 21 million bitcoin, in satoshis.63 public static let maxMoney: UInt64 = 2_100_000_000_000_00064 /// Consensus weight limit of a block, hence of a transaction.65 public static let maxWeight = 4_000_00066 /// Standardness weight limit of a transaction (Bitcoin Core policy).67 public static let maxStandardWeight = 400_00068 /// Largest script element (consensus).69 public static let maxScriptElementSize = 52070 /// Largest script (consensus).71 public static let maxScriptSize = 10_00072 /// Largest standard P2WSH witness script (policy).73 public static let maxStandardWitnessScriptSize = 3_60074 /// Keys in OP_CHECKMULTISIG (consensus).75 public static let maxMultisigKeys = 2076}7778/// Sequential reader over a byte array; every read is bounds-checked.79struct ByteReader {80 let bytes: Bytes81 private(set) var offset: Int8283 init(_ bytes: Bytes) {84 self.bytes = bytes85 offset = 086 }8788 var remaining: Int { bytes.count - offset }89 var isAtEnd: Bool { offset == bytes.count }9091 mutating func u8() throws -> UInt8 {92 guard remaining >= 1 else { throw BitcoinSerializationError.truncated }93 defer { offset += 1 }94 return bytes[offset]95 }9697 mutating func take(_ count: Int) throws -> Bytes {98 guard count >= 0, remaining >= count else { throw BitcoinSerializationError.truncated }99 defer { offset += count }100 return Bytes(bytes[offset..<(offset + count)])101 }102103 private mutating func le(_ count: Int) throws -> UInt64 {104 guard remaining >= count else { throw BitcoinSerializationError.truncated }105 var v: UInt64 = 0106 for i in 0..<count { v |= UInt64(bytes[offset + i]) << UInt64(8 * i) }107 offset += count108 return v109 }110111 mutating func u16() throws -> UInt16 { UInt16(try le(2)) }112 mutating func u32() throws -> UInt32 { UInt32(try le(4)) }113 mutating func u64() throws -> UInt64 { try le(8) }114115 /// CompactSize integer; the shortest encoding is mandatory, as in Bitcoin Core.116 mutating func varInt() throws -> UInt64 {117 let first = try u8()118 switch first {119 case 0xfd:120 let v = UInt64(try u16())121 guard v >= 0xfd else { throw BitcoinSerializationError.nonCanonicalVarInt }122 return v123 case 0xfe:124 let v = UInt64(try u32())125 guard v > 0xffff else { throw BitcoinSerializationError.nonCanonicalVarInt }126 return v127 case 0xff:128 let v = try u64()129 guard v > 0xffff_ffff else { throw BitcoinSerializationError.nonCanonicalVarInt }130 return v131 default:132 return UInt64(first)133 }134 }135136 /// A count of items that each take at least `minimumItemSize` bytes: rejected when the data cannot hold them.137 mutating func count(minimumItemSize: Int) throws -> Int {138 let v = try varInt()139 guard v <= UInt64(remaining / max(1, minimumItemSize)) else { throw BitcoinSerializationError.oversized }140 return Int(v)141 }142143 /// Length-prefixed byte string.144 mutating func varBytes() throws -> Bytes {145 let n = try varInt()146 guard n <= UInt64(remaining) else { throw BitcoinSerializationError.truncated }147 return try take(Int(n))148 }149}150151/// Little-endian writers of the wire format.152enum Wire {153 static func u16(_ v: UInt16) -> Bytes { [UInt8(v & 0xff), UInt8(v >> 8)] }154 static func u32(_ v: UInt32) -> Bytes { Endian.le32(v) }155 static func u64(_ v: UInt64) -> Bytes { Endian.le64(v) }156157 static func varInt(_ v: UInt64) -> Bytes {158 switch v {159 case 0..<0xfd: return [UInt8(v)]160 case 0xfd...0xffff: return [0xfd] + u16(UInt16(v))161 case 0x1_0000...0xffff_ffff: return [0xfe] + u32(UInt32(v))162 default: return [0xff] + u64(v)163 }164 }165166 static func varInt(_ v: Int) -> Bytes { varInt(UInt64(v)) }167168 static func varIntSize(_ v: Int) -> Int {169 switch v {170 case 0..<0xfd: return 1171 case 0xfd...0xffff: return 3172 case 0x1_0000...0xffff_ffff: return 5173 default: return 9174 }175 }176177 static func varBytes(_ b: Bytes) -> Bytes { varInt(b.count) + b }178}179180/// Lexicographic order on byte strings (BIP-67 key order, PSBT key order).181func lexicographicallyPrecedes(_ a: Bytes, _ b: Bytes) -> Bool { a.lexicographicallyPrecedes(b) }182183/// Wallet Import Format of a single private key (Base58Check: version ‖ key ‖ optional 0x01 for a compressed public key).184public enum BitcoinWIF {185 public enum Error: Swift.Error, Equatable, Sendable {186 case invalidEncoding187 case wrongNetwork188 case invalidPrivateKey189 }190191 public struct Decoded: Sendable {192 /// 32-byte private key.193 public let privateKey: Bytes194 /// Whether the matching public key is the 33-byte compressed form.195 public let compressed: Bool196 }197198 public static func decode(_ text: String, network: BitcoinNetwork) throws -> Decoded {199 // a WIF key is 51 or 52 characters; Base58 decoding is quadratic, so longer text is refused before decoding200 guard text.utf8.count <= 60, var payload = Base58Check.decode(text) else { throw Error.invalidEncoding }201 defer { SecureMemory.zero(&payload) }202 guard payload.count == 33 || (payload.count == 34 && payload[33] == 0x01) else { throw Error.invalidEncoding }203 guard payload[0] == network.wifVersion else { throw Error.wrongNetwork }204 let key = Bytes(payload[1..<33])205 guard key.contains(where: { $0 != 0 }) else { throw Error.invalidPrivateKey }206 return Decoded(privateKey: key, compressed: payload.count == 34)207 }208209 public static func encode(privateKey: Bytes, network: BitcoinNetwork, compressed: Bool = true) throws -> String {210 guard privateKey.count == 32 else { throw Error.invalidPrivateKey }211 var payload = [network.wifVersion] + privateKey + (compressed ? [0x01] : [])212 defer { SecureMemory.zero(&payload) }213 return Base58Check.encode(payload)214 }215}216