SPB Git

Repository Public

TronAuditRegressionTests.swift 14.4 KB 244 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraTronTests/TronAuditRegressionTests.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 Testing44import QyvoraCore45import QyvoraNetworking46@testable import QyvoraTron4748/// Regression tests of the multi-chain security audit, TRON module (QYV-SVC-040): the block a transaction refers to49/// is the only thing that ties it to a chain, and it used to be taken from the first node that answered.50@Suite struct TronAuditRegressionTests {51    static let endpoints = TronEndpoints(fullNodes: ["nile": ["https://node-a.example", "https://node-b.example", "https://node-c.example"]], history: [:])5253    static func block(_ number: UInt64, fill: UInt8) -> String {54        #"{"blockID":"\#(Hex.encode(Endian.be64(number) + Bytes(repeating: fill, count: 24)))","block_header":{"raw_data":{"timestamp":1796447373000,"number":\#(number)}}}"#55    }5657    func client(_ t: ScriptedTransport, endpoints: TronEndpoints = TronAuditRegressionTests.endpoints) -> TronClient {58        TronClient(network: .nile, endpoints: endpoints, transport: t, pacing: .unthrottled)59    }6061    func failure(_ body: () async throws -> Void) async -> NetworkError? {62        do {63            try await body()64            return nil65        } catch {66            return error as? NetworkError ?? .invalidResponse("not a NetworkError: \(error)")67        }68    }6970    @Test func nodesThatAgreeConfirmTheReferenceBlock() async throws {71        let t = ScriptedTransport()72        t.on("/walletsolidity/getblock", Self.block(1_000, fill: 0xaa))73        let r = try await client(t).referenceBlock()74        #expect(r.block.number == 1_000 && r.confirmations == 2)75        #expect(t.recorded.count == 3 && t.recorded.allSatisfy { $0.url?.path == "/walletsolidity/getblock" })76    }7778    /// Nodes are rarely at the same height: the oldest of their irreversible blocks is kept, and the nodes that are79    /// ahead are asked for the block of that number.80    @Test func theOldestIrreversibleBlockIsKeptAndTheOthersAreAskedForIt() async throws {81        let t = ScriptedTransport()82        t.on("node-a.example /walletsolidity/getblock", Self.block(1_003, fill: 0xaa))83        t.on("node-b.example /walletsolidity/getblock", Self.block(1_000, fill: 0xaa))84        t.on("node-c.example /walletsolidity/getblock", Self.block(1_001, fill: 0xaa))85        t.on("/walletsolidity/getblockbynum", Self.block(1_000, fill: 0xaa))86        let r = try await client(t).referenceBlock()87        #expect(r.block.number == 1_000 && r.confirmations == 2)88        let asked = t.recorded.filter { $0.url?.path == "/walletsolidity/getblockbynum" }89        #expect(asked.map { $0.url?.host } == ["node-a.example", "node-c.example"])90        #expect(asked.allSatisfy { String(decoding: $0.httpBody ?? Data(), as: UTF8.self) == #"{"num":1000}"# })91    }9293    /// QYV-SVC-040. One node hands out a block the others do not have at that height: nothing is returned, whatever94    /// the order of the nodes and whichever of them is behind.95    @Test func aNodeWithAnotherBlockAtTheSameHeightIsADisagreement() async throws {96        for liar in ["node-a.example", "node-b.example", "node-c.example"] {97            // same height everywhere98            let same = ScriptedTransport()99            same.on("/walletsolidity/getblock", Self.block(1_000, fill: 0xaa))100            same.on("\(liar) /walletsolidity/getblock", Self.block(1_000, fill: 0xee))101            guard case .disagreement(let text)? = await failure({ _ = try await client(same).referenceBlock() }) else {102                Issue.record("a different block at the same height must be refused (\(liar))")103                continue104            }105            #expect(text.contains("different irreversible blocks at height 1000"))106107            // the liar is ahead and lies when asked for the older block108            let ahead = ScriptedTransport()109            ahead.on("/walletsolidity/getblock", Self.block(1_000, fill: 0xaa))110            ahead.on("\(liar) /walletsolidity/getblock", Self.block(1_005, fill: 0xee))111            ahead.on("\(liar) /walletsolidity/getblockbynum", Self.block(1_000, fill: 0xee))112            guard case .disagreement? = await failure({ _ = try await client(ahead).referenceBlock() }) else {113                Issue.record("a different block for the same number must be refused (\(liar))")114                continue115            }116117            // the liar is behind: its block is the candidate, and the honest nodes do not know it118            let behind = ScriptedTransport()119            behind.on("/walletsolidity/getblock", Self.block(1_000, fill: 0xaa))120            behind.on("\(liar) /walletsolidity/getblock", Self.block(900, fill: 0xee))121            behind.on("/walletsolidity/getblockbynum", Self.block(900, fill: 0xaa))122            guard case .disagreement? = await failure({ _ = try await client(behind).referenceBlock() }) else {123                Issue.record("a block the other nodes do not have must be refused (\(liar))")124                continue125            }126127            // a node that answers the wrong height to getblockbynum is not a confirmation either128            let other = ScriptedTransport()129            other.on("/walletsolidity/getblock", Self.block(1_000, fill: 0xaa))130            other.on("\(liar) /walletsolidity/getblock", Self.block(1_005, fill: 0xaa))131            other.on("\(liar) /walletsolidity/getblockbynum", Self.block(1_001, fill: 0xaa))132            guard case .disagreement? = await failure({ _ = try await client(other).referenceBlock() }) else {133                Issue.record("another height in the answer must be refused (\(liar))")134                continue135            }136        }137    }138139    /// Nodes that do not answer, or do not have the block, neither confirm nor block; a single node has nobody to be140    /// compared with and the caller is told (`confirmations` 0).141    @Test func silentNodesAndASingleNodeGiveNoConfirmation() async throws {142        let t = ScriptedTransport()143        t.on("node-b.example /walletsolidity/getblock", Self.block(1_000, fill: 0xaa))144        let alone = try await client(t).referenceBlock()145        #expect(alone.block.number == 1_000 && alone.confirmations == 0)146147        let lagging = ScriptedTransport()148        lagging.on("node-a.example /walletsolidity/getblock", Self.block(1_000, fill: 0xaa))149        lagging.on("node-b.example /walletsolidity/getblock", Self.block(1_004, fill: 0xaa))150        lagging.on("node-b.example /walletsolidity/getblockbynum", "{}")151        lagging.on("node-c.example /walletsolidity/getblock", Self.block(1_004, fill: 0xaa))152        lagging.on("node-c.example /walletsolidity/getblockbynum", "not json", status: 502)153        let r = try await client(lagging).referenceBlock()154        #expect(r.block.number == 1_000 && r.confirmations == 0)155156        let single = ScriptedTransport()157        single.on("/walletsolidity/getblock", Self.block(7, fill: 1))158        let one = try await client(single, endpoints: TronEndpoints(fullNodes: ["nile": ["https://node-a.example"]], history: [:])).referenceBlock()159        #expect(one.confirmations == 0 && single.recorded.count == 1)160161        guard case .allEndpointsFailed? = await failure({ _ = try await client(ScriptedTransport()).referenceBlock() }) else {162            Issue.record("no answer at all must be a failure")163            return164        }165        // a malformed block (an id that does not start with its number) is never a reference166        let bad = ScriptedTransport()167        bad.on("/walletsolidity/getblock", #"{"blockID":"\#(String(repeating: "ab", count: 32))","block_header":{"raw_data":{"timestamp":1,"number":5}}}"#)168        guard case .allEndpointsFailed? = await failure({ _ = try await client(bad).referenceBlock() }) else {169            Issue.record("a block id that does not carry its number must be refused")170            return171        }172    }173174    /// QYV-SVC-040. Whether a chain would accept a reference (TaPoS): the latest block at or under the head whose175    /// number ends with `ref_block_bytes` must have `ref_block_hash` as bytes 8 to 15 of its id.176    @Test func whetherAChainAcceptsAReference() async throws {177        // head 0x0003_1234; references are looked up at the latest height with the same two low-order bytes178        let head: UInt64 = 0x0003_1234179        func ask(_ low: UInt16, hashFill: UInt8, chainFill: UInt8 = 0xaa) async throws -> (Bool, [String]) {180            let t = ScriptedTransport()181            t.on("/wallet/getblock", Self.block(head, fill: chainFill))182            let expected: UInt64 = (head & ~0xffff | UInt64(low)) > head ? (head & ~0xffff | UInt64(low)) - 0x1_0000 : (head & ~0xffff | UInt64(low))183            t.on("/wallet/getblockbynum", Self.block(expected, fill: chainFill))184            let single = TronEndpoints(fullNodes: ["nile": ["https://node-a.example"]], history: [:])185            let accepted = try await client(t, endpoints: single).acceptsReference(refBlockBytes: [UInt8(low >> 8), UInt8(low & 0xff)], refBlockHash: Bytes(repeating: hashFill, count: 8))186            return (accepted, t.recorded.filter { $0.url?.path == "/wallet/getblockbynum" }.map { String(decoding: $0.httpBody ?? Data(), as: UTF8.self) })187        }188        // the head itself: no second request189        #expect(try await ask(0x1234, hashFill: 0xaa) == (true, []))190        #expect(try await ask(0x1234, hashFill: 0xab) == (false, []))191        // a block under the head in the same 65 536-block span192        #expect(try await ask(0x1000, hashFill: 0xaa) == (true, [#"{"num":200704}"#]))193        #expect(try await ask(0x1000, hashFill: 0x01) == (false, [#"{"num":200704}"#]))194        // low bytes above the head's: the block of the previous span195        #expect(try await ask(0x1235, hashFill: 0xaa) == (true, [#"{"num":135733}"#]))196        #expect(try await ask(0xffff, hashFill: 0xaa) == (true, [#"{"num":196607}"#]))197198        // a young chain that has no block with these low bytes yet199        let young = ScriptedTransport()200        young.on("/wallet/getblock", Self.block(10, fill: 0xaa))201        let single = TronEndpoints(fullNodes: ["nile": ["https://node-a.example"]], history: [:])202        #expect(try await client(young, endpoints: single).acceptsReference(refBlockBytes: [0, 11], refBlockHash: Bytes(repeating: 0xaa, count: 8)) == false)203        // malformed fields, a node that answers another block, a node that has no such block: an error, never "not accepted"204        #expect(await failure { _ = try await client(young, endpoints: single).acceptsReference(refBlockBytes: [0], refBlockHash: Bytes(repeating: 0, count: 8)) } == .invalidURL)205        let other = ScriptedTransport()206        other.on("/wallet/getblock", Self.block(head, fill: 0xaa))207        other.on("/wallet/getblockbynum", Self.block(5, fill: 0xaa))208        guard case .invalidResponse? = await failure({ _ = try await client(other, endpoints: single).acceptsReference(refBlockBytes: [0x10, 0], refBlockHash: Bytes(repeating: 0xaa, count: 8)) }) else {209            Issue.record("another block than the one asked for must be an error")210            return211        }212        let empty = ScriptedTransport()213        empty.on("/wallet/getblock", Self.block(head, fill: 0xaa))214        empty.on("/wallet/getblockbynum", "{}")215        guard case .allEndpointsFailed? = await failure({ _ = try await client(empty, endpoints: single).acceptsReference(refBlockBytes: [0x10, 0], refBlockHash: Bytes(repeating: 0xaa, count: 8)) }) else {216            Issue.record("a missing block must be an error")217            return218        }219    }220221    /// The API key only goes to hosts of trongrid.io over https: look-alike hosts and user-info tricks get nothing.222    @Test func theAPIKeyIsNotSentToLookAlikeHosts() async throws {223        let key = try #require(TronAPIKey("0a1b2c3d-1111-2222-3333-444455556666"))224        #expect("\(key)".contains("0a1b") == false && String(reflecting: key).contains("0a1b") == false)225        for (base, expected) in [("https://api.trongrid.io", true), ("https://nile.trongrid.io", true), ("https://TRONGRID.io", true),226                                 ("https://api.trongrid.io.example.org", false), ("https://trongrid.io.example.org", false),227                                 ("https://eviltrongrid.io", false), ("https://api.trongrid.io@example.org", false),228                                 ("https://example.org/api.trongrid.io", false), ("https://trongrid.example.org", false)] {229            let t = ScriptedTransport()230            t.on("/wallet/getblock", Self.block(5, fill: 2))231            let c = TronClient(network: .nile, endpoints: TronEndpoints(fullNodes: ["nile": [base]], history: [:]), transport: t, apiKey: key, pacing: .unthrottled)232            guard c.isConfigured else {233                // refused as an endpoint altogether: nothing is sent234                #expect(!expected, "\(base)")235                continue236            }237            _ = try? await c.latestBlock()238            #expect(t.recorded.count == 1, "\(base)")239            #expect((t.recorded.first?.value(forHTTPHeaderField: "TRON-PRO-API-KEY") != nil) == expected, "\(base)")240            #expect(t.recorded.first?.url?.absoluteString.contains("0a1b") == false)241        }242    }243}244
Files main
Menu

Theme