Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraNetworking/Blockbook.swift8// Module : Qyvora Networking9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0512// 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/// Client of the Blockbook REST API v2 (Trezor's indexer and its forks), the protocol of the keyless public indexers45/// of Dogecoin and Bitcoin Cash, and a second source for Litecoin.46/// Reference: https://github.com/trezor/blockbook/blob/master/docs/api.md47///48/// Shapes that matter: amounts are decimal strings in base units; an input's `vout` is omitted when it is 0; an49/// unconfirmed transaction has `blockHeight` -1 and `confirmations` 0; fee estimates are whole coins per 1000 bytes;50/// Bitcoin Cash addresses are written in CashAddr with their prefix.51public struct BlockbookClient: UTXOIndexer {52 let bases: [URL]53 let transport: HTTPTransport54 public let network: BitcoinNetwork5556 /// Transactions per history page.57 static let pageSize = 2558 /// Confirmation targets asked of the node, in blocks.59 static let feeTargets = [2, 6, 25]6061 public init(network: BitcoinNetwork, configuration: EndpointConfiguration = .default, transport: HTTPTransport) {62 self.network = network63 bases = urls(configuration.blockbook[network.rawValue] ?? [])64 self.transport = transport65 }6667 public var indexerProtocol: UTXOIndexerProtocol { .blockbook }68 public var isConfigured: Bool { !bases.isEmpty }69 public var hosts: [String] { bases.compactMap(\.host) }70 public var servesRawTransactions: Bool { true }7172 // MARK: Wire models7374 struct Status: Decodable, Sendable {75 struct Blockbook: Decodable, Sendable {76 let bestHeight: Int77 let lastBlockTime: String?78 }79 let blockbook: Blockbook80 }8182 struct BlockIndex: Decodable, Sendable { let blockHash: String }8384 struct Address: Decodable, Sendable {85 let balance: String?86 let totalSent: String?87 let unconfirmedBalance: String?88 let unconfirmedTxs: Int?89 let txs: Int?90 let page: Int?91 let totalPages: Int?92 let transactions: [Transaction]?93 }9495 struct Coin: Decodable, Sendable {96 let txid: String97 let vout: UInt32?98 let value: String99 let height: Int?100 let confirmations: Int?101 let coinbase: Bool?102 }103104 struct Transaction: Decodable, Sendable {105 struct Vin: Decodable, Sendable {106 let txid: String?107 let vout: UInt32?108 let sequence: UInt32?109 let addresses: [String]?110 let isAddress: Bool?111 let value: String?112 }113 struct Vout: Decodable, Sendable {114 let value: String?115 let hex: String?116 let addresses: [String]?117 let isAddress: Bool?118 }119 let txid: String120 let vin: [Vin]121 let vout: [Vout]122 let blockHeight: Int?123 let confirmations: Int?124 let blockTime: Int?125 let size: Int?126 let vsize: Int?127 let fees: String?128 let hex: String?129 }130131 struct Estimate: Decodable, Sendable { let result: String }132 struct SendResult: Decodable, Sendable {133 let result: String?134 let error: String?135 }136137 // MARK: Parsing138139 /// A decimal string of base units; nil when it is not an exact non-negative 64-bit integer.140 static func amount(_ text: String?) -> UInt64? {141 guard let text, !text.isEmpty, text.utf8.count <= 20, text.utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }) else { return nil }142 return UInt64(text)143 }144145 /// True when a decimal string is a number other than zero ("-12" and numbers too large for 64 bits included).146 static func isNonZero(_ text: String?) -> Bool {147 guard let text, text.utf8.count <= 80 else { return false }148 return text.utf8.contains { $0 >= 0x31 && $0 <= 0x39 }149 }150151 static func convert(_ t: Transaction) throws -> UTXOIndexerTransaction {152 guard UTXOWire.isTxid(t.txid), t.vin.count <= UTXOWire.maximumEntriesPerTransaction, t.vout.count <= UTXOWire.maximumEntriesPerTransaction else {153 throw NetworkError.invalidResponse("transaction")154 }155 func address(_ list: [String]?, _ isAddress: Bool?) -> String? {156 guard isAddress == true, let list, list.count == 1 else { return nil }157 return UTXOWire.address(list[0])158 }159 let inputs = try t.vin.map { i -> UTXOIndexerTransaction.Input in160 guard let txid = i.txid else {161 // coinbase input: no outpoint162 return UTXOIndexerTransaction.Input(txid: nil, vout: nil, previous: nil, sequence: i.sequence)163 }164 guard UTXOWire.isTxid(txid) else { throw NetworkError.invalidResponse("transaction input") }165 let previous = amount(i.value).map { UTXOIndexerTransaction.Coin(address: address(i.addresses, i.isAddress), scriptPubKey: nil, value: $0) }166 return UTXOIndexerTransaction.Input(txid: txid, vout: i.vout ?? 0, previous: previous, sequence: i.sequence)167 }168 let outputs = try t.vout.map { o -> UTXOIndexerTransaction.Coin in169 guard let value = amount(o.value) else { throw NetworkError.invalidResponse("transaction output") }170 return UTXOIndexerTransaction.Coin(address: address(o.addresses, o.isAddress), scriptPubKey: UTXOWire.script(o.hex), value: value)171 }172 let confirmed = (t.confirmations ?? 0) > 0173 let size = (t.vsize ?? t.size).flatMap { $0 > 0 && $0 <= 4_000_000 ? $0 : nil }174 return UTXOIndexerTransaction(txid: t.txid, inputs: inputs, outputs: outputs, fee: amount(t.fees), virtualSize: size,175 height: confirmed ? UTXOWire.height(t.blockHeight) : nil,176 time: confirmed ? t.blockTime.flatMap { $0 > 0 ? $0 : nil } : nil)177 }178179 // MARK: Requests180181 private func get<T: Decodable & Sendable>(_ components: [String], query: [(String, String)] = [], as type: T.Type, what: String) async throws -> T {182 try await transport.firstSuccess(bases) { base in183 try await transport.json(try UTXOWire.url(base, components, query: query), as: T.self, what: what)184 }185 }186187 /// The address as Blockbook expects it: on Bitcoin Cash, CashAddr with its prefix (without it the answer is an188 /// error); unchanged elsewhere. Throws `invalidURL` for anything that is not a plain address.189 func pathAddress(_ address: String) throws -> String {190 guard UTXOWire.isAddress(address) else { throw NetworkError.invalidURL }191 if let prefix = network.cashAddrPrefix, !address.contains(":") { return prefix + ":" + address }192 return address193 }194195 public func verifyChain() async throws {196 try await UTXOWire.verifyChain(bases: bases, network: network) { base, height in197 try await transport.json(try UTXOWire.url(base, ["block-index", String(height)]), as: BlockIndex.self, what: "block index").blockHash198 }199 }200201 public func tip() async throws -> UTXOChainTip {202 // the status document is the API root itself203 let status = try await transport.firstSuccess(bases) { base in try await transport.json(base, as: Status.self, what: "status") }204 guard status.blockbook.bestHeight >= 0, status.blockbook.bestHeight < 1_000_000_000 else { throw NetworkError.invalidResponse("tip height") }205 return UTXOChainTip(height: status.blockbook.bestHeight, time: UTXOWire.date(status.blockbook.lastBlockTime))206 }207208 public func blockHash(height: Int) async throws -> String {209 guard height >= 0 else { throw NetworkError.invalidURL }210 let hash = try await get(["block-index", String(height)], as: BlockIndex.self, what: "block index").blockHash211 guard UTXOWire.isTxid(hash) else { throw NetworkError.invalidResponse("block hash") }212 return hash213 }214215 public func stats(address: String) async throws -> UTXOAddressStats {216 let a = try await get(["address", try pathAddress(address)], query: [("details", "basic")], as: Address.self, what: "address")217 let confirmed = max(0, a.txs ?? 0), pending = max(0, a.unconfirmedTxs ?? 0)218 // a spend is confirmed (totalSent) or pending (a negative unconfirmed balance can only come from one)219 let hasSpent = Self.isNonZero(a.totalSent) || (a.unconfirmedBalance?.hasPrefix("-") ?? false)220 let count = confirmed.addingReportingOverflow(pending)221 return UTXOAddressStats(address: address, isUsed: confirmed > 0 || pending > 0, hasSpent: hasSpent,222 transactionCount: count.overflow ? nil : count.partialValue, confirmedBalance: Self.amount(a.balance))223 }224225 public func coins(address: String) async throws -> [UTXOIndexerCoin] {226 let list = try await get(["utxo", try pathAddress(address)], as: [Coin].self, what: "unspent outputs")227 guard list.count <= UTXOWire.maximumCoins else { throw NetworkError.invalidResponse("too many coins") }228 return try list.map { c in229 guard UTXOWire.isTxid(c.txid), let value = Self.amount(c.value) else { throw NetworkError.invalidResponse("coin") }230 let confirmed = (c.confirmations ?? 0) > 0231 return UTXOIndexerCoin(txid: c.txid, vout: c.vout ?? 0, value: value, height: confirmed ? UTXOWire.height(c.height) : nil,232 isCoinbase: c.coinbase ?? false)233 }234 }235236 /// The cursor is the page number (1-based) as text.237 public func history(address: String, cursor: UTXOHistoryCursor?) async throws -> UTXOHistoryPage {238 let address = try pathAddress(address)239 var page = 1240 if let cursor {241 guard let p = Int(cursor.token), p >= 1, p <= 1_000_000 else { throw NetworkError.invalidURL }242 page = p243 }244 let a = try await get(["address", address], query: [("details", "txs"), ("pageSize", String(Self.pageSize)), ("page", String(page))],245 as: Address.self, what: "address history")246 let list = a.transactions ?? []247 guard list.count <= UTXOWire.maximumTransactionsPerPage else { throw NetworkError.invalidResponse("too many transactions") }248 // Blockbook answers the last page again when asked beyond it: the page it says it returned is what counts249 if let returned = a.page, returned != page { return UTXOHistoryPage(transactions: [], next: nil) }250 let total = a.totalPages ?? 1251 let next = page < total && !list.isEmpty ? UTXOHistoryCursor(token: String(page + 1)) : nil252 return UTXOHistoryPage(transactions: try list.map(Self.convert), next: next)253 }254255 public func rawTransaction(txid: String) async throws -> String {256 guard UTXOWire.isTxid(txid) else { throw NetworkError.invalidURL }257 let t = try await get(["tx", txid], as: Transaction.self, what: "transaction")258 guard let hex = t.hex, !hex.isEmpty, UTXOWire.isHex(hex, maximumCharacters: UTXOWire.maximumTransactionHex) else {259 throw NetworkError.invalidResponse("raw transaction")260 }261 return hex.lowercased()262 }263264 /// `estimatefee/<blocks>` answers whole coins per 1000 bytes ("-1" or "0" when the node has no estimate).265 public func feeEstimates() async throws -> [Int: Double] {266 var out = [Int: Double]()267 var lastError: (any Error)?268 for target in Self.feeTargets {269 do {270 let e = try await get(["estimatefee", String(target)], as: Estimate.self, what: "fee estimate")271 // plain decimal notation only: `Double("0x10")` is 16 and `Double("1e3")` is 1000 in Swift272 guard e.result.utf8.count <= 32, e.result.utf8.allSatisfy({ ($0 >= 0x30 && $0 <= 0x39) || $0 == 0x2e }),273 let perKiloByte = Double(e.result), perKiloByte.isFinite, perKiloByte > 0, perKiloByte <= 1_000 else { continue }274 // coins per kB → base units per byte275 out[target] = perKiloByte * 100_000276 } catch {277 lastError = error278 }279 }280 if out.isEmpty, let lastError { throw lastError }281 return out282 }283284 public func broadcast(rawHex: String) async throws -> String {285 guard !bases.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }286 guard UTXOWire.isHex(rawHex, maximumCharacters: UTXOWire.maximumTransactionHex), !rawHex.isEmpty else { throw NetworkError.invalidURL }287 var accepted: String?288 var failures = [String]()289 for base in bases {290 do {291 var r = URLRequest(url: try UTXOWire.url(base, ["sendtx"]).appendingPathComponent(""))292 r.httpMethod = "POST"293 r.httpBody = Data(rawHex.utf8)294 r.setValue("text/plain", forHTTPHeaderField: "Content-Type")295 let (data, response) = try await transport.send(r)296 let answer = try? JSONDecoder().decode(SendResult.self, from: data)297 if (200...299).contains(response.statusCode), let txid = answer?.result, UTXOWire.isTxid(txid) {298 accepted = txid299 continue300 }301 let body = answer?.error ?? String(decoding: data.prefix(400), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)302 if UTXOWire.saysAlreadyKnown(body) {303 accepted = accepted ?? ""304 } else {305 failures.append("\(base.host ?? "?"): \(String(body.prefix(300)))")306 }307 } catch {308 failures.append("\(base.host ?? "?"): \(NetworkError.transportSummary(error))")309 }310 }311 guard let accepted else { throw NetworkError.allEndpointsFailed(failures) }312 return accepted313 }314}315