Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraBitcoin/Address.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/// A standard address of a UTXO network: Base58Check P2PKH / P2SH, Bech32 P2WPKH / P2WSH (BIP-173), Bech32m P2TR and47/// future witness versions (BIP-350) on the networks that have SegWit, CashAddr P2PKH / P2SH on Bitcoin Cash.48public struct BitcoinAddress: Equatable, Hashable, Sendable, CustomStringConvertible {49 public enum Error: Swift.Error, Equatable, Sendable {50 /// Not an address of any format the network uses.51 case invalidFormat52 /// Bech32 or CashAddr text mixing upper and lower case.53 case mixedCase54 /// Well-formed text whose checksum does not verify (including Bech32 used where Bech32m is required, and the reverse).55 case invalidChecksum56 /// Valid address of another network.57 case wrongNetwork58 /// Witness version / program length combination that BIP-141 forbids.59 case invalidWitnessProgram60 /// The scriptPubKey has no address form (P2PK, bare multisig, OP_RETURN, non-standard), or it is a SegWit script61 /// and the network has no SegWit.62 case noAddressForScript63 /// Litecoin P2SH address in the former encoding shared with Bitcoin ("3…", "2…"): refused because it cannot be64 /// told from a Bitcoin address; the current form starts with "M" (mainnet) or "Q" (testnet).65 case ambiguousLegacyFormat66 /// A valid CashAddr of a kind QYVORA does not pay to: token-aware types, 32-byte script hashes.67 case unsupportedAddressType68 }6970 public let network: BitcoinNetwork71 /// `.p2pkh`, `.p2sh`, `.p2wpkh`, `.p2wsh`, `.p2tr` or `.witnessUnknown`.72 public let type: BitcoinScriptType73 public let scriptPubKey: Bytes74 /// Canonical text: Base58Check as given, Bech32 in lower case, CashAddr in lower case with its prefix.75 public let string: String76 /// True when the text that was parsed is a legacy Base58 address of Bitcoin Cash: valid, but `string` is its77 /// CashAddr form and the interface should say that the format was converted.78 public let isLegacyFormat: Bool7980 public var description: String { string }8182 /// Bech32 prefixes of every network QYVORA knows, and regtest ones, to tell "another network" from "not an address".83 private static let knownHRPs = ["bc", "tb", "bcrt", "ltc", "tltc", "rltc"]84 private static let knownCashAddrPrefixes = ["bitcoincash", "bchtest", "bchreg"]85 /// Base58 version bytes of P2PKH and P2SH addresses on every network QYVORA knows.86 private static let knownBase58Versions: Set<UInt8> = [0x00, 0x05, 0x6f, 0xc4, 0x30, 0x32, 0x3a, 0x1e, 0x16, 0x71]8788 /// Parses an address for `network`. Test networks of one coin share their prefixes (Bitcoin testnet and signet), so89 /// an address of one is accepted for the other. Some coins share Base58 versions (Bitcoin Cash legacy addresses and90 /// Bitcoin; P2SH on several test networks): such an address is valid on both and nothing in it says which was meant.91 public init(_ text: String, network: BitcoinNetwork) throws {92 let trimmed = text93 guard !trimmed.isEmpty, trimmed.utf8.count <= 130, trimmed.unicodeScalars.allSatisfy({ $0.isASCII }) else { throw Error.invalidFormat }94 let lower = trimmed.lowercased()95 let hasUpper = trimmed.contains { $0.isUppercase }, hasLower = trimmed.contains { $0.isLowercase }9697 // 1. Bech32 / Bech32m98 if let hrp = Self.knownHRPs.first(where: { lower.hasPrefix($0 + "1") }) {99 if hasUpper && hasLower { throw Error.mixedCase }100 guard let expected = network.bech32HRP else {101 // no SegWit here: a valid address of a SegWit network is "another network", anything else is not an address102 if Bech32.decode(trimmed, variant: .bech32) != nil || Bech32.decode(trimmed, variant: .bech32m) != nil { throw Error.wrongNetwork }103 throw Error.invalidFormat104 }105 if let decoded = SegWitAddress.decode(trimmed, hrp: expected) {106 let script = try BitcoinScript.witnessProgram(version: decoded.version, program: decoded.program)107 self.network = network108 self.scriptPubKey = script109 self.type = BitcoinScript.classify(script).type110 self.string = lower111 self.isLegacyFormat = false112 return113 }114 // Diagnose: which of the checks failed.115 let plain = Bech32.decode(trimmed, variant: .bech32), modern = Bech32.decode(trimmed, variant: .bech32m)116 guard let any = plain ?? modern else { throw Error.invalidChecksum }117 if any.hrp != expected { throw hrp == expected ? Error.invalidFormat : Error.wrongNetwork }118 guard let version = any.words.first, version <= 16 else { throw Error.invalidWitnessProgram }119 // Right prefix, valid checksum under the wrong variant for this version, or a forbidden program.120 if (version == 0) != (plain != nil) { throw Error.invalidChecksum }121 throw Error.invalidWitnessProgram122 }123124 // 2. CashAddr: with its prefix, or (on Bitcoin Cash only) without it — at least 42 characters of the Bech32 set125 let colon = lower.contains(":")126 let bare = !colon && network.cashAddrPrefix != nil && lower.utf8.count >= 42 && lower.utf8.allSatisfy { Self.isBech32Character($0) }127 if colon || bare {128 if hasUpper && hasLower { throw Error.mixedCase }129 guard let expected = network.cashAddrPrefix else {130 if CashAddr.decode(trimmed) != nil { throw Error.wrongNetwork }131 throw Error.invalidFormat132 }133 guard let decoded = CashAddr.decode(trimmed, defaultPrefix: expected), decoded.prefix == expected else {134 // another prefix, written or implied: an address of another Bitcoin Cash network135 if let other = CashAddr.decode(trimmed), other.prefix != expected { throw Error.wrongNetwork }136 if !colon, Self.knownCashAddrPrefixes.contains(where: { $0 != expected && CashAddr.decode(trimmed, defaultPrefix: $0) != nil }) {137 throw Error.wrongNetwork138 }139 let parts = lower.split(separator: ":", omittingEmptySubsequences: false)140 guard parts.count <= 2, let body = parts.last, (42...112).contains(body.utf8.count),141 body.utf8.allSatisfy({ Self.isBech32Character($0) }),142 parts.count == 1 || (!parts[0].isEmpty && parts[0].utf8.allSatisfy({ $0 >= 97 && $0 <= 122 })) else {143 throw Error.invalidFormat144 }145 throw Error.invalidChecksum146 }147 guard decoded.hash.count == 20 else { throw Error.unsupportedAddressType }148 switch decoded.type {149 case CashAddr.typeP2PKH:150 scriptPubKey = try BitcoinScript.p2pkh(publicKeyHash: decoded.hash)151 type = .p2pkh152 case CashAddr.typeP2SH:153 scriptPubKey = try BitcoinScript.p2sh(scriptHash: decoded.hash)154 type = .p2sh155 default:156 throw Error.unsupportedAddressType157 }158 guard let canonical = CashAddr.encode(prefix: expected, type: decoded.type, hash: decoded.hash) else { throw Error.invalidFormat }159 self.network = network160 string = canonical161 isLegacyFormat = false162 return163 }164165 // 3. Base58Check166 guard trimmed.utf8.count <= 40, let raw = Base58.bitcoin.decode(trimmed), raw.count >= 5 else { throw Error.invalidFormat }167 guard let payload = Base58Check.decode(trimmed) else { throw Error.invalidChecksum }168 guard payload.count == 21 else { throw Error.invalidFormat }169 let version = payload[0], hash = Bytes(payload[1...])170 let kind: UInt8171 if version == network.p2pkhVersion {172 scriptPubKey = try BitcoinScript.p2pkh(publicKeyHash: hash)173 type = .p2pkh174 kind = CashAddr.typeP2PKH175 } else if version == network.p2shVersion {176 scriptPubKey = try BitcoinScript.p2sh(scriptHash: hash)177 type = .p2sh178 kind = CashAddr.typeP2SH179 } else if version == network.deprecatedP2SHVersion {180 throw Error.ambiguousLegacyFormat181 } else if Self.knownBase58Versions.contains(version) {182 throw Error.wrongNetwork183 } else {184 throw Error.invalidFormat185 }186 self.network = network187 if let prefix = network.cashAddrPrefix {188 guard let canonical = CashAddr.encode(prefix: prefix, type: kind, hash: hash) else { throw Error.invalidFormat }189 string = canonical190 isLegacyFormat = true191 } else {192 string = trimmed193 isLegacyFormat = false194 }195 }196197 private static func isBech32Character(_ c: UInt8) -> Bool {198 // lower-case letters and digits except "1", "b", "i", "o"199 ((c >= 0x30 && c <= 0x39) || (c >= 0x61 && c <= 0x7a)) && c != 0x31 && c != 0x62 && c != 0x69 && c != 0x6f200 }201202 /// The address of a scriptPubKey; throws `noAddressForScript` for templates without an address on this network.203 public init(scriptPubKey: Bytes, network: BitcoinNetwork) throws {204 let cls = BitcoinScript.classify(scriptPubKey)205 func segwit(_ version: UInt8, _ program: Bytes) throws -> String {206 guard let hrp = network.bech32HRP else { throw Error.noAddressForScript }207 guard let s = SegWitAddress.encode(hrp: hrp, version: version, program: program) else { throw Error.invalidWitnessProgram }208 return s209 }210 func hashed(_ version: UInt8, _ kind: UInt8, _ hash: Bytes) throws -> String {211 guard let prefix = network.cashAddrPrefix else { return Base58Check.encode([version] + hash) }212 guard let s = CashAddr.encode(prefix: prefix, type: kind, hash: hash) else { throw Error.noAddressForScript }213 return s214 }215 switch cls {216 case .p2pkh(let h):217 string = try hashed(network.p2pkhVersion, CashAddr.typeP2PKH, h)218 case .p2sh(let h):219 string = try hashed(network.p2shVersion, CashAddr.typeP2SH, h)220 case .p2wpkh(let p), .p2wsh(let p):221 string = try segwit(0, p)222 case .p2tr(let p):223 string = try segwit(1, p)224 case .witnessUnknown(let v, let p):225 string = try segwit(v, p)226 case .p2pk, .multisig, .nullData, .unknown:227 throw Error.noAddressForScript228 }229 self.network = network230 self.scriptPubKey = scriptPubKey231 type = cls.type232 isLegacyFormat = false233 }234235 /// Convenience: nil instead of an error.236 public static func parse(_ text: String, network: BitcoinNetwork) -> BitcoinAddress? { try? BitcoinAddress(text, network: network) }237238 /// Base58Check form of a P2PKH or P2SH address (on Bitcoin Cash: the legacy form used before CashAddr);239 /// nil for SegWit addresses.240 public var base58String: String? {241 switch BitcoinScript.classify(scriptPubKey) {242 case .p2pkh(let h): return Base58Check.encode([network.p2pkhVersion] + h)243 case .p2sh(let h): return Base58Check.encode([network.p2shVersion] + h)244 default: return nil245 }246 }247248 /// The address without its CashAddr prefix (what some indexers expect); `string` on the other networks.249 public var stringWithoutPrefix: String {250 guard network.cashAddrPrefix != nil, let colon = string.firstIndex(of: ":") else { return string }251 return String(string[string.index(after: colon)...])252 }253254 /// Native SegWit address of a compressed public key (BIP-84 style). Throws on a network without SegWit.255 public static func p2wpkh(publicKey: Bytes, network: BitcoinNetwork) throws -> BitcoinAddress {256 try BitcoinAddress(scriptPubKey: BitcoinScript.p2wpkh(publicKey: publicKey), network: network)257 }258259 /// Native SegWit address of a witness script. Throws on a network without SegWit.260 public static func p2wsh(witnessScript: Bytes, network: BitcoinNetwork) throws -> BitcoinAddress {261 try BitcoinAddress(scriptPubKey: BitcoinScript.p2wsh(witnessScript: witnessScript), network: network)262 }263264 /// Legacy address of a public key (BIP-44 style): Base58Check, or CashAddr on Bitcoin Cash.265 public static func p2pkh(publicKey: Bytes, network: BitcoinNetwork) throws -> BitcoinAddress {266 try BitcoinAddress(scriptPubKey: BitcoinScript.p2pkh(publicKey: publicKey), network: network)267 }268}269