Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Tests/ConformanceAuditTests/TronVectors.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 conformance: fixed vectors.53//54// 1. 1 103 transactions of the public chain (three main-network blocks, two Nile blocks) exactly as55// `/wallet/getblockbynum` served them (security/vectors/tron/): the transaction id the chain gives must be56// SHA-256 of the `raw_data` bytes, the strict decoder must give those very bytes back when it accepts, every57// refusal must be one of the documented policy refusals, and each 65-byte signature must recover to an address;58// 2. the ten transactions TronWeb built and signed for the first account of the "abandon … about" phrase59// (Tests/QyvoraTronTests/ReferenceVectors.swift, read from that file): same bytes, same id, and — the nonce60// being deterministic (RFC 6979) and s low on both sides — the very same 65-byte signature from the key the61// engine derives at m/44'/195'/0'/0/0;62// 3. addresses: published Base58Check / hexadecimal pairs, the address of well-known private keys and the BIP-4463// account of fixed seeds, derived again at test time by tronpy, coincurve and bip-utils;64// 4. the genesis block ids of the three networks, against the values read from five public endpoints on65// 2026-12-05 and against the chain ids of TIP-474 (the last four bytes of the genesis block hash);66// 5. the signature format: r ‖ s ‖ v on 65 bytes, v = 27 + recovery id, low s; which v the verifier takes.6768@Suite struct TronConformance {69 static let script = "tron"70 static let abandon = ["abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "about"]7172 static func accountKey(seed: Bytes, index: UInt32 = 0) throws -> (privateKey: Bytes, address: TronAddress) {73 let key = try ExtendedKey.master(seed: seed).derive(TronPaths.account(index: index))74 guard let secret = key.privateKey else { throw AuditVectors.LoadError("no private key") }75 return (secret, try TronAddress(publicKey: key.publicKey))76 }7778 // MARK: 1. Transactions of the public chain7980 @Test func chainTransactions() throws {81 let name = "tron-chain-transactions"82 let url = AuditPaths.vectors.appendingPathComponent("tron/chain-transactions.json.gz")83 guard FileManager.default.fileExists(atPath: url.path) else {84 AuditRecorder.notRun(area: "conformance", name: name, reason: "security/vectors/tron/chain-transactions.json.gz is missing")85 return86 }87 guard let root = try AuditVectors.json(url) as? [String: Any], let blocks = root["blocks"] as? [[String: Any]] else {88 throw AuditVectors.LoadError("unexpected layout of chain-transactions.json.gz")89 }90 var cases = 0, failed = 0, decoded = 0, refusedScripts = 0, otherRefusals = 091 var signatures = 0, recovered = 0, byOwner = 0, oddSignatures = 0, signedRoundTrips = 092 var kinds = [String: Int]()93 var firstFailure = ""94 func fail(_ what: String) {95 failed += 196 if firstFailure.isEmpty { firstFailure = what }97 }98 for block in blocks {99 for t in block["transactions"] as? [[String: Any]] ?? [] {100 cases += 1101 guard let raw = t.hex("raw_data_hex"), let id = t["txID"] as? String, let type = t["type"] as? String else {102 fail("malformed vector")103 continue104 }105 // the identity the chain gives: SHA-256 of raw_data106 guard Hex.encode(SHA256.hash(raw)) == id else {107 fail("txID \(id): SHA-256 of raw_data differs")108 continue109 }110 let tx: TronTransaction111 do {112 tx = try TronTransaction.decode(rawData: raw)113 } catch TronProtobufError.unknownField(message: "Transaction.raw", field: 12) {114 // `scripts`: a field of the protocol the wallet never writes; such a transaction is not shown115 refusedScripts += 1116 continue117 } catch {118 otherRefusals += 1119 fail("txID \(id): refused with \(error)")120 continue121 }122 decoded += 1123 guard tx.rawData == raw, tx.txIDHex == id else {124 fail("txID \(id): decode then encode changed the bytes")125 continue126 }127 // what the review says against what the node's JSON says128 let review = TronTransactionReview(tx)129 let owner = (t["owner"] as? String).flatMap { TronAddress(hex: $0) }130 let permission = (t["permission_id"] as? Int) ?? 0131 var consistent = Int(review.permissionID) == permission132 switch review.action {133 case .trxTransfer(let from, _, _):134 kinds["TRX transfer", default: 0] += 1135 consistent = consistent && type == "TransferContract" && from == owner136 case .trc20Transfer(let from, _, _, _):137 kinds["TRC-20 transfer", default: 0] += 1138 consistent = consistent && type == "TriggerSmartContract" && from == owner139 case .trc20Approve(let from, _, _, _):140 kinds["TRC-20 approve", default: 0] += 1141 consistent = consistent && type == "TriggerSmartContract" && from == owner142 case .contractCall(let from, _, _, _, _, _):143 kinds["other contract call", default: 0] += 1144 consistent = consistent && type == "TriggerSmartContract" && from == owner && review.requiresBlindSigning145 case .unknownContract(_, let typeName, _, _):146 kinds["other contract type", default: 0] += 1147 consistent = consistent && typeName == type && review.requiresBlindSigning && review.owner == nil148 }149 if !consistent { fail("txID \(id): the review does not match the node's JSON (\(type))") }150 // signatures: 65 bytes each must recover to an address; other sizes are refused by the envelope151 let sigs = (t["signature"] as? [String] ?? []).compactMap { Hex.decode($0) }152 if sigs.contains(where: { $0.count != 65 }) {153 oddSignatures += 1154 if SignedTronTransaction(transaction: tx, signatures: sigs) != nil { fail("txID \(id): a signature that is not 65 bytes was accepted") }155 continue156 }157 guard let signed = SignedTronTransaction(transaction: tx, signatures: sigs) else {158 fail("txID \(id): \(sigs.count) signatures refused")159 continue160 }161 signatures += sigs.count162 if let signers = try? signed.signers() {163 recovered += signers.count164 if let owner, signers.contains(owner) { byOwner += 1 }165 } else {166 fail("txID \(id): a signature of the chain does not recover")167 }168 if (try? SignedTronTransaction.decode(signed.serialized)) == signed { signedRoundTrips += 1 } else { fail("txID \(id): signed envelope round trip") }169 }170 }171 let summary = kinds.sorted { $0.key < $1.key }.map { "\($0.value) \($0.key)" }.joined(separator: ", ")172 AuditRecorder.record(173 area: "conformance", name: name, algorithm: "TRON Transaction.raw decoding, transaction id, signature recovery",174 parameterSet: "main network blocks 65000000, 70000000, 70000001; Nile blocks 50000001, 50000003",175 oracle: "the public chain (TronGrid /wallet/getblockbynum, 2026-12-05): txID and raw_data_hex of each transaction",176 cases: cases, failed: failed,177 note: "\(decoded) decoded and re-encoded to the same bytes (\(summary)); \(refusedScripts) refused by policy (field 12 `scripts`); "178 + "\(signatures) signatures of 65 bytes, \(recovered) recovered, \(byOwner) transactions signed by the key of the owner address "179 + "(the others use account permissions with other keys); \(oddSignatures) transactions carry a signature that is not 65 bytes "180 + "(refused by the signed envelope, shown from raw_data only); \(signedRoundTrips) signed envelopes round-tripped"181 + (firstFailure.isEmpty ? "" : "; first failure: \(firstFailure)"))182 #expect(failed == 0, "\(firstFailure)")183 #expect(cases == 1103 && decoded + refusedScripts == cases && otherRefusals == 0)184 #expect(recovered == signatures && signatures > 1000)185 }186187 // MARK: 2. TronWeb vectors of the module188189 struct ModuleVector {190 let name: String, from: String, rawDataHex: String, txID: String, signature: String191 }192193 /// The `Transaction(…)` entries of Tests/QyvoraTronTests/ReferenceVectors.swift, read from the source text.194 static func moduleVectors() throws -> [ModuleVector] {195 let url = AuditPaths.repo.appendingPathComponent("Tests/QyvoraTronTests/ReferenceVectors.swift")196 let text = try String(contentsOf: url, encoding: .utf8)197 func field(_ name: String, in block: Substring) -> String? {198 guard let start = block.range(of: "\(name): \"") else { return nil }199 let rest = block[start.upperBound...]200 guard let end = rest.firstIndex(of: "\"") else { return nil }201 return String(rest[..<end])202 }203 var out = [ModuleVector]()204 for block in text.components(separatedBy: "Transaction(name: ").dropFirst() {205 let b = Substring("name: " + block)206 guard let name = field("name", in: b), let from = field("from", in: b), let raw = field("rawDataHex", in: b), let id = field("txID", in: b),207 let signature = field("signature", in: b) else { continue }208 out.append(ModuleVector(name: name, from: from, rawDataHex: raw, txID: id, signature: signature))209 }210 return out211 }212213 @Test func tronWebTransactions() throws {214 let name = "tron-tronweb-transactions"215 let vectors = try Self.moduleVectors()216 let account = try Self.accountKey(seed: try BIP39.seed(mnemonic: Self.abandon))217 var failed = 0218 var firstFailure = ""219 for v in vectors {220 var ok = false221 if let raw = Hex.decode(v.rawDataHex), let reference = Hex.decode(v.signature), let tx = try? TronTransaction.decode(rawData: raw) {222 ok = tx.rawData == raw && tx.txIDHex == v.txID && Hex.encode(SHA256.hash(raw)) == v.txID223 ok = ok && tx.owner?.base58 == v.from && account.address.base58 == v.from224 // the same signature as TronWeb, byte for byte, from the key derived here225 let signed = try? tx.sign(privateKey: account.privateKey)226 ok = ok && signed?.signatures == [reference]227 // and TronWeb's signature recovers to the account228 ok = ok && (try? SignedTronTransaction(transaction: tx, signatures: [reference])?.signers()) == [account.address]229 }230 if !ok {231 failed += 1232 if firstFailure.isEmpty { firstFailure = v.name }233 }234 }235 AuditRecorder.record(236 area: "conformance", name: name, algorithm: "TRON raw_data, transaction id and ECDSA signature (RFC 6979, low s, v = 27 + recovery id)",237 parameterSet: "TRX transfers (with and without memo), TRC-20 transfer and approve; account m/44'/195'/0'/0/0 of the test phrase",238 oracle: "TronWeb (vectors recorded in Tests/QyvoraTronTests/ReferenceVectors.swift)", cases: vectors.count, failed: failed,239 note: firstFailure.isEmpty ? "" : "first failure: \(firstFailure)")240 #expect(failed == 0, "\(firstFailure)")241 #expect(vectors.count == 10)242 }243244 // MARK: 3. Addresses245246 /// Published pairs: Base58Check form and the hexadecimal form of the node API.247 static let pairs: [(String, String, String)] = [248 ("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb", "410000000000000000000000000000000000000000", "the zero address"),249 ("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "41a614f803b6fd780986a42c78ec9c7f77e6ded13c", "USDT contract (main network)"),250 ("TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "41eca9bc828a3005b9a3b909f2cc5c2a54794de05f", "USDT contract (Nile)"),251 ("TLa2f6VPqDgRE67v1736s7bJ8Ray5wYjU7", "4174472e7d35395a6b5add427eecb7f4b62ad2b071", "an account of the public chain"),252 ("TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC", "417e5f4552091a69125d5dfcb7b8c2659029395bdf", "private key 1"),253 ]254255 @Test func addresses() throws {256 let name = "tron-address-vectors"257 var cases = 0, failed = 0258 func check(_ ok: Bool) {259 cases += 1260 if !ok { failed += 1 }261 }262 for (base58, hexForm, _) in Self.pairs {263 let a = TronAddress(base58), h = TronAddress(hex: hexForm)264 check(a != nil && a == h && a?.base58 == base58 && a?.hex == hexForm && a?.bytes.first == 0x41 && a?.bytes.count == 21)265 // the EVM form of the same twenty bytes is not a TRON address for any initialiser266 let evm = "0x" + hexForm.dropFirst(2)267 check(TronAddress(evm) == nil && TronAddress(hex: evm) == nil && TronAddress(any: evm) == nil && TronAddress(hex: String(hexForm.dropFirst(2))) == nil)268 }269 // private key 1: the generator point, Keccak-256 of X ‖ Y, last twenty bytes behind 0x41270 let one = Bytes(repeating: 0, count: 31) + [1]271 check((try? TronAddress(publicKey: Secp256k1.publicKey(privateKey: one, compressed: false)))?.base58 == "TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC")272 check((try? TronAddress(publicKey: Secp256k1.publicKey(privateKey: one, compressed: true)))?.base58 == "TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC")273 // the built-in tokens and the burn address parse, and are what the table above says274 check(TronBuiltInTokens.mainnet.count == 2 && TronBuiltInTokens.mainnet.first?.contract.hex == "41a614f803b6fd780986a42c78ec9c7f77e6ded13c")275 check(TronNetwork.mainnet.burnAddress?.base58 == "TLsV52sRDL79HXGGm9yzwKibb6BeruhUzy")276 // the derivation path printed on the recovery sheet277 check(TronPaths.account().description == "m/44'/195'/0'/0/0" && TronNetwork.allCases.allSatisfy { $0.coinType == 195 })278 check((try? Self.accountKey(seed: try BIP39.seed(mnemonic: Self.abandon)).address.base58) == "TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH")279 AuditRecorder.record(280 area: "conformance", name: name, algorithm: "TRON address (Base58Check of 0x41 ‖ Keccak-256(public key)[12...]), BIP-44 coin type 195",281 oracle: "published address pairs; tronscan.org; TronWeb (account of the test phrase)", cases: cases, failed: failed)282 #expect(failed == 0)283 }284285 @Test func addressesAndDerivationAgainstTheReferences() throws {286 let name = "tron-address-derivation-references"287 guard MCOracle.available(Self.script, campaign: name, area: "conformance", needs: ["tronpy", "coincurve", "bip-utils"]) else { return }288 var cases = 0, failed = 0289 var firstFailure = ""290 func check(_ ok: Bool, _ what: @autoclosure () -> String) {291 cases += 1292 if !ok {293 failed += 1294 if firstFailure.isEmpty { firstFailure = what() }295 }296 }297 // private keys at the edges of the scalar range298 let n = Hex.decode("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141")!299 var keys: [Bytes] = [Bytes(repeating: 0, count: 31) + [1], Bytes(repeating: 0, count: 31) + [2], Bytes(repeating: 0, count: 30) + [1, 0]]300 var nMinus1 = n301 nMinus1[31] -= 1302 keys.append(nMinus1)303 keys.append(Bytes(repeating: 0x7f, count: 32))304 keys.append(SHA256.hash(Bytes("qyvora tron audit".utf8)))305 let answers = try MCOracle.batch(Self.script, "address", keys.map { ["sk": Hex.encode($0)] })306 for (sk, a) in zip(keys, answers) {307 let ours = try? TronAddress(publicKey: Secp256k1.publicKey(privateKey: sk, compressed: false))308 check(ours != nil && ours?.base58 == a["base58"] as? String && ours?.hex == a["hex"] as? String309 && ours?.base58 == a["base58_coincurve"] as? String && ours?.hex == a["hex_coincurve"] as? String, "private key \(Hex.encode(sk)): \(a)")310 }311 // the account of fixed seeds, indices 0 to 4312 let seeds: [Bytes] = [try BIP39.seed(mnemonic: Self.abandon), try BIP39.seed(mnemonic: Self.abandon, passphrase: "TREZOR"), Bytes((0..<64).map { UInt8($0) })]313 var asked = [[String: Any]]()314 var mine = [(Bytes, TronAddress)]()315 for seed in seeds {316 for index in UInt32(0)..<5 {317 asked.append(["seed": Hex.encode(seed), "index": Int(index)])318 mine.append(try Self.accountKey(seed: seed, index: index))319 }320 }321 for ((key, address), a) in zip(mine, try MCOracle.batch(Self.script, "derive", asked)) {322 check(address.base58 == a["address"] as? String && Hex.encode(key) == a["private"] as? String, "derivation: ours \(address.base58), reference \(a)")323 }324 AuditRecorder.record(325 area: "conformance", name: name, algorithm: "TRON address from a private key; BIP-32/BIP-44 account m/44'/195'/0'/0/i",326 oracle: MCOracle.label(Self.script, "tronpy", "OpenSSL point, pycryptodome Keccak-256") + ", " + MCOracle.label(Self.script, "coincurve", "libsecp256k1")327 + ", " + MCOracle.label(Self.script, "bip-utils", "BIP-44 TRON"),328 cases: cases, failed: failed, note: firstFailure.isEmpty ? "" : "first failure: \(firstFailure)")329 #expect(failed == 0, "\(firstFailure)")330 }331332 // MARK: 4. Chain identity333334 /// Block id of block 0 as answered on 2026-12-05 by: api.trongrid.io and tron-rpc.publicnode.com (main network),335 /// nile.trongrid.io and api.nileex.io (Nile), api.shasta.trongrid.io (Shasta) — and the chain id TIP-474 gives336 /// each network for `eth_chainId` (the last four bytes of the genesis block hash).337 static let genesis: [(TronNetwork, String, UInt32)] = [338 (.mainnet, "00000000000000001ebf88508a03865c71d452e25f4d51194196a1d22b6653dc", 0x2b66_53dc),339 (.nile, "0000000000000000d698d4192c56cb6be724a558448e2684802de4d6cd8690dc", 0xcd86_90dc),340 (.shasta, "0000000000000000de1aa88295e1fcf982742f773e0419c5a9c134c994a9059e", 0x94a9_059e),341 ]342343 @Test func genesisBlocks() {344 var failed = 0345 for (network, id, chainID) in Self.genesis {346 let bytes = Hex.decode(network.genesisBlockID) ?? []347 let ok = network.genesisBlockID == id && bytes.count == 32 && bytes.prefix(8).allSatisfy { $0 == 0 }348 && bytes.suffix(4).reduce(UInt32(0)) { $0 << 8 | UInt32($1) } == chainID349 && TronBlockReference(number: 0, id: bytes, timestamp: 0) != nil350 if !ok { failed += 1 }351 }352 let distinct = Set(TronNetwork.allCases.map(\.genesisBlockID)).count == TronNetwork.allCases.count353 AuditRecorder.record(354 area: "conformance", name: "tron-genesis-block-ids", algorithm: "TRON chain identity (block id of block 0)",355 oracle: "five public endpoints read on 2026-12-05; TIP-474 chain ids (0x2b6653dc, 0xcd8690dc, 0x94a9059e)",356 cases: Self.genesis.count + 1, failed: failed + (distinct ? 0 : 1),357 note: "Shasta has a single public endpoint: its constant has one live source and the TIP-474 chain id")358 #expect(failed == 0 && distinct && Self.genesis.count == TronNetwork.allCases.count)359 }360361 // MARK: 5. Signature format362363 @Test func signatureFormat() throws {364 let n = UInt256(bigEndian: Hex.decode("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141")!)!365 let half = UInt256(bigEndian: Hex.decode("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0")!)!366 var cases = 0, failed = 0367 func check(_ ok: Bool) {368 cases += 1369 if !ok { failed += 1 }370 }371 for i in 0..<64 {372 let sk = SHA256.hash(Bytes("tron signature format \(i)".utf8))373 let owner = try TronAddress(publicKey: Secp256k1.publicKey(privateKey: sk, compressed: false))374 let to = TronAddress(hash: Bytes(SHA256.hash([UInt8(i)]).prefix(20)))!375 let tx = try TronTransaction(refBlockBytes: [UInt8(i), 1], refBlockHash: Bytes(repeating: UInt8(i), count: 8), expiration: 1_800_000_060_000,376 timestamp: 1_800_000_000_000, contract: .transfer(TronTransferContract(owner: owner, to: to, amount: UInt64(i) + 1)))377 let signed = try tx.sign(privateKey: sk)378 let s = signed.signatures[0]379 let sValue = UInt256(bigEndian: Bytes(s[32..<64]))!380 check(signed.signatures.count == 1 && s.count == 65 && (s[64] == 27 || s[64] == 28) && !(half < sValue) && !sValue.isZero)381 check((try? signed.signers()) == [owner] && signed.isSignedByOwner && signed.txID == SHA256.hash(tx.rawData))382 // the same signature twice (deterministic nonce)383 check((try? tx.sign(privateKey: sk)) == signed)384 // v = 0 / 1 is accepted like 27 / 28 (the network takes both); anything else is refused385 let plain = SignedTronTransaction(transaction: tx, signatures: [Bytes(s[0..<64]) + [s[64] - 27]])386 check((try? plain?.signers()) == [owner])387 for v: UInt8 in [2, 3, 26, 29, 30, 35, 36, 255] {388 check((try? SignedTronTransaction(transaction: tx, signatures: [Bytes(s[0..<64]) + [v]])?.signers()) == nil)389 }390 // the other recovery id gives another address, never the owner391 let flipped = SignedTronTransaction(transaction: tx, signatures: [Bytes(s[0..<64]) + [s[64] == 27 ? 28 : 27]])392 check(flipped?.isSignedByOwner == false)393 // the high-s twin (n − s, other recovery id) is the same signature for the curve: it recovers to the owner too.394 // Stated as a fact about the verifier, which the network shares; the wallet itself only ever writes low s.395 let twin = Bytes(s[0..<32]) + n.subtractingReportingOverflow(sValue).0.bytes32 + [s[64] == 27 ? 28 : 27]396 check((try? SignedTronTransaction(transaction: tx, signatures: [twin])?.signers()) == [owner])397 // a key that is not the owner's is refused before anything is signed398 check((try? tx.sign(privateKey: SHA256.hash(sk))) == nil)399 }400 AuditRecorder.record(401 area: "conformance", name: "tron-signature-format", algorithm: "TRON transaction signature: r ‖ s ‖ v, 65 bytes, v = 27 + recovery id, low s",402 oracle: "java-tron / TronWeb convention (v 27/28; 0/1 also accepted); RFC 6979", cases: cases, failed: failed,403 note: "the verifier recovers the high-s twin of a signature to the same signer, as the network does: a transaction id does not cover the signature, so this is not a malleability of the id")404 #expect(failed == 0)405 }406}407