Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraNetworking/Bitcore.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 Bitcore REST API (BitPay's indexer, https://github.com/bitpay/bitcore — base `…/api/<CHAIN>/<network>`),45/// a second keyless source for Litecoin, Dogecoin and Bitcoin Cash and the only one found for some test networks.46///47/// Shapes that matter: the API is coin-centred — an address is a list of coins, each with the transaction that48/// created it (`mintTxid`, `mintHeight`) and the one that spent it (`spentTxid`, `spentHeight`); heights use markers49/// (`mintHeight` -1 = in the mempool; `spentHeight` -2 = unspent, -1 = being spent in the mempool, -3 and below =50/// conflicting or invalid); amounts are JSON integers in base units; fee estimates are whole coins per 1000 bytes;51/// Bitcoin Cash addresses are passed without their CashAddr prefix (with it the answer is an empty list).52/// Limits: no raw transactions (`rawTransaction` throws `unsupported`); an address is read through its first53/// `coinLimit` coins, and a longer one is reported incomplete rather than silently truncated; a history page costs54/// two requests per transaction, and api.bitcore.io answers HTTP 429 to such bursts (seen on 2026-12-05): where a55/// Blockbook or Esplora source exists, read the history there and keep Bitcore for identity, tip, coins, fees and56/// broadcast.57public struct BitcoreClient: UTXOIndexer {58 let bases: [URL]59 let transport: HTTPTransport60 public let network: BitcoinNetwork6162 /// Coins read per address. An address with at least this many is not listed completely.63 static let coinLimit = 100064 /// Transactions per history page (each costs two requests).65 static let pageSize = 1066 static let feeTargets = [2, 6, 25]6768 public init(network: BitcoinNetwork, configuration: EndpointConfiguration = .default, transport: HTTPTransport) {69 self.network = network70 bases = urls(configuration.bitcore[network.rawValue] ?? [])71 self.transport = transport72 }7374 public var indexerProtocol: UTXOIndexerProtocol { .bitcore }75 public var isConfigured: Bool { !bases.isEmpty }76 public var hosts: [String] { bases.compactMap(\.host) }77 public var servesRawTransactions: Bool { false }7879 // MARK: Wire models8081 struct Block: Decodable, Sendable {82 let hash: String83 let height: Int84 let time: String?85 }8687 struct Coin: Decodable, Sendable {88 let mintTxid: String89 let mintIndex: UInt3290 let mintHeight: Int91 let spentTxid: String?92 let spentHeight: Int93 let value: UInt6494 let script: String?95 let address: String?96 let coinbase: Bool?97 let sequenceNumber: UInt32?98 }99100 struct Transaction: Decodable, Sendable {101 let txid: String102 let blockHeight: Int?103 let blockTime: String?104 let size: Int?105 let fee: Int64?106 let coinbase: Bool?107 }108109 struct TransactionCoins: Decodable, Sendable {110 let inputs: [Coin]111 let outputs: [Coin]112 }113114 struct Fee: Decodable, Sendable { let feerate: Double }115 struct SendResult: Decodable, Sendable { let txid: String? }116117 // MARK: Parsing118119 static func time(_ text: String?) -> Date? { UTXOWire.date(text) }120121 /// Coins that exist on the main chain or in the mempool (not the conflicting or invalid ones).122 static func isLive(_ c: Coin) -> Bool { c.mintHeight >= -1 }123 static func isUnspent(_ c: Coin) -> Bool { c.spentHeight == -2 }124 /// Spent in a block or being spent in the mempool.125 static func isSpent(_ c: Coin) -> Bool { c.spentHeight >= -1 }126127 private func checked(_ coins: [Coin]) throws -> [Coin] {128 for c in coins {129 guard UTXOWire.isTxid(c.mintTxid), c.spentTxid.map({ $0.isEmpty || UTXOWire.isTxid($0) }) ?? true else {130 throw NetworkError.invalidResponse("coin")131 }132 }133 return coins134 }135136 // MARK: Requests137138 private func get<T: Decodable & Sendable>(_ components: [String], query: [(String, String)] = [], as type: T.Type, what: String) async throws -> T {139 try await transport.firstSuccess(bases) { base in140 try await transport.json(try UTXOWire.url(base, components, query: query), as: T.self, what: what)141 }142 }143144 /// The first `coinLimit` coins of an address (spent ones included unless `unspentOnly`), and whether that is all.145 private func addressCoins(_ address: String, unspentOnly: Bool) async throws -> (coins: [Coin], complete: Bool) {146 guard UTXOWire.isAddress(address) else { throw NetworkError.invalidURL }147 var query = [("limit", String(Self.coinLimit))]148 if unspentOnly { query.append(("unspent", "true")) }149 let list = try await get(["address", UTXOWire.bare(address)], query: query, as: [Coin].self, what: "address coins")150 guard list.count <= Self.coinLimit else { throw NetworkError.invalidResponse("too many coins") }151 return (try checked(list).filter(Self.isLive), list.count < Self.coinLimit)152 }153154 public func verifyChain() async throws {155 try await UTXOWire.verifyChain(bases: bases, network: network) { base, height in156 let block = try await transport.json(try UTXOWire.url(base, ["block", String(height)]), as: Block.self, what: "block")157 // an instance that numbers its blocks differently is not serving what the wallet expects158 guard block.height == height else { throw NetworkError.invalidResponse("block height") }159 return block.hash160 }161 }162163 public func tip() async throws -> UTXOChainTip {164 let block = try await get(["block", "tip"], as: Block.self, what: "tip")165 guard block.height >= 0, block.height < 1_000_000_000 else { throw NetworkError.invalidResponse("tip height") }166 return UTXOChainTip(height: block.height, time: Self.time(block.time))167 }168169 public func blockHash(height: Int) async throws -> String {170 guard height >= 0 else { throw NetworkError.invalidURL }171 let block = try await get(["block", String(height)], as: Block.self, what: "block")172 guard block.height == height, UTXOWire.isTxid(block.hash) else { throw NetworkError.invalidResponse("block hash") }173 return block.hash174 }175176 /// Derived from the coins of the address. When the list is cut at `coinLimit`, `hasSpent` is reported true and the177 /// count and balance are nil.178 public func stats(address: String) async throws -> UTXOAddressStats {179 let (coins, complete) = try await addressCoins(address, unspentOnly: false)180 let spent = coins.contains(where: Self.isSpent)181 guard complete else {182 return UTXOAddressStats(address: address, isUsed: true, hasSpent: true, transactionCount: nil, confirmedBalance: nil, isComplete: false)183 }184 var txids = Set<String>()185 var balance: UInt64? = 0186 for c in coins {187 txids.insert(c.mintTxid)188 if Self.isSpent(c), let s = c.spentTxid, !s.isEmpty { txids.insert(s) }189 if c.mintHeight >= 0, !(c.spentHeight >= 0) {190 // confirmed and not spent in a block191 if let b = balance {192 let (sum, overflow) = b.addingReportingOverflow(c.value)193 balance = overflow ? nil : sum194 }195 }196 }197 return UTXOAddressStats(address: address, isUsed: !coins.isEmpty, hasSpent: spent, transactionCount: txids.count, confirmedBalance: balance)198 }199200 /// Throws `invalidResponse` when the address holds `coinLimit` coins or more: a partial coin set would understate201 /// the balance without saying so.202 public func coins(address: String) async throws -> [UTXOIndexerCoin] {203 let (coins, complete) = try await addressCoins(address, unspentOnly: true)204 guard complete else { throw NetworkError.invalidResponse("more than \(Self.coinLimit) coins on one address") }205 return coins.filter(Self.isUnspent).map {206 UTXOIndexerCoin(txid: $0.mintTxid, vout: $0.mintIndex, value: $0.value, height: $0.mintHeight >= 0 ? UTXOWire.height($0.mintHeight) : nil,207 isCoinbase: $0.coinbase)208 }209 }210211 /// The history is rebuilt from the coins of the address: the transactions that created or spent them, newest212 /// first (mempool, then by height), `pageSize` at a time; each one costs two requests (`tx/<id>` and213 /// `tx/<id>/coins`). The cursor is the offset in that list. Limited to the first `coinLimit` coins of the address.214 public func history(address: String, cursor: UTXOHistoryCursor?) async throws -> UTXOHistoryPage {215 var offset = 0216 if let cursor {217 guard let o = Int(cursor.token), o >= 0, o <= 4 * Self.coinLimit else { throw NetworkError.invalidURL }218 offset = o219 }220 let (coins, _) = try await addressCoins(address, unspentOnly: false)221 // txid → height (-1 for the mempool)222 var heights = [String: Int]()223 for c in coins {224 heights[c.mintTxid] = c.mintHeight225 if Self.isSpent(c), let s = c.spentTxid, !s.isEmpty { heights[s] = c.spentHeight }226 }227 let ordered = heights.sorted { a, b in228 let ha = a.value < 0 ? Int.max : a.value, hb = b.value < 0 ? Int.max : b.value229 return ha != hb ? ha > hb : a.key < b.key230 }.map(\.key)231 guard offset < ordered.count else { return UTXOHistoryPage(transactions: [], next: nil) }232 let slice = ordered[offset..<min(ordered.count, offset + Self.pageSize)]233 var list = [UTXOIndexerTransaction]()234 for txid in slice { list.append(try await transaction(txid)) }235 let end = offset + slice.count236 return UTXOHistoryPage(transactions: list, next: end < ordered.count ? UTXOHistoryCursor(token: String(end)) : nil)237 }238239 /// One transaction with its inputs and outputs (two requests).240 public func transaction(_ txid: String) async throws -> UTXOIndexerTransaction {241 guard UTXOWire.isTxid(txid) else { throw NetworkError.invalidURL }242 let t = try await get(["tx", txid], as: Transaction.self, what: "transaction")243 let c = try await get(["tx", txid, "coins"], as: TransactionCoins.self, what: "transaction coins")244 guard t.txid == txid, c.inputs.count <= UTXOWire.maximumEntriesPerTransaction, c.outputs.count <= UTXOWire.maximumEntriesPerTransaction else {245 throw NetworkError.invalidResponse("transaction")246 }247 func coin(_ x: Coin) -> UTXOIndexerTransaction.Coin {248 // unparsed scripts carry the address "false"249 let address = x.address == "false" ? nil : UTXOWire.address(x.address)250 return UTXOIndexerTransaction.Coin(address: address, scriptPubKey: UTXOWire.script(x.script), value: x.value)251 }252 let inputs = try checked(c.inputs).map {253 UTXOIndexerTransaction.Input(txid: $0.mintTxid, vout: $0.mintIndex, previous: coin($0), sequence: $0.sequenceNumber)254 }255 // outputs are listed in no guaranteed order: mintIndex is their position256 let outputs = try checked(c.outputs).sorted { $0.mintIndex < $1.mintIndex }257 guard outputs.allSatisfy({ $0.mintTxid == txid }) else { throw NetworkError.invalidResponse("transaction outputs") }258 let height = UTXOWire.height(t.blockHeight)259 let time = height == nil ? nil : Self.time(t.blockTime).map { Int($0.timeIntervalSince1970) }260 return UTXOIndexerTransaction(txid: txid, inputs: t.coinbase == true ? [UTXOIndexerTransaction.Input(txid: nil, vout: nil, previous: nil, sequence: nil)] : inputs,261 outputs: outputs.map(coin), fee: t.fee.flatMap { $0 >= 0 ? UInt64($0) : nil },262 virtualSize: t.size.flatMap { $0 > 0 && $0 <= 4_000_000 ? $0 : nil }, height: height, time: time)263 }264265 /// Bitcore does not serve raw transactions.266 public func rawTransaction(txid: String) async throws -> String {267 throw NetworkError.unsupported("the Bitcore API does not serve raw transactions")268 }269270 /// `fee/<blocks>` answers whole coins per 1000 bytes.271 public func feeEstimates() async throws -> [Int: Double] {272 var out = [Int: Double]()273 var lastError: (any Error)?274 for target in Self.feeTargets {275 do {276 let perKiloByte = try await get(["fee", String(target)], as: Fee.self, what: "fee estimate").feerate277 guard perKiloByte.isFinite, perKiloByte > 0, perKiloByte <= 1_000 else { continue }278 out[target] = perKiloByte * 100_000279 } catch {280 lastError = error281 }282 }283 if out.isEmpty, let lastError { throw lastError }284 return out285 }286287 public func broadcast(rawHex: String) async throws -> String {288 guard !bases.isEmpty else { throw NetworkError.allEndpointsFailed(["no endpoint configured"]) }289 guard UTXOWire.isHex(rawHex, maximumCharacters: UTXOWire.maximumTransactionHex), !rawHex.isEmpty else { throw NetworkError.invalidURL }290 var accepted: String?291 var failures = [String]()292 for base in bases {293 do {294 var r = URLRequest(url: try UTXOWire.url(base, ["tx", "send"]))295 r.httpMethod = "POST"296 r.httpBody = try JSONEncoder().encode(["rawTx": rawHex])297 r.setValue("application/json", forHTTPHeaderField: "Content-Type")298 let (data, response) = try await transport.send(r)299 if (200...299).contains(response.statusCode), let txid = (try? JSONDecoder().decode(SendResult.self, from: data))?.txid,300 UTXOWire.isTxid(txid) {301 accepted = txid302 continue303 }304 // a refusal is the node's message as plain text, with status 500305 let body = String(decoding: data.prefix(400), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)306 if UTXOWire.saysAlreadyKnown(body) {307 accepted = accepted ?? ""308 } else {309 failures.append("\(base.host ?? "?"): \(String(body.prefix(300)))")310 }311 } catch {312 failures.append("\(base.host ?? "?"): \(NetworkError.transportSummary(error))")313 }314 }315 guard let accepted else { throw NetworkError.allEndpointsFailed(failures) }316 return accepted317 }318}319