SPB Git

Repository Public

TronDiffTests.swift 36.8 KB 591 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Tests/DifferentialAuditTests/TronDiffTests.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 against independent references (security/tests/oracles/mc/tron.py), random cases with a logged seed:53//54//   addresses        tronpy `PrivateKey(...).public_key.to_base58check_address()` (OpenSSL point, pycryptodome55//                    Keccak-256, the base58 package) and coincurve (libsecp256k1) for the same key;56//   address parsing  a strict rule written in the oracle (34 characters, "T", Base58Check, 21 bytes, prefix 0x41),57//                    and what tronpy itself accepts, which is more — the differences are counted and named;58//   raw_data         Google's protobuf runtime on the descriptors generated from the protocol's tron.proto, and a59//                    second encoder written by hand in the oracle; both must agree before the engine is compared;60//   signatures       coincurve (RFC 6979, low s) and tronpy's own signer: same r, s and recovery id, same signer;61//   decoding         every altered encoding is given to the protobuf runtime, which says what it read and whether62//                    the bytes are the canonical encoding of it; the engine must accept exactly the inputs that63//                    are canonical AND within its documented policy (`enginePolicy` below), and refuse the rest;64//   TRC-20 ABI       eth-abi;   derivation   bip-utils.6566@Suite struct TronDifferential {67    static let script = "tron"68    static let int64Max = UInt64(Int64.max)6970    static func address(_ rng: inout AuditRNG) -> TronAddress {71        TronAddress(hash: rng.bytes(20, orEdge: [Bytes(repeating: 0, count: 20), Bytes(repeating: 0xff, count: 20)], oneIn: 40))!72    }7374    static func amount(_ rng: inout AuditRNG) -> UInt64 {75        rng.pick([0, 1, 127, 128, 16_383, 16_384, 1_000_000, 9_007_199_254_740_991, int64Max - 1, int64Max, rng.next() >> UInt64(rng.int(1...63)), rng.next() >> 1])76    }7778    static func privateKey(_ rng: inout AuditRNG) -> Bytes {79        while true {80            let k = rng.bytes(32)81            if Secp256k1.isValidPrivateKey(k) { return k }82        }83    }8485    // MARK: Addresses8687    @Test func addressesFromPrivateKeys() throws {88        let name = "tron-address-from-private-key"89        guard MCOracle.available(Self.script, campaign: name, needs: ["tronpy", "coincurve"]) else { return }90        let seed = DiffSeed.make(name)91        var rng = AuditRNG(seed: seed)92        var tally = DiffTally(name, algorithm: "TRON address of a secp256k1 key", parameterSet: "Base58Check and hexadecimal forms, compressed and uncompressed public key",93                              oracle: MCOracle.label(Self.script, "tronpy", "OpenSSL, pycryptodome Keccak-256, base58") + ", " + MCOracle.label(Self.script, "coincurve", "libsecp256k1"), seed: seed)94        let keys = (0..<AuditMode.cases(quick: 400, full: 6000)).map { _ in Self.privateKey(&rng) }95        let answers = try MCOracle.batch(Self.script, "address", keys.map { ["sk": hex($0)] })96        for (sk, a) in zip(keys, answers) {97            let u = try? TronAddress(publicKey: Secp256k1.publicKey(privateKey: sk, compressed: false))98            let c = try? TronAddress(publicKey: Secp256k1.publicKey(privateKey: sk, compressed: true))99            var ok = u != nil && u == c && u?.base58 == a.string("base58") && u?.hex == a.string("hex")100            ok = ok && u?.base58 == a.string("base58_coincurve") && u?.hex == a.string("hex_coincurve")101            // and back through both text forms102            ok = ok && u.flatMap { TronAddress($0.base58) } == u && u.flatMap { TronAddress(hex: $0.hex) } == u103            tally.check(ok, "private_key=\(hex(sk)) ours=\(u?.base58 ?? "nil") reference=\(a)")104        }105        #expect(tally.finish() == 0)106    }107108    /// Texts around valid addresses: one character changed, case changed, cut, extended, another version byte, the109    /// hexadecimal forms, the EVM form, white space.110    static func addressTexts(_ rng: inout AuditRNG, count: Int) -> [String] {111        let alphabet = Array("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")112        var out = [String]()113        while out.count < count {114            let a = address(&rng)115            var chars = Array(a.base58)116            switch rng.int(0...15) {117            case 0, 1: break118            case 2: chars[rng.int(0...33)] = rng.pick(alphabet)119            case 3: chars[rng.int(1...33)] = rng.pick(Array("0OIl+/ ="))120            case 4:121                let i = rng.int(0...33)122                chars[i] = Character(chars[i].isUppercase ? chars[i].lowercased() : chars[i].uppercased())123            case 5: chars.removeLast(rng.int(1...3))124            case 6: chars.append(rng.pick(alphabet))125            case 7: chars = Array(rng.pick([" ", "\n", "\t"]) + String(chars)) + (rng.bool() ? [" "] : [])126            case 8: chars = Array(Base58Check.encode([rng.pick([0x00, 0x05, 0x42, 0x40, 0xa0, 0x1e])] + a.hash))127            case 9: chars = Array(Base58Check.encode(a.bytes + (rng.bool() ? [0] : [])).dropLast(rng.int(0...1)))128            case 10: chars = Array(a.hex)129            case 11: chars = Array(a.hex.uppercased())130            case 12: chars = Array("0x" + a.hex.dropFirst(2))131            case 13: chars = Array(a.hex.dropFirst(2))132            case 14: chars = Array("0x" + a.hex)133            default: chars = Array(Base58.bitcoin.encode(a.bytes + rng.bytes(4)))134            }135            out.append(String(chars))136        }137        return out138    }139140    @Test func addressParsing() throws {141        let name = "tron-address-parsing"142        guard MCOracle.available(Self.script, campaign: name, needs: ["tronpy", "base58"]) else { return }143        let seed = DiffSeed.make(name)144        var rng = AuditRNG(seed: seed)145        var tally = DiffTally(name, algorithm: "TRON address validation", parameterSet: "valid, altered, other version bytes, hexadecimal and EVM forms, white space",146                              oracle: "strict rule written in the oracle on " + MCOracle.label(Self.script, "base58") + "; " + MCOracle.label(Self.script, "tronpy") + " for the record of what it accepts", seed: seed)147        let texts = Self.addressTexts(&rng, count: AuditMode.cases(quick: 1200, full: 20000))148        let answers = try MCOracle.batch(Self.script, "parse", texts.map { ["text": $0] })149        var tronpyOnly = 0, tronpyEVM = 0, tronpyHex = 0, hexAccepted = 0150        for (text, a) in zip(texts, answers) {151            let strict = TronAddress(text)152            let viaHex = TronAddress(hex: text)153            tally.verdict(strict != nil)154            // the Base58Check initialiser is exactly the strict rule155            var ok = strict?.hex == a.string("strict")156            // whatever the engine accepts in either form, tronpy reads as the same 21 bytes157            if let any = TronAddress(any: text) { ok = ok && any.hex == a.string("tronpy") }158            // the hexadecimal initialiser: 42 hexadecimal digits starting with 41, nothing else159            let isHexForm = text.utf8.count == 42 && text.lowercased().hasPrefix("41") && text.utf8.allSatisfy { ($0 >= 0x30 && $0 <= 0x39) || ($0 | 0x20 >= 0x61 && $0 | 0x20 <= 0x66) }160            ok = ok && (viaHex != nil) == isHexForm161            if viaHex != nil { hexAccepted += 1 }162            // never an EVM-form text163            if text.hasPrefix("0x") { ok = ok && strict == nil && viaHex == nil }164            if strict == nil, a.string("tronpy") != nil {165                tronpyOnly += 1166                if text.hasPrefix("0x") { tronpyEVM += 1 } else if isHexForm { tronpyHex += 1 }167            }168            tally.check(ok, "text=\(text.debugDescription) ours=\(strict?.hex ?? "nil") hex_form=\(viaHex?.hex ?? "nil") reference=\(a)")169        }170        #expect(tally.finish() == 0)171        AuditRecorder.record(172            area: "differential", name: name + "-policy", algorithm: "TRON address validation: texts tronpy converts and the wallet's Base58Check parser refuses",173            oracle: MCOracle.label(Self.script, "tronpy"), cases: tronpyOnly, failed: 0, seed: seed,174            note: "policy difference, not a mismatch: \(tronpyEVM) EVM-form texts (0x…, which tronpy turns into a TRON address), \(tronpyHex) hexadecimal 41… texts "175                + "(the engine reads those only through init(hex:), \(hexAccepted) accepted there, and the wallet's recipient check refuses the form), "176                + "\(tronpyOnly - tronpyEVM - tronpyHex) others (tronpy does not check the version byte nor the length after decoding)")177    }178179    // MARK: Transactions180181    struct Built {182        let tx: TronTransaction183        let sk: Bytes184        let oracle: Case185    }186187    /// A random transaction as the wallet can build one (TRX transfer, TRC-20 transfer, or any contract call), with188    /// every integer at its edges, and the same thing as a case for the oracle.189    static func transaction(_ rng: inout AuditRNG) throws -> Built {190        let sk = privateKey(&rng)191        let owner = try TronAddress(publicKey: Secp256k1.publicKey(privateKey: sk, compressed: false))192        let to = address(&rng), contract = address(&rng)193        let refBytes = rng.bytes(2, orEdge: [[0, 0], [0xff, 0xff]], oneIn: 20), refHash = rng.bytes(8, orEdge: [Bytes(repeating: 0, count: 8)], oneIn: 20)194        let timestamp = rng.pick([0, 1, 1_800_000_000_000, int64Max - 86_400_000, rng.next() >> UInt64(rng.int(2...40))])195        let expiration = timestamp + rng.pick([1, 60_000, 120_000, 3_600_000, 86_400_000, UInt64(rng.int(1...86_400_000))])196        let memo = rng.int(0...3) == 0 ? rng.bytes(rng.pick([1, 2, 31, 127, 128, 255, 256])) : []197        let permission = rng.int(0...9) == 0 ? UInt32(rng.pick([1, 2, 127, 128, Int(Int32.max)])) : 0198        var oracle: Case = ["owner": owner.hex, "ref_bytes": hex(refBytes), "ref_hash": hex(refHash), "expiration": String(expiration), "timestamp": String(timestamp),199                            "memo": hex(memo), "permission": String(permission), "sk": hex(sk)]200        let tx: TronTransaction201        switch rng.int(0...2) {202        case 0:203            let sun = amount(&rng)204            oracle.merge(["kind": "trx", "to": to.hex, "amount": String(sun)]) { $1 }205            tx = try TronTransaction(refBlockBytes: refBytes, refBlockHash: refHash, expiration: expiration, timestamp: timestamp, memo: memo,206                                     contract: .transfer(TronTransferContract(owner: owner, to: to, amount: sun)), permissionID: permission)207        case 1:208            let value = UInt256(bigEndian: rng.bytes(rng.pick([0, 1, 8, 9, 31, 32]), orEdge: [Bytes(repeating: 0xff, count: 32)], oneIn: 12))!209            let feeLimit = amount(&rng)210            oracle.merge(["kind": "trc20", "to": to.hex, "contract": contract.hex, "amount": value.description, "fee_limit": String(feeLimit)]) { $1 }211            tx = try TronTransaction(refBlockBytes: refBytes, refBlockHash: refHash, expiration: expiration, timestamp: timestamp, feeLimit: feeLimit, memo: memo,212                                     contract: .triggerSmartContract(TronTriggerSmartContract(owner: owner, contract: contract, data: ERC20.transfer(to: to.evm, amount: value))),213                                     permissionID: permission)214        default:215            let data = rng.bytes(rng.pick([0, 1, 4, 36, 68, 100, 300]))216            let value = rng.bool() ? 0 : amount(&rng), tokenValue = rng.int(0...3) == 0 ? amount(&rng) : 0, tokenID = rng.int(0...3) == 0 ? amount(&rng) : 0217            let feeLimit = amount(&rng)218            oracle.merge(["kind": "trigger", "contract": contract.hex, "data": hex(data), "call_value": String(value), "token_value": String(tokenValue),219                          "token_id": String(tokenID), "fee_limit": String(feeLimit)]) { $1 }220            tx = try TronTransaction(refBlockBytes: refBytes, refBlockHash: refHash, expiration: expiration, timestamp: timestamp, feeLimit: feeLimit, memo: memo,221                                     contract: .triggerSmartContract(TronTriggerSmartContract(owner: owner, contract: contract, callValue: value, data: data,222                                                                                               callTokenValue: tokenValue, tokenID: tokenID)),223                                     permissionID: permission)224        }225        return Built(tx: tx, sk: sk, oracle: oracle)226    }227228    @Test func rawDataTransactionIDAndSignature() throws {229        let name = "tron-raw-data-txid-signature"230        guard MCOracle.available(Self.script, campaign: name, needs: ["tronpy", "coincurve", "protobuf", "eth-abi"]) else { return }231        let seed = DiffSeed.make(name)232        var rng = AuditRNG(seed: seed)233        var tally = DiffTally(name, algorithm: "TRON Transaction.raw encoding, transaction id, ECDSA signature, signed Transaction",234                              parameterSet: "TRX transfer, TRC-20 transfer, contract call; integers at the int64 edges; memo; permission id",235                              oracle: MCOracle.label(Self.script, "protobuf", "Google runtime on the tron.proto descriptors shipped by tronpy") + " + a second encoder written in the oracle; "236                                  + MCOracle.label(Self.script, "coincurve", "libsecp256k1, RFC 6979") + "; " + MCOracle.label(Self.script, "tronpy", "its OpenSSL signer and recovery") + "; "237                                  + MCOracle.label(Self.script, "eth-abi"), seed: seed)238        let built = try (0..<AuditMode.cases(quick: 1200, full: 12000)).map { _ in try Self.transaction(&rng) }239        let answers = try MCOracle.batch(Self.script, "raw", built.map(\.oracle))240        for (b, a) in zip(built, answers) {241            if let e = a.oracleError {242                tally.check(false, "the reference refused or its two encoders disagree: \(e) case=\(b.oracle)")243                continue244            }245            var ok = b.tx.rawData == a.bytes("raw") && b.tx.txID == a.bytes("txid") && b.tx.txID == SHA256.hash(b.tx.rawData)246            // the review is read back from the very bytes247            let again = try? TronTransaction.decode(rawData: b.tx.rawData)248            ok = ok && again == b.tx && again.map { TronTransactionReview($0) } == TronTransactionReview(b.tx) && TronTransactionReview(b.tx).rawData == b.tx.rawData249            // signature: the same r and s as libsecp256k1 and as tronpy, v = 27 + recovery id250            let blind = TronTransactionReview(b.tx).requiresBlindSigning251            let signed = try? b.tx.sign(privateKey: b.sk, allowBlindSigning: blind)252            if blind { ok = ok && (try? b.tx.sign(privateKey: b.sk)) == nil }253            if let s = signed?.signatures.first, let reference = a.bytes("sig"), let tronpy = a.bytes("sig_tronpy"), reference.count == 65 {254                ok = ok && Bytes(s[0..<64]) == Bytes(reference[0..<64]) && s[64] == 27 + reference[64] && tronpy == reference255                ok = ok && signed?.serialized == a.bytes("signed") && (try? signed?.signers().map(\.base58)) == [a.string("signer") ?? ""]256                ok = ok && signed.flatMap { try? SignedTronTransaction.decode($0.serialized) } == signed257            } else {258                ok = false259            }260            tally.check(ok, "case=\(b.oracle) ours_raw=\(hex(b.tx.rawData)) ours_signature=\(signed.map { hex($0.signatures[0]) } ?? "nil") reference=\(a)")261        }262        #expect(tally.finish() == 0)263    }264265    // MARK: Decoding of altered encodings266267    static func varint(_ value: UInt64, padding: Int = 0) -> Bytes {268        var v = value269        var out = Bytes()270        while v >= 0x80 {271            out.append(UInt8(v & 0x7f) | 0x80)272            v >>= 7273        }274        out.append(UInt8(v))275        // useless leading groups: the same value on more bytes276        if padding > 0 {277            out[out.count - 1] |= 0x80278            out += Bytes(repeating: 0x80, count: padding - 1) + [0]279        }280        return out281    }282283    /// The top-level fields of a message as (tag bytes ‖ value bytes) slices, when it parses as varint and284    /// length-delimited fields.285    static func fields(_ data: Bytes) -> [Bytes]? {286        var out = [Bytes]()287        var i = 0288        func readVarint() -> UInt64? {289            var v: UInt64 = 0290            var shift: UInt64 = 0291            while i < data.count, shift < 64 {292                let b = data[i]293                i += 1294                v |= UInt64(b & 0x7f) << shift295                if b & 0x80 == 0 { return v }296                shift += 7297            }298            return nil299        }300        while i < data.count {301            let start = i302            guard let tag = readVarint() else { return nil }303            switch tag & 7 {304            case 0: guard readVarint() != nil else { return nil }305            case 2:306                guard let n = readVarint(), n <= UInt64(data.count - i) else { return nil }307                i += Int(n)308            default: return nil309            }310            out.append(Bytes(data[start..<i]))311        }312        return out313    }314315    /// One alteration of valid `raw_data` bytes: some keep the structure (and are often still canonical), most break316    /// one rule of the encoding.317    static func alter(_ raw: Bytes, _ rng: inout AuditRNG) -> Bytes {318        var b = raw319        let parts = fields(raw) ?? []320        func joined(_ p: [Bytes]) -> Bytes { p.reduce(into: Bytes()) { $0 += $1 } }321        switch rng.int(0...19) {322        case 0: break323        case 1, 2: b[rng.int(0...(b.count - 1))] ^= UInt8(1) << UInt8(rng.int(0...7))324        case 3: b[rng.int(0...(b.count - 1))] = UInt8(truncatingIfNeeded: rng.next())325        case 4: b.removeLast(rng.int(1...min(8, b.count - 1)))326        case 5: b += rng.bytes(rng.int(1...4))327        case 6: b.insert(UInt8(truncatingIfNeeded: rng.next()), at: rng.int(0...b.count))328        case 7: b.remove(at: rng.int(0...(b.count - 1)))329        case 8 where parts.count > 1:330            // two fields swapped: the same content out of order331            var p = parts332            p.swapAt(rng.int(0...(p.count - 1)), rng.int(0...(p.count - 1)))333            b = joined(p)334        case 9 where !parts.isEmpty:335            // one field written twice336            var p = parts337            let i = rng.int(0...(p.count - 1))338            p.insert(p[i], at: rng.bool() ? i : p.count)339            b = joined(p)340        case 10:341            // a field of the protocol the wallet does not write, or one nobody defines, of each wire type342            let extra: [Bytes] = [[0x18, 0x01], [0x18, 0x00], [0x4a, 0x00], [0x4a, 0x02, 0x0a, 0x00], [0x62, 0x01, 0x00], [0x98, 0x06, 0x01], [0x9a, 0x06, 0x00],343                                  [0x19] + rng.bytes(8), [0x1d] + rng.bytes(4), [0x1b, 0x1c], [0x0a, 0x00], [0x40, 0x00], [0x70, 0x00], [0x90, 0x01, 0x00], [0x52, 0x00]]344            let e = rng.pick(extra)345            var p = parts346            p.insert(e, at: rng.int(0...p.count))347            b = joined(p)348        case 11 where !parts.isEmpty:349            // a non-minimal varint in a tag, a length or a value350            var p = parts351            let i = rng.int(0...(p.count - 1))352            let f = p[i]353            let pad = rng.int(1...3)354            if f[0] & 7 == 0, rng.bool() {355                // value of a varint field (single-byte tags only: fields 1 to 15)356                var j = 1357                while j < f.count, f[j] & 0x80 != 0 { j += 1 }358                if f[0] & 0x80 == 0, j < f.count {359                    var g = f360                    g[f.count - 1] |= 0x80361                    p[i] = g + Bytes(repeating: 0x80, count: pad - 1) + [0]362                }363            } else if f[0] & 0x80 == 0 {364                p[i] = [f[0] | 0x80] + Bytes(repeating: 0x80, count: pad - 1) + [0] + f.dropFirst()365            }366            b = joined(p)367        case 12 where !parts.isEmpty:368            // a field removed369            var p = parts370            p.remove(at: rng.int(0...(p.count - 1)))371            b = joined(p)372        case 13:373            // an over-long varint (eleven bytes) or one that overflows 64 bits, as a new field value374            let over: [Bytes] = [[0x40] + Bytes(repeating: 0xff, count: 10) + [0x01], [0x40] + Bytes(repeating: 0xff, count: 9) + [0x7f],375                                 [0x40] + Bytes(repeating: 0xff, count: 9) + [0x02], [0x40] + Bytes(repeating: 0xff, count: 9) + [0x01]]376            b = joined(parts.filter { $0.first != 0x40 }) + rng.pick(over)377        case 14:378            // a length prefix larger than what is left379            b += [0x52] + varint(rng.pick([1, 5, 1 << 20, 1 << 31, 1 << 32, UInt64(Int64.max), UInt64.max]))380        case 15 where raw.count > 12:381            // one byte changed inside the nested contract (addresses, amounts, type URL)382            b[rng.int((raw.count / 3)...(raw.count - 4))] = UInt8(truncatingIfNeeded: rng.next())383        default:384            let i = rng.int(0...(b.count - 1))385            b[i] = b[i] &+ 1386        }387        return b388    }389390    /// What the engine's decoder accepts, said from the facts the protobuf runtime reports: the canonical encodings391    /// of transactions made of the fields the wallet knows, within its ranges. Each line is one policy rule.392    static func enginePolicy(_ f: Case) -> Bool {393        func nonNegative(_ key: String, in c: Case) -> Bool { (c[key] as? String).map { !$0.hasPrefix("-") } ?? false }394        func isAddress(_ key: String, in c: Case) -> Bool { (c[key] as? String).map { $0.count == 42 && $0.hasPrefix("41") } ?? false }395        guard f.bool("parse") == true else { return false }                                   // well-formed protobuf396        guard f.bool("canonical") == true else { return false }                               // minimal varints, field order, no explicit default, no duplicate397        guard (f["unknown"] as? Int) == 0, (f["unknown_contract"] as? Int) == 0, (f["unknown_any"] as? Int) == 0 else { return false }   // no unknown field, no wrong wire type398        guard f.string("ref_block_num") == "0", (f["auths"] as? Int) == 0, f.string("scripts") == "" else { return false }               // protocol fields the wallet refuses399        guard (f["contracts"] as? Int) == 1 else { return false }                              // exactly one contract400        guard f.string("ref_bytes")?.count == 4, f.string("ref_hash")?.count == 16 else { return false }                                  // two and eight bytes401        guard nonNegative("expiration", in: f), nonNegative("timestamp", in: f), nonNegative("fee_limit", in: f), nonNegative("permission", in: f) else { return false }402        guard f.bool("has_parameter") == true, f.string("provider") == "", f.string("name") == "" else { return false }403        guard let type = f["type"] as? Int, type >= 0, let urlHex = f.string("url"), let url = Hex.decode(urlHex) else { return false }404        guard url.count <= 200, url.allSatisfy({ $0 >= 0x21 && $0 <= 0x7e }) else { return false }                                        // printable type URL405        let text = String(decoding: url, as: UTF8.self)406        let transferURL = "type.googleapis.com/protocol.TransferContract", triggerURL = "type.googleapis.com/protocol.TriggerSmartContract"407        switch type {408        case 1, 31:409            guard text == (type == 1 ? transferURL : triggerURL), let inner = f["inner"] as? Case else { return false }410            guard inner.bool("parse") == true, inner.bool("canonical") == true, (inner["unknown"] as? Int) == 0, isAddress("owner", in: inner) else { return false }411            if type == 1 { return isAddress("to", in: inner) && nonNegative("amount", in: inner) }412            return isAddress("contract", in: inner) && nonNegative("call_value", in: inner) && nonNegative("token_value", in: inner) && nonNegative("token_id", in: inner)413        default:414            return text != transferURL && text != triggerURL                                   // a known wrapper under another type number415        }416    }417418    @Test func decodingOfAlteredRawData() throws {419        let name = "tron-raw-data-decoding"420        guard MCOracle.available(Self.script, campaign: name, needs: ["tronpy", "protobuf"]) else { return }421        let seed = DiffSeed.make(name)422        var rng = AuditRNG(seed: seed)423        var tally = DiffTally(name, algorithm: "TRON Transaction.raw strict decoding", parameterSet: "valid encodings and twenty kinds of alteration",424                              oracle: MCOracle.label(Self.script, "protobuf", "Google runtime: parse, unknown-field sets, deterministic re-serialisation") + ", then the engine's policy stated in the test", seed: seed)425        var inputs = [Bytes]()426        for _ in 0..<AuditMode.cases(quick: 2000, full: 30000) {427            inputs.append(Self.alter(try Self.transaction(&rng).tx.rawData, &rng))428        }429        let answers = try MCOracle.batch(Self.script, "decode", inputs.map { ["raw": hex($0)] })430        for (raw, a) in zip(inputs, answers) {431            let ours: TronTransaction?432            var why = ""433            do {434                ours = try TronTransaction.decode(rawData: raw)435            } catch {436                ours = nil437                why = "\(error)"438            }439            tally.verdict(ours != nil)440            var ok = (ours != nil) == Self.enginePolicy(a)441            if let ours {442                // accepted: the bytes are the canonical encoding, the id is the reference's, and the fields are the ones the runtime read443                ok = ok && ours.rawData == raw && ours.txIDHex == a.string("txid")444                ok = ok && hex(ours.refBlockBytes) == a.string("ref_bytes") && hex(ours.refBlockHash) == a.string("ref_hash") && String(ours.expiration) == a.string("expiration")445                ok = ok && String(ours.timestamp) == a.string("timestamp") && String(ours.feeLimit) == a.string("fee_limit") && hex(ours.memo) == a.string("memo")446                ok = ok && Int(ours.contract.type) == a["type"] as? Int && String(ours.permissionID) == a.string("permission")447                let inner = a["inner"] as? Case448                switch ours.contract {449                case .transfer(let c):450                    ok = ok && c.owner.hex == inner?.string("owner") && c.to.hex == inner?.string("to") && String(c.amount) == inner?.string("amount")451                case .triggerSmartContract(let c):452                    ok = ok && c.owner.hex == inner?.string("owner") && c.contract.hex == inner?.string("contract") && String(c.callValue) == inner?.string("call_value")453                    ok = ok && hex(c.data) == inner?.string("data") && String(c.callTokenValue) == inner?.string("token_value") && String(c.tokenID) == inner?.string("token_id")454                case .unknown(_, let url, let value):455                    ok = ok && hex(Bytes(url.utf8)) == a.string("url") && hex(value) == a.string("value")456                }457            }458            tally.check(ok, "raw=\(hex(raw)) ours=\(ours == nil ? "refused (\(why))" : "accepted") policy=\(Self.enginePolicy(a)) reference=\(a)")459        }460        #expect(tally.finish() == 0)461        #expect(tally.accepted > 0 && tally.accepted < tally.judged)462    }463464    @Test func signedTransactionsAndSignerRecovery() throws {465        let name = "tron-signed-transaction-decoding"466        guard MCOracle.available(Self.script, campaign: name, needs: ["tronpy", "protobuf", "coincurve"]) else { return }467        let seed = DiffSeed.make(name)468        var rng = AuditRNG(seed: seed)469        var tally = DiffTally(name, algorithm: "TRON signed Transaction decoding and signer recovery", parameterSet: "zero to six signatures; v 0, 1, 27, 28 and others; high s; altered bytes",470                              oracle: MCOracle.label(Self.script, "protobuf", "Google runtime") + "; " + MCOracle.label(Self.script, "coincurve", "libsecp256k1 recovery"), seed: seed)471        let n = UInt256(bigEndian: Hex.decode("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141")!)!472        var inputs = [Bytes]()473        for _ in 0..<AuditMode.cases(quick: 800, full: 10000) {474            let b = try Self.transaction(&rng)475            let own = try b.tx.sign(privateKey: b.sk, allowBlindSigning: true).signatures[0]476            var signatures = [Bytes]()477            for _ in 0..<rng.pick([1, 1, 1, 0, 2, 5, 6]) {478                var s = rng.bool() ? own : try Secp256k1.sign(digest: b.tx.txID, privateKey: Self.privateKey(&rng)).compact + [UInt8(27 + rng.int(0...1))]479                switch rng.int(0...11) {480                case 0: s[64] = s[64] >= 27 ? s[64] - 27 : s[64]481                case 1: s[64] = rng.pick([2, 3, 26, 29, 35, 36, 255])482                case 2:483                    // the high-s twin484                    let high = n.subtractingReportingOverflow(UInt256(bigEndian: Bytes(s[32..<64]))!).0485                    s = Bytes(s[0..<32]) + high.bytes32 + [s[64] == 27 ? 28 : 27]486                case 3: s = Bytes(repeating: 0, count: 32) + Bytes(s[32...])487                case 4: s = Bytes(s[0..<32]) + Bytes(repeating: 0, count: 32) + [s[64]]488                case 5: s = Bytes(repeating: 0xff, count: 32) + Bytes(s[32...])489                case 6: s[rng.int(0...63)] ^= 1490                case 7: s = rng.bool() ? Bytes(s.dropLast()) : s + [0]491                default: break492                }493                signatures.append(s)494            }495            // the envelope written by hand, so that sizes and counts the engine's own type refuses can be tried496            var envelope = [0x0a] + Self.varint(UInt64(b.tx.rawData.count)) + b.tx.rawData497            for s in signatures { envelope += [0x12] + Self.varint(UInt64(s.count)) + s }498            switch rng.int(0...9) {499            case 0: envelope = Self.alter(envelope, &rng)500            case 1: envelope += [0x2a, 0x02, 0x08, 0x01]   // `ret`: what a node appends, not part of what is signed501            default: break502            }503            inputs.append(envelope)504        }505        let answers = try MCOracle.batch(Self.script, "signed", inputs.map { ["hex": hex($0)] })506        for (bytes, a) in zip(inputs, answers) {507            let ours = try? SignedTronTransaction.decode(bytes)508            tally.verdict(ours != nil)509            let signatures = (a["signatures"] as? [String]) ?? []510            let policy = a.bool("parse") == true && a.bool("canonical") == true && (a["unknown"] as? Int) == 0 && a.bool("has_raw") == true511                && signatures.count <= 5 && signatures.allSatisfy { $0.count == 130 } && Self.enginePolicy((a["raw_facts"] as? Case) ?? [:])512            var ok = (ours != nil) == policy513            if let ours {514                ok = ok && ours.serialized == bytes && hex(ours.transaction.rawData) == a.string("raw") && ours.txIDHex == a.string("txid") && ours.signatures.map(hex) == signatures515                // signers: all of them, in order, or none when one signature recovers to nothing516                let reference = (a["signers"] as? [Any])?.map { $0 as? String }517                let mine = try? ours.signers().map(\.base58)518                if let reference, reference.allSatisfy({ $0 != nil }) { ok = ok && mine == reference.compactMap { $0 } } else { ok = ok && mine == nil }519            }520            tally.check(ok, "signed=\(hex(bytes)) ours=\(ours == nil ? "refused" : "accepted") policy=\(policy) reference=\(a)")521        }522        #expect(tally.finish() == 0)523        #expect(tally.accepted > 0 && tally.accepted < tally.judged)524    }525526    // MARK: TRC-20 call data and derivation527528    @Test func trc20CallData() throws {529        let name = "tron-trc20-call-data"530        guard MCOracle.available(Self.script, campaign: name, needs: ["eth-abi"]) else { return }531        let seed = DiffSeed.make(name)532        var rng = AuditRNG(seed: seed)533        var tally = DiffTally(name, algorithm: "TRC-20 transfer / approve call data (ABI)", parameterSet: "encoding of transfer(address,uint256); decoding of valid and altered call data",534                              oracle: MCOracle.label(Self.script, "eth-abi", "strict decoding"), seed: seed)535        var inputs = [(to: TronAddress, amount: UInt256, data: Bytes)]()536        for _ in 0..<AuditMode.cases(quick: 800, full: 10000) {537            let to = Self.address(&rng)538            let amount = UInt256(bigEndian: rng.bytes(rng.pick([0, 1, 8, 16, 31, 32]), orEdge: [Bytes(repeating: 0xff, count: 32)], oneIn: 10))!539            var data = rng.bool() ? ERC20.transfer(to: to.evm, amount: amount) : ERC20.approve(spender: to.evm, amount: amount)540            switch rng.int(0...9) {541            case 0: data[rng.int(0...3)] ^= UInt8(1) << UInt8(rng.int(0...7))542            case 1: data[rng.int(4...15)] = UInt8(truncatingIfNeeded: rng.next() | 1)543            case 2: data.removeLast(rng.int(1...32))544            case 3: data += rng.bytes(rng.int(1...32))545            case 4: data = rng.bytes(rng.pick([0, 3, 4, 36, 68]))546            default: break547            }548            inputs.append((to, amount, data))549        }550        let encoded = try MCOracle.batch(Self.script, "abi_transfer", inputs.map { ["to": $0.to.hex, "amount": $0.amount.description] })551        let decoded = try MCOracle.batch(Self.script, "abi_decode", inputs.map { ["data": hex($0.data)] })552        for ((i, e), d) in zip(zip(inputs, encoded), decoded) {553            var ok = ERC20.transfer(to: i.to.evm, amount: i.amount) == e.bytes("data")554            // the call a TriggerSmartContract carries, as the review reads it555            let call = TronTriggerSmartContract(owner: i.to, contract: i.to, data: i.data).trc20Call556            tally.verdict(call != nil)557            switch call {558            case .transfer(let to, let amount)?:559                ok = ok && d.string("call") == "transfer" && "0x" + hex(to.bytes) == d.string("address") && amount.description == d.string("amount")560            case .approve(let spender, let amount)?:561                ok = ok && d.string("call") == "approve" && "0x" + hex(spender.bytes) == d.string("address") && amount.description == d.string("amount")562            case nil:563                ok = ok && d["call"] is NSNull564            }565            // TRX or a TRC-10 token attached: never presented as a plain token transfer566            ok = ok && TronTriggerSmartContract(owner: i.to, contract: i.to, callValue: 1, data: i.data).trc20Call == nil567            ok = ok && TronTriggerSmartContract(owner: i.to, contract: i.to, data: i.data, callTokenValue: 1, tokenID: 1_000_001).trc20Call == nil568            tally.check(ok, "data=\(hex(i.data)) ours=\(String(describing: call)) reference=\(d)")569        }570        #expect(tally.finish() == 0)571    }572573    @Test func accountDerivation() throws {574        let name = "tron-account-derivation"575        guard MCOracle.available(Self.script, campaign: name, needs: ["bip-utils"]) else { return }576        let seed = DiffSeed.make(name)577        var rng = AuditRNG(seed: seed)578        var tally = DiffTally(name, algorithm: "TRON account m/44'/195'/0'/0/i from a BIP-39 seed", oracle: MCOracle.label(Self.script, "bip-utils", "BIP-32, BIP-44 TRON"), seed: seed)579        var inputs = [(seed: Bytes, index: UInt32)]()580        for _ in 0..<AuditMode.cases(quick: 60, full: 600) { inputs.append((rng.bytes(64), UInt32(rng.pick([0, 0, 1, 2, 19, 1000])))) }581        let answers = try MCOracle.batch(Self.script, "derive", inputs.map { ["seed": hex($0.seed), "index": Int($0.index)] })582        for (i, a) in zip(inputs, answers) {583            let key = try? ExtendedKey.master(seed: i.seed).derive(TronPaths.account(index: i.index))584            let address = key.flatMap { try? TronAddress(publicKey: $0.publicKey) }585            tally.check(address != nil && address?.base58 == a.string("address") && key?.privateKey.map(hex) == a.string("private"),586                        "seed=\(hex(i.seed)) index=\(i.index) ours=\(address?.base58 ?? "nil") reference=\(a)")587        }588        #expect(tally.finish() == 0)589    }590}591
Files main
Menu

Theme