SPB Git

Repository Public

ResponseValidationTests.swift 8.6 KB 192 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraNetworkingTests/ResponseValidationTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//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/// Answers every request locally: the last path component is the number of body bytes to send.47/// No shared state, so the tests can run in parallel.48final class SizedBodyProtocol: URLProtocol, @unchecked Sendable {49    override class func canInit(with request: URLRequest) -> Bool { true }50    override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }5152    override func startLoading() {53        guard let url = request.url, let size = Int(url.lastPathComponent),54              let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["Content-Type": "text/plain"])55        else {56            client?.urlProtocol(self, didFailWithError: URLError(.badURL))57            return58        }59        client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)60        // sent in pieces, as a server streaming an endless body would61        var remaining = size62        while remaining > 0 {63            let n = min(remaining, 4096)64            client?.urlProtocol(self, didLoad: Data(repeating: 0x61, count: n))65            remaining -= n66        }67        client?.urlProtocolDidFinishLoading(self)68    }6970    override func stopLoading() {}71}7273/// A scripted transport: one fixed body for every request.74struct FixedBodyTransport: HTTPTransport {75    let body: String7677    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {78        guard let url = request.url, let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) else {79            throw NetworkError.invalidURL80        }81        return (Data(body.utf8), response)82    }83}8485/// Regression tests of the audit findings QYV-SVC-001, QYV-SVC-002 and QYV-SVC-007: nothing a server sends may86/// trap the process or make it buffer an unbounded answer.87struct ResponseValidationTests {88    // MARK: QYV-SVC-001 — numbers of the indexer8990    @Test func indexerNumberNeverTraps() {91        #expect(EthereumIndexer.number(.number(0)) == 0)92        #expect(EthereumIndexer.number(.number(18)) == 18)93        #expect(EthereumIndexer.number(.number(1.9)) == 1)94        #expect(EthereumIndexer.number(.string("21000000")) == 21_000_000)95        // values that used to trap in UInt64(Double)96        #expect(EthereumIndexer.number(.number(1e300)) == nil)97        #expect(EthereumIndexer.number(.number(18_446_744_073_709_551_616.0)) == nil)98        #expect(EthereumIndexer.number(.number(.infinity)) == nil)99        #expect(EthereumIndexer.number(.number(.nan)) == nil)100        #expect(EthereumIndexer.number(.number(-1)) == nil)101        #expect(EthereumIndexer.number(.string("-1")) == nil)102        #expect(EthereumIndexer.number(.string("1e3")) == nil)103        #expect(EthereumIndexer.number(.null) == nil)104        #expect(EthereumIndexer.number(nil) == nil)105        // the largest value below 2^64 that a Double holds106        #expect(EthereumIndexer.number(.number(18_446_744_073_709_549_568.0)) == 18_446_744_073_709_549_568)107    }108109    @Test func hostileIndexerAnswersAreParsedWithoutTrap() async throws {110        let owner = "0x00000000000000000000000000000000000000aa"111        let hash = "0x" + String(repeating: "ab", count: 32)112        let body = """113        {"items":[114          {"hash":"\(hash)","transaction_hash":"\(hash)","from":{"hash":"\(owner)"},"to":{"hash":"\(owner)"},"value":"1","total":{"value":"1"},115           "block_number":1e300,"timestamp":"2026-01-01T00:00:00.000000Z",116           "token":{"address_hash":"\(owner)","symbol":"X","decimals":"18446744073709551615"}},117          {"hash":"\(hash)","transaction_hash":"\(hash)","from":{"hash":"\(owner)"},"to":{"hash":"\(owner)"},"value":"2","total":{"value":"2"},118           "block_number":-5,"token":{"address_hash":"\(owner)","symbol":"Y","decimals":1e40}},119          {"token":{"address_hash":"\(owner)","symbol":"Z","name":"Z","decimals":9223372036854775808},"value":"3"}120        ]}121        """122        var configuration = EndpointConfiguration.default123        configuration.ethereumIndexer = ["sepolia": ["https://indexer.invalid"]]124        let indexer = EthereumIndexer(network: .sepolia, configuration: configuration, transport: FixedBodyTransport(body: body))125126        let native = try await indexer.transactions(of: owner)127        #expect(native.count == 2)128        #expect(native.allSatisfy { $0.blockNumber == nil })129130        let transfers = try await indexer.tokenTransfers(of: owner)131        #expect(transfers.count == 2)132        // 2^64 − 1 does not fit Int, 1e40 does not fit UInt64: both are reported as unknown, never trapped on133        #expect(transfers.allSatisfy { $0.tokenDecimals == nil })134135        // decimals above the accepted range: the holding is dropped136        #expect(try await indexer.tokenHoldings(of: owner).isEmpty)137    }138139    // MARK: QYV-SVC-002 — counters of the Esplora address statistics140141    @Test func addressStatisticsWithExtremeCountersDoNotOverflow() throws {142        let m = Int.max143        let json = """144        {"address":"tb1q6rz28mcfaxtmd6v789l9rrlrusdprr9pqcpvkl",145         "chain_stats":{"funded_txo_count":\(m),"funded_txo_sum":18446744073709551615,"spent_txo_count":\(m),"spent_txo_sum":18446744073709551615,"tx_count":\(m)},146         "mempool_stats":{"funded_txo_count":\(m),"funded_txo_sum":18446744073709551615,"spent_txo_count":\(m),"spent_txo_sum":18446744073709551615,"tx_count":\(m)}}147        """148        let stats = try JSONDecoder().decode(EsploraAddressStats.self, from: Data(json.utf8))149        // both used to add two server-supplied Int values and trap on overflow150        #expect(stats.isUsed)151        #expect(stats.hasSpent)152153        let empty = json.replacingOccurrences(of: "\(m)", with: "0")154        let none = try JSONDecoder().decode(EsploraAddressStats.self, from: Data(empty.utf8))155        #expect(!none.isUsed)156        #expect(!none.hasSpent)157    }158159    // MARK: QYV-SVC-007 — response size160161    private func transport(limit: Int) -> URLSessionTransport {162        URLSessionTransport(timeout: 10, maximumResponseBytes: limit, protocolClasses: [SizedBodyProtocol.self])163    }164165    private func request(bytes: Int) throws -> URLRequest {166        URLRequest(url: try #require(URL(string: "https://sized.invalid/\(bytes)")))167    }168169    @Test func bodyWithinTheLimitIsReturnedWhole() async throws {170        let t = transport(limit: 10_000)171        for size in [0, 1, 9_999, 10_000] {172            let (data, response) = try await t.send(try request(bytes: size))173            #expect(response.statusCode == 200)174            #expect(data.count == size)175            #expect(data.allSatisfy { $0 == 0x61 })176        }177    }178179    @Test func oversizedBodyIsRefused() async throws {180        let t = transport(limit: 10_000)181        for size in [10_001, 250_000] {182            await #expect(throws: NetworkError.self) {183                _ = try await t.send(try request(bytes: size))184            }185        }186    }187188    @Test func defaultLimitIsFinite() {189        #expect(URLSessionTransport.defaultMaximumResponseBytes == 32 << 20)190    }191}192
Files main
Menu

Theme