Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraNetworking/Esplora.swift8// Module : Qyvora Networking9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0513//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 QyvoraCore4344/// Models of the Esplora REST API (mempool.space, blockstream.info, litecoinspace.org, or the user's own instance).45public struct EsploraUTXO: Codable, Equatable, Hashable, Sendable {46 public struct Status: Codable, Equatable, Hashable, Sendable {47 public let confirmed: Bool48 public let block_height: Int?49 public let block_time: Int?50 }51 public let txid: String52 public let vout: Int53 public let value: UInt6454 public let status: Status55}5657public struct EsploraTransaction: Codable, Equatable, Sendable, Identifiable {58 public struct Prevout: Codable, Equatable, Sendable {59 public let scriptpubkey: String60 public let scriptpubkey_type: String?61 public let scriptpubkey_address: String?62 public let value: UInt6463 }64 public struct Input: Codable, Equatable, Sendable {65 public let txid: String66 public let vout: Int67 public let prevout: Prevout?68 public let witness: [String]?69 public let scriptsig: String?70 public let sequence: UInt32?71 }72 public let txid: String73 public let vin: [Input]74 public let vout: [Prevout]75 public let fee: UInt64?76 public let weight: Int?77 public let status: EsploraUTXO.Status78 public var id: String { txid }79}8081public struct EsploraAddressStats: Codable, Equatable, Sendable {82 public struct Stats: Codable, Equatable, Sendable {83 public let funded_txo_count: Int84 public let funded_txo_sum: UInt6485 public let spent_txo_count: Int86 public let spent_txo_sum: UInt6487 public let tx_count: Int88 }89 public let address: String90 public let chain_stats: Stats91 public let mempool_stats: Stats9293 /// True when the address appeared in any transaction, confirmed or not.94 /// (The counters come from the server: they are compared one by one, never added, so no value can overflow.)95 public var isUsed: Bool { chain_stats.tx_count > 0 || mempool_stats.tx_count > 0 }96 /// True when an output of this address was spent: its public key is then on chain.97 public var hasSpent: Bool { chain_stats.spent_txo_count > 0 || mempool_stats.spent_txo_count > 0 }98}99100public struct EsploraClient: Sendable {101 let bases: [URL]102 let transport: HTTPTransport103 public let network: BitcoinNetwork104105 public init(network: BitcoinNetwork, configuration: EndpointConfiguration = .default, transport: HTTPTransport) {106 self.network = network107 bases = urls(configuration.esplora[network.rawValue] ?? [])108 self.transport = transport109 }110111 public var isConfigured: Bool { !bases.isEmpty }112113 private static func isTxid(_ s: String) -> Bool { s.utf8.count == 64 && s.utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x61 && $0 <= 0x66) } }114 private static func isAddress(_ s: String) -> Bool { !s.isEmpty && s.utf8.count <= 100 && s.utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 >= 0x41 && $0 <= 0x5a) || ($0 >= 0x61 && $0 <= 0x7a) } }115116 private func json<T: Decodable & Sendable>(_ path: String, as type: T.Type) async throws -> T {117 try await transport.firstSuccess(bases) { base in118 let data = try await transport.get(base.appendingPathComponent(path))119 do { return try JSONDecoder().decode(T.self, from: data) } catch {120 // the decoding error is not interpolated: it would print Swift internals into a message shown to the user121 throw NetworkError.invalidResponse("\(path) is not the expected JSON")122 }123 }124 }125126 private func text(_ path: String) async throws -> String {127 try await transport.firstSuccess(bases) { base in128 String(decoding: try await transport.get(base.appendingPathComponent(path)), as: UTF8.self)129 .trimmingCharacters(in: .whitespacesAndNewlines)130 }131 }132133 public func tipHeight() async throws -> Int {134 guard let h = Int(try await text("blocks/tip/height")) else { throw NetworkError.invalidResponse("tip height") }135 return h136 }137138 /// Hash of the block at `height`; height 0 identifies the chain.139 public func blockHash(height: Int) async throws -> String { try await text("block-height/\(height)") }140141 /// Checks that every configured endpoint serves the expected chain: the hash of the network's identity block142 /// (block 0 on every network Esplora serves here). Called before the wallet trusts balances or broadcasts.143 public func verifyChain() async throws {144 try await UTXOWire.verifyChain(bases: bases, network: network) { base, height in145 String(decoding: try await transport.get(base.appendingPathComponent("block-height/\(height)")), as: UTF8.self)146 .trimmingCharacters(in: .whitespacesAndNewlines)147 }148 }149150 public func addressStats(_ address: String) async throws -> EsploraAddressStats {151 guard Self.isAddress(address) else { throw NetworkError.invalidURL }152 return try await json("address/\(address)", as: EsploraAddressStats.self)153 }154155 public func utxos(_ address: String) async throws -> [EsploraUTXO] {156 guard Self.isAddress(address) else { throw NetworkError.invalidURL }157 return try await json("address/\(address)/utxo", as: [EsploraUTXO].self)158 }159160 /// One page of history (newest first: mempool, then up to 25 confirmed). Pass the last confirmed txid for the next page.161 public func transactions(_ address: String, after lastSeen: String? = nil) async throws -> [EsploraTransaction] {162 guard Self.isAddress(address) else { throw NetworkError.invalidURL }163 if let lastSeen {164 guard Self.isTxid(lastSeen) else { throw NetworkError.invalidURL }165 return try await json("address/\(address)/txs/chain/\(lastSeen)", as: [EsploraTransaction].self)166 }167 return try await json("address/\(address)/txs", as: [EsploraTransaction].self)168 }169170 public func transaction(_ txid: String) async throws -> EsploraTransaction {171 guard Self.isTxid(txid) else { throw NetworkError.invalidURL }172 return try await json("tx/\(txid)", as: EsploraTransaction.self)173 }174175 public func transactionHex(_ txid: String) async throws -> String {176 guard Self.isTxid(txid) else { throw NetworkError.invalidURL }177 return try await text("tx/\(txid)/hex")178 }179180 /// Fee estimates in sat/vB keyed by confirmation target in blocks.181 ///182 /// Esplora serves them at `/fee-estimates`. mempool-based instances without an Esplora back end (litecoinspace.org)183 /// answer 404 there and publish `/v1/fees/recommended` instead: when the first request fails on every endpoint the184 /// second is tried, its five figures mapped to the targets 1, 3, 6, 144 and 1008 blocks.185 public func feeEstimates() async throws -> [Int: Double] {186 let raw: [String: Double]187 do {188 raw = try await json("fee-estimates", as: [String: Double].self)189 } catch let first {190 guard let recommended = try? await json("v1/fees/recommended", as: [String: Double].self) else { throw first }191 var out = [Int: Double]()192 for (name, target) in [("fastestFee", 1), ("halfHourFee", 3), ("hourFee", 6), ("economyFee", 144), ("minimumFee", 1008)] {193 if let v = recommended[name], v.isFinite, v > 0 { out[target] = v }194 }195 return out196 }197 var out = [Int: Double]()198 for (k, v) in raw { if let t = Int(k), v.isFinite, v > 0 { out[t] = v } }199 return out200 }201202 /// Sends the raw transaction to every configured endpoint. Success when one accepts it or already knows it.203 /// Returns the txid reported by the endpoint; callers compare it with the locally computed txid.204 public func broadcast(rawHex: String) async throws -> String {205 guard !bases.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }206 var accepted: String?207 var failures = [String]()208 for base in bases {209 var r = URLRequest(url: base.appendingPathComponent("tx"))210 r.httpMethod = "POST"211 r.httpBody = Data(rawHex.utf8)212 r.setValue("text/plain", forHTTPHeaderField: "Content-Type")213 do {214 let (data, response) = try await transport.send(r)215 let body = String(decoding: data.prefix(400), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)216 if (200...299).contains(response.statusCode), Self.isTxid(body) {217 accepted = body218 } else if UTXOWire.saysAlreadyKnown(body) {219 accepted = accepted ?? ""220 } else {221 failures.append("\(base.host ?? "?"): \(body)")222 }223 } catch {224 failures.append("\(base.host ?? "?"): \(NetworkError.transportSummary(error))")225 }226 }227 guard let accepted else { throw NetworkError.allEndpointsFailed(failures) }228 return accepted229 }230}231