SPB Git

Repository Public

TronProperties.swift 58.3 KB 875 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/PropertyAuditTests/TronProperties.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 AuditSupport42import Foundation43import QyvoraCore44import QyvoraEthereum45import QyvoraMath46import QyvoraSecp256k147import QyvoraSymmetric48import Testing4950@testable import QyvoraTron5152// TRON properties (no reference needed: each one is a statement that must hold for every input).53//54//   canonical encoding   decode∘encode is the identity on everything the encoder writes, and every class of55//                        non-canonical encoding is refused by the strict decoder, at each nesting level;56//   lengths              a length taken from the input is compared with what is left before anything is sliced or57//                        allocated, whatever its value (2^31, 2^63, 2^64 − 1);58//   exhaustive bytes     every single-byte change of a valid transaction is either refused or decodes to a59//                        transaction that encodes to exactly the changed bytes;60//   planner              no trap and no overflow for any chain state a node can report; amount + fee never above61//                        the balance; send-max never above the balance; fee limit never above the ceiling; the62//                        lifetime never above an hour;63//   signing              the engine signs only what it decodes, for the owner key only;64//   identity             the transaction id depends on every field that ties the transaction to a chain and a time;65//   JSON                 the response parser is exact on integers, strict, and bounded;66//   API key              the type cannot hold anything that would break out of a header, and never prints itself.6768@Suite struct TronProperties {69    static let int64Max = UInt64(Int64.max)7071    static func varint(_ value: UInt64) -> Bytes {72        var v = value73        var out = Bytes()74        while v >= 0x80 {75            out.append(UInt8(v & 0x7f) | 0x80)76            v >>= 777        }78        out.append(UInt8(v))79        return out80    }8182    static func field(_ number: UInt64, varint value: UInt64) -> Bytes { varint(number << 3) + varint(value) }83    static func field(_ number: UInt64, bytes value: Bytes) -> Bytes { varint(number << 3 | 2) + varint(UInt64(value.count)) + value }8485    static let owner = TronAddress(hash: Bytes(repeating: 0x11, count: 20))!86    static let recipient = TronAddress(hash: Bytes(repeating: 0x22, count: 20))!87    static let token = TronAddress(hash: Bytes(repeating: 0x33, count: 20))!88    static let transferURL = Bytes("type.googleapis.com/protocol.TransferContract".utf8)89    static let triggerURL = Bytes("type.googleapis.com/protocol.TriggerSmartContract".utf8)9091    /// A transaction assembled field by field, so that each piece can be replaced by a non-canonical variant.92    struct Parts {93        var refBytes = TronProperties.field(1, bytes: [0x12, 0x34])94        var refHash = TronProperties.field(4, bytes: Bytes(repeating: 0x56, count: 8))95        var expiration = TronProperties.field(8, varint: 1_800_000_060_000)96        var memo = Bytes()97        var timestamp = TronProperties.field(14, varint: 1_800_000_000_000)98        var feeLimit = Bytes()99        var type = TronProperties.field(1, varint: 1)100        var url = TronProperties.field(1, bytes: TronProperties.transferURL)101        var innerOwner = TronProperties.field(1, bytes: TronProperties.owner.bytes)102        var innerTo = TronProperties.field(2, bytes: TronProperties.recipient.bytes)103        var innerAmount = TronProperties.field(3, varint: 1_000_000)104        var innerExtra = Bytes()105        var anyExtra = Bytes()106        var permission = Bytes()107        var contractExtra = Bytes()108        var before = Bytes()109        var after = Bytes()110        var secondContract = Bytes()111112        var inner: Bytes { innerOwner + innerTo + innerAmount + innerExtra }113        var any: Bytes { url + TronProperties.field(2, bytes: inner) + anyExtra }114        var contract: Bytes { type + TronProperties.field(2, bytes: any) + permission + contractExtra }115        var raw: Bytes {116            before + refBytes + refHash + expiration + memo + TronProperties.field(11, bytes: contract) + secondContract + timestamp + feeLimit + after117        }118    }119120    static func refused(_ raw: Bytes) -> Bool { (try? TronTransaction.decode(rawData: raw)) == nil }121122    @Test func everyClassOfNonCanonicalEncodingIsRefused() throws {123        var cases = 0, failed = 0124        var failures = [String]()125        func expectRefused(_ what: String, _ edit: (inout Parts) -> Void) {126            var p = Parts()127            edit(&p)128            cases += 1129            if !Self.refused(p.raw) {130                failed += 1131                failures.append(what)132            }133        }134        func expectAccepted(_ what: String, _ edit: (inout Parts) -> Void) {135            var p = Parts()136            edit(&p)137            cases += 1138            if (try? TronTransaction.decode(rawData: p.raw))?.rawData != p.raw {139                failed += 1140                failures.append("valid but refused: " + what)141            }142        }143        let F = Self.self144        // the base, and the optional fields at non-default values, are accepted: the classes below are refused for what they are145        expectAccepted("base") { _ in }146        expectAccepted("memo") { $0.memo = F.field(10, bytes: [0x68, 0x69]) }147        expectAccepted("fee limit") { $0.feeLimit = F.field(18, varint: 5) }148        expectAccepted("permission") { $0.permission = F.field(5, varint: 2) }149        expectAccepted("no timestamp") { $0.timestamp = [] }150        expectAccepted("zero amount omitted") { $0.innerAmount = [] }151        expectAccepted("int64 max") { $0.innerAmount = F.field(3, varint: F.int64Max) }152        expectAccepted("unknown contract type kept raw") {153            $0.type = F.field(1, varint: 4)154            $0.url = F.field(1, bytes: Bytes("type.googleapis.com/protocol.VoteWitnessContract".utf8))155            $0.innerExtra = [0xff, 0xff, 0xff]   // opaque bytes: not parsed, kept as they are156        }157158        // 1. non-minimal varints: in a value, in a tag, in a length — at each nesting level159        expectRefused("non-minimal varint value (raw)") { $0.expiration = [0x40, 0x81, 0x00] }160        expectRefused("non-minimal varint value, zero on two bytes (raw)") { $0.feeLimit = [0x90, 0x01, 0x80, 0x00] }161        expectRefused("non-minimal tag (raw)") { $0.refBytes = [0x8a, 0x00, 0x02, 0x12, 0x34] }162        expectRefused("non-minimal length (raw)") { $0.refBytes = [0x0a, 0x82, 0x00, 0x12, 0x34] }163        expectRefused("non-minimal varint value (contract)") { $0.type = [0x08, 0x81, 0x00] }164        expectRefused("non-minimal length (Any)") { $0.url = [0x0a, 0x80 | UInt8(F.transferURL.count), 0x00] + F.transferURL }165        expectRefused("non-minimal varint value (TransferContract)") { $0.innerAmount = [0x18, 0xc0, 0x84, 0xbd, 0x80, 0x00] }166        expectRefused("non-minimal tag (TransferContract)") { $0.innerAmount = [0x98, 0x00, 0x01] }167        // 2. over-long varints and values beyond 64 bits168        expectRefused("eleven-byte varint") { $0.feeLimit = [0x90, 0x01] + Bytes(repeating: 0xff, count: 10) + [0x01] }169        expectRefused("ten-byte varint above 2^64") { $0.feeLimit = [0x90, 0x01] + Bytes(repeating: 0xff, count: 9) + [0x02] }170        expectRefused("ten-byte varint, all ones in the last group") { $0.feeLimit = [0x90, 0x01] + Bytes(repeating: 0xff, count: 9) + [0x7f] }171        expectRefused("unterminated varint") { $0.after = Bytes(repeating: 0x80, count: 12) }172        // 3. negative int64 (ten-byte varints with the sign bit): amounts, times and limits are never negative173        expectRefused("negative expiration") { $0.expiration = [0x40] + F.varint(UInt64.max) }174        expectRefused("negative timestamp") { $0.timestamp = [0x70] + F.varint(F.int64Max + 1) }175        expectRefused("negative fee limit") { $0.feeLimit = [0x90, 0x01] + F.varint(UInt64.max) }176        expectRefused("negative amount") { $0.innerAmount = [0x18] + F.varint(UInt64.max) }177        expectRefused("negative contract type") { $0.type = [0x08] + F.varint(UInt64.max) }178        expectRefused("contract type above int32") { $0.type = [0x08] + F.varint(1 << 32 | 1) }179        expectRefused("negative permission id") { $0.permission = [0x28] + F.varint(UInt64.max) }180        expectRefused("permission id above int32") { $0.permission = [0x28] + F.varint(1 << 31) }181        // 4. fields out of order182        expectRefused("ref_block_hash before ref_block_bytes") { p in183            let a = p.refBytes184            p.refBytes = p.refHash185            p.refHash = a186        }187        expectRefused("timestamp before the contract") { p in188            p.memo = p.timestamp189            p.timestamp = []190        }191        expectRefused("to before owner (TransferContract)") { p in192            let a = p.innerOwner193            p.innerOwner = p.innerTo194            p.innerTo = a195        }196        expectRefused("value before type URL (Any)") { p in197            p.anyExtra = p.url198            p.url = []199        }200        expectRefused("permission before type (contract)") { p in201            p.contractExtra = p.type202            p.type = F.field(5, varint: 2)203            p.permission = []204        }205        // 5. duplicated fields206        expectRefused("ref_block_bytes twice") { $0.before = $0.refBytes }207        expectRefused("expiration twice") { $0.memo = $0.expiration }208        expectRefused("timestamp twice") { $0.after = $0.timestamp }209        expectRefused("two contracts") { $0.secondContract = F.field(11, bytes: $0.contract) }210        expectRefused("amount twice") { $0.innerExtra = $0.innerAmount }211        expectRefused("owner twice") { $0.innerExtra = $0.innerOwner }212        expectRefused("type URL twice") { $0.anyExtra = $0.url }213        expectRefused("contract type twice") { $0.contractExtra = $0.type }214        // 6. unknown fields: of the protocol (ref_block_num, auths, scripts, provider, ContractName) and of nobody215        expectRefused("ref_block_num") { $0.refBytes += F.field(3, varint: 7) }216        expectRefused("auths") { $0.expiration += F.field(9, bytes: [0x0a, 0x00]) }217        expectRefused("scripts") { $0.secondContract = F.field(12, bytes: [0x00]) }218        expectRefused("field 99 (raw)") { $0.after = F.field(99, varint: 1) }219        expectRefused("field 2 (raw)") { $0.refBytes += F.field(2, bytes: [1]) }220        expectRefused("provider (contract)") { $0.contractExtra = F.field(3, bytes: [1]) }221        expectRefused("ContractName (contract)") { $0.contractExtra = F.field(4, bytes: [1]) }222        expectRefused("field 6 (contract)") { $0.contractExtra = F.field(6, varint: 1) }223        expectRefused("field 3 (Any)") { $0.anyExtra = F.field(3, varint: 1) }224        expectRefused("field 4 (TransferContract)") { $0.innerExtra = F.field(4, varint: 1) }225        expectRefused("field 0") { $0.after = [0x00, 0x00] }226        expectRefused("field number above 2^29 - 1") { $0.after = F.varint((1 << 29) << 3) + [0x00] }227        // 7. wrong wire types: a known field under the other wire type, and wire types 1, 3, 4, 5, 6, 7228        expectRefused("expiration as bytes") { $0.expiration = F.field(8, bytes: [1]) }229        expectRefused("ref_block_bytes as varint") { $0.refBytes = F.field(1, varint: 0x1234) }230        expectRefused("contract as varint") { $0.secondContract = F.field(11, varint: 1) }231        expectRefused("amount as bytes") { $0.innerAmount = F.field(3, bytes: [1]) }232        expectRefused("owner as varint") { $0.innerOwner = F.field(1, varint: 1) }233        expectRefused("type URL as varint") { $0.url = F.field(1, varint: 1) }234        for wire: UInt8 in [1, 3, 4, 5, 6, 7] {235            expectRefused("wire type \(wire) (raw)") { $0.after = [UInt8(19 << 3 & 0x7f) | wire] + Bytes(repeating: 0, count: 8) }236            expectRefused("wire type \(wire) (TransferContract)") { $0.innerExtra = [UInt8(4 << 3) | wire] + Bytes(repeating: 0, count: 8) }237        }238        // 8. lengths: larger than what is left, huge, and truncated length-delimited fields239        for length: UInt64 in [3, 0x7f, 1 << 14, 1 << 31, 1 << 32, F.int64Max, F.int64Max + 1, UInt64.max] {240            expectRefused("length \(length) with two bytes left") { $0.after = [0x52] + F.varint(length) + [0x01, 0x02] }241            expectRefused("inner length \(length)") { $0.innerExtra = [0x22] + F.varint(length) + [0x01] }242        }243        expectRefused("contract length one too long") { p in244            let c = p.contract245            p.secondContract = []246            p.after = []247            p.timestamp = []248            p.feeLimit = []249            // rebuilt by hand below through `before`: the whole message is the bad field250            p.before = [0x5a] + F.varint(UInt64(c.count + 1)) + c251            p.refBytes = []252            p.refHash = []253            p.expiration = []254        }255        // 9. default values written explicitly (proto3 omits them: one value, one encoding)256        expectRefused("expiration 0 written") { $0.expiration = [0x40, 0x00] }257        expectRefused("timestamp 0 written") { $0.timestamp = [0x70, 0x00] }258        expectRefused("fee limit 0 written") { $0.feeLimit = [0x90, 0x01, 0x00] }259        expectRefused("empty memo written") { $0.memo = [0x52, 0x00] }260        expectRefused("amount 0 written") { $0.innerAmount = [0x18, 0x00] }261        expectRefused("permission 0 written") { $0.permission = [0x28, 0x00] }262        expectRefused("contract type 0 written") { p in263            p.type = [0x08, 0x00]264            p.url = F.field(1, bytes: Bytes("type.googleapis.com/protocol.AccountCreateContract".utf8))265        }266        // 10. trailing bytes267        expectRefused("one trailing zero byte") { $0.after = [0x00] }268        expectRefused("trailing bytes inside the contract") { $0.contractExtra = [0x00] }269        expectRefused("trailing bytes inside TransferContract") { $0.innerExtra = [0x00] }270        expectRefused("a trailing tag without value") { $0.after = [0x90, 0x01] }271        // 11. field values out of the wallet's rules272        expectRefused("ref_block_bytes of three bytes") { $0.refBytes = F.field(1, bytes: [1, 2, 3]) }273        expectRefused("ref_block_bytes absent") { $0.refBytes = [] }274        expectRefused("ref_block_hash of seven bytes") { $0.refHash = F.field(4, bytes: Bytes(repeating: 1, count: 7)) }275        expectRefused("no contract") { p in276            p.refBytes += []277            p.before = []278            p.secondContract = []279            p.type = []280            p.url = []281            p.innerOwner = []282            p.innerTo = []283            p.innerAmount = []284            // an empty contract message: no parameter285        }286        expectRefused("owner of twenty bytes") { $0.innerOwner = F.field(1, bytes: F.owner.hash) }287        expectRefused("owner with another prefix") { $0.innerOwner = F.field(1, bytes: [0xa0] + F.owner.hash) }288        expectRefused("recipient of twenty-two bytes") { $0.innerTo = F.field(2, bytes: F.recipient.bytes + [0]) }289        expectRefused("no recipient") { $0.innerTo = [] }290        expectRefused("no owner") { $0.innerOwner = [] }291        expectRefused("type URL of another contract") { $0.url = F.field(1, bytes: F.triggerURL) }292        expectRefused("TransferContract wrapper under another type number") { $0.type = F.field(1, varint: 2) }293        expectRefused("type URL with a control character") { $0.url = F.field(1, bytes: F.transferURL + [0x0a]) }294        expectRefused("type URL with a space") { $0.url = F.field(1, bytes: Bytes("type.googleapis.com/protocol.Transfer Contract".utf8)) }295        expectRefused("type URL that is not ASCII") { p in296            p.type = F.field(1, varint: 4)297            p.url = F.field(1, bytes: Bytes("type.googleapis.com/protocol.Vote\u{202e}Contract".utf8))298        }299        expectRefused("type URL of 201 characters") { p in300            p.type = F.field(1, varint: 4)301            p.url = F.field(1, bytes: Bytes(repeating: 0x61, count: 201))302        }303        // 12. size and depth: larger than the accepted size; deep nesting inside an unknown contract stays opaque304        cases += 2305        if !Self.refused(Bytes(repeating: 0, count: TronTransaction.maximumRawDataBytes + 1)) {306            failed += 1307            failures.append("oversized input")308        }309        var nested = Bytes()310        for _ in 0..<2_000 { nested = Self.field(2, bytes: nested) }311        var deep = Parts()312        deep.type = Self.field(1, varint: 4)313        deep.url = Self.field(1, bytes: Bytes("type.googleapis.com/protocol.VoteWitnessContract".utf8))314        deep.innerOwner = []315        deep.innerTo = []316        deep.innerAmount = []317        deep.innerExtra = Bytes(nested.prefix(8_000))318        if case .unknown(_, _, let value)? = (try? TronTransaction.decode(rawData: deep.raw))?.contract, value == deep.innerExtra {} else {319            failed += 1320            failures.append("nested bytes of an unknown contract must stay opaque")321        }322        // 13. truncation at each byte. Every proper prefix is refused, except the one that ends exactly where an323        //     optional trailing field begins: cutting the whole `timestamp` (or `fee_limit`) field off leaves the324        //     canonical encoding of ANOTHER transaction, with another id, which the review shows as it is. That is325        //     how a length-less format behaves; what matters is that no prefix is taken for the original.326        var full = Parts()327        full.feeLimit = Self.field(18, varint: 5)328        for whole in [Parts().raw, full.raw] {329            let original = try TronTransaction.decode(rawData: whole)330            var boundaries = Set<Int>()331            var end = whole.count332            for trailing in (whole == full.raw ? [full.feeLimit, full.timestamp] : [Parts().timestamp]) {333                end -= trailing.count334                boundaries.insert(end)335            }336            for cut in 0..<whole.count {337                cases += 1338                let prefix = Bytes(whole[0..<cut])339                if boundaries.contains(cut) {340                    let shorter = try? TronTransaction.decode(rawData: prefix)341                    if shorter == nil || shorter?.rawData != prefix || shorter?.txID == original.txID || shorter?.contract != original.contract {342                        failed += 1343                        failures.append("prefix of \(cut) bytes at a field boundary")344                    }345                } else if !Self.refused(prefix) {346                    failed += 1347                    failures.append("prefix of \(cut) bytes accepted")348                }349            }350        }351        AuditRecorder.record(352            area: "property", name: "tron-protobuf-non-canonical-classes", algorithm: "TRON Transaction.raw strict decoding",353            parameterSet: "non-minimal and over-long varints, negative integers, order, duplicates, unknown fields, wire types, lengths, explicit defaults, trailing bytes, values, size, truncation at every byte",354            cases: cases, failed: failed, note: failures.isEmpty ? "" : "first failures: " + failures.prefix(5).joined(separator: "; "))355        #expect(failed == 0, "\(failures.prefix(10))")356    }357358    /// The low-level reader: a length taken from the input never slices or allocates beyond the input.359    @Test func lengthsFromTheInputNeverReachBeyondIt() {360        let seed = AuditSeed.make("tron-protobuf-reader")361        var rng = AuditRNG(seed: seed)362        var cases = 0, failed = 0363        for _ in 0..<AuditMode.cases(quick: 20_000, full: 400_000) {364            cases += 1365            var data: Bytes366            switch rng.int(0...3) {367            case 0: data = rng.bytes(rng.int(0...40))368            case 1: data = [UInt8(rng.int(1...15) << 3 | 2)] + Self.varint(rng.pick([0, 1, 5, 127, 128, 1 << 31, 1 << 32, 1 << 62, 1 << 63, UInt64.max, rng.next()])) + rng.bytes(rng.int(0...6))369            case 2: data = [UInt8(rng.int(1...15) << 3)] + Bytes(repeating: 0xff, count: rng.int(0...12)) + [UInt8(rng.int(0...127))]370            default: data = Self.field(UInt64(rng.int(1...40)), bytes: rng.bytes(rng.int(0...20))) + Self.field(UInt64(rng.int(1...40)), varint: rng.next())371            }372            var reader = ProtoReader(data)373            var consumed = 0374            do {375                while let (field, value) = try reader.next() {376                    guard field >= 1, field <= 0x1fff_ffff else {377                        failed += 1378                        break379                    }380                    if case .bytes(let b) = value {381                        consumed += b.count382                        if consumed > data.count {383                            failed += 1384                            break385                        }386                    }387                }388                // read to the end without error: the fields re-encode to the input (canonical by construction of the reader)389                var again = ProtoReader(data)390                var w = ProtoWriter()391                while let (field, value) = try again.next() {392                    switch value {393                    case .varint(let v):394                        w.bytes += ProtoWriter.varint(UInt64(field) << 3)395                        w.bytes += ProtoWriter.varint(v)396                    case .bytes(let b): w.message(field, b)397                    }398                }399                if w.bytes != data { failed += 1 }400            } catch {401                // refused: fine402            }403        }404        AuditRecorder.record(area: "property", name: "tron-protobuf-reader-bounds", algorithm: "TRON protobuf reader (varint, tag, length-delimited)",405                             parameterSet: "random bytes, hostile lengths up to 2^64 − 1, long varints; accepted input re-encodes to itself", cases: cases, failed: failed, seed: seed)406        #expect(failed == 0)407    }408409    static func randomTransaction(_ rng: inout AuditRNG) throws -> TronTransaction {410        func address() -> TronAddress { TronAddress(hash: rng.bytes(20))! }411        func amount() -> UInt64 { rng.pick([0, 1, 127, 128, int64Max, rng.next() >> 1, rng.next() >> UInt64(rng.int(1...63))]) }412        let timestamp = rng.pick([0, 1_800_000_000_000, rng.next() >> UInt64(rng.int(2...40))])413        let contract: TronContract414        switch rng.int(0...3) {415        case 0: contract = .transfer(TronTransferContract(owner: address(), to: address(), amount: amount()))416        case 1: contract = .triggerSmartContract(TronTriggerSmartContract(owner: address(), contract: address(), data: ERC20.transfer(to: address().evm, amount: UInt256(rng.next()))))417        case 2: contract = .triggerSmartContract(TronTriggerSmartContract(owner: address(), contract: address(), callValue: amount(), data: rng.bytes(rng.int(0...80)),418                                                                           callTokenValue: amount(), tokenID: amount()))419        default:420            let type = UInt32(rng.pick([0, 2, 4, 11, 46, 54, 57, 59, 100, Int(Int32.max)]))421            let url = rng.bool() ? "type.googleapis.com/protocol.\(TronContract.typeName(type) ?? "X")" : String(decoding: rng.bytes(rng.int(0...40)).map { 0x21 + $0 % 94 }, as: UTF8.self)422            contract = .unknown(type: type, typeURL: url, value: rng.bytes(rng.int(0...120)))423        }424        return try TronTransaction(refBlockBytes: rng.bytes(2), refBlockHash: rng.bytes(8), expiration: timestamp + UInt64(rng.int(1...86_400_000)), timestamp: timestamp,425                                   feeLimit: rng.bool() ? 0 : amount(), memo: rng.int(0...3) == 0 ? rng.bytes(rng.int(1...256)) : [], contract: contract,426                                   permissionID: rng.int(0...7) == 0 ? UInt32(rng.int(1...Int(Int32.max))) : 0)427    }428429    @Test func decodeAfterEncodeIsTheIdentity() throws {430        let seed = AuditSeed.make("tron-encode-decode")431        var rng = AuditRNG(seed: seed)432        var cases = 0, failed = 0433        for _ in 0..<AuditMode.cases(quick: 5_000, full: 100_000) {434            cases += 1435            let tx = try Self.randomTransaction(&rng)436            let raw = tx.rawData437            let back = try? TronTransaction.decode(rawData: raw)438            var ok = back == tx && back?.rawData == raw && back?.txID == SHA256.hash(raw) && tx.txID.count == 32439            // the review is a function of the bytes: the same from the original and from the decoded transaction440            let review = TronTransactionReview(tx)441            ok = ok && back.map { TronTransactionReview($0) } == review && review.rawData == raw && review.txID == tx.txID442            // the signed envelope, with zero to five signatures of any content, round-trips too443            let signatures = (0..<rng.int(0...5)).map { _ in rng.bytes(65) }444            if let signed = SignedTronTransaction(transaction: tx, signatures: signatures) {445                ok = ok && (try? SignedTronTransaction.decode(signed.serialized)) == signed && signed.txID == tx.txID446            } else {447                ok = false448            }449            ok = ok && SignedTronTransaction(transaction: tx, signatures: (0..<6).map { _ in rng.bytes(65) }) == nil450            ok = ok && tx.bandwidthSize() == 1 + Self.varint(UInt64(raw.count)).count + raw.count + 67 + 64451            if !ok { failed += 1 }452        }453        AuditRecorder.record(area: "property", name: "tron-encode-decode-identity", algorithm: "TRON Transaction.raw and signed Transaction",454                             parameterSet: "TRX transfer, TRC-20 transfer, contract call, unknown contract types; memo, permission id, 0 to 5 signatures",455                             cases: cases, failed: failed, seed: seed)456        #expect(failed == 0)457    }458459    /// Every value of every byte of valid transactions: refused, or accepted as exactly those bytes.460    @Test func everySingleByteChangeIsRefusedOrCanonical() throws {461        var rng = AuditRNG(seed: 0x7472_6f6e)462        let key = SHA256.hash(Bytes("tron single byte".utf8))463        let me = try TronAddress(publicKey: Secp256k1.publicKey(privateKey: key, compressed: false))464        let reference = TronBlockReference(number: 0x1234, id: Endian.be64(0x1234) + Bytes(repeating: 7, count: 24), timestamp: 1_800_000_000_000)!465        let bases: [TronTransaction] = [466            try .transfer(from: me, to: Self.recipient, amountSun: 1_500_000, reference: reference, timestamp: 1_800_000_000_000, expiration: 1_800_000_120_000),467            try .transfer(from: me, to: Self.recipient, amountSun: 1, reference: reference, timestamp: 1_800_000_000_000, expiration: 1_800_000_120_000, memo: Bytes("rent".utf8)),468            try .trc20Transfer(from: me, token: Self.token, to: Self.recipient, amount: UInt256(25_000_000), feeLimitSun: 30_000_000, reference: reference,469                               timestamp: 1_800_000_000_000, expiration: 1_800_000_120_000),470        ]471        var cases = 0, failed = 0, accepted = 0, changedPayment = 0472        for base in bases {473            let raw = base.rawData474            for i in 0..<raw.count {475                for value in UInt8.min...UInt8.max where value != raw[i] {476                    cases += 1477                    var changed = raw478                    changed[i] = value479                    guard let tx = try? TronTransaction.decode(rawData: changed) else { continue }480                    accepted += 1481                    // accepted: the bytes are canonical, and they are another transaction with another id482                    if tx.rawData != changed || tx == base || tx.txID == base.txID { failed += 1 }483                    // and it can no longer be signed for another owner484                    if tx.owner != me, (try? tx.sign(privateKey: key, allowBlindSigning: true)) != nil, tx.owner != nil { failed += 1 }485                    if TronTransactionReview(tx).action != TronTransactionReview(base).action { changedPayment += 1 }486                }487            }488            // and pairs of changes, sampled489            for _ in 0..<AuditMode.cases(quick: 20_000, full: 300_000) {490                cases += 1491                var changed = raw492                changed[rng.int(0...(raw.count - 1))] = UInt8(truncatingIfNeeded: rng.next())493                changed[rng.int(0...(raw.count - 1))] = UInt8(truncatingIfNeeded: rng.next())494                if let tx = try? TronTransaction.decode(rawData: changed) {495                    accepted += 1496                    if tx.rawData != changed { failed += 1 }497                }498            }499        }500        AuditRecorder.record(area: "property", name: "tron-single-byte-changes", algorithm: "TRON Transaction.raw strict decoding",501                             parameterSet: "every value of every byte of three transactions, and sampled pairs of changes", cases: cases, failed: failed, seed: rng.seed,502                             note: "\(accepted) changed inputs still decode, each to exactly its own bytes and to another transaction id; \(changedPayment) of them change the payment shown")503        #expect(failed == 0 && accepted > 0)504    }505506    // MARK: Planner507508    static func hostileUInt64(_ rng: inout AuditRNG) -> UInt64 {509        rng.pick([0, 1, 100, 1_000, 420, 100_000, 1_000_000, 1_100_000, 15_000_000_000, int64Max - 1, int64Max, int64Max + 1, UInt64.max, rng.next(), rng.next() >> UInt64(rng.int(1...63))])510    }511512    @Test func plannerArithmeticHoldsForAnyChainState() throws {513        let seed = AuditSeed.make("tron-planner")514        var rng = AuditRNG(seed: seed)515        var cases = 0, failed = 0, planned = 0516        var failures = [String]()517        var refusals = [String: Int]()518        func fail(_ what: String) {519            failed += 1520            if failures.count < 5 { failures.append(what) }521        }522        let sender = Self.owner523        for _ in 0..<AuditMode.cases(quick: 6_000, full: 120_000) {524            cases += 1525            let h = { Self.hostileUInt64(&rng) }526            // everything a node reports, hostile or not527            let realistic = rng.int(0...2) != 0528            let parameters = realistic529                ? TronChainParameters(bandwidthPriceSun: 1_000, energyPriceSun: rng.pick([100, 210, 420]), accountActivationFeeSun: 1_000_000, createAccountFeeSun: 100_000,530                                      createAccountBandwidthRate: 1, maximumFeeLimitSun: 15_000_000_000, memoFeeSun: 1_000_000)531                : TronChainParameters(bandwidthPriceSun: h(), energyPriceSun: h(), accountActivationFeeSun: h(), createAccountFeeSun: h(), createAccountBandwidthRate: h(),532                                      maximumFeeLimitSun: h(), memoFeeSun: h())533            let now = rng.pick([1_800_000_000_000, 0, Self.int64Max - 1_000, Self.int64Max, UInt64.max, rng.next() >> 20])534            let blockTime = rng.int(0...5) == 0 ? h() : now &- UInt64(rng.int(0...400_000)) &+ UInt64(rng.int(0...400_000))535            let number = rng.next() >> UInt64(rng.int(8...40))536            let reference = TronBlockReference(number: number, id: Endian.be64(number) + rng.bytes(24), timestamp: blockTime)!537            let state = TronSendPlanner.ChainState(network: rng.pick(TronNetwork.allCases), parameters: parameters, reference: reference, nowMilliseconds: now)538            let balance = realistic ? rng.next() >> UInt64(rng.int(20...50)) : h()539            let senderAccount = TronAccount(address: sender, isActivated: rng.int(0...9) != 0, balanceSun: balance, isContract: false)540            let resources = rng.bool() ? TronResources(freeNetLimit: 600, freeNetUsed: UInt64(rng.int(0...600)), netLimit: 0, netUsed: 0, energyLimit: 0, energyUsed: 0)541                : TronResources(freeNetLimit: h(), freeNetUsed: h(), netLimit: h(), netUsed: h(), energyLimit: h(), energyUsed: h())542            let recipientAddress = rng.int(0...30) == 0 ? rng.pick([sender, TronAddress.zero, TronBuiltInTokens.mainnet[0].contract]) : TronAddress(hash: rng.bytes(20))!543            let recipient = TronAccount(address: recipientAddress, isActivated: rng.bool(), balanceSun: h(), isContract: rng.int(0...5) == 0)544            var policy = TronSendPlanner.Policy()545            if rng.int(0...3) == 0 {546                policy = TronSendPlanner.Policy(maximumFeeLimitSun: h(), energyMarginPercent: rng.pick([0, 25, 100, 101, UInt64.max]), lifetimeSeconds: rng.pick([29, 30, 120, 1_800, 3_600, 3_601, UInt64.max]),547                                                maximumClockSkewSeconds: rng.pick([0, 300, 3_600, 3_601, UInt64.max]), maximumAmountSun: rng.bool() ? nil : h())548            }549            let planner = TronSendPlanner(policy: policy)550            let memo = rng.int(0...4) == 0 ? rng.bytes(rng.int(1...300)) : []551            let isToken = rng.bool()552            let plan: TronSendPlan553            let sendMax = rng.int(0...3) == 0554            do {555                if isToken {556                    let tokenAccount = TronAccount(address: Self.token, isActivated: rng.int(0...20) != 0, balanceSun: 0, isContract: rng.int(0...20) != 0)557                    let tokenBalance = UInt256(bigEndian: rng.bytes(rng.pick([0, 4, 8, 32])))!558                    let amount = rng.bool() ? tokenBalance : UInt256(bigEndian: rng.bytes(rng.pick([0, 1, 4, 8, 32])))!559                    let simulation = TronConstantResult(succeeded: rng.int(0...15) != 0, message: "", output: [], energyUsed: realistic ? UInt64(rng.int(0...200_000)) : h())560                    plan = try planner.planTokenTransfer(state: state, sender: senderAccount, resources: resources, recipient: recipient, token: tokenAccount,561                                                         tokenBalance: tokenBalance, amount: amount, simulation: simulation)562                    // token invariants563                    if plan.amount != amount || tokenBalance < amount || amount.isZero { fail("token amount") }564                    if plan.energyLimit < plan.energyEstimate || plan.energyEstimate != simulation.energyUsed || simulation.energyUsed == 0 { fail("energy limit under the estimate") }565                    let (fee, overflow) = plan.energyLimit.multipliedReportingOverflow(by: parameters.energyPriceSun)566                    if overflow || fee != plan.feeLimitSun || plan.transaction.feeLimit != fee { fail("fee limit is not energy limit × price") }567                    if plan.feeLimitSun > min(policy.maximumFeeLimitSun, parameters.maximumFeeLimitSun) { fail("fee limit above the ceiling") }568                    if plan.energyFeeSun > plan.feeLimitSun || plan.maximumDebitSun != plan.maximumFeeSun { fail("energy fee above the fee limit") }569                    guard case .trc20Transfer(let from, let contract, let to, let shown) = plan.review.action, from == sender, contract == Self.token, to == recipientAddress, shown == amount else {570                        fail("token review differs from the plan")571                        continue572                    }573                } else {574                    let asked: UInt64 = h()575                    plan = try planner.planTransfer(state: state, sender: senderAccount, resources: resources, recipient: recipient,576                                                    amount: sendMax ? .max : .exact(asked), memo: memo)577                    guard let sun = plan.amount.uint64, case .trxTransfer(let from, let to, let shown) = plan.review.action, from == sender, to == recipientAddress, shown == sun else {578                        fail("TRX review differs from the plan")579                        continue580                    }581                    if !sendMax, sun != asked { fail("amount differs from the one asked") }582                    if sun == 0 || sun > Self.int64Max { fail("amount out of range") }583                    if let cap = policy.maximumAmountSun, sun > cap { fail("amount above the policy limit") }584                    // amount + expected fee never above the balance; for send-max the amount is positive and leaves the fee585                    let (needed, overflow) = sun.addingReportingOverflow(plan.estimatedFeeSun)586                    if overflow || needed > balance { fail("amount + fee above the balance: \(sun) + \(plan.estimatedFeeSun) > \(balance)") }587                    let (debit, overflow2) = sun.addingReportingOverflow(plan.maximumFeeSun)588                    if overflow2 || debit != plan.maximumDebitSun { fail("maximum debit") }589                    if plan.feeLimitSun != 0 || plan.transaction.feeLimit != 0 || plan.energyFeeSun != 0 { fail("a TRX transfer has no fee limit") }590                    if plan.transaction.memo != memo || (memo.isEmpty && plan.memoFeeSun != 0) { fail("memo") }591                    if !recipient.isActivated, plan.activationFeeSun < parameters.accountActivationFeeSun { fail("activation fee under the chain parameter") }592                    if recipient.isActivated, plan.activationFeeSun != 0 { fail("activation fee for an activated recipient") }593                }594                planned += 1595                // common invariants of any plan596                if !policy.isValid { fail("a plan under an invalid policy") }597                if !senderAccount.isActivated || recipientAddress == sender || recipientAddress.isZero { fail("refusal missing") }598                if TronBuiltInTokens.token(recipientAddress, on: state.network) != nil { fail("token contract as recipient") }599                if plan.estimatedFeeSun > plan.maximumFeeSun { fail("expected fee above the maximum fee") }600                if plan.maximumFeeSun > Self.int64Max || plan.maximumDebitSun > Self.int64Max { fail("fee beyond int64") }601                let t = plan.transaction602                if t.expiration <= t.timestamp || t.expiration - t.timestamp != policy.lifetimeSeconds * 1000 || t.expiration - t.timestamp > 3_600_000 { fail("lifetime") }603                if t.timestamp != max(now, blockTime) || t.expiration > Self.int64Max { fail("timestamp") }604                if t.refBlockBytes != reference.refBlockBytes || t.refBlockHash != reference.refBlockHash || t.permissionID != 0 { fail("reference block") }605                if (now > blockTime ? now - blockTime : blockTime - now) > policy.maximumClockSkewSeconds * 1000 { fail("clock skew accepted") }606                if (try? TronTransaction.decode(rawData: t.rawData)) != t || plan.review.requiresBlindSigning { fail("the planned transaction is not canonical or needs blind signing") }607                if plan.bandwidthBytes != UInt64(t.bandwidthSize()) { fail("bandwidth size") }608            } catch let e as TronPlanError {609                refusals[String(describing: e).split(separator: "(").first.map(String.init) ?? "?", default: 0] += 1610            }611        }612        AuditRecorder.record(613            area: "property", name: "tron-planner-arithmetic", algorithm: "TRON send planner (TRX and TRC-20): fees, send-max, fee limit, lifetime",614            parameterSet: "realistic and hostile chain parameters, resources, balances, clocks and policies (values up to 2^64 − 1)", cases: cases, failed: failed, seed: seed,615            note: "\(planned) plans, every invariant held; refusals: " + refusals.sorted { $0.key < $1.key }.map { "\($0.key) \($0.value)" }.joined(separator: ", ")616                + (failures.isEmpty ? "" : "; first failures: " + failures.joined(separator: "; ")))617        #expect(failed == 0, "\(failures)")618        #expect(planned > cases / 50)619    }620621    /// Send-max on realistic states: what is planned is the most that leaves its own fee, and never the balance plus anything.622    @Test func sendMaxNeverExceedsTheBalance() throws {623        let seed = AuditSeed.make("tron-send-max")624        var rng = AuditRNG(seed: seed)625        var cases = 0, failed = 0, planned = 0626        let parameters = TronChainParameters(bandwidthPriceSun: 1_000, energyPriceSun: 420, accountActivationFeeSun: 1_000_000, createAccountFeeSun: 100_000,627                                             createAccountBandwidthRate: 1, maximumFeeLimitSun: 15_000_000_000, memoFeeSun: 1_000_000)628        let reference = TronBlockReference(number: 9, id: Endian.be64(9) + Bytes(repeating: 3, count: 24), timestamp: 1_800_000_000_000)!629        let state = TronSendPlanner.ChainState(network: .nile, parameters: parameters, reference: reference, nowMilliseconds: 1_800_000_001_000)630        for _ in 0..<AuditMode.cases(quick: 5_000, full: 100_000) {631            cases += 1632            let balance = rng.pick([0, 1, 999, 267_000, 268_000, 269_000, 1_100_000, 1_100_001, 1_367_000, 2_000_000, rng.next() >> UInt64(rng.int(1...60)), Self.int64Max, UInt64.max])633            let resources = TronResources(freeNetLimit: 600, freeNetUsed: UInt64(rng.pick([0, 300, 331, 332, 333, 600])), netLimit: UInt64(rng.pick([0, 0, 5_000])), netUsed: 0, energyLimit: 0, energyUsed: 0)634            let recipient = TronAccount(address: Self.recipient, isActivated: rng.bool(), balanceSun: 0, isContract: false)635            let memo = rng.int(0...3) == 0 ? rng.bytes(rng.int(1...256)) : []636            let plan = try? TronSendPlanner().planTransfer(state: state, sender: TronAccount(address: Self.owner, isActivated: true, balanceSun: balance, isContract: false),637                                                           resources: resources, recipient: recipient, amount: .max, memo: memo)638            guard let plan, let sun = plan.amount.uint64 else { continue }639            planned += 1640            let (total, overflow) = sun.addingReportingOverflow(plan.estimatedFeeSun)641            var ok = !overflow && total <= balance && sun > 0 && sun <= Self.int64Max642            // Nothing more could have been sent: one more sun does not fit with its own fee. (The amount's size changes643            // the fee, so at an encoding boundary the best amount legitimately leaves up to one bandwidth fee behind:644            // the remainder itself is not bounded here, the maximality is.)645            if ok, sun < min(balance, Self.int64Max) {646                let more = try? TronSendPlanner().planTransfer(state: state, sender: TronAccount(address: Self.owner, isActivated: true, balanceSun: balance, isContract: false),647                                                               resources: resources, recipient: recipient, amount: .exact(sun + 1), memo: memo)648                ok = more == nil649            }650            if !ok { failed += 1 }651        }652        AuditRecorder.record(area: "property", name: "tron-send-max", algorithm: "TRON send-max of TRX", parameterSet: "balances at the fee boundaries; free, staked and burned bandwidth; new and known recipients; memo",653                             cases: cases, failed: failed, seed: seed, note: "\(planned) plans")654        #expect(failed == 0 && planned > 0)655    }656657    // MARK: Signing, identity658659    @Test func theEngineSignsOnlyWhatItDecodesForTheOwnerKey() throws {660        let seed = AuditSeed.make("tron-signing-rules")661        var rng = AuditRNG(seed: seed)662        var cases = 0, failed = 0663        for _ in 0..<AuditMode.cases(quick: 600, full: 8_000) {664            cases += 1665            var tx = try Self.randomTransaction(&rng)666            let key = SHA256.hash(rng.bytes(32)), stranger = SHA256.hash(rng.bytes(32))667            let me = try TronAddress(publicKey: Secp256k1.publicKey(privateKey: key, compressed: false))668            // the same transaction owned by the key, when the contract has an owner the engine reads669            switch tx.contract {670            case .transfer(let c):671                tx = try TronTransaction(refBlockBytes: tx.refBlockBytes, refBlockHash: tx.refBlockHash, expiration: tx.expiration, timestamp: tx.timestamp, feeLimit: tx.feeLimit, memo: tx.memo,672                                         contract: .transfer(TronTransferContract(owner: me, to: c.to, amount: c.amount)), permissionID: tx.permissionID)673            case .triggerSmartContract(let c):674                tx = try TronTransaction(refBlockBytes: tx.refBlockBytes, refBlockHash: tx.refBlockHash, expiration: tx.expiration, timestamp: tx.timestamp, feeLimit: tx.feeLimit, memo: tx.memo,675                                         contract: .triggerSmartContract(TronTriggerSmartContract(owner: me, contract: c.contract, callValue: c.callValue, data: c.data,676                                                                                                   callTokenValue: c.callTokenValue, tokenID: c.tokenID)), permissionID: tx.permissionID)677            case .unknown: break678            }679            let review = TronTransactionReview(tx)680            var ok = true681            let plain = try? tx.sign(privateKey: key)682            let blind = try? tx.sign(privateKey: key, allowBlindSigning: true)683            if review.requiresBlindSigning {684                // never without the explicit flag685                ok = ok && plain == nil && blind != nil686            } else {687                ok = ok && plain != nil && plain == blind688            }689            if let signed = blind {690                ok = ok && signed.transaction == tx && (try? signed.signers()) == [me] && signed.signatures[0].count == 65691            }692            // another key never signs a transaction whose owner the engine reads693            if tx.owner != nil { ok = ok && (try? tx.sign(privateKey: stranger, allowBlindSigning: true)) == nil }694            // an invalid key signs nothing695            ok = ok && (try? tx.sign(privateKey: Bytes(repeating: 0, count: 32), allowBlindSigning: true)) == nil696            ok = ok && (try? tx.sign(privateKey: Bytes(repeating: 0xff, count: 32), allowBlindSigning: true)) == nil697            // what needs blind signing: exactly unknown contracts and calls that are not a plain transfer or approval698            switch review.action {699            case .trxTransfer, .trc20Transfer, .trc20Approve: ok = ok && !review.requiresBlindSigning700            case .contractCall, .unknownContract: ok = ok && review.requiresBlindSigning701            }702            if !ok { failed += 1 }703        }704        AuditRecorder.record(area: "property", name: "tron-signing-rules", algorithm: "TRON signing: owner check, blind-signing refusal, self-verification",705                             cases: cases, failed: failed, seed: seed)706        #expect(failed == 0)707    }708709    /// The transaction id changes with each field that binds the transaction: reference block, expiration, timestamp,710    /// owner, recipient, amount, token, fee limit, memo, permission. (Nothing in it names the network: see the711    /// replay-protection section of the review register.)712    @Test func theTransactionIDCoversEveryBindingField() throws {713        let seed = AuditSeed.make("tron-txid-binding")714        var rng = AuditRNG(seed: seed)715        var cases = 0, failed = 0716        for _ in 0..<AuditMode.cases(quick: 1_000, full: 20_000) {717            let a = TronAddress(hash: rng.bytes(20))!, b = TronAddress(hash: rng.bytes(20))!, c = TronAddress(hash: rng.bytes(20))!718            let ts = 1_800_000_000_000 + UInt64(rng.int(0...1_000_000))719            let amount = rng.next() >> 2 | 1720            func make(refBytes: Bytes = [1, 2], refHash: Bytes = Bytes(repeating: 9, count: 8), expiration: UInt64? = nil, timestamp: UInt64? = nil, from: TronAddress? = nil,721                      to: TronAddress? = nil, sun: UInt64? = nil, memo: Bytes = [], permission: UInt32 = 0, feeLimit: UInt64 = 0) throws -> TronTransaction {722                try TronTransaction(refBlockBytes: refBytes, refBlockHash: refHash, expiration: expiration ?? ts + 60_000, timestamp: timestamp ?? ts, feeLimit: feeLimit, memo: memo,723                                    contract: .transfer(TronTransferContract(owner: from ?? a, to: to ?? b, amount: sun ?? amount)), permissionID: permission)724            }725            let base = try make()726            let variants = [727                try make(refBytes: [1, 3]), try make(refHash: Bytes(repeating: 9, count: 7) + [8]), try make(expiration: ts + 60_001), try make(timestamp: ts - 1),728                try make(from: c), try make(to: c), try make(sun: amount + 1), try make(memo: [0]), try make(permission: 1), try make(feeLimit: 1),729            ]730            var ids = Set([base.txID])731            for v in variants {732                cases += 1733                if !ids.insert(v.txID).inserted || v.rawData == base.rawData { failed += 1 }734            }735            // the same fields give the same id (no randomness in the encoding), on every network736            cases += 1737            if try make().txID != base.txID { failed += 1 }738        }739        AuditRecorder.record(area: "property", name: "tron-txid-binding", algorithm: "TRON transaction id = SHA-256(raw_data)",740                             parameterSet: "reference block bytes and hash, expiration, timestamp, owner, recipient, amount, memo, permission id, fee limit", cases: cases, failed: failed, seed: seed)741        #expect(failed == 0)742    }743744    // MARK: Addresses745746    @Test func addressFormsRoundTripAndNothingElseParses() throws {747        let seed = AuditSeed.make("tron-address-forms")748        var rng = AuditRNG(seed: seed)749        var cases = 0, failed = 0750        let alphabet = Array("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")751        for _ in 0..<AuditMode.cases(quick: 3_000, full: 60_000) {752            cases += 1753            let a = TronAddress(hash: rng.bytes(20))!754            var ok = TronAddress(a.base58) == a && TronAddress(hex: a.hex) == a && TronAddress(bytes: a.bytes) == a && TronAddress(any: a.base58) == a && TronAddress(any: a.hex) == a755            ok = ok && a.base58.utf8.count == 34 && a.base58.hasPrefix("T") && a.hex.utf8.count == 42 && a.hex.hasPrefix("41") && a.bytes.count == 21756            ok = ok && TronAddress(evm: a.evm) == a && a.evm.bytes == a.hash757            // one character changed: the checksum refuses it758            var chars = Array(a.base58)759            let i = rng.int(0...33)760            let other = rng.pick(alphabet.filter { $0 != chars[i] })761            chars[i] = other762            ok = ok && TronAddress(String(chars)) == nil763            // forms that are not a TRON address for the Base58Check parser: hexadecimal, EVM, padded, wrong length764            let evmText = a.evm.checksummed765            for text in [a.hex, evmText, evmText.lowercased(), " " + a.base58, a.base58 + " ", a.base58 + "\n", String(a.base58.dropLast()), a.base58 + "1", "0x" + a.hex, ""] {766                ok = ok && TronAddress(text) == nil767            }768            // the EVM form is refused by every text initialiser: the same twenty bytes pasted from an EVM context are not a TRON address769            ok = ok && TronAddress(hex: evmText) == nil && TronAddress(any: evmText) == nil && TronAddress(hex: String(a.hex.dropFirst(2))) == nil && TronAddress(hex: "0x" + a.hex) == nil770            // other version bytes and lengths in protocol bytes771            ok = ok && TronAddress(bytes: [0x42] + a.hash) == nil && TronAddress(bytes: a.hash) == nil && TronAddress(bytes: a.bytes + [0]) == nil && TronAddress(hash: a.bytes) == nil772            // Codable: the Base58Check text, strictly773            let json = try JSONEncoder().encode([a])774            ok = ok && String(decoding: json, as: UTF8.self) == "[\"\(a.base58)\"]" && (try? JSONDecoder().decode([TronAddress].self, from: json)) == [a]775            ok = ok && (try? JSONDecoder().decode([TronAddress].self, from: Data("[\"\(a.hex)\"]".utf8))) == nil776            if !ok { failed += 1 }777        }778        AuditRecorder.record(area: "property", name: "tron-address-forms", algorithm: "TRON address text forms", parameterSet: "Base58Check, hexadecimal, EVM form, altered characters, white space, other version bytes",779                             cases: cases, failed: failed, seed: seed)780        #expect(failed == 0)781    }782783    // MARK: JSON, units, API key784785    static func randomJSON(_ rng: inout AuditRNG, depth: Int) -> TronJSON {786        switch rng.int(0...(depth > 3 ? 4 : 6)) {787        case 0: return .null788        case 1: return .bool(rng.bool())789        case 2: return .number(rng.pick(["0", "-1", "18446744073709551615", "9223372036854775807", "1.5", "1e9", "-0", String(rng.next())]))790        case 3, 4:791            let scalars: [String] = ["", "a", "\"", "\\", "/", "\u{08}\u{0c}\n\r\t", "é", "\u{1F600}", "\u{7f}", "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", String(rng.next(), radix: 16)]792            return .string(rng.pick(scalars) + rng.pick(scalars))793        case 5: return .array((0..<rng.int(0...4)).map { _ in randomJSON(&rng, depth: depth + 1) })794        default:795            var o = [String: TronJSON]()796            for _ in 0..<rng.int(0...4) { o[rng.pick(["a", "b", "balance", "", "\u{1F600}", "k\"", "x\\y"]) + String(rng.int(0...9))] = randomJSON(&rng, depth: depth + 1) }797            return .object(o)798        }799    }800801    @Test func jsonIsExactStrictAndBounded() {802        let seed = AuditSeed.make("tron-json")803        var rng = AuditRNG(seed: seed)804        var cases = 0, failed = 0805        func check(_ ok: Bool) {806            cases += 1807            if !ok { failed += 1 }808        }809        // integers: exact up to 2^64 − 1, nothing beyond, nothing that is not plain digits810        for (text, value) in [("0", UInt64(0)), ("9007199254740993", 9_007_199_254_740_993), ("9223372036854775807", UInt64(Int64.max)), ("18446744073709551615", UInt64.max)] {811            check(TronJSON.parse(Bytes(text.utf8))?.uint64 == value && TronJSON.parse(Bytes("\"\(text)\"".utf8))?.uint64 == value)812        }813        for text in ["18446744073709551616", "-1", "1.0", "1e3", "1E3", "0x10", "\" 1\"", "\"1 \"", "\"+1\"", "\"\"", "true", "null", "[1]", "99999999999999999999999999"] {814            check(TronJSON.parse(Bytes(text.utf8))?.uint64 == nil)815        }816        // strictness: what RFC 8259 does not allow, duplicate keys, lone surrogates, depth, long numbers, trailing content817        let invalid = ["", " ", "{", "[", "{\"a\":1,}", "[1,]", "{\"a\":1 \"b\":2}", "{'a':1}", "{a:1}", "01", "-", "1.", ".5", "+1", "1e", "tru", "nul", "NaN", "Infinity",818                       "\"\\x41\"", "\"\\ud800\"", "\"\\udc00\"", "\"\\ud800\\u0041\"", "\"a\nb\"", "\"abc", "{\"a\":1,\"a\":2}", "{\"a\":1}{\"a\":1}", "[1] 2", "1 1", "\u{feff}1",819                       String(repeating: "[", count: 60) + String(repeating: "]", count: 60), "1" + String(repeating: "0", count: 70), "\"\\u12\"", "{\"a\"}", "[1 2]", "{1:2}"]820        for text in invalid { check(TronJSON.parse(Bytes(text.utf8)) == nil) }821        check(TronJSON.parse([0x22, 0xff, 0x22]) == nil)                       // invalid UTF-8 in a string822        check(TronJSON.parse([0x22, 0xc0, 0x80, 0x22]) == nil)                 // over-long UTF-8823        check(TronJSON.parse(Bytes((String(repeating: "[", count: 49) + String(repeating: "]", count: 49)).utf8)) != nil)   // the depth limit itself824        check(TronJSON.parse(Bytes("\"\\ud83d\\ude00\"".utf8)) == .string("\u{1F600}"))825        check(TronJSON.parse(Bytes(" { \"a\" : [ 1 , true , null ] } ".utf8)) == .object(["a": .array([.number("1"), .bool(true), .null])]))826        // write then read is the identity827        for _ in 0..<AuditMode.cases(quick: 4_000, full: 60_000) {828            let value = Self.randomJSON(&rng, depth: 0)829            check(TronJSON.parse(value.serialized) == value)830        }831        // arbitrary bytes: an answer or nil, and an accepted document is stable through one more round832        for _ in 0..<AuditMode.cases(quick: 20_000, full: 300_000) {833            var bytes = rng.int(0...2) == 0 ? rng.bytes(rng.int(0...40)) : Bytes(Self.randomJSON(&rng, depth: 2).serialized)834            if !bytes.isEmpty, rng.bool() { bytes[rng.int(0...(bytes.count - 1))] = UInt8(truncatingIfNeeded: rng.next()) }835            if let parsed = TronJSON.parse(bytes) { check(TronJSON.parse(parsed.serialized) == parsed) } else { check(true) }836        }837        // units: text ↔ sun without floating point838        for (text, sun) in [("0", UInt64(0)), ("1", 1_000_000), ("0.000001", 1), ("1.5", 1_500_000), ("9223372036854.775807", UInt64(Int64.max))] {839            check(TronUnits.parseTRX(text) == sun && TronUnits.parseTRX(TronUnits.formatTRX(sun)) == sun)840        }841        for text in ["0.0000001", "9223372036854.775808", "-1", "1e3", "", " 1", "1,5", "18446744073709.551616"] { check(TronUnits.parseTRX(text) == nil) }842        AuditRecorder.record(area: "property", name: "tron-json-parser", algorithm: "TRON node JSON: exact integers, RFC 8259 strictness, bounds; TRX units",843                             cases: cases, failed: failed, seed: seed)844        #expect(failed == 0)845    }846847    @Test func theAPIKeyTypeHoldsNothingThatBreaksAHeaderAndNeverPrintsItself() {848        var cases = 0, failed = 0849        func check(_ ok: Bool) {850            cases += 1851            if !ok { failed += 1 }852        }853        let good = "0a1b2c3d-1111-2222-3333-444455556666"854        for text in [good, "ABCDEFGH", "abc_def-123", String(repeating: "a", count: 128)] {855            guard let key = TronAPIKey(text) else {856                check(false)857                continue858            }859            var dumped = ""860            dump(key, to: &dumped)861            let shown = ["\(key)", String(describing: key), String(reflecting: key), dumped, "\(Optional(key) as Any)", "\([key])"]862            check(shown.allSatisfy { !$0.contains(text) } && Mirror(reflecting: key).children.isEmpty)863        }864        for text in ["", "short", String(repeating: "a", count: 129), good + "\r\nX-Injected: 1", good + "\n", " " + good, good + " ", "key:value1", "key;value1", "kéy-12345", "key/12345",865                     "key 12345", "key\t12345", "key\u{0}12345", "\"key12345\"", good + "\u{202e}"] {866            check(TronAPIKey(text) == nil)867        }868        // endpoints: only https (or http to a local host), no query, no fragment869        check(TronEndpoints.bases(["https://api.trongrid.io/", "https://api.trongrid.io?x=1", "https://api.trongrid.io/#f", "http://api.trongrid.io", "ftp://api.trongrid.io", "api.trongrid.io"]).map(\.absoluteString)870            == ["https://api.trongrid.io"])871        AuditRecorder.record(area: "property", name: "tron-api-key-type", algorithm: "TronGrid API key: accepted characters, redaction in every textual form; endpoint URL rules", cases: cases, failed: failed)872        #expect(failed == 0)873    }874}875
Files main
Menu

Theme