SPB Git

Repository Public

UTXOIndexerTests.swift 67.3 KB 861 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraNetworkingTests/UTXOIndexerTests.swift8// Module           : Tests9// 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 Testing43import QyvoraCore44@testable import QyvoraNetworking4546// Indexers of the UTXO coins: Blockbook, Bitcore and Esplora behind `UTXOIndexer`, answered locally.47// The fixtures are answers of the public instances read on 2026-12-05 (public chain data), shortened.4849/// Answers requests from a table keyed by "path?query" (after the host); records what was asked.50final class RoutedTransport: HTTPTransport, @unchecked Sendable {51    private let lock = NSLock()52    private var routes: [String: (status: Int, body: String)]53    private var asked: [String] = []54    private var posted: [String] = []55    /// Answer for anything not in the table.56    let fallback: (status: Int, body: String)5758    init(_ routes: [String: String] = [:], fallback: (status: Int, body: String) = (404, "not found")) {59        self.routes = routes.mapValues { (200, $0) }60        self.fallback = fallback61    }6263    func set(_ key: String, status: Int = 200, _ body: String) {64        lock.lock(); defer { lock.unlock() }65        routes[key] = (status, body)66    }6768    var requests: [String] { lock.lock(); defer { lock.unlock() }; return asked }69    var bodies: [String] { lock.lock(); defer { lock.unlock() }; return posted }7071    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {72        guard let url = request.url, let parts = URLComponents(url: url, resolvingAgainstBaseURL: false) else { throw NetworkError.invalidURL }73        let key = (parts.host ?? "") + parts.percentEncodedPath + (parts.percentEncodedQuery.map { "?" + $0 } ?? "")74        let answer: (status: Int, body: String) = lock.withLock {75            asked.append((request.httpMethod ?? "GET") + " " + key)76            if let body = request.httpBody { posted.append(String(decoding: body, as: UTF8.self)) }77            return routes[key] ?? fallback78        }79        guard let response = HTTPURLResponse(url: url, statusCode: answer.status, httpVersion: nil, headerFields: nil) else { throw NetworkError.invalidURL }80        return (Data(answer.body.utf8), response)81    }82}8384private let testConfiguration = EndpointConfiguration(85    esplora: ["litecoin": ["https://es.test/api"]],86    blockbook: ["dogecoin": ["https://bb.test/api/v2"], "bitcoinCash": ["https://bbch.test/api/v2"]],87    bitcore: ["dogecoin": ["https://bc.test/api/DOGE/mainnet"], "bitcoinCash": ["https://bcash.test/api/BCH/mainnet"]],88    ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")8990private enum Fixture {91    static let dogeGenesis = "1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"92    static let txid = "ca46963830d638857a50acfaee60191d5ee4dddfd655265d81ee80369c2a2bbd"93    static let spent = "e7427cc2b0ab58881a17ea1a5aaff34a4fc83eb698c0d600ddeffeb70d6afa53"94    static let address = "DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L"95    static let rawTransaction = "010000000153fa6a0db7feefdd00d6c098b63ec84f4af3af5a1aea171a8858abb0c27c42e7000000006a47304402202f9d15ec6ac1c724ac46fcb968118cf007443c0a972f46e82e78dd56cc143529022063228fbae381fc582873fedec3d7eaa5a29b8b0eb22a865e6efb66eb00f2250c012103192d80c8ba63d24a1c1d99742afe5c954a8dcf96e0356627626d76273e83f635feffffff024033225b000000001976a914b1dd193bf5040d7184423c3e683bf228a127333488ac80841e00000000001976a914830a7420e63d76244ff7cbd1c248e94c1446325988ac4dd76200"9697    // Blockbook (blockbook.doge.zelcore.io)98    static let bbStatus = #"{"blockbook":{"coin":"Dogecoin","network":"DOGE","host":"FX-DOGE-01","version":"0.6.0+zelcore.2","syncMode":true,"initialSync":false,"inSync":true,"bestHeight":6485462,"lastBlockTime":"2026-12-05T05:11:35.43573209Z","inSyncMempool":true,"mempoolSize":16,"decimals":8},"backend":{"chain":"main","blocks":6485462,"headers":6485462,"bestBlockHash":"258028fb464ad2e57fd09594eb82cc48f4f85d287305f12f8cacfa608deea58c","difficulty":"31703089.60410599","version":"1140900","subversion":"/Shibetoshi:1.14.9/"}}"#99    static let bbBlockIndex = #"{"blockHash":"1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691"}"#100    static let bbBasic = #"{"address":"DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L","balance":"6223538467666","totalReceived":"5581286333513200844","totalSent":"5581280109974733178","unconfirmedBalance":"0","unconfirmedTxs":0,"txs":1488}"#101    static let bbUnused = #"{"address":"DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L","balance":"0","totalReceived":"0","totalSent":"0","unconfirmedBalance":"0","unconfirmedTxs":0,"txs":0}"#102    static let bbUTXO = #"[{"txid":"ca46963830d638857a50acfaee60191d5ee4dddfd655265d81ee80369c2a2bbd","vout":1,"value":"2000000","height":6477647,"confirmations":7816},{"txid":"f5142957d5b9aeae590bec009aab7ec8d5fcc9ccbde05115a3687c5e4d728b7a","vout":0,"value":"100000000","height":6465039,"confirmations":20424},{"txid":"117ba721ae74124b44f5ee071c60027b899e5e815638a3165b6049a6d4d5f9a0","vout":1,"value":"1230000000","confirmations":0},{"txid":"1b51a116ba75cc0dd9e13b86bd570629427a5d7d009d80706f4ba16137f5eee8","value":"95347802","height":6423225,"confirmations":62238,"coinbase":true}]"#103    static let bbTransaction = #"{"txid":"ca46963830d638857a50acfaee60191d5ee4dddfd655265d81ee80369c2a2bbd","version":1,"lockTime":6477645,"vin":[{"txid":"e7427cc2b0ab58881a17ea1a5aaff34a4fc83eb698c0d600ddeffeb70d6afa53","sequence":4294967294,"n":0,"addresses":["D7JeqAsJ9Vie3VnpticCJ2N9s2RJQQjgiG"],"isAddress":true,"value":"1531194000","hex":"47304402202f9d15ec6ac1c724ac46fcb968118cf007443c0a972f46e82e78dd56cc143529022063228fbae381fc582873fedec3d7eaa5a29b8b0eb22a865e6efb66eb00f2250c012103192d80c8ba63d24a1c1d99742afe5c954a8dcf96e0356627626d76273e83f635"}],"vout":[{"value":"1528968000","n":0,"spent":true,"hex":"76a914b1dd193bf5040d7184423c3e683bf228a127333488ac","addresses":["DMMZ1Qm3sU6LM2GZCH5UzojRZA8SFjPDBH"],"isAddress":true},{"value":"2000000","n":1,"hex":"76a914830a7420e63d76244ff7cbd1c248e94c1446325988ac","addresses":["DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L"],"isAddress":true,"isOwn":true}],"blockHash":"b76f98ac63cecb07e3f79d6a0f636e7d7fb57e8b004aa8e2ad25c71a5621f38c","blockHeight":6477647,"confirmations":7816,"blockTime":1795951329,"size":225,"value":"1530968000","valueIn":"1531194000","fees":"226000","hex":"010000000153fa6a0db7feefdd00d6c098b63ec84f4af3af5a1aea171a8858abb0c27c42e7000000006a47304402202f9d15ec6ac1c724ac46fcb968118cf007443c0a972f46e82e78dd56cc143529022063228fbae381fc582873fedec3d7eaa5a29b8b0eb22a865e6efb66eb00f2250c012103192d80c8ba63d24a1c1d99742afe5c954a8dcf96e0356627626d76273e83f635feffffff024033225b000000001976a914b1dd193bf5040d7184423c3e683bf228a127333488ac80841e00000000001976a914830a7420e63d76244ff7cbd1c248e94c1446325988ac4dd76200"}"#104    /// A coinbase transaction and an unconfirmed one, as Blockbook writes them.105    static let bbCoinbase = #"{"txid":"9719d7187a919b06e7c1c29d764f1af770d7196e2bd25e1f9de43ab26f4ff4e0","vin":[{"n":0,"isAddress":false,"value":"0"}],"vout":[{"value":"312579328","n":0,"addresses":["bitcoincash:qqjyycerhgygpzwxmnfe83nchng8v66qas5yt745rm"],"isAddress":true},{"value":"0","n":1,"addresses":["OP_RETURN aa21a9ed"],"isAddress":false}],"blockHeight":980350,"confirmations":10,"blockTime":1796439551,"value":"312579328","valueIn":"0","fees":"0"}"#106    static func bbHistory(page: Int, totalPages: Int, transactions: [String]) -> String {107        #"{"page":\#(page),"totalPages":\#(totalPages),"itemsOnPage":25,"address":"DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L","balance":"6223538467666","totalReceived":"1","totalSent":"1","unconfirmedBalance":"0","unconfirmedTxs":0,"txs":1488,"transactions":[\#(transactions.joined(separator: ","))]}"#108    }109110    // Bitcore (api.bitcore.io)111    static let bcTip = #"{"_id":"6b139c46321d63613d65656e","chain":"DOGE","hash":"7947887e10b1279fb0174d2d3a8719e4c4224aef6f4748df2cfa0a6b0e1153c5","network":"mainnet","bits":426453082,"height":6485457,"merkleRoot":"d2ec90ef89d42a0dca86bfa7da88b0000000000000000000000000000000000000000000000000000000000000000000","time":"2026-12-05T05:08:10.000Z","timeNormalized":"2026-12-05T05:08:10.000Z","nonce":0,"previousBlockHash":"00","nextBlockHash":"","reward":1000000000000,"size":1,"transactionCount":3,"version":6422788,"processed":true}"#112    static let bcBlock0 = #"{"chain":"DOGE","network":"mainnet","hash":"1a91e3dace36e2be3bf030a65679fe821aa1d6ef92e7c9902eb318182c355691","height":0,"version":1,"size":224,"merkleRoot":"5b2a3f53f605d62c53e62932dac6925e3d74afa5a4b459745c36d42d0ed26a69","time":"2013-12-06T10:25:40.000Z","timeNormalized":"2013-12-06T10:25:40.000Z","nonce":99943,"bits":504365040,"previousBlockHash":"0000000000000000000000000000000000000000000000000000000000000000","nextBlockHash":"","reward":8800000000,"transactionCount":1,"confirmations":6484496}"#113    /// What the stalled Dogecoin Testnet instance answered for "block 0" on 2026-12-05: the first block after genesis.114    static let bcShiftedBlock0 = #"{"chain":"DOGE","network":"testnet3","hash":"ea11f3fdb69e2006beb2c951ff6d7ce6e01a599df7f5d8a61c85a75cd4ac5161","height":0,"version":2,"size":301,"time":"2014-02-12T04:56:43.000Z","previousBlockHash":"bb0a78264637406b6360aad926284d544d7049f45189db5664f3c4d07350559e"}"#115    static func bcCoin(mint: String, index: Int, mintHeight: Int, spent: String = "", spentHeight: Int = -2, value: UInt64, address: String = "DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L") -> String {116        #"{"chain":"DOGE","network":"mainnet","coinbase":false,"mintIndex":\#(index),"spentTxid":"\#(spent)","mintTxid":"\#(mint)","mintHeight":\#(mintHeight),"spentHeight":\#(spentHeight),"address":"\#(address)","script":"76a914830a7420e63d76244ff7cbd1c248e94c1446325988ac","value":\#(value),"confirmations":-1,"sequenceNumber":4294967294}"#117    }118    static let bcTransaction = #"{"txid":"ca46963830d638857a50acfaee60191d5ee4dddfd655265d81ee80369c2a2bbd","network":"mainnet","chain":"DOGE","blockHeight":6477647,"blockHash":"b76f98ac63cecb07e3f79d6a0f636e7d7fb57e8b004aa8e2ad25c71a5621f38c","blockTime":"2026-11-29T11:22:09.000Z","blockTimeNormalized":"2026-11-29T11:22:09.000Z","coinbase":false,"locktime":6477645,"inputCount":1,"outputCount":2,"size":225,"fee":226000,"value":1530968000,"confirmations":6114}"#119    static let bcTransactionCoins = #"{"inputs":[{"chain":"DOGE","network":"mainnet","coinbase":false,"mintIndex":0,"spentTxid":"ca46963830d638857a50acfaee60191d5ee4dddfd655265d81ee80369c2a2bbd","mintTxid":"e7427cc2b0ab58881a17ea1a5aaff34a4fc83eb698c0d600ddeffeb70d6afa53","mintHeight":6477620,"spentHeight":6477647,"address":"D7JeqAsJ9Vie3VnpticCJ2N9s2RJQQjgiG","script":"76a91417bef36d7f6f4948f1d9aa0adc348f6f58ad52d188ac","value":1531194000,"confirmations":7814,"sequenceNumber":4294967294}],"outputs":[{"chain":"DOGE","network":"mainnet","coinbase":false,"mintIndex":1,"spentTxid":"","mintTxid":"ca46963830d638857a50acfaee60191d5ee4dddfd655265d81ee80369c2a2bbd","mintHeight":6477647,"spentHeight":-2,"address":"DH5yaieqoZN36fDVciNyRueRGvGLR3mr7L","script":"76a914830a7420e63d76244ff7cbd1c248e94c1446325988ac","value":2000000,"confirmations":7814},{"chain":"DOGE","network":"mainnet","coinbase":false,"mintIndex":0,"spentTxid":"749939cf6f8425d4014dd3c3eff8d83890bcf69bc973bef62591df1aec2f1143","mintTxid":"ca46963830d638857a50acfaee60191d5ee4dddfd655265d81ee80369c2a2bbd","mintHeight":6477647,"spentHeight":6477681,"address":"DMMZ1Qm3sU6LM2GZCH5UzojRZA8SFjPDBH","script":"76a914b1dd193bf5040d7184423c3e683bf228a127333488ac","value":1528968000,"confirmations":7814,"sequenceNumber":4294967294}]}"#120121    // Esplora (litecoinspace.org)122    static let ltcGenesis = "12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2"123    static let ltcAddress = "ltc1qgunrprvr9a25qfgj3c4s0p6qp5xgqa5ll086cj"124    static let esStats = #"{"address":"ltc1qgunrprvr9a25qfgj3c4s0p6qp5xgqa5ll086cj","chain_stats":{"funded_txo_count":105,"funded_txo_sum":10635131096,"spent_txo_count":105,"spent_txo_sum":10635131096,"tx_count":204},"mempool_stats":{"funded_txo_count":0,"funded_txo_sum":0,"spent_txo_count":0,"spent_txo_sum":0,"tx_count":0}}"#125    static let esUTXO = #"[{"txid":"84e98892c2b944d5efbb5e7e287ca076c2430ae5a756c17b770fd36cdde45c85","vout":1,"status":{"confirmed":true,"block_height":3224500,"block_hash":"10f00ac6465f82cf43f82de747ae913b05fa7e7f7be822117dde825c38726c80","block_time":1796432878},"value":300480770},{"txid":"627c16d6abb04ee5cf6861ae5ddf65542de91023c052bfbca184089f6af1a61a","vout":0,"status":{"confirmed":false},"value":5000}]"#126    static func esTransaction(txid: String, confirmed: Bool) -> String {127        let status = confirmed ? #"{"confirmed":true,"block_height":3224521,"block_hash":"10f00ac6465f82cf43f82de747ae913b05fa7e7f7be822117dde825c38726c80","block_time":1796435000}"# : #"{"confirmed":false}"#128        return #"{"txid":"\#(txid)","version":2,"locktime":3224521,"vin":[{"txid":"58b0f3ca359bc6daf33abd8c3fb4a63de3649949e8b013e929de21e2b569bffd","vout":0,"prevout":{"scriptpubkey":"0014bb3382704991f65e391fa7a58169cd6062bd48a3","scriptpubkey_asm":"OP_0 OP_PUSHBYTES_20 bb3382704991f65e391fa7a58169cd6062bd48a3","scriptpubkey_type":"v0_p2wpkh","scriptpubkey_address":"ltc1qhvecyuzfj8m9uwgl57jcz6wdvp3t6j9rrdgt60","value":59486352},"scriptsig":"","scriptsig_asm":"","witness":["30","02"],"is_coinbase":false,"sequence":4294967294}],"vout":[{"scriptpubkey":"00144726308d832f554025128e2b0787400d0c80769f","scriptpubkey_asm":"OP_0","scriptpubkey_type":"v0_p2wpkh","scriptpubkey_address":"ltc1qgunrprvr9a25qfgj3c4s0p6qp5xgqa5ll086cj","value":59453352}],"size":191,"weight":437,"fee":33000,"status":\#(status)}"#129    }130    static let esRecommended = #"{"fastestFee":1,"halfHourFee":1,"hourFee":1,"economyFee":1,"minimumFee":1}"#131}132133private func txid(_ n: Int) -> String {134    let s = String(n, radix: 16)135    return String(repeating: "0", count: 64 - s.count) + s136}137138@Suite struct BlockbookClientTests {139    func client(_ transport: RoutedTransport, _ network: BitcoinNetwork = .dogecoin) -> BlockbookClient {140        BlockbookClient(network: network, configuration: testConfiguration, transport: transport)141    }142143    @Test func readsChainAddressAndCoins() async throws {144        let t = RoutedTransport([145            "bb.test/api/v2": Fixture.bbStatus,146            "bb.test/api/v2/block-index/0": Fixture.bbBlockIndex,147            "bb.test/api/v2/address/\(Fixture.address)?details=basic": Fixture.bbBasic,148            "bb.test/api/v2/utxo/\(Fixture.address)": Fixture.bbUTXO,149            "bb.test/api/v2/tx/\(Fixture.txid)": Fixture.bbTransaction,150        ])151        let c = client(t)152        #expect(c.isConfigured && c.hosts == ["bb.test"] && c.indexerProtocol == .blockbook && c.servesRawTransactions)153        try await c.verifyChain()154        let tip = try await c.tip()155        #expect(tip.height == 6_485_462)156        #expect(try await c.tipHeight() == 6_485_462)157        #expect(tip.time.map { Int($0.timeIntervalSince1970) } == 1_796_447_495)158        #expect(try await c.blockHash(height: 0) == Fixture.dogeGenesis)159160        let stats = try await c.stats(address: Fixture.address)161        #expect(stats == UTXOAddressStats(address: Fixture.address, isUsed: true, hasSpent: true, transactionCount: 1488, confirmedBalance: 6_223_538_467_666))162163        let coins = try await c.coins(address: Fixture.address)164        #expect(coins.count == 4)165        #expect(coins[0] == UTXOIndexerCoin(txid: Fixture.txid, vout: 1, value: 2_000_000, height: 6_477_647, isCoinbase: false))166        #expect(coins[0].confirmations(tipHeight: tip.height) == 7_816)167        // unconfirmed: no height, zero confirmations168        #expect(coins[2].height == nil && coins[2].confirmations(tipHeight: tip.height) == 0)169        // "vout" is omitted when it is 0; coinbase flag170        #expect(coins[3].vout == 0 && coins[3].isCoinbase == true)171        #expect(UTXOIndexerCoin(txid: Fixture.txid, vout: 0, value: 1, height: 100).confirmations(tipHeight: 99) == 0)172173        #expect(try await c.rawTransaction(txid: Fixture.txid) == Fixture.rawTransaction)174        #expect(t.requests.allSatisfy { $0.hasPrefix("GET bb.test/api/v2") })175    }176177    @Test func addressStatsVariants() async throws {178        let t = RoutedTransport()179        let c = client(t)180        let key = "bb.test/api/v2/address/\(Fixture.address)?details=basic"181        t.set(key, Fixture.bbUnused)182        #expect(try await c.stats(address: Fixture.address) == UTXOAddressStats(address: Fixture.address, isUsed: false, hasSpent: false, transactionCount: 0, confirmedBalance: 0))183        // received only184        t.set(key, #"{"balance":"500","totalReceived":"500","totalSent":"0","unconfirmedBalance":"0","unconfirmedTxs":0,"txs":2}"#)185        var s = try await c.stats(address: Fixture.address)186        #expect(s.isUsed && !s.hasSpent && s.transactionCount == 2 && s.confirmedBalance == 500)187        // a spend still in the mempool shows as a negative unconfirmed balance188        t.set(key, #"{"balance":"500","totalReceived":"500","totalSent":"0","unconfirmedBalance":"-500","unconfirmedTxs":1,"txs":1}"#)189        s = try await c.stats(address: Fixture.address)190        #expect(s.hasSpent && s.transactionCount == 2)191        // only unconfirmed activity192        t.set(key, #"{"balance":"0","totalReceived":"0","totalSent":"0","unconfirmedBalance":"700","unconfirmedTxs":1,"txs":0}"#)193        s = try await c.stats(address: Fixture.address)194        #expect(s.isUsed && !s.hasSpent)195        // totals beyond 64 bits (Dogecoin exchange addresses) do not break the answer196        t.set(key, #"{"balance":"99999999999999999999999","totalReceived":"99999999999999999999999","totalSent":"99999999999999999999990","unconfirmedBalance":"0","unconfirmedTxs":0,"txs":7}"#)197        s = try await c.stats(address: Fixture.address)198        #expect(s.hasSpent && s.confirmedBalance == nil && s.transactionCount == 7)199    }200201    @Test func historyPages() async throws {202        let t = RoutedTransport()203        let c = client(t)204        func key(_ page: Int) -> String { "bb.test/api/v2/address/\(Fixture.address)?details=txs&pageSize=25&page=\(page)" }205        let unconfirmed = Fixture.bbTransaction.replacingOccurrences(of: #""blockHeight":6477647,"confirmations":7816"#, with: #""blockHeight":-1,"confirmations":0"#)206            .replacingOccurrences(of: Fixture.txid, with: txid(7))207        t.set(key(1), Fixture.bbHistory(page: 1, totalPages: 3, transactions: [unconfirmed, Fixture.bbTransaction]))208        t.set(key(2), Fixture.bbHistory(page: 2, totalPages: 3, transactions: [Fixture.bbCoinbase]))209        t.set(key(3), Fixture.bbHistory(page: 3, totalPages: 3, transactions: []))210        // asked beyond the end, Blockbook answers its last page again211        t.set(key(4), Fixture.bbHistory(page: 3, totalPages: 3, transactions: [Fixture.bbCoinbase]))212213        let first = try await c.history(address: Fixture.address, cursor: nil)214        #expect(first.transactions.count == 2 && first.next == UTXOHistoryCursor(token: "2"))215        #expect(first.transactions[0].txid == txid(7) && first.transactions[0].height == nil && first.transactions[0].time == nil)216        let tx = first.transactions[1]217        #expect(tx.txid == Fixture.txid && tx.height == 6_477_647 && tx.time == 1_795_951_329 && tx.fee == 226_000 && tx.virtualSize == 225)218        #expect(tx.inputs == [UTXOIndexerTransaction.Input(txid: Fixture.spent, vout: 0,219                                                           previous: .init(address: "D7JeqAsJ9Vie3VnpticCJ2N9s2RJQQjgiG", scriptPubKey: nil, value: 1_531_194_000),220                                                           sequence: 4_294_967_294)])221        #expect(tx.outputs == [222            .init(address: "DMMZ1Qm3sU6LM2GZCH5UzojRZA8SFjPDBH", scriptPubKey: "76a914b1dd193bf5040d7184423c3e683bf228a127333488ac", value: 1_528_968_000),223            .init(address: Fixture.address, scriptPubKey: "76a914830a7420e63d76244ff7cbd1c248e94c1446325988ac", value: 2_000_000),224        ])225        let second = try await c.history(address: Fixture.address, cursor: first.next)226        #expect(second.next == UTXOHistoryCursor(token: "3"))227        // coinbase: an input without outpoint; an OP_RETURN "address" is not an address228        let coinbase = try #require(second.transactions.first)229        #expect(coinbase.inputs == [UTXOIndexerTransaction.Input(txid: nil, vout: nil, previous: nil, sequence: nil)])230        #expect(coinbase.outputs[1].address == nil && coinbase.outputs[1].value == 0 && coinbase.fee == 0)231        let third = try await c.history(address: Fixture.address, cursor: second.next)232        #expect(third.transactions.isEmpty && third.next == nil)233        let beyond = try await c.history(address: Fixture.address, cursor: UTXOHistoryCursor(token: "4"))234        #expect(beyond.transactions.isEmpty && beyond.next == nil)235        for token in ["0", "-1", "x", "2/../3", "1000001", ""] {236            await #expect(throws: NetworkError.invalidURL) { try await c.history(address: Fixture.address, cursor: UTXOHistoryCursor(token: token)) }237        }238    }239240    @Test func feeEstimatesAreConvertedToBaseUnitsPerByte() async throws {241        let t = RoutedTransport([242            "bb.test/api/v2/estimatefee/2": #"{"result":"0.50756077"}"#,243            "bb.test/api/v2/estimatefee/6": #"{"result":"0.01"}"#,244            "bb.test/api/v2/estimatefee/25": #"{"result":"-1"}"#,245        ])246        let fees = try await client(t).feeEstimates()247        // 0.50756077 DOGE per kB = 50 756.077 koinu per byte; "-1" means no estimate248        #expect(Set(fees.keys) == [2, 6])249        let fast = try #require(fees[2]), slow = try #require(fees[6])250        #expect(abs(fast - 50_756.077) < 1e-6)251        #expect(abs(slow - 1_000) < 1e-9)252        // no estimate at all is an empty answer, not an error; no answer at all is an error253        let none = RoutedTransport(fallback: (200, #"{"result":"0"}"#))254        #expect(try await client(none).feeEstimates().isEmpty)255        await #expect(throws: NetworkError.self) { try await client(RoutedTransport()).feeEstimates() }256        for hostile in [#"{"result":"1e999"}"#, #"{"result":"nan"}"#, #"{"result":"5000"}"#, #"{"result":"0x10"}"#] {257            #expect(try await client(RoutedTransport(fallback: (200, hostile))).feeEstimates().isEmpty)258        }259    }260261    @Test func chainIdentity() async throws {262        // the right chain263        try await client(RoutedTransport(["bb.test/api/v2/block-index/0": Fixture.bbBlockIndex])).verifyChain()264        // another chain: Litecoin's genesis served under a Dogecoin endpoint265        let other = RoutedTransport(["bb.test/api/v2/block-index/0": #"{"blockHash":"\#(Fixture.ltcGenesis)"}"#])266        await #expect(throws: NetworkError.disagreement("bb.test serves another chain than Dogecoin")) { try await client(other).verifyChain() }267        // nothing answers268        do {269            try await client(RoutedTransport()).verifyChain()270            Issue.record("expected a failure")271        } catch NetworkError.allEndpointsFailed(let failures) {272            #expect(failures == ["bb.test: HTTP 404 (not found)"])273        }274        // Bitcoin Cash is identified by block 661648, not by the genesis block it shares with Bitcoin275        let cash = RoutedTransport(["bbch.test/api/v2/block-index/661648": #"{"blockHash":"0000000000000000029e471c41818d24b8b74c911071c4ef0b4a0509f9b5a8ce"}"#])276        try await client(cash, .bitcoinCash).verifyChain()277        #expect(cash.requests == ["GET bbch.test/api/v2/block-index/661648"])278        // a Bitcoin node behind a "Bitcoin Cash" endpoint has another block there (Bitcoin's block 661648)279        let bitcoin = RoutedTransport(["bbch.test/api/v2/block-index/661648": #"{"blockHash":"0000000000000000000a9e2f4a6f8b0e2f0e1a3c4d5e6f708192a3b4c5d6e7f8"}"#])280        await #expect(throws: NetworkError.disagreement("bbch.test serves another chain than Bitcoin Cash")) { try await client(bitcoin, .bitcoinCash).verifyChain() }281        // no endpoint configured for the network282        let none = client(RoutedTransport(), .litecoin)283        #expect(!none.isConfigured)284        await #expect(throws: NetworkError.allEndpointsFailed(["no endpoint configured"])) { try await none.verifyChain() }285    }286287    @Test func bitcoinCashAddressesCarryTheirPrefix() async throws {288        let body = "qpzvmgyt554gfu04u7wxrhneyk88dzvknvl94aq775"289        let t = RoutedTransport(fallback: (200, Fixture.bbUnused))290        let c = client(t, .bitcoinCash)291        _ = try await c.stats(address: "bitcoincash:" + body)292        _ = try await c.stats(address: body)293        // Blockbook answers an error for a bare CashAddr: the prefix is always sent294        #expect(t.requests == Array(repeating: "GET bbch.test/api/v2/address/bitcoincash:\(body)?details=basic", count: 2))295    }296297    @Test func broadcast() async throws {298        let raw = Fixture.rawTransaction299        let ok = RoutedTransport(["bb.test/api/v2/sendtx/": #"{"result":"\#(Fixture.txid)"}"#])300        #expect(try await client(ok).broadcast(rawHex: raw) == Fixture.txid)301        #expect(ok.requests == ["POST bb.test/api/v2/sendtx/"] && ok.bodies == [raw])302        // already in the mempool or in a block: success, without a txid303        let known = RoutedTransport()304        known.set("bb.test/api/v2/sendtx/", status: 400, #"{"error":"-27: transaction already in block chain"}"#)305        #expect(try await client(known).broadcast(rawHex: raw) == "")306        // refused: the node's reason is reported307        let refused = RoutedTransport()308        refused.set("bb.test/api/v2/sendtx/", status: 400, #"{"error":"-26: 66: min relay fee not met"}"#)309        do {310            _ = try await client(refused).broadcast(rawHex: raw)311            Issue.record("expected a failure")312        } catch NetworkError.allEndpointsFailed(let failures) {313            #expect(failures == ["bb.test: -26: 66: min relay fee not met"])314        }315        // a 200 answer that is not a txid is not an acknowledgement316        let odd = RoutedTransport(["bb.test/api/v2/sendtx/": #"{"result":"ok"}"#])317        await #expect(throws: NetworkError.self) { try await client(odd).broadcast(rawHex: raw) }318        // only hexadecimal leaves the device319        for bad in ["", "zz", "abc", raw + " ", "00\n"] {320            await #expect(throws: NetworkError.invalidURL) { try await client(ok).broadcast(rawHex: bad) }321        }322    }323324    @Test func nothingButAnAddressReachesThePath() async throws {325        let t = RoutedTransport(fallback: (200, Fixture.bbUnused))326        let c = client(t)327        for bad in ["", "a/b", "../status", "D7Jeq?x=1", "D7Jeq#f", "D7Jeq%2F", "a b", "bitcoincash:q:q", ":q", "q:", "BITCOINCASH:q", String(repeating: "a", count: 131), "ä"] {328            await #expect(throws: NetworkError.invalidURL) { try await c.stats(address: bad) }329            await #expect(throws: NetworkError.invalidURL) { try await c.coins(address: bad) }330            await #expect(throws: NetworkError.invalidURL) { try await c.history(address: bad, cursor: nil) }331        }332        for bad in ["", "zz", String(repeating: "A", count: 64), String(repeating: "a", count: 63), "../" + String(repeating: "a", count: 61)] {333            await #expect(throws: NetworkError.invalidURL) { try await c.rawTransaction(txid: bad) }334        }335        await #expect(throws: NetworkError.invalidURL) { try await c.blockHash(height: -1) }336        #expect(t.requests.isEmpty)337    }338}339340@Suite struct BitcoreClientTests {341    func client(_ transport: RoutedTransport, _ network: BitcoinNetwork = .dogecoin) -> BitcoreClient {342        BitcoreClient(network: network, configuration: testConfiguration, transport: transport)343    }344    let base = "bc.test/api/DOGE/mainnet"345346    @Test func readsChainAndCoins() async throws {347        let unspent = "[" + [348            Fixture.bcCoin(mint: Fixture.txid, index: 1, mintHeight: 6_477_647, value: 2_000_000),349            Fixture.bcCoin(mint: txid(2), index: 0, mintHeight: -1, value: 500),                               // in the mempool350            Fixture.bcCoin(mint: txid(3), index: 4, mintHeight: 6_400_000, spent: txid(9), spentHeight: -1, value: 900),   // being spent351            Fixture.bcCoin(mint: txid(4), index: 0, mintHeight: -3, value: 700),                               // conflicting: not a coin352        ].joined(separator: ",") + "]"353        let t = RoutedTransport([354            "\(base)/block/tip": Fixture.bcTip,355            "\(base)/block/0": Fixture.bcBlock0,356            "\(base)/address/\(Fixture.address)?limit=1000&unspent=true": unspent,357        ])358        let c = client(t)359        #expect(c.isConfigured && c.indexerProtocol == .bitcore && !c.servesRawTransactions && c.hosts == ["bc.test"])360        try await c.verifyChain()361        let tip = try await c.tip()362        #expect(tip.height == 6_485_457 && tip.time.map { Int($0.timeIntervalSince1970) } == 1_796_447_290)363        #expect(try await c.blockHash(height: 0) == Fixture.dogeGenesis)364        let coins = try await c.coins(address: Fixture.address)365        #expect(coins == [366            UTXOIndexerCoin(txid: Fixture.txid, vout: 1, value: 2_000_000, height: 6_477_647, isCoinbase: false),367            UTXOIndexerCoin(txid: txid(2), vout: 0, value: 500, height: nil, isCoinbase: false),368        ])369        // raw transactions are not served: a typed error, no request370        let before = t.requests.count371        await #expect(throws: NetworkError.unsupported("the Bitcore API does not serve raw transactions")) { try await c.rawTransaction(txid: Fixture.txid) }372        #expect(t.requests.count == before)373    }374375    @Test func statsComeFromTheCoins() async throws {376        let t = RoutedTransport()377        let c = client(t)378        let key = "\(base)/address/\(Fixture.address)?limit=1000"379        t.set(key, "[]")380        #expect(try await c.stats(address: Fixture.address) == UTXOAddressStats(address: Fixture.address, isUsed: false, hasSpent: false, transactionCount: 0, confirmedBalance: 0))381        // two coins received, nothing spent382        t.set(key, "[" + [Fixture.bcCoin(mint: txid(1), index: 0, mintHeight: 100, value: 40), Fixture.bcCoin(mint: txid(2), index: 1, mintHeight: -1, value: 2)].joined(separator: ",") + "]")383        var s = try await c.stats(address: Fixture.address)384        #expect(s == UTXOAddressStats(address: Fixture.address, isUsed: true, hasSpent: false, transactionCount: 2, confirmedBalance: 40))385        // one of them spent in a block, another being spent in the mempool386        t.set(key, "[" + [387            Fixture.bcCoin(mint: txid(1), index: 0, mintHeight: 100, spent: txid(5), spentHeight: 120, value: 40),388            Fixture.bcCoin(mint: txid(2), index: 1, mintHeight: 110, spent: txid(6), spentHeight: -1, value: 7),389            Fixture.bcCoin(mint: txid(3), index: 0, mintHeight: 115, value: 9),390        ].joined(separator: ",") + "]")391        s = try await c.stats(address: Fixture.address)392        #expect(s.hasSpent && s.transactionCount == 5 && s.confirmedBalance == 16 && s.isComplete)393        // the server-side limit is reached: the list is not complete, exposure is assumed and nothing is counted394        let many = "[" + (0..<1000).map { Fixture.bcCoin(mint: txid($0 + 1), index: 0, mintHeight: 100, value: 1) }.joined(separator: ",") + "]"395        t.set(key, many)396        s = try await c.stats(address: Fixture.address)397        #expect(s == UTXOAddressStats(address: Fixture.address, isUsed: true, hasSpent: true, transactionCount: nil, confirmedBalance: nil, isComplete: false))398        // …and the coin list refuses to return a partial set399        t.set(key + "&unspent=true", many)400        await #expect(throws: NetworkError.invalidResponse("more than 1000 coins on one address")) { try await c.coins(address: Fixture.address) }401        // more than asked for is not an answer to the request402        t.set(key, "[" + (0..<1001).map { Fixture.bcCoin(mint: txid($0 + 1), index: 0, mintHeight: 100, value: 1) }.joined(separator: ",") + "]")403        await #expect(throws: NetworkError.self) { try await c.stats(address: Fixture.address) }404    }405406    @Test func historyIsRebuiltFromCoins() async throws {407        let t = RoutedTransport()408        let c = client(t)409        // 12 transactions touch the address: 11 mints (one in the mempool) and one spend410        var coins = (1...10).map { Fixture.bcCoin(mint: txid($0), index: 0, mintHeight: 1000 + $0, value: UInt64($0)) }411        coins.append(Fixture.bcCoin(mint: txid(11), index: 0, mintHeight: -1, value: 5))412        coins[0] = Fixture.bcCoin(mint: txid(1), index: 0, mintHeight: 1001, spent: txid(12), spentHeight: 2000, value: 1)413        t.set("\(base)/address/\(Fixture.address)?limit=1000", "[" + coins.joined(separator: ",") + "]")414        for n in 1...12 {415            t.set("\(base)/tx/\(txid(n))", Fixture.bcTransaction.replacingOccurrences(of: Fixture.txid, with: txid(n)))416            t.set("\(base)/tx/\(txid(n))/coins", Fixture.bcTransactionCoins.replacingOccurrences(of: Fixture.txid, with: txid(n)))417        }418        let first = try await c.history(address: Fixture.address, cursor: nil)419        // newest first: the mempool, then by height420        #expect(first.transactions.map(\.txid) == [txid(11), txid(12)] + (3...10).reversed().map { txid($0) })421        #expect(first.next == UTXOHistoryCursor(token: "10"))422        let tx = first.transactions[1]423        #expect(tx.fee == 226_000 && tx.virtualSize == 225 && tx.height == 6_477_647 && tx.time == 1_795_951_329)424        #expect(tx.inputs == [UTXOIndexerTransaction.Input(425            txid: Fixture.spent, vout: 0,426            previous: .init(address: "D7JeqAsJ9Vie3VnpticCJ2N9s2RJQQjgiG", scriptPubKey: "76a91417bef36d7f6f4948f1d9aa0adc348f6f58ad52d188ac", value: 1_531_194_000),427            sequence: 4_294_967_294)])428        // outputs come back in the order of the transaction, whatever the order of the answer429        #expect(tx.outputs.map(\.value) == [1_528_968_000, 2_000_000])430        #expect(tx.outputs.map(\.address) == ["DMMZ1Qm3sU6LM2GZCH5UzojRZA8SFjPDBH", Fixture.address])431        let second = try await c.history(address: Fixture.address, cursor: first.next)432        #expect(second.transactions.map(\.txid) == [txid(2), txid(1)] && second.next == nil)433        #expect(try await c.history(address: Fixture.address, cursor: UTXOHistoryCursor(token: "12")).transactions.isEmpty)434        for token in ["-1", "x", "4001"] {435            await #expect(throws: NetworkError.invalidURL) { try await c.history(address: Fixture.address, cursor: UTXOHistoryCursor(token: token)) }436        }437        // an answer about another transaction than the one asked is refused438        t.set("\(base)/tx/\(txid(11))", Fixture.bcTransaction)439        await #expect(throws: NetworkError.self) { try await c.history(address: Fixture.address, cursor: nil) }440    }441442    @Test func chainIdentityAndBlockNumbering() async throws {443        // an instance that numbers its blocks one below their height (seen on Dogecoin Testnet) is not on the expected chain444        let config = EndpointConfiguration(esplora: [:], bitcore: ["dogecoinTestnet": ["https://bc.test/api/DOGE/testnet"]], ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")445        let shifted = RoutedTransport(["bc.test/api/DOGE/testnet/block/0": Fixture.bcShiftedBlock0])446        await #expect(throws: NetworkError.disagreement("bc.test serves another chain than Dogecoin Testnet")) {447            try await BitcoreClient(network: .dogecoinTestnet, configuration: config, transport: shifted).verifyChain()448        }449        // a block of another height than the one asked450        let wrongHeight = RoutedTransport(["\(base)/block/0": Fixture.bcBlock0.replacingOccurrences(of: #""height":0"#, with: #""height":1"#)])451        await #expect(throws: NetworkError.self) { try await client(wrongHeight).verifyChain() }452        await #expect(throws: NetworkError.self) { try await client(wrongHeight).blockHash(height: 0) }453    }454455    @Test func bitcoinCashAddressesAreSentWithoutPrefix() async throws {456        let body = "qpzvmgyt554gfu04u7wxrhneyk88dzvknvl94aq775"457        let t = RoutedTransport(fallback: (200, "[]"))458        let c = client(t, .bitcoinCash)459        _ = try await c.stats(address: "bitcoincash:" + body)460        _ = try await c.coins(address: body)461        // with the prefix this API answers an empty list: a funded address would look empty462        #expect(t.requests == ["GET bcash.test/api/BCH/mainnet/address/\(body)?limit=1000", "GET bcash.test/api/BCH/mainnet/address/\(body)?limit=1000&unspent=true"])463    }464465    @Test func feesAndBroadcast() async throws {466        let t = RoutedTransport([467            "\(base)/fee/2": #"{"feerate":0.50756077,"blocks":2}"#,468            "\(base)/fee/6": #"{"feerate":0.00001}"#,469            "\(base)/tx/send": #"{"txid":"\#(Fixture.txid)"}"#,470        ])471        let c = client(t)472        let fees = try await c.feeEstimates()473        #expect(Set(fees.keys) == [2, 6])474        let fast = try #require(fees[2]), slow = try #require(fees[6])475        #expect(abs(fast - 50_756.077) < 1e-6 && abs(slow - 1) < 1e-9)476        #expect(try await c.broadcast(rawHex: Fixture.rawTransaction) == Fixture.txid)477        #expect(t.bodies == [#"{"rawTx":"\#(Fixture.rawTransaction)"}"#])478        // a refusal is plain text with status 500479        let refused = RoutedTransport()480        refused.set("\(base)/tx/send", status: 500, "66: min relay fee not met")481        do {482            _ = try await client(refused).broadcast(rawHex: Fixture.rawTransaction)483            Issue.record("expected a failure")484        } catch NetworkError.allEndpointsFailed(let failures) {485            #expect(failures == ["bc.test: 66: min relay fee not met"])486        }487        let known = RoutedTransport()488        known.set("\(base)/tx/send", status: 500, "transaction already in block chain")489        #expect(try await client(known).broadcast(rawHex: Fixture.rawTransaction) == "")490        await #expect(throws: NetworkError.invalidURL) { try await c.broadcast(rawHex: "not hex") }491    }492}493494@Suite struct EsploraIndexerTests {495    func client(_ transport: RoutedTransport) -> EsploraClient { EsploraClient(network: .litecoin, configuration: testConfiguration, transport: transport) }496    let base = "es.test/api"497498    @Test func esploraSpeaksTheCommonProtocol() async throws {499        let confirmed = (1...25).map { Fixture.esTransaction(txid: txid($0), confirmed: true) }500        let t = RoutedTransport([501            "\(base)/block-height/0": Fixture.ltcGenesis + "\n",502            "\(base)/blocks/tip/height": "3224582",503            "\(base)/address/\(Fixture.ltcAddress)": Fixture.esStats,504            "\(base)/address/\(Fixture.ltcAddress)/utxo": Fixture.esUTXO,505            "\(base)/address/\(Fixture.ltcAddress)/txs": "[" + ([Fixture.esTransaction(txid: txid(99), confirmed: false)] + confirmed).joined(separator: ",") + "]",506            "\(base)/address/\(Fixture.ltcAddress)/txs/chain/\(txid(25))": "[" + Fixture.esTransaction(txid: txid(26), confirmed: true) + "]",507            "\(base)/tx/\(txid(1))/hex": Fixture.rawTransaction.uppercased() + "\n",508        ])509        let c: any UTXOIndexer = client(t)510        #expect(c.indexerProtocol == .esplora && c.servesRawTransactions && c.hosts == ["es.test"] && c.network == .litecoin)511        try await c.verifyChain()512        #expect(try await c.tip() == UTXOChainTip(height: 3_224_582, time: nil))513        #expect(try await c.stats(address: Fixture.ltcAddress) == UTXOAddressStats(address: Fixture.ltcAddress, isUsed: true, hasSpent: true, transactionCount: 204, confirmedBalance: 0))514        let coins = try await c.coins(address: Fixture.ltcAddress)515        #expect(coins == [516            UTXOIndexerCoin(txid: "84e98892c2b944d5efbb5e7e287ca076c2430ae5a756c17b770fd36cdde45c85", vout: 1, value: 300_480_770, height: 3_224_500),517            UTXOIndexerCoin(txid: "627c16d6abb04ee5cf6861ae5ddf65542de91023c052bfbca184089f6af1a61a", vout: 0, value: 5_000, height: nil),518        ])519        #expect(coins[0].confirmations(tipHeight: 3_224_582) == 83)520        let first = try await c.history(address: Fixture.ltcAddress, cursor: nil)521        #expect(first.transactions.count == 26 && first.next == UTXOHistoryCursor(token: txid(25)))522        #expect(first.transactions[0].height == nil && first.transactions[1].height == 3_224_521)523        let tx = first.transactions[1]524        #expect(tx.fee == 33_000 && tx.virtualSize == 110 && tx.time == 1_796_435_000)525        #expect(tx.inputs.first?.previous == .init(address: "ltc1qhvecyuzfj8m9uwgl57jcz6wdvp3t6j9rrdgt60", scriptPubKey: "0014bb3382704991f65e391fa7a58169cd6062bd48a3", value: 59_486_352))526        #expect(tx.outputs == [.init(address: Fixture.ltcAddress, scriptPubKey: "00144726308d832f554025128e2b0787400d0c80769f", value: 59_453_352)])527        let second = try await c.history(address: Fixture.ltcAddress, cursor: first.next)528        #expect(second.transactions.map(\.txid) == [txid(26)] && second.next == nil)529        #expect(try await c.rawTransaction(txid: txid(1)) == Fixture.rawTransaction)530    }531532    /// litecoinspace.org has no `/fee-estimates`: the recommended fees are used instead.533    @Test func feeEstimatesFallBackToRecommendedFees() async throws {534        let t = RoutedTransport(["\(base)/v1/fees/recommended": #"{"fastestFee":4,"halfHourFee":3,"hourFee":2,"economyFee":1,"minimumFee":1}"#])535        #expect(try await client(t).feeEstimates() == [1: 4, 3: 3, 6: 2, 144: 1, 1008: 1])536        #expect(t.requests == ["GET \(base)/fee-estimates", "GET \(base)/v1/fees/recommended"])537        // the Esplora answer is preferred when it exists (Bitcoin: unchanged)538        let both = RoutedTransport(["\(base)/fee-estimates": #"{"1":12.5,"6":3.0,"x":1,"144":-2}"#, "\(base)/v1/fees/recommended": Fixture.esRecommended])539        #expect(try await client(both).feeEstimates() == [1: 12.5, 6: 3.0])540        #expect(both.requests == ["GET \(base)/fee-estimates"])541        // neither: the first error is reported542        await #expect(throws: NetworkError.self) { try await client(RoutedTransport()).feeEstimates() }543    }544545    @Test func wrongChainIsRefused() async throws {546        let t = RoutedTransport(["\(base)/block-height/0": "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"])547        await #expect(throws: NetworkError.disagreement("es.test serves another chain than Litecoin")) { try await client(t).verifyChain() }548    }549}550551/// Nothing an indexer sends may trap the process: every method of every client either returns or throws.552@Suite struct HostileIndexerTests {553    static let bodies: [String] = {554        let id = String(repeating: "ab", count: 32)555        var list = [556            "", " ", "null", "true", "0", "-1", "1e999", "\"\"", "[]", "{}", "[[]]", "[{}]", "[null]", "{\"a\":", "\u{0}\u{1}\u{2}", "<html>503</html>",557            String(repeating: "[", count: 2_000) + String(repeating: "]", count: 2_000),558            String(repeating: "{\"a\":", count: 600) + "1" + String(repeating: "}", count: 600),559            "\"" + String(repeating: "x", count: 300_000) + "\"",560            // Blockbook shapes with hostile values561            #"{"blockbook":{"bestHeight":-5}}"#, #"{"blockbook":{"bestHeight":1e400}}"#, #"{"blockbook":{"bestHeight":99999999999999999999}}"#,562            #"{"blockbook":{"bestHeight":"12"}}"#, #"{"blockbook":{"bestHeight":12,"lastBlockTime":"\#(String(repeating: "9", count: 5_000))"}}"#,563            #"{"blockHash":12}"#, #"{"blockHash":"../../x"}"#, #"{"blockHash":""}"#,564            #"{"balance":"-1","totalSent":"-1","unconfirmedBalance":"-","unconfirmedTxs":-9223372036854775808,"txs":9223372036854775807}"#,565            #"{"balance":12,"txs":"3"}"#, #"{"txs":1e308,"unconfirmedTxs":1e308}"#,566            #"{"page":1,"totalPages":-3,"transactions":[{"txid":"zz","vin":[],"vout":[]}]}"#,567            #"{"page":1,"totalPages":2,"transactions":[{"txid":"\#(id)","vin":[{"txid":"../x","vout":4294967296}],"vout":[{"value":"-1"}]}]}"#,568            #"{"page":1,"totalPages":2,"transactions":[{"txid":"\#(id)","vin":[{"txid":"\#(id)","vout":-1,"value":"1e9","sequence":-1}],"vout":[{"value":"18446744073709551616","hex":"zz","addresses":[1,2]}],"blockHeight":-7,"confirmations":-7,"blockTime":-1,"size":-1,"fees":"x"}]}"#,569            #"{"page":1,"totalPages":2,"transactions":[{"txid":"\#(id)","vin":[],"vout":[{"value":"1","hex":"\#(String(repeating: "ab", count: 20_001))","addresses":["\#(String(repeating: "a", count: 5_000))"],"isAddress":true}],"confirmations":3,"blockHeight":99999999999}]}"#,570            #"[{"txid":"\#(id)","vout":1,"value":"18446744073709551616"}]"#, #"[{"txid":"\#(id)","vout":-1,"value":"1"}]"#,571            #"[{"txid":"\#(id)","vout":1.5,"value":"1"}]"#, #"[{"txid":"\#(id)","value":1}]"#, #"[{"txid":12,"value":"1"}]"#,572            #"[{"txid":"\#(id)","value":"1","height":-1,"confirmations":-5,"coinbase":"yes"}]"#,573            #"{"txid":"\#(id)","vin":[],"vout":[],"hex":"zz"}"#, #"{"txid":"\#(id)","vin":[],"vout":[],"hex":"abc"}"#, #"{"txid":"\#(id)","vin":[],"vout":[]}"#,574            #"{"result":""}"#, #"{"result":"inf"}"#, #"{"result":"-0.0"}"#, #"{"result":12}"#, #"{"result":"\#(id)"}"#, #"{"error":{"message":"x"}}"#,575            // Bitcore shapes with hostile values576            #"{"hash":"\#(id)","height":-1}"#, #"{"hash":12,"height":0}"#, #"{"hash":"\#(id)","height":1e999,"time":"never"}"#,577            #"{"hash":"\#(id)","height":0,"time":"\#(String(repeating: "2", count: 10_000))"}"#,578            #"[{"mintTxid":"\#(id)","mintIndex":-1,"mintHeight":1,"spentHeight":-2,"value":1}]"#,579            #"[{"mintTxid":"\#(id)","mintIndex":0,"mintHeight":1,"spentHeight":-2,"value":-1}]"#,580            #"[{"mintTxid":"\#(id)","mintIndex":0,"mintHeight":1,"spentHeight":-2,"value":1.5}]"#,581            #"[{"mintTxid":"\#(id)","mintIndex":0,"mintHeight":1,"spentHeight":-2,"value":18446744073709551616}]"#,582            #"[{"mintTxid":"x","mintIndex":0,"mintHeight":1,"spentHeight":-2,"value":1}]"#,583            #"[{"mintTxid":"\#(id)","mintIndex":0,"mintHeight":9223372036854775807,"spentHeight":-9223372036854775808,"spentTxid":"y","value":18446744073709551615}]"#,584            #"[{"mintTxid":"\#(id)","mintIndex":4294967295,"mintHeight":-9,"spentHeight":7,"spentTxid":"\#(id)","value":18446744073709551615,"script":"zz","address":false}]"#,585            #"{"txid":"\#(id)","blockHeight":-1,"blockTime":"x","size":-4,"fee":-1,"coinbase":true}"#,586            #"{"txid":"\#(id)","blockHeight":1e999,"fee":1e999}"#,587            #"{"inputs":[{"mintTxid":"\#(id)","mintIndex":0,"mintHeight":1,"spentHeight":2,"value":1}],"outputs":[{"mintTxid":"\#(String(repeating: "cd", count: 32))","mintIndex":0,"mintHeight":1,"spentHeight":-2,"value":1}]}"#,588            #"{"inputs":null,"outputs":{}}"#, #"{"feerate":-1}"#, #"{"feerate":1e999}"#, #"{"feerate":"0.1"}"#, #"{"feerate":5000}"#, #"{"txid":7}"#,589            // Esplora shapes with hostile values590            "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "99999999999999999999999999", "-12", "12.5",591            #"{"address":"x","chain_stats":{"funded_txo_count":-1,"funded_txo_sum":1,"spent_txo_count":9223372036854775807,"spent_txo_sum":2,"tx_count":9223372036854775807},"mempool_stats":{"funded_txo_count":0,"funded_txo_sum":0,"spent_txo_count":0,"spent_txo_sum":0,"tx_count":9223372036854775807}}"#,592            #"[{"txid":"\#(id)","vout":-1,"value":1,"status":{"confirmed":true,"block_height":-1}}]"#,593            #"[{"txid":"x","vout":1,"value":1,"status":{"confirmed":true}}]"#,594            #"[{"txid":"\#(id)","vout":4294967296,"value":18446744073709551615,"status":{"confirmed":true,"block_height":1e9}}]"#,595            #"[{"txid":"\#(id)","vin":[{"txid":"q","vout":-1,"prevout":{"scriptpubkey":"zz","value":1}}],"vout":[{"scriptpubkey":"","value":1}],"fee":1,"weight":-4,"status":{"confirmed":true,"block_height":-2,"block_time":-2}}]"#,596            #"{"1":1e999,"2":-1,"x":3,"3":"4"}"#, #"{"fastestFee":-1,"hourFee":1e999}"#,597        ]598        // more items than any legitimate answer holds599        list.append("[" + Array(repeating: #"{"txid":"\#(id)","vout":1,"value":"1","height":5,"confirmations":2}"#, count: 10_001).joined(separator: ",") + "]")600        list.append(#"{"page":1,"totalPages":9,"transactions":["# + Array(repeating: #"{"txid":"\#(id)","vin":[],"vout":[]}"#, count: 101).joined(separator: ",") + "]}")601        list.append("[" + Array(repeating: #"{"txid":"\#(id)","vout":1,"value":1,"status":{"confirmed":true,"block_height":5}}"#, count: 10_001).joined(separator: ",") + "]")602        return list603    }()604605    static func exercise(_ c: any UTXOIndexer) async -> (returned: Int, threw: Int) {606        let address = c.network == .litecoin ? Fixture.ltcAddress : Fixture.address607        var returned = 0, threw = 0608        func run(_ work: () async throws -> Void) async {609            do {610                try await work()611                returned += 1612            } catch {613                // anything thrown must be one of the typed network errors, with a readable summary614                #expect(error is NetworkError, "\(type(of: error))")615                if let e = error as? NetworkError { #expect(!e.summary.isEmpty) }616                threw += 1617            }618        }619        await run { try await c.verifyChain() }620        await run { _ = try await c.tip() }621        await run { _ = try await c.blockHash(height: 5) }622        await run { _ = try await c.stats(address: address) }623        await run { _ = try await c.coins(address: address) }624        await run { _ = try await c.history(address: address, cursor: nil) }625        await run { _ = try await c.history(address: address, cursor: UTXOHistoryCursor(token: c.indexerProtocol == .esplora ? String(repeating: "ab", count: 32) : "3")) }626        await run { _ = try await c.rawTransaction(txid: String(repeating: "ab", count: 32)) }627        await run { _ = try await c.feeEstimates() }628        await run { _ = try await c.broadcast(rawHex: "00") }629        return (returned, threw)630    }631632    @Test func hostileAnswersNeverTrap() async throws {633        #expect(Self.bodies.count >= 70)634        var calls = 0, thrown = 0635        for body in Self.bodies {636            for status in [200, 500] {637                let t = RoutedTransport(fallback: (status, body))638                let clients: [any UTXOIndexer] = [639                    BlockbookClient(network: .dogecoin, configuration: testConfiguration, transport: t),640                    BitcoreClient(network: .dogecoin, configuration: testConfiguration, transport: t),641                    EsploraClient(network: .litecoin, configuration: testConfiguration, transport: t),642                ]643                for c in clients {644                    let r = await Self.exercise(c)645                    calls += r.returned + r.threw646                    thrown += r.threw647                }648            }649        }650        #expect(calls == Self.bodies.count * 2 * 3 * 10)651        // the great majority of these answers must be refused; the few accepted ones are empty lists and the like652        #expect(thrown * 10 >= calls * 7, "\(thrown) of \(calls) threw")653    }654655    /// Specific refusals: values that would be dangerous if they were silently accepted.656    @Test func dangerousValuesAreRefused() async throws {657        let id = String(repeating: "ab", count: 32)658        func blockbook(_ body: String) -> BlockbookClient { BlockbookClient(network: .dogecoin, configuration: testConfiguration, transport: RoutedTransport(fallback: (200, body))) }659        func bitcore(_ body: String) -> BitcoreClient { BitcoreClient(network: .dogecoin, configuration: testConfiguration, transport: RoutedTransport(fallback: (200, body))) }660        // amounts that are not exact integers are never rounded661        for value in ["\"1.5\"", "\"1e3\"", "\"-1\"", "\" 1\"", "\"0x10\"", "\"18446744073709551616\"", "1", "null"] {662            await #expect(throws: NetworkError.self) { try await blockbook(#"[{"txid":"\#(id)","vout":0,"value":\#(value)}]"#).coins(address: Fixture.address) }663        }664        for value in ["1.5", "-1", "\"1\"", "18446744073709551616", "null"] {665            await #expect(throws: NetworkError.self) {666                try await bitcore(#"[{"mintTxid":"\#(id)","mintIndex":0,"mintHeight":1,"spentHeight":-2,"value":\#(value)}]"#).coins(address: Fixture.address)667            }668        }669        // identifiers that are not 64 lower-case hexadecimal characters670        for bad in ["", "zz", id.uppercased(), id + "00", "../" + id] {671            await #expect(throws: NetworkError.self) { try await blockbook(#"[{"txid":"\#(bad)","vout":0,"value":"1"}]"#).coins(address: Fixture.address) }672            await #expect(throws: NetworkError.self) {673                try await bitcore(#"[{"mintTxid":"\#(bad)","mintIndex":0,"mintHeight":1,"spentHeight":-2,"value":1}]"#).coins(address: Fixture.address)674            }675        }676        // a raw transaction that is not hexadecimal, or empty677        for hex in ["", "zz", "abc", "00 11"] {678            await #expect(throws: NetworkError.self) { try await blockbook(#"{"txid":"\#(id)","vin":[],"vout":[],"hex":"\#(hex)"}"#).rawTransaction(txid: id) }679        }680        // heights: nonsense becomes "unconfirmed", never a huge confirmation count681        let coins = try await blockbook(#"[{"txid":"\#(id)","vout":0,"value":"1","height":-5,"confirmations":7},{"txid":"\#(id)","vout":1,"value":"1","height":99999999999,"confirmations":7}]"#).coins(address: Fixture.address)682        #expect(coins.allSatisfy { $0.height == nil && $0.confirmations(tipHeight: 1_000) == 0 })683        #expect(UTXOIndexerCoin(txid: id, vout: 0, value: 1, height: 1).confirmations(tipHeight: Int.max) == UInt32.max)684    }685}686687@Suite struct UTXOEndpointConfigurationTests {688    /// A configuration stored before the UTXO upgrade (QYVORA 1.0 wrote exactly these four fields).689    static let stored = #"{"esplora":{"mainnet":["https://my.node/api"],"testnet":[],"signet":["https://mempool.space/signet/api"]},"ethereumRPC":{"mainnet":["https://rpc.example"],"sepolia":[]},"ethereumIndexer":{},"priceAPI":""}"#690691    @Test func storedConfigurationsStillDecode() throws {692        let c = try JSONDecoder().decode(EndpointConfiguration.self, from: Data(Self.stored.utf8))693        // what the user had is untouched, including what was emptied694        #expect(c.esplora["mainnet"] == ["https://my.node/api"] && c.esplora["testnet"] == [] && c.esplora["signet"] == ["https://mempool.space/signet/api"])695        #expect(c.ethereumRPC["mainnet"] == ["https://rpc.example"] && c.ethereumRPC["sepolia"] == [] && c.priceAPI.isEmpty)696        // the networks that did not exist receive their built-in endpoints697        #expect(c.esplora["litecoin"] == EndpointConfiguration.default.esplora["litecoin"])698        #expect(c.esplora["litecoinTestnet"] == EndpointConfiguration.default.esplora["litecoinTestnet"])699        #expect(c.blockbook == EndpointConfiguration.defaultBlockbook && c.bitcore == EndpointConfiguration.defaultBitcore)700        #expect(Set(c.esplora.keys) == ["mainnet", "testnet", "signet", "litecoin", "litecoinTestnet"])701702        // a value written after the EVM networks were added and before the UTXO coins (schema 2, no `blockbook` field):703        // its EVM lists are complete and stay as they are, its UTXO lists receive the new networks704        let between = #"{"schema":2,"esplora":{"mainnet":[],"testnet":["https://t.example/api"],"signet":[]},"ethereumRPC":{"base":[]},"ethereumIndexer":{},"priceAPI":"https://p.example"}"#705        let b = try JSONDecoder().decode(EndpointConfiguration.self, from: Data(between.utf8))706        #expect(b.esplora["mainnet"] == [] && b.esplora["testnet"] == ["https://t.example/api"] && b.esplora["signet"] == [])707        #expect(b.esplora["litecoin"] == ["https://litecoinspace.org/api"])708        #expect(b.blockbook == EndpointConfiguration.defaultBlockbook && b.bitcore == EndpointConfiguration.defaultBitcore)709        #expect(b.ethereumRPC == ["base": []] && b.ethereumIndexer.isEmpty && b.priceAPI == "https://p.example")710        for n in BitcoinNetwork.allCases where n.coin != .bitcoin && n.indexerAvailable {711            #expect(!UTXOIndexers.clients(for: n, configuration: b, transport: RoutedTransport()).isEmpty, "\(n)")712            #expect(!UTXOIndexers.clients(for: n, configuration: c, transport: RoutedTransport()).isEmpty, "\(n)")713        }714    }715716    @Test func currentConfigurationsRoundTripExactly() throws {717        func roundTrip(_ c: EndpointConfiguration) throws -> EndpointConfiguration {718            try JSONDecoder().decode(EndpointConfiguration.self, from: try JSONEncoder().encode(c))719        }720        #expect(try roundTrip(.default) == .default)721        // what the user removed or emptied stays so: nothing is added back to a configuration of this version722        var edited = EndpointConfiguration.default723        edited.esplora["litecoin"] = []724        edited.esplora["litecoinTestnet"] = nil725        edited.blockbook = [:]726        edited.bitcore["dogecoin"] = ["http://192.168.1.9:3000/api/DOGE/mainnet"]727        #expect(try roundTrip(edited) == edited)728        let minimal = EndpointConfiguration(esplora: ["signet": ["https://esplora.test/api"]], ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")729        #expect(minimal.blockbook.isEmpty && minimal.bitcore.isEmpty)730        #expect(try roundTrip(minimal) == minimal)731        // a field of the wrong type is an error, not a silent default732        #expect(throws: (any Error).self) {733            try JSONDecoder().decode(EndpointConfiguration.self, from: Data(#"{"esplora":{},"blockbook":"x","ethereumRPC":{},"ethereumIndexer":{},"priceAPI":""}"#.utf8))734        }735        #expect(throws: (any Error).self) {736            try JSONDecoder().decode(EndpointConfiguration.self, from: Data(#"{"schema":2,"esplora":{},"blockbook":{},"bitcore":[1],"ethereumRPC":{},"ethereumIndexer":{},"priceAPI":""}"#.utf8))737        }738        // the stored form names its schema and the three UTXO lists739        let stored = try JSONDecoder().decode(JSONValue.self, from: try JSONEncoder().encode(minimal))740        #expect(stored["schema"] == .number(2) && stored["blockbook"] == .object([:]) && stored["bitcore"] == .object([:]))741        #expect(stored["esplora"] == .object(["signet": .array([.string("https://esplora.test/api")])]))742    }743744    @Test func defaultEndpointsPerNetwork() {745        let d = EndpointConfiguration.default746        // Bitcoin: unchanged747        #expect(d.esplora["mainnet"] == ["https://mempool.space/api", "https://blockstream.info/api"])748        #expect(d.esplora["testnet"] == ["https://mempool.space/testnet/api", "https://blockstream.info/testnet/api"])749        #expect(d.esplora["signet"] == ["https://mempool.space/signet/api", "https://blockstream.info/signet/api"])750        let expected: [BitcoinNetwork: [UTXOIndexerProtocol: Int]] = [751            .mainnet: [.esplora: 2], .testnet: [.esplora: 2], .signet: [.esplora: 2],752            .litecoin: [.esplora: 1, .blockbook: 2, .bitcore: 1], .litecoinTestnet: [.esplora: 1, .bitcore: 1],753            .dogecoin: [.blockbook: 1, .bitcore: 1], .dogecoinTestnet: [:],754            .bitcoinCash: [.blockbook: 1, .bitcore: 1], .bitcoinCashTestnet: [.bitcore: 1],755        ]756        let transport = RoutedTransport()757        for n in BitcoinNetwork.allCases {758            let endpoints = d.utxoEndpoints(n)759            #expect(endpoints.mapValues(\.count) == expected[n], "\(n)")760            let clients = UTXOIndexers.clients(for: n, configuration: d, transport: transport)761            #expect(clients.map(\.indexerProtocol) == [UTXOIndexerProtocol.esplora, .blockbook, .bitcore].filter { endpoints[$0] != nil })762            #expect(clients.allSatisfy { $0.network == n && $0.isConfigured })763            // a network without any built-in endpoint is exactly the one flagged as unavailable764            #expect(clients.isEmpty == !n.indexerAvailable)765            // legacy inputs need raw transactions: where signatures do not commit to amounts, one source must serve them766            if !n.signatureCommitsToAmounts, n.indexerAvailable { #expect(clients.contains { $0.servesRawTransactions }) }767            // at least two independent hosts on every production network768            if !n.isTest { #expect(Set(clients.flatMap(\.hosts)).count >= 2, "\(n)") }769        }770        #expect(d.utxoIndexerURLs.count == 6 + 2 + 4 + 5)771        #expect(d.utxoIndexerURLs.allSatisfy { EndpointConfiguration.isAcceptable($0) && $0.hasPrefix("https://") && !$0.hasSuffix("/") })772        #expect(Set(d.blockbook.keys).union(d.bitcore.keys).union(d.esplora.keys).isSubset(of: Set(BitcoinNetwork.allCases.map(\.rawValue))))773        // an endpoint that is not acceptable (plain http to a public host) is ignored by the clients774        let unsafe = EndpointConfiguration(esplora: [:], blockbook: ["dogecoin": ["http://example.com/api/v2"]], ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")775        #expect(UTXOIndexers.clients(for: .dogecoin, configuration: unsafe, transport: transport).isEmpty)776    }777778    @Test func surveyRanksSourcesAndFlagsStaleOnes() async throws {779        // Litecoin Testnet on 2026-12-05: one source three days (29 000 blocks) behind the other780        let config = EndpointConfiguration(esplora: ["litecoinTestnet": ["https://es.test/api"]], blockbook: ["litecoinTestnet": ["https://bb.test/api/v2"]],781                                           bitcore: ["litecoinTestnet": ["https://bc.test/api/LTC/testnet"]], ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")782        let t = RoutedTransport([783            "es.test/api/blocks/tip/height": "5077964",784            "bc.test/api/LTC/testnet/block/tip": #"{"hash":"f7405bf7a6aa9885bfab546738e79338a66280af6e784ab9469be30d91a7d487","height":5106909,"time":"2026-12-05T07:04:07.000Z"}"#,785        ])786        let survey = await UTXOIndexers.survey(UTXOIndexers.clients(for: .litecoinTestnet, configuration: config, transport: t))787        #expect(survey.map(\.client.indexerProtocol) == [.bitcore, .esplora, .blockbook])788        #expect(survey.map(\.lag) == [0, 28_945, nil])789        #expect(survey.map(\.isStale) == [false, true, false])790        #expect(survey[2].tip == nil)791        // sources within the confirmation depth of each other are all usable792        t.set("es.test/api/blocks/tip/height", "5106905")793        let close = await UTXOIndexers.survey(UTXOIndexers.clients(for: .litecoinTestnet, configuration: config, transport: t))794        #expect(close.prefix(2).allSatisfy { !$0.isStale })795    }796}797798/// Opt-in tests against the public indexers: `QYVORA_LIVE=1 swift test --filter UTXOLiveTests`.799/// Read-only: chain identity, tip, one public address (statistics, coins, a history page), fee estimates.800@Suite(.enabled(if: ProcessInfo.processInfo.environment["QYVORA_LIVE"] == "1"), .serialized)801struct UTXOLiveTests {802    /// Public addresses seen in recent blocks on 2026-12-05 (they belong to nobody in particular).803    static let addresses: [BitcoinNetwork: String] = [804        .litecoin: "ltc1qgunrprvr9a25qfgj3c4s0p6qp5xgqa5ll086cj",805        .litecoinTestnet: "tltc1qd8408gr8lpjwmf0d3m7d58rlr5hkxl7vxnmw93",806        .dogecoin: "D7JeqAsJ9Vie3VnpticCJ2N9s2RJQQjgiG",807        .bitcoinCash: "bitcoincash:qqav0x3avd28ymvage43xtjhrptsu2ax3gqrkc97r9",808        .bitcoinCashTestnet: "bchtest:qrj36dmsnpu6xu88962ye280mgzecmxcayyjx7h9sg",809    ]810811    @Test func everyDefaultEndpointOfTheNewCoins() async throws {812        let transport = URLSessionTransport(timeout: 25)813        func attempt<T>(_ work: () async throws -> T) async -> Result<T, any Error> {814            do { return .success(try await work()) } catch { return .failure(error) }815        }816        func text<T>(_ r: Result<T, any Error>, _ describe: (T) -> String) -> String {817            switch r {818            case .success(let v): return describe(v)819            case .failure(let e): return "FAILED: " + ((e as? NetworkError)?.summary ?? "\(e)")820            }821        }822        for network in BitcoinNetwork.allCases where network.coin != .bitcoin {823            // one client per endpoint, so that each default URL is checked by itself824            var clients = [any UTXOIndexer]()825            for (kind, list) in EndpointConfiguration.default.utxoEndpoints(network).sorted(by: { $0.key.rawValue < $1.key.rawValue }) {826                for url in list {827                    let one = EndpointConfiguration(esplora: kind == .esplora ? [network.rawValue: [url]] : [:], blockbook: kind == .blockbook ? [network.rawValue: [url]] : [:],828                                                    bitcore: kind == .bitcore ? [network.rawValue: [url]] : [:], ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")829                    clients += UTXOIndexers.clients(for: network, configuration: one, transport: transport)830                }831            }832            print("LIVE \(network.rawValue): \(clients.count) endpoint(s), identity block \(network.identityBlock.height)")833            #expect(clients.isEmpty == !network.indexerAvailable)834            guard let address = Self.addresses[network] else { continue }835            var identified = 0836            for c in clients {837                let host = "\(c.indexerProtocol.rawValue) \(c.hosts.first ?? "?")"838                let identity = await attempt { try await c.verifyChain() }839                if case .success = identity { identified += 1 }840                let tip = await attempt { try await c.tip() }841                let stats = await attempt { try await c.stats(address: address) }842                let coins = await attempt { try await c.coins(address: address) }843                let history = await attempt { try await c.history(address: address, cursor: nil) }844                let fees = await attempt { try await c.feeEstimates() }845                print("LIVE   \(host): chain \(text(identity) { "verified" }); tip \(text(tip) { "\($0.height)" + ($0.time.map { " (\(Int(Date().timeIntervalSince($0) / 60)) min old)" } ?? "") })")846                print("LIVE     stats \(text(stats) { "used \($0.isUsed) spent \($0.hasSpent) txs \($0.transactionCount.map(String.init) ?? "?") balance \($0.confirmedBalance.map(String.init) ?? "?") complete \($0.isComplete)" })")847                print("LIVE     coins \(text(coins) { "\($0.count)" }); history \(text(history) { "\($0.transactions.count) tx, more \($0.next != nil)" + ($0.transactions.first.map { ", first \($0.txid.prefix(12))… height \($0.height.map(String.init) ?? "mempool") fee \($0.fee.map(String.init) ?? "?")" } ?? "") })")848                print("LIVE     fees (base units per vbyte) \(text(fees) { $0.sorted { $0.key < $1.key }.map { "\($0.key): \($0.value)" }.joined(separator: ", ") })")849                if case .success(let page) = history, c.servesRawTransactions, let first = page.transactions.first {850                    let raw = await attempt { try await c.rawTransaction(txid: first.txid) }851                    print("LIVE     raw transaction \(text(raw) { "\($0.utf8.count / 2) bytes" })")852                }853            }854            let survey = await UTXOIndexers.survey(clients)855            print("LIVE   survey: " + survey.map { "\($0.client.indexerProtocol.rawValue) \($0.client.hosts.first ?? "?") lag \($0.lag.map(String.init) ?? "?")\($0.isStale ? " STALE" : "")" }.joined(separator: "; "))856            // every network that is announced as available has at least one endpoint that proves its chain857            #expect(identified >= 1, "\(network)")858        }859    }860}861
Files main
Menu

Theme