Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraTronTests/ClientTests.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 QyvoraMath43import QyvoraSymmetric44import Testing45import QyvoraCore46import QyvoraNetworking47@testable import QyvoraTron4849/// A scripted transport: answers by URL path (and host when given), and records what was asked.50final class ScriptedTransport: HTTPTransport, @unchecked Sendable {51 struct Answer {52 var status = 20053 var body: Data54 var headers: [String: String] = [:]55 }5657 private let lock = NSLock()58 private var answers = [String: [Answer]]()59 private var fallback: Answer?60 private(set) var requests = [URLRequest]()6162 /// Answers for a key "path" or "host path"; several answers are served in order, the last one repeating.63 func on(_ key: String, _ body: String, status: Int = 200, headers: [String: String] = [:]) {64 lock.withLock { answers[key, default: []].append(Answer(status: status, body: Data(body.utf8), headers: headers)) }65 }6667 func otherwise(_ body: Data, status: Int = 200) {68 lock.withLock { fallback = Answer(status: status, body: body) }69 }7071 var recorded: [URLRequest] { lock.withLock { requests } }7273 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {74 guard let url = request.url else { throw NetworkError.invalidURL }75 let answer: Answer? = lock.withLock {76 requests.append(request)77 for key in ["\(url.host ?? "") \(url.path)", url.path] {78 if var list = answers[key], let first = list.first {79 if list.count > 1 {80 list.removeFirst()81 answers[key] = list82 }83 return first84 }85 }86 return fallback87 }88 guard let answer else { throw URLError(.cannotConnectToHost) }89 guard let response = HTTPURLResponse(url: url, statusCode: answer.status, httpVersion: nil, headerFields: answer.headers) else { throw NetworkError.invalidURL }90 return (answer.body, response)91 }92}9394/// Answers below are the shapes read from the Nile test network on 2026-12-05 (trimmed of members the client ignores).95@Suite struct TronClientTests {96 static let endpoints = TronEndpoints(fullNodes: ["nile": ["https://node-a.example", "https://node-b.example"]], history: ["nile": ["https://index.example"]])97 let a = TronAddress("TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs")!98 let usdt = TronAddress("TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf")!99100 func client(_ t: ScriptedTransport, network: TronNetwork = .nile, endpoints: TronEndpoints = TronClientTests.endpoints, apiKey: TronAPIKey? = nil,101 pacing: TronPacing = .unthrottled) -> TronClient {102 TronClient(network: network, endpoints: endpoints, transport: t, apiKey: apiKey, pacing: pacing)103 }104105 func failure(_ body: () async throws -> Void) async -> NetworkError? {106 do {107 try await body()108 return nil109 } catch {110 return error as? NetworkError ?? .invalidResponse("not a NetworkError: \(error)")111 }112 }113114 static let genesis = #"{"blockID":"0000000000000000d698d4192c56cb6be724a558448e2684802de4d6cd8690dc","block_header":{"raw_data":{"txTrieRoot":"6556a96828248d6b89cfd0487d4cef82b134b5544dc428c8a218beb2db85ab24","parentHash":"e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f","witness_address":"41206e65"}},"transactions":[]}"#115 static let head = #"{"blockID":"00000000045e795daa66025ed5d34821c5dfbc2af3333c1b117c4d8b24fc3b4b","block_header":{"raw_data":{"timestamp":1796447373000,"txTrieRoot":"c6f5668b4f2441d5704f42359a62b078559d4db270f4203c2c4ef34112bfe856","parentHash":"00000000045e795cdb9e16f864a63f146e196db45919f32321547dec8e8f6a77","number":73300317,"witness_address":"414bbb38ac8f2c666f56c16e0b21ccda04d18b6b6b","version":40},"witness_signature":"b442"}}"#116117 // MARK: Chain identity and blocks118119 @Test func chainIdentity() async throws {120 let t = ScriptedTransport()121 t.on("/wallet/getblockbynum", Self.genesis)122 try await client(t).verifyChain()123 #expect(t.recorded.count == 2) // every node is asked124 #expect(String(decoding: t.recorded[0].httpBody ?? Data(), as: UTF8.self) == #"{"num":0}"#)125 #expect(t.recorded[0].httpMethod == "POST" && t.recorded[0].url?.absoluteString == "https://node-a.example/wallet/getblockbynum")126 // the same endpoints presented as mainnet: another chain127 let wrong = await failure { try await client(t, network: .mainnet, endpoints: TronEndpoints(fullNodes: ["mainnet": ["https://node-a.example"]], history: [:])).verifyChain() }128 guard case .disagreement(let text)? = wrong else {129 Issue.record("expected a disagreement, got \(String(describing: wrong))")130 return131 }132 #expect(text.contains("node-a.example") && text.contains("another chain"))133 // one node down, the other right: accepted; one right and one wrong: refused whatever the order134 let mixed = ScriptedTransport()135 mixed.on("node-b.example /wallet/getblockbynum", Self.genesis)136 try await client(mixed).verifyChain()137 let split = ScriptedTransport()138 split.on("node-a.example /wallet/getblockbynum", Self.genesis)139 split.on("node-b.example /wallet/getblockbynum", Self.genesis.replacingOccurrences(of: "d698d419", with: "1ebf8850"))140 guard case .disagreement? = await failure({ try await client(split).verifyChain() }) else {141 Issue.record("a node on another chain must be a disagreement")142 return143 }144 // nobody answers, nothing configured, a block that is not block 0145 guard case .allEndpointsFailed(let list)? = await failure({ try await client(ScriptedTransport()).verifyChain() }) else {146 Issue.record("expected allEndpointsFailed")147 return148 }149 #expect(list.count == 2 && list[0].hasPrefix("node-a.example: "))150 #expect(await failure { try await client(t, network: .shasta).verifyChain() } == .allEndpointsFailed(["no endpoint configured"]))151 let notGenesis = ScriptedTransport()152 notGenesis.on("/wallet/getblockbynum", Self.head)153 guard case .disagreement? = await failure({ try await client(notGenesis).verifyChain() }) else {154 Issue.record("a block other than block 0 must not verify")155 return156 }157 }158159 @Test func blocks() async throws {160 let t = ScriptedTransport()161 t.on("/wallet/getblock", Self.head)162 t.on("/walletsolidity/getblock", Self.head.replacingOccurrences(of: "5daa66025e", with: "5daa66025f"))163 let c = client(t)164 let head = try await c.latestBlock()165 #expect(head.number == 73_300_317 && head.timestamp == 1_796_447_373_000)166 #expect(Hex.encode(head.refBlockBytes) == "795d" && Hex.encode(head.refBlockHash) == "aa66025ed5d34821")167 #expect(String(decoding: t.recorded[0].httpBody ?? Data(), as: UTF8.self) == #"{"detail":false}"#)168 #expect(try await c.latestSolidBlock().idHex.hasPrefix("00000000045e795daa66025f"))169 // an id that does not start with the announced number, a short id, a non-numeric number170 for bad in [Self.head.replacingOccurrences(of: "73300317", with: "73300318"), Self.head.replacingOccurrences(of: "00000000045e795d", with: "045e795d"),171 Self.head.replacingOccurrences(of: "73300317", with: "\"x\""), Self.head.replacingOccurrences(of: "73300317", with: "7.33e7"), "{}", "[]", "null"] {172 let b = ScriptedTransport()173 b.on("/wallet/getblock", bad)174 guard case .allEndpointsFailed? = await failure({ _ = try await client(b).latestBlock() }) else {175 Issue.record("accepted \(bad.prefix(60))")176 continue177 }178 }179 }180181 // MARK: Accounts182183 @Test func accounts() async throws {184 let t = ScriptedTransport()185 t.on("/wallet/getaccount", #"{"address": "4166426c7ac3d98b29191063833345b6bc540d7278","balance": 4146792736,"create_time": 1625714463000,"net_window_size": 28800000,"account_resource": {"energy_window_size": 28800000}}"#)186 let account = try await client(t).account(a)187 #expect(account == TronAccount(address: a, isActivated: true, balanceSun: 4_146_792_736, isContract: false))188 #expect(String(decoding: t.recorded[0].httpBody ?? Data(), as: UTF8.self) == #"{"address":"4166426c7ac3d98b29191063833345b6bc540d7278"}"#)189190 // never seen by the chain191 let empty = ScriptedTransport()192 empty.on("/wallet/getaccount", "{}")193 #expect(try await client(empty).account(a) == TronAccount(address: a, isActivated: false, balanceSun: 0, isContract: false))194 // a contract; the visible form of the address is understood too; no balance member = 0195 let contract = ScriptedTransport()196 contract.on("/wallet/getaccount", #"{"account_name": "TetherToken","type": "Contract","address": "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf"}"#)197 #expect(try await client(contract).account(usdt) == TronAccount(address: usdt, isActivated: true, balanceSun: 0, isContract: true))198 // balances beyond 2^53 are exact199 let big = ScriptedTransport()200 big.on("/wallet/getaccount", #"{"address":"4166426c7ac3d98b29191063833345b6bc540d7278","balance":9007199254740993}"#)201 #expect(try await client(big).account(a).balanceSun == 9_007_199_254_740_993)202 // another account than the one asked, a negative, fractional or oversized balance203 for bad in [#"{"address":"41eca9bc828a3005b9a3b909f2cc5c2a54794de05f","balance":5}"#, #"{"address":"4166426c7ac3d98b29191063833345b6bc540d7278","balance":-5}"#,204 #"{"address":"4166426c7ac3d98b29191063833345b6bc540d7278","balance":1.5}"#, #"{"address":"4166426c7ac3d98b29191063833345b6bc540d7278","balance":9223372036854775808}"#,205 #"{"address":"4166426c7ac3d98b29191063833345b6bc540d7278","balance":1e30}"#, #"{"address":41}"#, "[]", "7", ""] {206 let b = ScriptedTransport()207 b.on("/wallet/getaccount", bad)208 guard case .allEndpointsFailed? = await failure({ _ = try await client(b).account(a) }) else {209 Issue.record("accepted \(bad)")210 continue211 }212 }213 // an error reported by the node is an answer: it is not retried on the next node214 let refused = ScriptedTransport()215 refused.on("/wallet/getaccount", #"{"Error":"class org.tron.core.services.http.JsonFormat$ParseException : 1:12: INVALID hex String"}"#)216 guard case .rpc(_, let message)? = await failure({ _ = try await client(refused).account(a) }) else {217 Issue.record("expected the node error")218 return219 }220 #expect(message.contains("INVALID hex String") && refused.recorded.count == 1)221 }222223 @Test func resources() async throws {224 let t = ScriptedTransport()225 t.on("/wallet/getaccountresource", #"{"freeNetLimit": 600,"freeNetUsed": 345,"NetLimit": 5000,"NetUsed": 5200,"assetNetUsed": [{"key": "1000016","value": 0}],"TotalNetLimit": 43200000000,"TotalNetWeight": 68475282221,"EnergyLimit": 416789,"EnergyUsed": 16789,"TotalEnergyLimit": 180000000000,"TotalEnergyWeight": 2453572445}"#)226 let r = try await client(t).resources(a)227 #expect(r == TronResources(freeNetLimit: 600, freeNetUsed: 345, netLimit: 5000, netUsed: 5200, energyLimit: 416_789, energyUsed: 16_789))228 #expect(r.freeBandwidth == 255 && r.stakedBandwidth == 0 && r.energy == 400_000)229 let empty = ScriptedTransport()230 empty.on("/wallet/getaccountresource", "{}")231 #expect(try await client(empty).resources(a) == .none)232 let bad = ScriptedTransport()233 bad.on("/wallet/getaccountresource", #"{"freeNetLimit": "many"}"#)234 guard case .allEndpointsFailed? = await failure({ _ = try await client(bad).resources(a) }) else {235 Issue.record("accepted a non-numeric limit")236 return237 }238 }239240 static let parameters = #"{"chainParameter": [{"key": "getMaintenanceTimeInterval","value": 1800000},{"key": "getCreateAccountFee","value": 100000},{"key": "getTransactionFee","value": 1000},{"key": "getCreateNewAccountFeeInSystemContract","value": 1000000},{"key": "getCreateNewAccountBandwidthRate","value": 1},{"key": "getRemoveThePowerOfTheGr","value": -1},{"key": "getEnergyFee","value": 100},{"key": "getAllowUpdateAccountName"},{"key": "getMaxFeeLimit","value": 15000000000},{"key": "getFreeNetLimit","value": 600},{"key": "getMemoFee","value": 1000000}]}"#241242 @Test func chainParameters() async throws {243 let t = ScriptedTransport()244 t.on("/wallet/getchainparameters", Self.parameters)245 #expect(try await client(t).chainParameters() == TronSendPlannerTests.parameters)246 // no memo fee on the chain: 0247 let noMemo = ScriptedTransport()248 noMemo.on("/wallet/getchainparameters", Self.parameters.replacingOccurrences(of: #",{"key": "getMemoFee","value": 1000000}"#, with: ""))249 #expect(try await client(noMemo).chainParameters().memoFeeSun == 0)250 // a price that is missing, zero, negative or not a number is refused: no default is ever substituted251 for bad in [Self.parameters.replacingOccurrences(of: #"{"key": "getEnergyFee","value": 100},"#, with: ""),252 Self.parameters.replacingOccurrences(of: #""getEnergyFee","value": 100"#, with: #""getEnergyFee","value": 0"#),253 Self.parameters.replacingOccurrences(of: #""getTransactionFee","value": 1000"#, with: #""getTransactionFee","value": -1000"#),254 Self.parameters.replacingOccurrences(of: #""getMaxFeeLimit","value": 15000000000"#, with: #""getMaxFeeLimit","value": 1.5e10"#),255 Self.parameters.replacingOccurrences(of: #""getCreateAccountFee","value": 100000"#, with: #""getCreateAccountFee","value": 18446744073709551615"#),256 #"{"chainParameter": {}}"#, "{}"] {257 let b = ScriptedTransport()258 b.on("/wallet/getchainparameters", bad)259 guard case .allEndpointsFailed? = await failure({ _ = try await client(b).chainParameters() }) else {260 Issue.record("accepted \(bad.prefix(80))")261 continue262 }263 }264 }265266 // MARK: Contracts267268 static func constant(_ result: String, energy: Int, extra: String = "", resultObject: String = #"{"result":true}"#) -> String {269 #"{"transaction":{"raw_data":{"ref_block_bytes":"794c"},"ret":[{\#(extra)}],"txID":"c62c"},"constant_result":["\#(result)"],"result":\#(resultObject),"energy_used":\#(energy)}"#270 }271272 @Test func constantCalls() async throws {273 let word6 = String(repeating: "0", count: 63) + "6"274 let t = ScriptedTransport()275 t.on("/wallet/triggerconstantcontract", Self.constant(word6, energy: 508))276 let c = client(t)277 #expect(try await c.tokenDecimals(usdt) == 6)278 #expect(String(decoding: t.recorded[0].httpBody ?? Data(), as: UTF8.self)279 == #"{"contract_address":"41eca9bc828a3005b9a3b909f2cc5c2a54794de05f","data":"313ce567","owner_address":"410000000000000000000000000000000000000000"}"#)280281 let symbol = ScriptedTransport()282 symbol.on("/wallet/triggerconstantcontract", Self.constant("000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000045553445400000000000000000000000000000000000000000000000000000000", energy: 1364))283 #expect(try await client(symbol).tokenSymbol(usdt) == "USDT")284285 let balance = ScriptedTransport()286 balance.on("/wallet/triggerconstantcontract", Self.constant("0000000000000000000000000000000000000000000000000000000078d5523f", energy: 935))287 #expect(try await client(balance).tokenBalance(token: usdt, owner: a) == UInt256(2_027_246_143))288 #expect(String(decoding: balance.recorded[0].httpBody ?? Data(), as: UTF8.self).contains(#""data":"70a0823100000000000000000000000066426c7ac3d98b29191063833345b6bc540d7278""#))289290 // a transfer simulation: the call returns false (as USDT does) and still succeeded; the energy is the estimate291 let transfer = ScriptedTransport()292 transfer.on("/wallet/triggerconstantcontract", Self.constant(String(repeating: "0", count: 64), energy: 29650))293 let to = TronAddress(TronVectors.keys[0].address)!294 let sim = try await client(transfer).simulateTokenTransfer(token: usdt, from: a, to: to, amount: UInt256(1))295 #expect(sim == TronConstantResult(succeeded: true, message: "", output: Bytes(repeating: 0, count: 32), energyUsed: 29_650))296 #expect(String(decoding: transfer.recorded[0].httpBody ?? Data(), as: UTF8.self).contains(297 #""data":"a9059cbb000000000000000000000000068d6c866dbbfadce6510642bec051a9cabeaf820000000000000000000000000000000000000000000000000000000000000001""#))298299 // a revert is a result, not an error300 let revert = ScriptedTransport()301 revert.on("/wallet/triggerconstantcontract", Self.constant("", energy: 1984, extra: #""ret":"FAILED""#, resultObject: #"{"result":true,"message":"REVERT opcode executed"}"#))302 let reverted = try await client(revert).simulateTokenTransfer(token: usdt, from: to, to: a, amount: UInt256(1_000_000))303 #expect(reverted == TronConstantResult(succeeded: false, message: "REVERT opcode executed", output: [], energyUsed: 1984))304 // …and a metadata read that reverts is refused305 guard case .invalidResponse? = await failure({ _ = try await client(revert).tokenDecimals(usdt) }) else {306 Issue.record("a reverted read must fail")307 return308 }309 // no contract at the address: the node refuses to run the call310 let none = ScriptedTransport()311 none.on("/wallet/triggerconstantcontract", #"{"result":{"code":"CONTRACT_VALIDATE_ERROR","message":"Smart contract is not exist."}}"#)312 #expect(await failure { _ = try await client(none).tokenDecimals(a) } == .rpc(code: 0, message: "CONTRACT_VALIDATE_ERROR: Smart contract is not exist."))313 // decimals beyond 77, a result that is not hexadecimal, an energy that is not an integer314 for bad in [Self.constant(String(repeating: "0", count: 62) + "4e", energy: 1), Self.constant("zz", energy: 1), Self.constant(word6, energy: -4),315 #"{"constant_result":["06"],"result":{"result":true},"energy_used":5}"#, #"{"result":true}"#] {316 let b = ScriptedTransport()317 b.on("/wallet/triggerconstantcontract", bad)318 #expect(await failure { _ = try await client(b).tokenDecimals(usdt) } != nil, "accepted \(bad.prefix(60))")319 }320 }321322 @Test func tokenVerification() async throws {323 let usdtMain = TronBuiltInTokens.mainnet[0]324 let endpoints = TronEndpoints(fullNodes: ["mainnet": ["https://node-a.example"]], history: [:])325 func transport(type: String, decimals: String, symbol: String) -> ScriptedTransport {326 let t = ScriptedTransport()327 t.on("/wallet/getaccount", #"{"type":"\#(type)","address":"41a614f803b6fd780986a42c78ec9c7f77e6ded13c","balance":1}"#)328 t.on("/wallet/triggerconstantcontract", Self.constant(String(repeating: "0", count: 63) + decimals, energy: 2207))329 let s = Bytes(symbol.utf8)330 t.on("/wallet/triggerconstantcontract", Self.constant(String(repeating: "0", count: 62) + "20" + String(repeating: "0", count: 62) + Hex.encode([UInt8(s.count)])331 + Hex.encode(s + Bytes(repeating: 0, count: 32 - s.count)), energy: 5922))332 return t333 }334 #expect(try await client(transport(type: "Contract", decimals: "6", symbol: "USDT"), network: .mainnet, endpoints: endpoints).verify(token: usdtMain))335 #expect(try await client(transport(type: "Contract", decimals: "8", symbol: "USDT"), network: .mainnet, endpoints: endpoints).verify(token: usdtMain) == false)336 #expect(try await client(transport(type: "Contract", decimals: "6", symbol: "USDt"), network: .mainnet, endpoints: endpoints).verify(token: usdtMain) == false)337 #expect(try await client(transport(type: "Normal", decimals: "6", symbol: "USDT"), network: .mainnet, endpoints: endpoints).verify(token: usdtMain) == false)338 // a token of another network is never verified by this client339 #expect(try await client(transport(type: "Contract", decimals: "6", symbol: "USDT")).verify(token: usdtMain) == false)340 }341342 // MARK: Broadcast343344 func signedSample() throws -> SignedTronTransaction {345 try build(TronVectors.transactions[1]).sign(privateKey: hex(TronVectors.derivation[0].privateKey))346 }347348 @Test func broadcast() async throws {349 let signed = try signedSample()350 let ok = ScriptedTransport()351 ok.on("/wallet/broadcasthex", #"{"result":true,"code":"SUCCESS","txid":"\#(signed.txIDHex)","message":"","transaction":"{}"}"#)352 #expect(try await client(ok).broadcast(signed) == .accepted(txID: signed.txIDHex))353 #expect(ok.recorded.count == 1)354 #expect(String(decoding: ok.recorded[0].httpBody ?? Data(), as: UTF8.self) == #"{"transaction":"\#(signed.hex)"}"#)355356 let dup = ScriptedTransport()357 dup.on("/wallet/broadcasthex", #"{"code":"DUP_TRANSACTION_ERROR","txid":"\#(signed.txIDHex)","message":"447570207472616e73616374696f6e2e"}"#)358 #expect(try await client(dup).broadcast(signed) == .alreadyKnown(txID: signed.txIDHex))359360 // refused by every node: the first refusal, its message decoded from hexadecimal361 let refused = ScriptedTransport()362 refused.on("/wallet/broadcasthex", #"{"code":"TRANSACTION_EXPIRATION_ERROR","txid":"\#(signed.txIDHex)","message":"5472616e73616374696f6e2065787069726564"}"#)363 #expect(try await client(refused).broadcast(signed) == .rejected(code: "TRANSACTION_EXPIRATION_ERROR", message: "Transaction expired"))364 #expect(refused.recorded.count == 2)365366 // the first node refuses (it lags), the second accepts367 let second = ScriptedTransport()368 second.on("node-a.example /wallet/broadcasthex", #"{"code":"TAPOS_ERROR","message":"Tapos failed"}"#)369 second.on("node-b.example /wallet/broadcasthex", #"{"result":true,"txid":"\#(signed.txIDHex)"}"#)370 #expect(try await client(second).broadcast(signed) == .accepted(txID: signed.txIDHex))371372 // a node that answers for another transaction id is not believed373 let lying = ScriptedTransport()374 lying.on("/wallet/broadcasthex", #"{"result":true,"txid":"\#(String(repeating: "ab", count: 32))"}"#)375 guard case .allEndpointsFailed? = await failure({ _ = try await client(lying).broadcast(signed) }) else {376 Issue.record("accepted another transaction id")377 return378 }379 // no signature: nothing is sent380 let silent = ScriptedTransport()381 let unsigned = try #require(SignedTronTransaction(transaction: signed.transaction, signatures: []))382 guard case .rejected(let code, _) = try await client(silent).broadcast(unsigned) else {383 Issue.record("an unsigned transaction must be refused")384 return385 }386 #expect(code == "UNSIGNED" && silent.recorded.isEmpty)387 // nobody answers388 guard case .allEndpointsFailed? = await failure({ _ = try await client(ScriptedTransport()).broadcast(signed) }) else {389 Issue.record("expected allEndpointsFailed")390 return391 }392 }393394 // MARK: Status395396 static let info = #"{"id": "fe6bdc97a3934657d79edb5839ae7db9dcadce572186c2aee61d0ade882e64d8","fee": 346000,"blockNumber": 73300315,"blockTimeStamp": 1796447367000,"contractResult": ["0000000000000000000000000000000000000000000000000000000000000000"],"contract_address": "41eca9bc828a3005b9a3b909f2cc5c2a54794de05f","receipt": {"origin_energy_usage": 29650,"energy_usage_total": 29650,"net_fee": 346000,"result": "SUCCESS"},"log": []}"#397 static let byID = #"{"raw_data":{"fee_limit":1000000000},"signature":["\#(NileSamples.tokenSignature)"],"ret":[{"contractRet":"SUCCESS"}],"raw_data_hex":"\#(NileSamples.tokenRaw)","txID":"\#(NileSamples.tokenTxID)"}"#398399 @Test func transactionStatus() async throws {400 let t = ScriptedTransport()401 t.on("/wallet/gettransactioninfobyid", Self.info)402 t.on("/wallet/gettransactionbyid", Self.byID)403 let s = try await client(t).transactionStatus(id: NileSamples.tokenTxID)404 #expect(s.state == .succeeded && !s.irreversible && s.blockNumber == 73_300_315 && s.blockTimestamp == 1_796_447_367_000)405 #expect(s.feeSun == 346_000 && s.netFeeSun == 346_000 && s.energyUsed == 29_650 && s.energyFeeSun == 0)406 #expect(s.contractResult == "SUCCESS" && s.receiptResult == "SUCCESS" && s.message == nil)407 #expect(s.transaction?.txIDHex == NileSamples.tokenTxID)408 #expect(String(decoding: t.recorded[0].httpBody ?? Data(), as: UTF8.self) == #"{"value":"\#(NileSamples.tokenTxID)"}"#)409410 // irreversible state is asked on the solidity API411 let solid = ScriptedTransport()412 solid.on("/walletsolidity/gettransactioninfobyid", Self.info)413 solid.on("/walletsolidity/gettransactionbyid", Self.byID)414 #expect(try await client(solid).transactionStatus(id: NileSamples.tokenTxID, irreversibleOnly: true).irreversible)415416 // a failed token transfer: the receipt says so even though the transaction is in a block (the fee is gone)417 let failed = ScriptedTransport()418 failed.on("/wallet/gettransactioninfobyid", Self.info.replacingOccurrences(of: #""result": "SUCCESS""#, with: #""result": "OUT_OF_ENERGY""#)419 .replacingOccurrences(of: #""log": []"#, with: #""result": "FAILED","resMessage": "4e6f7420656e6f75676820656e65726779""#))420 failed.on("/wallet/gettransactionbyid", Self.byID.replacingOccurrences(of: #""contractRet":"SUCCESS""#, with: #""contractRet":"OUT_OF_ENERGY""#))421 let f = try await client(failed).transactionStatus(id: NileSamples.tokenTxID)422 #expect(f.state == .failed && f.receiptResult == "OUT_OF_ENERGY" && f.contractResult == "OUT_OF_ENERGY" && f.message == "Not enough energy" && f.feeSun == 346_000)423 // each indicator alone is enough to report a failure424 for (infoBody, txBody) in [(Self.info.replacingOccurrences(of: #""result": "SUCCESS""#, with: #""result": "REVERT""#), Self.byID),425 (Self.info, Self.byID.replacingOccurrences(of: #""contractRet":"SUCCESS""#, with: #""contractRet":"REVERT""#)),426 (Self.info.replacingOccurrences(of: #""log": []"#, with: #""result": "FAILED""#), Self.byID)] {427 let b = ScriptedTransport()428 b.on("/wallet/gettransactioninfobyid", infoBody)429 b.on("/wallet/gettransactionbyid", txBody)430 #expect(try await client(b).transactionStatus(id: NileSamples.tokenTxID).state == .failed)431 }432433 // unknown to the node; known but without an execution record yet434 let unknown = ScriptedTransport()435 unknown.on("/wallet/gettransactioninfobyid", "{}")436 unknown.on("/wallet/gettransactionbyid", "{}")437 let u = try await client(unknown).transactionStatus(id: NileSamples.tokenTxID)438 #expect(u.state == .notFound && u.transaction == nil && u.blockNumber == nil)439 let pending = ScriptedTransport()440 pending.on("/wallet/gettransactioninfobyid", "{}")441 pending.on("/wallet/gettransactionbyid", Self.byID)442 #expect(try await client(pending).transactionStatus(id: NileSamples.tokenTxID).state == .pending)443 // a record for another id is not this transaction444 let other = ScriptedTransport()445 other.on("/wallet/gettransactioninfobyid", Self.info.replacingOccurrences(of: "fe6bdc97", with: "00000000"))446 other.on("/wallet/gettransactionbyid", "{}")447 #expect(try await client(other).transactionStatus(id: NileSamples.tokenTxID).state == .notFound)448 // bytes that do not hash to the id449 let forged = ScriptedTransport()450 forged.on("/wallet/gettransactioninfobyid", Self.info)451 forged.on("/wallet/gettransactionbyid", Self.byID.replacingOccurrences(of: "3b9aca00", with: "3b9aca01"))452 guard case .invalidResponse? = await failure({ _ = try await client(forged).transactionStatus(id: NileSamples.tokenTxID) }) else {453 Issue.record("accepted bytes that do not hash to the id")454 return455 }456 // malformed ids never reach the network457 let silent = ScriptedTransport()458 for bad in ["", "fe6b", NileSamples.tokenTxID.uppercased(), NileSamples.tokenTxID + "00", String(repeating: "g", count: 64), "../" + String(NileSamples.tokenTxID.dropFirst(3))] {459 #expect(await failure { _ = try await client(silent).transactionStatus(id: bad) } == .invalidURL)460 }461 #expect(silent.recorded.isEmpty)462 }463464 // MARK: History465466 static let secondRaw = "0a023be322082b16df41468314bb409bc1eff893345a67080112630a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412320a15411fab686441481c0df7970d951fb158df04eed31312154166426c7ac3d98b29191063833345b6bc540d727818ed9e0670bbecebf89334"467 static let secondID = "fbc0b3ab98ba1de47050237cf86427f8d2f1b89041ff4adedd5b14e5ab6ad2fe"468469 static func historyItem(id: String, raw: String, fee: Int = 267000, ret: String = "SUCCESS", extra: String = "") -> String {470 #"{"ret":[{"contractRet":"\#(ret)","fee":\#(fee)}],"signature":["2d3d"],"txID":"\#(id)","net_usage":0,"raw_data_hex":"\#(raw)","net_fee":267000,"energy_usage":0,"blockNumber":71843090,"block_timestamp":1792060953000,"energy_fee":0,"raw_data":{"contract":[{"parameter":{"value":{"amount":103205,"owner_address":"411fab686441481c0df7970d951fb158df04eed313","to_address":"4166426c7ac3d98b29191063833345b6bc540d7278"},"type_url":"type.googleapis.com/protocol.TransferContract"},"type":"TransferContract"}]},"internal_transactions":[]\#(extra)}"#471 }472473 @Test func nativeHistory() async throws {474 let t = ScriptedTransport()475 let items = [Self.historyItem(id: NileSamples.trxTxID, raw: NileSamples.trxRaw),476 Self.historyItem(id: Self.secondID, raw: Self.secondRaw, extra: #","_unconfirmed":true"#),477 // a token call of the account: listed as "other"478 Self.historyItem(id: NileSamples.tokenTxID, raw: NileSamples.tokenRaw, fee: 346000),479 // tampered bytes, a foreign id, a failed transfer480 Self.historyItem(id: NileSamples.trxTxID, raw: NileSamples.trxRaw.replacingOccurrences(of: "a5a606", with: "a5a607")),481 Self.historyItem(id: String(repeating: "0", count: 64), raw: NileSamples.trxRaw),482 Self.historyItem(id: NileSamples.trxTxID, raw: NileSamples.trxRaw, ret: "REVERT"),483 "17", #"{"txID":5}"#, "null"]484 t.on("/v1/accounts/TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs/transactions", #"{"data":[\#(items.joined(separator: ","))],"success":true,"meta":{"at":1796447491175,"fingerprint":"2NgPQPX6egFQe6mpJFEk4FFnK","links":{"next":"https://evil.example/next"},"page_size":2}}"#)485 let page = try await client(t).transactions(of: a, limit: 50, fingerprint: "abcDEF123", confirmedOnly: true)486 #expect(t.recorded[0].httpMethod == "GET" && t.recorded[0].httpBody == nil)487 #expect(t.recorded[0].url?.absoluteString488 == "https://index.example/v1/accounts/TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs/transactions?limit=50&order_by=block_timestamp,desc&only_confirmed=true&fingerprint=abcDEF123")489 #expect(page.nextFingerprint == "2NgPQPX6egFQe6mpJFEk4FFnK")490 #expect(page.items.count == 4)491 let sender = TronAddress(hex: "411fab686441481c0df7970d951fb158df04eed313")!492 #expect(page.items[0] == TronTransfer(kind: .trx, txID: NileSamples.trxTxID, from: sender, to: a, amount: UInt256(103_205), timestamp: 1_792_060_953_000,493 blockNumber: 71_843_090, succeeded: true, confirmed: true, feeSun: 267_000, token: nil, tokenSymbol: nil, tokenDecimals: nil, contractType: nil))494 #expect(page.items[1].txID == Self.secondID && page.items[1].amount == UInt256(102_253) && !page.items[1].confirmed)495 #expect(page.items[2].kind == .other && page.items[2].contractType == "TriggerSmartContract" && page.items[2].to == usdt && page.items[2].feeSun == 346_000)496 #expect(page.items[3].succeeded == false)497 #expect(Set(page.items.map(\.id)).count == 3) // the failed one repeats the id of the first: same transaction498 #expect(page.items[0].date == Date(timeIntervalSince1970: 1_792_060_953))499500 // limits are clamped, a hostile fingerprint never reaches the URL, a page cut to the limit501 let c = client(t)502 _ = try await c.transactions(of: a, limit: 100_000)503 #expect(t.recorded.last?.url?.query == "limit=200&order_by=block_timestamp,desc")504 _ = try await c.transactions(of: a, limit: -3)505 #expect(t.recorded.last?.url?.query == "limit=1&order_by=block_timestamp,desc")506 #expect(try await c.transactions(of: a, limit: 2).items.count == 2)507 let before = t.recorded.count508 for bad in ["a&only_to=true", "a b", "", String(repeating: "a", count: 1025), "é", "a/../b", "a#b"] {509 #expect(await failure { _ = try await c.transactions(of: a, fingerprint: bad) } == .invalidURL)510 }511 #expect(t.recorded.count == before)512513 // an index that reports failure, a page without data, no index configured514 for bad in [#"{"success":false,"error":"x","statusCode":400}"#, #"{"success":true}"#, #"{"success":true,"data":{}}"#, "[]"] {515 let b = ScriptedTransport()516 b.otherwise(Data(bad.utf8))517 guard case .allEndpointsFailed? = await failure({ _ = try await client(b).transactions(of: a) }) else {518 Issue.record("accepted \(bad)")519 continue520 }521 }522 let none = client(t, endpoints: TronEndpoints(fullNodes: [:], history: [:]))523 #expect(!none.hasHistory && !none.isConfigured)524 #expect(await failure { _ = try await none.transactions(of: a) } == .allEndpointsFailed(["no endpoint configured"]))525 // a fingerprint that is not plain text is dropped526 let odd = ScriptedTransport()527 odd.otherwise(Data(#"{"data":[],"success":true,"meta":{"fingerprint":"a&b=c"}}"#.utf8))528 #expect(try await client(odd).transactions(of: a) == TronHistoryPage(items: [], nextFingerprint: nil))529 }530531 @Test func tokenHistory() async throws {532 let t = ScriptedTransport()533 let good = #"{"transaction_id":"0277f4ce0ee7fedebdd087205865358d2f81f5e6413d483cb2febc343c8ea2dc","token_info":{"symbol":"USDT","address":"TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf","decimals":6,"name":"Tether USD"},"block_timestamp":1794675069000,"from":"TPQ4R9qRz8q5LMJJCbsQFrUoHB5mB7GkEb","to":"TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs","type":"Transfer","value":"5000000"}"#534 let items = [good,535 // a value beyond 64 bits is exact; a long symbol is cut; absurd decimals are dropped536 good.replacingOccurrences(of: "\"5000000\"", with: "\"115792089237316195423570985008687907853269984665640564039457584007913129639935\"")537 .replacingOccurrences(of: "\"USDT\"", with: "\"USDTUSDTUSDTUSDTUSDTUSDT\\u0007\"").replacingOccurrences(of: "\"decimals\":6", with: "\"decimals\":300"),538 // an approval, a value that is not a number, one beyond 2^256, a bad address, a bad id539 good.replacingOccurrences(of: "\"Transfer\"", with: "\"Approval\""),540 good.replacingOccurrences(of: "\"5000000\"", with: "\"5e6\""),541 good.replacingOccurrences(of: "\"5000000\"", with: "\"115792089237316195423570985008687907853269984665640564039457584007913129639936\""),542 good.replacingOccurrences(of: "TPQ4R9qRz8q5LMJJCbsQFrUoHB5mB7GkEb", with: "TPQ4R9qRz8q5LMJJCbsQFrUoHB5mB7GkEc"),543 good.replacingOccurrences(of: "0277f4ce", with: "0277F4CE"),544 good.replacingOccurrences(of: "\"value\":\"5000000\"", with: "\"value\":5000000"), "{}"]545 t.on("/v1/accounts/TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs/transactions/trc20", #"{"data":[\#(items.joined(separator: ","))],"success":true,"meta":{"at":1,"page_size":2}}"#)546 let page = try await client(t).tokenTransfers(of: a, token: usdt, limit: 20)547 #expect(t.recorded[0].url?.absoluteString548 == "https://index.example/v1/accounts/TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs/transactions/trc20?limit=20&order_by=block_timestamp,desc&contract_address=TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf")549 #expect(page.nextFingerprint == nil && page.items.count == 2)550 #expect(page.items[0] == TronTransfer(kind: .trc20, txID: "0277f4ce0ee7fedebdd087205865358d2f81f5e6413d483cb2febc343c8ea2dc", from: TronAddress("TPQ4R9qRz8q5LMJJCbsQFrUoHB5mB7GkEb")!, to: a,551 amount: UInt256(5_000_000), timestamp: 1_794_675_069_000, blockNumber: nil, succeeded: true, confirmed: true, feeSun: nil,552 token: usdt, tokenSymbol: "USDT", tokenDecimals: 6, contractType: nil))553 #expect(page.items[1].amount == .max && page.items[1].tokenSymbol == "USDTUSDTUSDTUSDT" && page.items[1].tokenDecimals == nil)554 // entries of another token than the one asked for are dropped even if the index returns them555 let filtered = try await client(t).tokenTransfers(of: a, token: a)556 #expect(filtered.items.isEmpty)557 }558559 // MARK: Politeness, key, limits560561 @Test func apiKey() async throws {562 #expect(TronAPIKey("") == nil && TronAPIKey("short") == nil && TronAPIKey("abc def 12345") == nil && TronAPIKey("abcdefgh\r\nX-Evil: 1") == nil)563 #expect(TronAPIKey(String(repeating: "a", count: 129)) == nil && TronAPIKey("clé-secrète-123") == nil)564 let key = try #require(TronAPIKey("0a1b2c3d-1111-2222-3333-444455556666"))565 // never printed566 #expect("\(key)" == "TronAPIKey(redacted)" && String(reflecting: key) == "TronAPIKey(redacted)")567 var dumped = ""568 dump(key, to: &dumped)569 #expect(!dumped.contains("0a1b2c3d") && !String(describing: [key]).contains("0a1b2c3d"))570571 let t = ScriptedTransport()572 t.on("/wallet/getblock", Self.head)573 t.on("/wallet/getaccount", "{}")574 // TronGrid over https gets the header; another host, plain http or a look-alike host does not575 let endpoints = TronEndpoints(fullNodes: ["nile": ["https://nile.trongrid.io"], "shasta": ["https://node.example"], "mainnet": ["https://trongrid.io.evil.example", "http://192.168.1.9:8090"]],576 history: [:])577 _ = try await client(t, endpoints: endpoints, apiKey: key).latestBlock()578 #expect(t.recorded.last?.value(forHTTPHeaderField: "TRON-PRO-API-KEY") == "0a1b2c3d-1111-2222-3333-444455556666")579 #expect(t.recorded.last?.url?.absoluteString == "https://nile.trongrid.io/wallet/getblock")580 _ = try await client(t, network: .shasta, endpoints: endpoints, apiKey: key).latestBlock()581 #expect(t.recorded.last?.value(forHTTPHeaderField: "TRON-PRO-API-KEY") == nil)582 let look = ScriptedTransport()583 look.on("192.168.1.9 /wallet/getblock", Self.head)584 _ = try await client(look, network: .mainnet, endpoints: endpoints, apiKey: key).latestBlock()585 #expect(look.recorded.count == 2 && look.recorded.allSatisfy { $0.value(forHTTPHeaderField: "TRON-PRO-API-KEY") == nil })586 // without a key no header at all; the key is in no URL and no error587 _ = try await client(t, endpoints: endpoints).latestBlock()588 #expect(t.recorded.last?.value(forHTTPHeaderField: "TRON-PRO-API-KEY") == nil)589 let down = ScriptedTransport()590 down.otherwise(Data("slow down".utf8), status: 403)591 let error = await failure { _ = try await client(down, endpoints: endpoints, apiKey: key).latestBlock() }592 #expect(error != nil && !String(describing: error).contains("0a1b2c3d") && !(error?.summary ?? "").contains("0a1b2c3d"))593 #expect(down.recorded.allSatisfy { $0.url?.absoluteString.contains("0a1b2c3d") == false })594 }595596 @Test func rateLimit() async throws {597 // one 429, then the answer: waited out once598 let t = ScriptedTransport()599 t.on("/wallet/getblock", "", status: 429)600 t.on("/wallet/getblock", Self.head)601 let patient = TronPacing(tronGridIntervalMilliseconds: 0, otherIntervalMilliseconds: 0, rateLimitBackoffMilliseconds: 30, rateLimitRetries: 1)602 let started = ContinuousClock.now603 #expect(try await client(t, pacing: patient).latestBlock().number == 73_300_317)604 #expect(ContinuousClock.now - started >= .milliseconds(30) && t.recorded.count == 2)605 // Retry-After is honoured (here: none to wait)606 let hinted = ScriptedTransport()607 hinted.on("/wallet/getblock", "", status: 429, headers: ["Retry-After": "0"])608 hinted.on("/wallet/getblock", Self.head)609 let slow = TronPacing(tronGridIntervalMilliseconds: 0, otherIntervalMilliseconds: 0, rateLimitBackoffMilliseconds: 20_000, rateLimitRetries: 1)610 let begun = ContinuousClock.now611 _ = try await client(hinted, pacing: slow).latestBlock()612 #expect(ContinuousClock.now - begun < .seconds(5))613 // still limited after the retry: reported as HTTP 429, on every node614 let limited = ScriptedTransport()615 limited.otherwise(Data(), status: 429)616 guard case .allEndpointsFailed(let list)? = await failure({ _ = try await client(limited, pacing: patient).latestBlock() }) else {617 Issue.record("expected the rate limit to be reported")618 return619 }620 #expect(list == ["node-a.example: HTTP 429 (too many requests)", "node-b.example: HTTP 429 (too many requests)"] && limited.recorded.count == 4)621 // no retry configured622 let once = ScriptedTransport()623 once.otherwise(Data(), status: 429)624 _ = await failure { _ = try await client(once).latestBlock() }625 #expect(once.recorded.count == 2)626 #expect(TronPacing(tronGridIntervalMilliseconds: 0, otherIntervalMilliseconds: 0, rateLimitBackoffMilliseconds: 0, rateLimitRetries: 99).rateLimitRetries == 3)627 #expect(TronPacing.default.tronGridIntervalMilliseconds >= 350 && TronPacing.default.rateLimitRetries == 1)628 }629630 @Test func spacing() async throws {631 // three requests to one host with a 60 ms interval take at least 120 ms; another host is not held back632 let t = ScriptedTransport()633 t.on("/wallet/getblock", Self.head)634 let endpoints = TronEndpoints(fullNodes: ["nile": ["https://spacing-test.trongrid.io"], "shasta": ["https://spacing-other.example"]], history: [:])635 let pacing = TronPacing(tronGridIntervalMilliseconds: 60, otherIntervalMilliseconds: 0, rateLimitBackoffMilliseconds: 0, rateLimitRetries: 0)636 let c = client(t, endpoints: endpoints, pacing: pacing)637 let started = ContinuousClock.now638 for _ in 0..<3 { _ = try await c.latestBlock() }639 #expect(ContinuousClock.now - started >= .milliseconds(120))640 let other = client(t, network: .shasta, endpoints: endpoints, pacing: pacing)641 let begun = ContinuousClock.now642 for _ in 0..<3 { _ = try await other.latestBlock() }643 #expect(ContinuousClock.now - begun < .milliseconds(100))644 }645646 /// Whatever a server sends, every call either returns a validated value or throws: nothing traps.647 @Test func hostileResponses() async throws {648 var bodies: [Data] = [649 "", " ", "null", "true", "0", "-1", "1e999", "\"text\"", "[]", "[[[[[[[[[[]]]]]]]]]]", "{}", "{", "}", "{\"a\":}", "{\"a\":1,}", "{\"a\":1,\"a\":2}",650 "{\"blockID\":null}", "{\"blockID\":5,\"block_header\":7}", "{\"blockID\":\"zz\",\"block_header\":{\"raw_data\":{\"number\":-1}}}",651 "{\"block_header\":{\"raw_data\":{\"number\":18446744073709551616,\"timestamp\":1e400}},\"blockID\":\"00\"}",652 "{\"address\":\"\",\"balance\":\"\"}", "{\"address\":[],\"balance\":{}}", "{\"balance\":99999999999999999999999999999999999999}",653 "{\"chainParameter\":[{\"key\":5,\"value\":\"x\"},null,7,{\"key\":\"getEnergyFee\",\"value\":[]}]}", "{\"chainParameter\":null}",654 "{\"result\":{\"result\":true},\"constant_result\":[5],\"energy_used\":\"lots\"}", "{\"result\":{\"result\":\"true\"}}", "{\"result\":[]}",655 "{\"result\":{\"result\":true},\"constant_result\":[],\"transaction\":{\"ret\":\"FAILED\"}}",656 "{\"result\":true,\"txid\":7,\"code\":[],\"message\":{}}", "{\"code\":\"\\u0000\\u001b[31m\",\"message\":\"zz\"}", "{\"Error\":\"\\u0007\\u001b[2J boom\"}", "{\"Error\":5}",657 "{\"id\":7,\"fee\":-1,\"blockNumber\":1.5,\"receipt\":[],\"result\":7}", "{\"txID\":[],\"raw_data_hex\":7,\"ret\":{}}",658 "{\"id\":\"\(NileSamples.tokenTxID)\",\"fee\":\"x\",\"blockNumber\":[],\"receipt\":{\"result\":7,\"energy_usage_total\":-5},\"resMessage\":7}",659 "{\"txID\":\"\(NileSamples.tokenTxID)\",\"raw_data_hex\":\"zz\",\"ret\":[7]}",660 "{\"success\":true,\"data\":[null,1,\"x\",[],{},{\"txID\":\"\(NileSamples.trxTxID)\",\"raw_data_hex\":\"00\"}],\"meta\":7}",661 "{\"success\":true,\"data\":[{\"transaction_id\":7,\"token_info\":[],\"value\":{}}],\"meta\":{\"fingerprint\":7}}", "{\"success\":\"true\",\"data\":[]}",662 ].map { Data($0.utf8) }663 bodies.append(Data([0xff, 0xfe, 0x00, 0x7b]))664 bodies.append(Data("{\"a\":\"\\ud800\"}".utf8))665 bodies.append(Data("{\"a\":\"".utf8) + Data([0xc3, 0x28]) + Data("\"}".utf8))666 bodies.append(Data(String(repeating: "[", count: 5000).utf8))667 bodies.append(Data((String(repeating: "{\"a\":", count: 200) + "1" + String(repeating: "}", count: 200)).utf8))668 bodies.append(Data(("{\"balance\":" + String(repeating: "9", count: 5000) + "}").utf8))669 bodies.append(Data(repeating: 0x20, count: TronClient.maximumResponseBytes + 1))670671 let signed = try signedSample()672 var calls = 0, thrown = 0673 for body in bodies {674 for status in [200, 500] {675 let t = ScriptedTransport()676 t.otherwise(body, status: status)677 let c = client(t)678 func attempt(_ work: () async throws -> Void) async {679 calls += 1680 do { try await work() } catch { thrown += 1 }681 }682 await attempt { try await c.verifyChain() }683 await attempt { _ = try await c.latestBlock() }684 await attempt { _ = try await c.latestSolidBlock() }685 await attempt { _ = try await c.account(a) }686 await attempt { _ = try await c.resources(a) }687 await attempt { _ = try await c.chainParameters() }688 await attempt { _ = try await c.constantCall(owner: a, contract: usdt, data: [1, 2, 3, 4]) }689 await attempt { _ = try await c.tokenBalance(token: usdt, owner: a) }690 await attempt { _ = try await c.tokenDecimals(usdt) }691 await attempt { _ = try await c.tokenSymbol(usdt) }692 await attempt { _ = try await c.tokenName(usdt) }693 await attempt { _ = try await c.simulateTokenTransfer(token: usdt, from: a, to: usdt, amount: UInt256(1)) }694 await attempt { _ = try await c.nodeBuiltTransfer(from: a, to: usdt, amountSun: 1) }695 await attempt { _ = try await c.broadcast(signed) }696 await attempt { _ = try await c.transactionStatus(id: NileSamples.tokenTxID) }697 await attempt { _ = try await c.transactions(of: a) }698 await attempt { _ = try await c.tokenTransfers(of: a) }699 }700 }701 #expect(calls == bodies.count * 2 * 17)702 // a few of these bodies are acceptable answers to some calls ("{}" is an unactivated account); most are not703 #expect(thrown > calls * 3 / 4)704 // an oversized answer is refused as such705 let big = ScriptedTransport()706 big.otherwise(Data(repeating: 0x20, count: TronClient.maximumResponseBytes + 1))707 guard case .allEndpointsFailed(let list)? = await failure({ _ = try await client(big).account(a) }) else {708 Issue.record("accepted an oversized answer")709 return710 }711 #expect(list[0].contains("larger than"))712 // text from a server is cleaned before it can reach a screen or a log713 let noisy = ScriptedTransport()714 noisy.otherwise(Data("{\"Error\":\"\\u0007\\u001b[2J boom \(String(repeating: "x", count: 500))\"}".utf8))715 guard case .rpc(_, let message)? = await failure({ _ = try await client(noisy).account(a) }) else {716 Issue.record("expected the node error")717 return718 }719 #expect(message.hasPrefix("[2J boom ") && message.count == 200)720 }721722 @Test func crossCheckBuilder() async throws {723 let t = ScriptedTransport()724 t.on("/wallet/createtransaction", #"{"raw_data":{},"raw_data_hex":"\#(NileSamples.trxRaw)","txID":"\#(NileSamples.trxTxID)","visible":false}"#)725 let raw = try await client(t).nodeBuiltTransfer(from: TronAddress(hex: "411fab686441481c0df7970d951fb158df04eed313")!, to: a, amountSun: 103_205)726 #expect(Hex.encode(raw) == NileSamples.trxRaw)727 #expect(String(decoding: t.recorded[0].httpBody ?? Data(), as: UTF8.self)728 == #"{"amount":103205,"owner_address":"411fab686441481c0df7970d951fb158df04eed313","to_address":"4166426c7ac3d98b29191063833345b6bc540d7278"}"#)729 // the comparison the wallet makes: rebuild with the node's block and time fields, then compare the bytes730 let theirs = try TronTransaction.decode(rawData: raw)731 let mine = try TronTransaction(refBlockBytes: theirs.refBlockBytes, refBlockHash: theirs.refBlockHash, expiration: theirs.expiration, timestamp: theirs.timestamp,732 contract: .transfer(TronTransferContract(owner: TronAddress(hex: "411fab686441481c0df7970d951fb158df04eed313")!, to: a, amount: 103_205)))733 #expect(mine.rawData == raw)734 #expect(await failure { _ = try await client(t).nodeBuiltTransfer(from: a, to: a, amountSun: UInt64.max) } == .invalidURL)735 }736}737738@Suite struct TronJSONTests {739 @Test func exactIntegers() {740 #expect(TronJSON.parse(Bytes("9007199254740993".utf8))?.uint64 == 9_007_199_254_740_993)741 #expect(TronJSON.parse(Bytes("18446744073709551615".utf8))?.uint64 == UInt64.max)742 #expect(TronJSON.parse(Bytes("18446744073709551616".utf8))?.uint64 == nil)743 #expect(TronJSON.parse(Bytes("\"12\"".utf8))?.uint64 == 12)744 for notInteger in ["-1", "1.0", "1e3", "\"-1\"", "\"1.0\"", "\" 1\"", "\"\"", "true", "null", "[1]"] {745 #expect(TronJSON.parse(Bytes(notInteger.utf8))?.uint64 == nil, "\(notInteger)")746 }747 #expect(TronJSON.parse(Bytes("1.50".utf8)) == .number("1.50"))748 #expect(TronJSON.parse(Bytes("-0.5e-3".utf8)) == .number("-0.5e-3"))749 }750751 @Test func strictGrammar() {752 let value = TronJSON.parse(Bytes(#" { "a" : [ 1 , "x\n\u00e9\ud83d\ude00\/" , true , false , null , { } , [ ] ] } "#.utf8))753 #expect(value == .object(["a": .array([.number("1"), .string("x\né😀/"), .bool(true), .bool(false), .null, .object([:]), .array([])])]))754 for bad in ["", "01", "1.", ".5", "+1", "1e", "--1", "tru", "nul", "[1,]", "[,1]", "[1 2]", "{\"a\"}", "{a:1}", "{\"a\":1,}", "{\"a\":1 \"b\":2}", "{\"a\":1,\"a\":1}",755 "\"abc", "\"\\x\"", "\"\\u12\"", "\"\\ud800\"", "\"\\udc00\"", "\"\\ud800\\u0041\"", "\"a\nb\"", "\"\t\"", "1 2", "[1]]", "{}{}", "'a'", "NaN", "Infinity",756 String(repeating: "9", count: 65)] {757 #expect(TronJSON.parse(Bytes(bad.utf8)) == nil, "accepted \(bad)")758 }759 #expect(TronJSON.parse([0x22, 0xff, 0x22]) == nil)760 #expect(TronJSON.parse([0xef, 0xbb, 0xbf, 0x31]) == nil) // byte-order mark761 // nesting is bounded762 #expect(TronJSON.parse(Bytes((String(repeating: "[", count: 48) + String(repeating: "]", count: 48)).utf8)) != nil)763 #expect(TronJSON.parse(Bytes((String(repeating: "[", count: 50) + String(repeating: "]", count: 50)).utf8)) == nil)764 #expect(TronJSON.parse(Bytes(String(repeating: "[", count: 100_000).utf8)) == nil)765 }766767 @Test func requestBodies() {768 let body = TronJSON.object(["b": .string("a\"b\\c\n\u{7f}é"), "a": .number("5"), "c": .bool(false), "d": .array([.null])])769 #expect(String(decoding: body.serialized, as: UTF8.self) == #"{"a":5,"b":"a\"b\\c\u000a\u007fé","c":false,"d":[null]}"#)770 #expect(TronJSON.parse(body.serialized) == body)771 }772}773