Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraNetworkingTests/UTXOCoinsAuditRegressionTests.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/// Regression tests of the multi-chain security audit, UTXO coins (findings QYV-SVC-060 and QYV-SVC-061).47@Suite struct UTXOCoinsAuditRegressionTests {48 static let configuration = EndpointConfiguration(49 esplora: ["litecoin": ["https://es.test/api"]],50 blockbook: ["litecoin": ["https://bb.test/api/v2"], "dogecoin": ["https://bb.test/api/v2"]],51 bitcore: ["litecoin": ["https://bc.test/api/LTC/mainnet"], "dogecoin": ["https://bc.test/api/DOGE/mainnet"]],52 ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")53 static let raw = "0100000001" + String(repeating: "11", count: 32) + "00000000015100000000010100000000000000015100000000"54 static let txid = String(repeating: "ab", count: 32)5556 static func status(_ height: String) -> String { #"{"blockbook":{"bestHeight":\#(height),"lastBlockTime":"2026-12-05T05:11:35Z"}}"# }57 static func block(_ height: String) -> String { #"{"hash":"\#(String(repeating: "cd", count: 32))","height":\#(height),"time":"2026-12-05T05:08:10.000Z"}"# }5859 /// QYV-SVC-060. An Esplora endpoint answers a tip height of Int.min (the text is the endpoint's). The survey that60 /// ranks the indexers subtracted every tip from the best one: `best - Int.min` overflowed and trapped the process61 /// at every synchronization. A tip outside 0 ..< 100 000 000 (the bound of the wallet service) is now no answer at all.62 @Test func hostileTipHeightsNeitherTrapNorWinTheSurvey() async throws {63 for hostile in ["-9223372036854775808", "9223372036854775807", "-1", "100000000", "1000000000", "99999999999"] {64 let t = RoutedTransport([65 "es.test/api/blocks/tip/height": hostile,66 "bb.test/api/v2": Self.status("3000000"),67 "bc.test/api/LTC/mainnet/block/tip": Self.block("2999990"),68 ])69 let esplora = EsploraClient(network: .litecoin, configuration: Self.configuration, transport: t)70 await #expect(throws: NetworkError.invalidResponse("tip height")) { try await esplora.tip() }71 let clients = UTXOIndexers.clients(for: .litecoin, configuration: Self.configuration, transport: t)72 #expect(clients.count == 3)73 let survey = await UTXOIndexers.survey(clients)74 #expect(survey.count == 3)75 #expect(survey[0].client.indexerProtocol == .blockbook && survey[0].tip?.height == 3_000_000 && survey[0].lag == 0 && !survey[0].isStale)76 #expect(survey[1].client.indexerProtocol == .bitcore && survey[1].lag == 10 && survey[1].isStale)77 #expect(survey[2].client.indexerProtocol == .esplora && survey[2].tip == nil && survey[2].lag == nil)78 }79 // the same heights from the other protocols were already refused by their clients80 // (a tip of 10^8 or more passes the Blockbook and Bitcore clients, which bound at 10^9, and is left out by the survey)81 for hostile in ["-9223372036854775808", "9223372036854775807", "1000000000", "100000000", "999999999"] {82 let t = RoutedTransport(["es.test/api/blocks/tip/height": "3000000", "bb.test/api/v2": Self.status(hostile), "bc.test/api/LTC/mainnet/block/tip": Self.block(hostile)])83 let survey = await UTXOIndexers.survey(UTXOIndexers.clients(for: .litecoin, configuration: Self.configuration, transport: t))84 #expect(survey[0].client.indexerProtocol == .esplora && survey[0].tip?.height == 3_000_000)85 #expect(survey.dropFirst().allSatisfy { $0.tip == nil && $0.lag == nil && !$0.isStale })86 }87 // an honest Esplora tip is unchanged88 let honest = RoutedTransport(["es.test/api/blocks/tip/height": "3000001\n"])89 #expect(try await EsploraClient(network: .litecoin, configuration: Self.configuration, transport: honest).tip().height == 3_000_001)90 }9192 /// QYV-APP-061. The sources that are current must follow the same chain: the hash of a block under the93 /// confirmation depth is compared. Agreement is counted, a different hash is a refusal, and a source that is94 /// alone (or whose neighbours are stale or silent) is reported as alone.95 @Test func currentIndexersMustAgreeOnAConfirmedBlock() async throws {96 let depth = BitcoinNetwork.litecoin.minimumConfirmationsHint97 let height = 2_999_998 - depth98 let good = String(repeating: "ab", count: 32), other = String(repeating: "cd", count: 32)99 func transport(esplora: String?, blockbook: String?, bitcore: String?, bitcoreTip: String = "2999998") -> RoutedTransport {100 var routes = ["es.test/api/blocks/tip/height": "3000000", "bb.test/api/v2": Self.status("2999999"), "bc.test/api/LTC/mainnet/block/tip": Self.block(bitcoreTip)]101 if let esplora { routes["es.test/api/block-height/\(height)"] = esplora }102 if let blockbook { routes["bb.test/api/v2/block-index/\(height)"] = "{\"blockHash\":\"\(blockbook)\"}" }103 if let bitcore { routes["bc.test/api/LTC/mainnet/block/\(height)"] = "{\"hash\":\"\(bitcore)\",\"height\":\(height),\"time\":\"2026-12-05T05:08:10.000Z\"}" }104 return RoutedTransport(routes)105 }106 func check(_ t: RoutedTransport) async throws -> UTXOIndexers.Corroboration {107 try await UTXOIndexers.corroborate(await UTXOIndexers.survey(UTXOIndexers.clients(for: .litecoin, configuration: Self.configuration, transport: t)))108 }109 // three sources, one chain110 #expect(try await check(transport(esplora: good, blockbook: good, bitcore: good)) == .init(agreeing: 2, height: height))111 // a hash that is not written as the protocol writes it (upper case) is no answer: that source is not counted112 #expect(try await check(transport(esplora: good, blockbook: good.uppercased(), bitcore: good)).agreeing == 1)113 // one of them follows another chain: refused, whichever it is — the best one included114 for (e, b, c) in [(good, other, good), (good, good, other), (other, good, good)] {115 await #expect(throws: NetworkError.self) { try await check(transport(esplora: e, blockbook: b, bitcore: c)) }116 }117 // a source that does not answer the question is not counted; alone, the best one is alone118 #expect(try await check(transport(esplora: good, blockbook: nil, bitcore: good)).agreeing == 1)119 #expect(try await check(transport(esplora: good, blockbook: nil, bitcore: nil)).agreeing == 0)120 #expect(try await check(transport(esplora: nil, blockbook: good, bitcore: good)).agreeing == 0)121 // a stale source is not asked (it trails by more than the depth) and does not count122 let stale = transport(esplora: good, blockbook: good, bitcore: other, bitcoreTip: "2990000")123 stale.set("bb.test/api/v2/block-index/\(2_999_999 - depth)", "{\"blockHash\":\"\(good)\"}")124 stale.set("es.test/api/block-height/\(2_999_999 - depth)", good)125 #expect(try await check(stale) == .init(agreeing: 1, height: 2_999_999 - depth))126 // a single configured source, and an empty survey127 let single = EndpointConfiguration(esplora: ["litecoin": ["https://es.test/api"]], ethereumRPC: [:], ethereumIndexer: [:], priceAPI: "")128 let alone = await UTXOIndexers.survey(UTXOIndexers.clients(for: .litecoin, configuration: single, transport: transport(esplora: good, blockbook: nil, bitcore: nil)))129 #expect(try await UTXOIndexers.corroborate(alone).agreeing == 0)130 #expect(try await UTXOIndexers.corroborate([]).agreeing == 0)131 }132133 /// QYV-SVC-061. A refused broadcast was reported as a success ("the node already knows it") when the refusal134 /// merely contained "known" ("unknown error") or was a conflict with another transaction of the mempool135 /// (`txn-mempool-conflict`). Only the messages that say the node holds this very transaction count now.136 @Test func aRefusedBroadcastIsNeverReportedAsAlreadyKnown() async throws {137 let refusals = [138 "-26: txn-mempool-conflict", "unknown error", "-25: bad-txns-inputs-missingorspent", "Unknown transaction version",139 "-26: 66: min relay fee not met", "-26: dust", "-22: TX decode failed", "non-mandatory-script-verify-flag (Signature must use SIGHASH_FORKID)",140 "sendrawtransaction RPC error: {\"code\":-26,\"message\":\"txn-mempool-conflict\"}", "insufficient priority", "",141 ]142 let acknowledgements = [143 "-27: transaction already in block chain", "-27: Transaction already in block chain", "-26: txn-already-in-mempool", "-26: 18: txn-already-known",144 "sendrawtransaction RPC error: {\"code\":-27,\"message\":\"Transaction outputs already in utxo set\"}", "Transaction already exists", "already known",145 ]146 for text in refusals { #expect(!UTXOWire.saysAlreadyKnown(text), "\(text)") }147 for text in acknowledgements { #expect(UTXOWire.saysAlreadyKnown(text), "\(text)") }148149 func outcome(_ client: any UTXOIndexer) async -> String? {150 do { return try await client.broadcast(rawHex: Self.raw) } catch NetworkError.allEndpointsFailed { return nil } catch { return "unexpected error \(error)" }151 }152 for text in refusals + acknowledgements {153 let expected: String? = acknowledgements.contains(text) ? "" : nil154 let json = String(decoding: try JSONEncoder().encode(["error": text]), as: UTF8.self)155 // Blockbook (JSON error), Bitcore (plain text, HTTP 500), Esplora (plain text, HTTP 400)156 let t = RoutedTransport()157 t.set("bb.test/api/v2/sendtx/", status: 400, json)158 t.set("bc.test/api/DOGE/mainnet/tx/send", status: 500, text)159 t.set("es.test/api/tx", status: 400, text)160 #expect(await outcome(BlockbookClient(network: .dogecoin, configuration: Self.configuration, transport: t)) == expected, "Blockbook: \(text)")161 #expect(await outcome(BitcoreClient(network: .dogecoin, configuration: Self.configuration, transport: t)) == expected, "Bitcore: \(text)")162 #expect(await outcome(EsploraClient(network: .litecoin, configuration: Self.configuration, transport: t)) == expected, "Esplora: \(text)")163 }164 // an accepted broadcast still returns the identifier the endpoint gives165 let ok = RoutedTransport(["bb.test/api/v2/sendtx/": #"{"result":"\#(Self.txid)"}"#, "es.test/api/tx": Self.txid])166 #expect(await outcome(BlockbookClient(network: .dogecoin, configuration: Self.configuration, transport: ok)) == Self.txid)167 #expect(await outcome(EsploraClient(network: .litecoin, configuration: Self.configuration, transport: ok)) == Self.txid)168 }169}170