Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Sources/FuzzTargets/Targets+Tron.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// 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 QyvoraNetworking47import QyvoraSecp256k148import QyvoraSymmetric49@testable import QyvoraTron50@testable import QyvoraWallet5152// TRON: everything that reads bytes or text the wallet did not write itself.53//54// tron-protobuf the strict protobuf reader (tags, varints, lengths): accepted input re-encodes to itself;55// tron-raw-data `Transaction.raw` → transaction → review → the same bytes;56// tron-signed-transaction the signed envelope, its signatures and the signers they recover to;57// tron-address the Base58Check and hexadecimal text forms;58// tron-json every answer of a node or of the history index the client reads (letter selector);59// tron-abi TRC-20 call data and returned data;60// tron-review the unsigned bytes a cold device receives: review, then signature of what was reviewed.61//62// The keys below are derived from fixed labels: test material, public by construction.6364let tronFuzzKey = SHA256.hash(Bytes("qyfuzz tron account".utf8))65let tronFuzzOwner: TronAddress = (try? TronAddress(publicKey: Secp256k1.publicKey(privateKey: tronFuzzKey, compressed: false))) ?? .zero66let tronFuzzRecipient = TronAddress(hash: Bytes(repeating: 0x33, count: 20)) ?? .zero67let tronFuzzToken = TronAddress("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t") ?? .zero68/// The clock of the fuzz wallet (`MCFuzzWallet.fixedNow`), in milliseconds.69let tronFuzzNow: UInt64 = 1_800_000_000_0007071func tronFuzzTransactions(owner: TronAddress = tronFuzzOwner) -> [TronTransaction] {72 let ts = tronFuzzNow, exp = tronFuzzNow + 600_00073 let voteURL = "type.googleapis.com/protocol.VoteWitnessContract"74 let candidates: [TronTransaction?] = [75 try? TronTransaction(refBlockBytes: [0x26, 0x60], refBlockHash: Bytes(repeating: 0xaf, count: 8), expiration: exp, timestamp: ts,76 contract: .transfer(TronTransferContract(owner: owner, to: tronFuzzRecipient, amount: 1_500_000))),77 try? TronTransaction(refBlockBytes: [0xff, 0xff], refBlockHash: Bytes(repeating: 0, count: 8), expiration: exp, timestamp: ts, memo: Bytes("rent".utf8),78 contract: .transfer(TronTransferContract(owner: owner, to: tronFuzzRecipient, amount: UInt64(Int64.max)))),79 try? TronTransaction(refBlockBytes: [0x00, 0x01], refBlockHash: Bytes(repeating: 1, count: 8), expiration: exp, timestamp: ts, feeLimit: 30_000_000,80 contract: .triggerSmartContract(TronTriggerSmartContract(owner: owner, contract: tronFuzzToken, data: ERC20.transfer(to: tronFuzzRecipient.evm, amount: UInt256(25_000_000))))),81 try? TronTransaction(refBlockBytes: [0x00, 0x02], refBlockHash: Bytes(repeating: 2, count: 8), expiration: exp, timestamp: ts, feeLimit: 100_000_000,82 contract: .triggerSmartContract(TronTriggerSmartContract(owner: owner, contract: tronFuzzToken, data: ERC20.approve(spender: tronFuzzRecipient.evm, amount: .max)))),83 try? TronTransaction(refBlockBytes: [0x00, 0x03], refBlockHash: Bytes(repeating: 3, count: 8), expiration: exp, timestamp: ts, feeLimit: 5_000_000,84 contract: .triggerSmartContract(TronTriggerSmartContract(owner: owner, contract: tronFuzzToken, callValue: 7, data: [0xde, 0xad, 0xbe, 0xef], callTokenValue: 3, tokenID: 1_000_001)),85 permissionID: 2),86 try? TronTransaction(refBlockBytes: [0x00, 0x04], refBlockHash: Bytes(repeating: 4, count: 8), expiration: exp, timestamp: ts,87 contract: .unknown(type: 4, typeURL: voteURL, value: [0x0a, 0x15] + owner.bytes + [0x12, 0x04, 0x08, 0x01, 0x10, 0x02])),88 ]89 return candidates.compactMap { $0 }90}9192func tronSignedSeeds() -> [Bytes] {93 var out = [Bytes]()94 for tx in tronFuzzTransactions() {95 if let signed = try? tx.sign(privateKey: tronFuzzKey, allowBlindSigning: true) {96 out.append(signed.serialized)97 // v as 0 / 1, two signatures, none98 let s = signed.signatures[0]99 if let plain = SignedTronTransaction(transaction: tx, signatures: [Bytes(s[0..<64]) + [s[64] - 27]]) { out.append(plain.serialized) }100 if let two = SignedTronTransaction(transaction: tx, signatures: [s, Bytes(repeating: 0x11, count: 65)]) { out.append(two.serialized) }101 }102 if let none = SignedTronTransaction(transaction: tx, signatures: []) { out.append(none.serialized) }103 }104 return out105}106107func tronJSONSeeds() -> [Bytes] {108 let a = tronFuzzOwner, tx = tronFuzzTransactions()109 let id = tx.first?.txIDHex ?? String(repeating: "ab", count: 32)110 let rawHex = Hex.encode(tx.first?.rawData ?? [])111 let block = #"{"blockID":"00000000045e795daa66025ed5d34821c5dfbc2af3333c1b117c4d8b24fc3b4b","block_header":{"raw_data":{"timestamp":1796447373000,"number":73300317,"version":32},"witness_signature":"00"}}"#112 let texts = [113 "0" + #"{"address":"\#(a.hex)","balance":2000000000,"create_time":1700000000000,"type":"Contract","account_resource":{}}"#,114 "0{}",115 "1" + #"{"freeNetLimit":600,"freeNetUsed":123,"NetLimit":5000,"NetUsed":17,"EnergyLimit":90000,"EnergyUsed":1,"TotalNetLimit":43200000000}"#,116 "2" + block,117 "2" + #"{"blockID":"\#(TronNetwork.nile.genesisBlockID)","block_header":{"raw_data":{"txTrieRoot":"00"}}}"#,118 "3" + #"{"chainParameter":[{"key":"getCreateAccountFee","value":100000},{"key":"getTransactionFee","value":1000},{"key":"getCreateNewAccountFeeInSystemContract","value":1000000},{"key":"getCreateNewAccountBandwidthRate","value":1},{"key":"getEnergyFee","value":100},{"key":"getMaxFeeLimit","value":15000000000},{"key":"getMemoFee","value":1000000},{"key":"getAllowTvmCancun"}]}"#,119 "4" + #"{"result":{"result":true},"energy_used":29650,"constant_result":["0000000000000000000000000000000000000000000000000000000000000006"],"transaction":{"ret":[{}]}}"#,120 "4" + #"{"result":{"result":true,"message":"52455645525420 6f70636f6465206578656375746564"},"energy_used":500,"constant_result":[""],"transaction":{"ret":[{"ret":"FAILED"}]}}"#,121 "4" + #"{"result":{"code":"CONTRACT_VALIDATE_ERROR","message":"536d61727420636f6e7472616374206973206e6f742065786973742e"}}"#,122 "4" + #"{"result":{"result":true},"energy_used":1300,"constant_result":["0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000455534454000000000000000000000000000000000000000000000000000000000"]}"#,123 "5" + #"{"id":"\#(id)","fee":1100000,"blockNumber":73300317,"blockTimeStamp":1796447373000,"receipt":{"result":"SUCCESS","energy_usage_total":29650,"energy_fee":2965000,"net_fee":345000},"resMessage":"","txID":"\#(id)","raw_data_hex":"\#(rawHex)","ret":[{"contractRet":"SUCCESS"}]}"#,124 "5" + #"{"id":"\#(id)","result":"FAILED","resMessage":"4f55545f4f465f454e45524759","receipt":{"result":"OUT_OF_ENERGY"}}"#,125 "5{}",126 "6" + #"{"data":[{"txID":"\#(id)","raw_data_hex":"\#(rawHex)","ret":[{"contractRet":"SUCCESS","fee":1100000}],"block_timestamp":1796447373000,"blockNumber":73300317,"raw_data":{"contract":[{"parameter":{"value":{"owner_address":"\#(a.hex)"}}}]}}],"success":true,"meta":{"at":1796447373000,"fingerprint":"abcDEF123","page_size":1}}"#,127 "7" + #"{"data":[{"transaction_id":"\#(id)","token_info":{"symbol":"USDT","address":"\#(tronFuzzToken.base58)","decimals":6,"name":"Tether USD"},"block_timestamp":1796447373000,"from":"\#(a.base58)","to":"\#(tronFuzzRecipient.base58)","type":"Transfer","value":"25000000"}],"success":true,"meta":{"at":1796447373000,"page_size":1}}"#,128 "8" + #"{"result":true,"code":"SUCCESS","txid":"\#(id)","message":""}"#,129 "8" + #"{"code":"DUP_TRANSACTION_ERROR","txid":"\#(id)","message":"4475702074726e73616374696f6e2e"}"#,130 "8" + #"{"code":"SIGERROR","message":"76616c6964617465207369676e6174757265206572726f72"}"#,131 "8" + #"{"Error":"class org.tron.core.exception.BadItemException : something"}"#,132 "9" + #"{"visible":false,"txID":"\#(id)","raw_data_hex":"\#(rawHex)","raw_data":{}}"#,133 "a" + block,134 "b" + #"{"a":[1,-2.5e3,true,null,"😀é"],"b":{"c":"18446744073709551615"}}"#,135 ]136 return texts.map { Bytes(letterSelector($0).utf8) }137}138139func tronABISeeds() -> [Bytes] {140 let word6 = UInt256(6).bytes32141 let symbol = UInt256(32).bytes32 + UInt256(4).bytes32 + Bytes("USDT".utf8) + Bytes(repeating: 0, count: 28)142 return [143 [0x00] + ERC20.transfer(to: tronFuzzRecipient.evm, amount: UInt256(25_000_000)),144 [0x00] + ERC20.approve(spender: tronFuzzRecipient.evm, amount: .max),145 [0x00] + ERC20.balanceOf(tronFuzzOwner.evm),146 [0x01] + word6,147 [0x02] + symbol,148 [0x02] + Bytes("MKR".utf8) + Bytes(repeating: 0, count: 29),149 ]150}151152func tronReviewSeeds() -> [Bytes] {153 guard let w = MCFuzzWallet.shared, let me = TronAddress(w.profile.tronAddress ?? "") else { return [] }154 return tronFuzzTransactions(owner: me).map(\.rawData) + tronFuzzTransactions().prefix(1).map(\.rawData)155}156157/// Text from a server that the client hands to the interface: bounded, without control characters.158func tronFuzzClean(_ text: String, limit: Int = 200) -> Bool {159 text.unicodeScalars.count <= limit && text.unicodeScalars.allSatisfy { $0.value >= 0x20 && $0.value != 0x7f }160}161162let tronTargets: [FuzzTarget] = [163 FuzzTarget(164 "tron-protobuf", "Strict protobuf reader of the TRON module: tags, varints, length-delimited fields; whatever is read to the end re-encodes to the input",165 maxLength: 512, tokens: [[0x0a, 0x02], [0x22, 0x08], [0x40], [0x5a], [0x70], [0x90, 0x01], [0x80, 0x00], [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01], [0x12, 0x41], [0x08, 0x1f]],166 seeds: { tronFuzzTransactions().map(\.rawData) + tronSignedSeeds().prefix(4) + [[0x08, 0x01], [0x0a, 0x00], [0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01]] }167 ) { input in168 var reader = ProtoReader(input)169 var writer = ProtoWriter()170 var count = 0171 do {172 while let (field, value) = try reader.next() {173 count += 1174 fuzzCheck(field >= 1 && field <= 0x1fff_ffff, "field number out of range")175 switch value {176 case .varint(let v):177 writer.bytes += ProtoWriter.varint(UInt64(field) << 3)178 writer.bytes += ProtoWriter.varint(v)179 case .bytes(let b):180 fuzzCheck(b.count <= input.count, "a field longer than the input")181 writer.message(field, b)182 }183 fuzzCheck(writer.bytes.count <= input.count, "more was read than the input holds")184 }185 } catch {186 FuzzOutcome.note(error: error)187 return188 }189 FuzzOutcome.note("fields\(min(count, 6))")190 fuzzCheck(writer.bytes == input, "an accepted message does not re-encode to itself")191 // a single varint: minimal, and the writer gives it back192 var one = ProtoReader(input)193 if let v = try? one.varint(), one.isAtEnd { fuzzCheck(ProtoWriter.varint(v) == input, "a varint is not minimal") }194 },195 FuzzTarget(196 "tron-raw-data", "TRON Transaction.raw: strict decoding, review of what was decoded, canonical re-encoding, transaction id",197 maxLength: 1024,198 dictionary: ["type.googleapis.com/protocol.TransferContract", "type.googleapis.com/protocol.TriggerSmartContract", "type.googleapis.com/protocol."],199 tokens: [[0x0a, 0x02], [0x22, 0x08], [0x40], [0x52], [0x5a], [0x70], [0x90, 0x01], [0x08, 0x01], [0x08, 0x1f], [0x28, 0x02], [0x0a, 0x15, 0x41], [0x12, 0x15, 0x41], [0xa9, 0x05, 0x9c, 0xbb],200 [0x09, 0x5e, 0xa7, 0xb3], [0x18, 0x03], [0x4a, 0x00], [0x62, 0x00], [0x80, 0x00], [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f]],201 seeds: { tronFuzzTransactions().map(\.rawData) }202 ) { input in203 let tx: TronTransaction204 do {205 tx = try TronTransaction.decode(rawData: input)206 } catch {207 FuzzOutcome.note(error: error)208 return209 }210 fuzzCheck(tx.rawData == input, "an accepted transaction does not re-encode to its bytes")211 fuzzCheck(tx.txID == SHA256.hash(input) && tx.txID.count == 32, "the transaction id is not SHA-256 of the bytes")212 fuzzCheck(tx.refBlockBytes.count == 2 && tx.refBlockHash.count == 8, "reference block fields of another size")213 let limit = UInt64(Int64.max)214 fuzzCheck(tx.expiration <= limit && tx.timestamp <= limit && tx.feeLimit <= limit && tx.permissionID <= UInt32(Int32.max), "an integer beyond the protocol's range")215 let review = TronTransactionReview(tx)216 fuzzCheck(review.rawData == input && review.txID == tx.txID && review.owner == tx.owner, "the review is not the review of these bytes")217 fuzzCheck(review.feeLimitSun == tx.feeLimit && review.expiration == tx.expiration && review.memo == tx.memo && review.signatureCount == 0, "the review misreports a field")218 switch (tx.contract, review.action) {219 case (.transfer(let c), .trxTransfer(let from, let to, let amount)):220 FuzzOutcome.note("trx")221 fuzzCheck(from == c.owner && to == c.to && amount == c.amount && amount <= limit && !review.requiresBlindSigning, "TRX transfer misread")222 case (.triggerSmartContract(let c), .trc20Transfer(let from, let token, let to, let amount)):223 FuzzOutcome.note("trc20")224 fuzzCheck(from == c.owner && token == c.contract && c.callValue == 0 && c.callTokenValue == 0 && c.tokenID == 0 && !review.requiresBlindSigning, "TRC-20 transfer misread")225 fuzzCheck(c.data == ERC20.transfer(to: to.evm, amount: amount), "the token transfer shown is not the call data")226 case (.triggerSmartContract(let c), .trc20Approve(let owner, let token, let spender, let amount)):227 FuzzOutcome.note("approve")228 fuzzCheck(owner == c.owner && token == c.contract && c.callValue == 0 && c.callTokenValue == 0 && c.tokenID == 0, "approval misread")229 fuzzCheck(c.data == ERC20.approve(spender: spender.evm, amount: amount), "the approval shown is not the call data")230 fuzzCheck(review.warnings.contains(.unlimitedApproval) == ERC20.isUnlimited(amount), "unlimited approval not flagged")231 case (.triggerSmartContract(let c), .contractCall(let owner, let contract, let value, let data, let tokenValue, let tokenID)):232 FuzzOutcome.note("call")233 fuzzCheck(owner == c.owner && contract == c.contract && value == c.callValue && data == c.data && tokenValue == c.callTokenValue && tokenID == c.tokenID, "contract call misread")234 fuzzCheck(review.requiresBlindSigning, "a contract call the wallet cannot show is not blind signing")235 case (.unknown(let type, let url, let value), .unknownContract(let shownType, _, let shownURL, let shownValue)):236 FuzzOutcome.note("unknown")237 fuzzCheck(type == shownType && url == shownURL && value == shownValue && type != 1 && type != 31 && review.requiresBlindSigning && tx.owner == nil, "unknown contract misread")238 fuzzCheck(url.utf8.count <= 200 && url.utf8.allSatisfy { $0 >= 0x21 && $0 <= 0x7e }, "a type URL that cannot be shown")239 default:240 fuzzFail("the review shows another kind of contract than the transaction holds")241 }242 fuzzCheck(review.warnings.contains(.nonOwnerPermission) == (tx.permissionID != 0) && review.warnings.contains(.memo) == !tx.memo.isEmpty, "warnings")243 if let text = review.memoText { fuzzCheck(Bytes(text.utf8) == tx.memo && tronFuzzClean(text, limit: 16_384), "memo text") }244 fuzzCheck(tx.bandwidthSize() > input.count && tx.bandwidthSize() <= input.count + 200, "bandwidth size")245 // signing: only for the owner, never blind without the flag246 if review.requiresBlindSigning {247 fuzzCheck((try? tx.sign(privateKey: tronFuzzKey)) == nil, "blind signing without the flag")248 } else if tx.owner != tronFuzzOwner {249 fuzzCheck((try? tx.sign(privateKey: tronFuzzKey, allowBlindSigning: true)) == nil, "signed for another owner")250 } else if let signed = try? tx.sign(privateKey: tronFuzzKey) {251 FuzzOutcome.note("signed")252 fuzzCheck(signed.transaction == tx && signed.isSignedByOwner && (try? SignedTronTransaction.decode(signed.serialized)) == signed, "signature of the decoded transaction")253 } else {254 fuzzFail("the owner key does not sign a transaction the wallet decodes")255 }256 },257 FuzzTarget(258 "tron-signed-transaction", "TRON signed Transaction: strict decoding, signature sizes, signer recovery, canonical re-encoding",259 maxLength: 1500,260 tokens: [[0x0a], [0x12, 0x41], [0x2a, 0x02, 0x08, 0x01], [0x1b], [0x1c], [0x00], [0x01], [0x0a, 0x02], [0x5a], [0x80, 0x00]],261 seeds: tronSignedSeeds262 ) { input in263 let signed: SignedTronTransaction264 do {265 signed = try SignedTronTransaction.decode(input)266 } catch {267 FuzzOutcome.note(error: error)268 return269 }270 fuzzCheck(signed.serialized == input && Bytes(signed.hex.utf8).count == input.count * 2, "an accepted envelope does not re-encode to its bytes")271 fuzzCheck(signed.signatures.count <= SignedTronTransaction.maximumSignatures && signed.signatures.allSatisfy { $0.count == 65 }, "signature count or size")272 fuzzCheck((try? TronTransaction.decode(rawData: signed.transaction.rawData)) == signed.transaction && signed.txID == SHA256.hash(signed.transaction.rawData), "inner transaction")273 let review = TronTransactionReview(signed)274 fuzzCheck(review.signatureCount == signed.signatures.count && review.txID == signed.txID, "review of the envelope")275 if let signers = try? signed.signers() {276 FuzzOutcome.note("signers\(signers.count)")277 fuzzCheck(signers.count == signed.signatures.count && review.signers == signers, "one signer per signature")278 for s in signed.signatures { fuzzCheck([0, 1, 27, 28].contains(s[64]), "a recovery byte outside 0, 1, 27, 28 recovered") }279 fuzzCheck(signed.isSignedByOwner == (signed.transaction.owner.map { signers.contains($0) } ?? false), "isSignedByOwner")280 if let owner = signed.transaction.owner, !signed.signatures.isEmpty {281 fuzzCheck(review.warnings.contains(.notSignedByOwner) == !signers.contains(owner), "notSignedByOwner")282 }283 // a signature that verifies for the fuzz key can only be over this very transaction id284 if signers.contains(tronFuzzOwner) { FuzzOutcome.note("by-fuzz-key") }285 } else {286 FuzzOutcome.note("no-signers")287 fuzzCheck(!signed.signatures.isEmpty && !signed.isSignedByOwner && review.signers.isEmpty, "signers failed without a signature")288 }289 },290 FuzzTarget(291 "tron-address", "TRON address text: Base58Check (34 characters, T…), hexadecimal (41…), and what must never parse (EVM form, other version bytes, padding)",292 maxLength: 80, text: true,293 dictionary: ["T", "41", "0x", "0X", "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb", "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "410000000000000000000000000000000000000000", " ", "\n", "O", "0", "I", "l"],294 seeds: {295 let a = tronFuzzOwner296 return [a.base58, a.hex, a.hex.uppercased(), "0x" + a.hex.dropFirst(2), a.evm.checksummed, String(a.hex.dropFirst(2)), "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb",297 Base58Check.encode([0x00] + a.hash), Base58Check.encode([0x42] + a.hash), " " + a.base58, a.base58 + "\n"].map { Bytes($0.utf8) }298 }299 ) { input in300 let text = fuzzString(input)301 let strict = TronAddress(text), viaHex = TronAddress(hex: text), any = TronAddress(any: text)302 fuzzCheck(any == (strict ?? viaHex), "init(any:) is not one of the two forms")303 if let a = strict {304 FuzzOutcome.note("base58")305 fuzzCheck(a.base58 == text && text.utf8.count == 34 && text.hasPrefix("T") && a.bytes.count == 21 && a.bytes[0] == 0x41, "Base58Check form is not canonical")306 fuzzCheck(TronAddress(bytes: a.bytes) == a && TronAddress(hex: a.hex) == a && viaHex == nil, "round trip")307 }308 if let a = viaHex {309 FuzzOutcome.note("hex")310 fuzzCheck(a.hex == text.lowercased() && text.utf8.count == 42 && input.count == 42 && (input[0] == 0x34 && input[1] == 0x31), "hexadecimal form is not 41 and forty digits")311 fuzzCheck(TronAddress(a.base58) == a, "round trip")312 }313 if strict == nil, viaHex == nil { FuzzOutcome.note("refused") }314 // the EVM form of an address is never a TRON address315 if text.hasPrefix("0x") || text.hasPrefix("0X") { fuzzCheck(any == nil, "an EVM-form text parsed as a TRON address") }316 if let json = try? JSONEncoder().encode([text]), let decoded = try? JSONDecoder().decode([TronAddress].self, from: json) {317 fuzzCheck(decoded == [strict].compactMap { $0 } && strict != nil, "Codable accepts another form than Base58Check")318 }319 fuzzUse(TronUnits.parseTRX(text))320 fuzzUse(TronAPIKey(text) == nil)321 },322 FuzzTarget(323 "tron-json", "Answers of a TRON node and of the TronGrid history index, behind a selector: account, resources, blocks and chain identity, chain parameters, constant calls and TRC-20 reads, transaction status, history pages, broadcast, node-built transaction, reference block, raw JSON",324 maxLength: 4096, text: true,325 dictionary: ["\"address\":", "\"balance\":", "\"type\":\"Contract\"", "\"blockID\":", "\"block_header\":{\"raw_data\":{", "\"number\":", "\"timestamp\":", "\"chainParameter\":[", "\"key\":", "\"value\":",326 "getTransactionFee", "getEnergyFee", "getMaxFeeLimit", "getCreateNewAccountFeeInSystemContract", "getCreateAccountFee", "getCreateNewAccountBandwidthRate", "getMemoFee",327 "\"result\":{\"result\":true}", "\"constant_result\":[", "\"energy_used\":", "\"message\":", "\"Error\":", "\"id\":", "\"txID\":", "\"raw_data_hex\":", "\"ret\":[{\"contractRet\":\"SUCCESS\"}]",328 "\"receipt\":{", "\"fee\":", "\"data\":[", "\"success\":true", "\"meta\":{\"fingerprint\":", "\"token_info\":{", "\"transaction_id\":", "\"code\":\"SUCCESS\"", "DUP_TRANSACTION_ERROR",329 "18446744073709551615", "9223372036854775807", "9223372036854775808", "-1", "1e999", "1.5", "null", "true", "[", "]", "{", "}", "\\ud800", "\\u0000", "41", "00"],330 seeds: tronJSONSeeds331 ) { input in332 guard let selector = input.first else { return }333 let body = Data(input.dropFirst())334 let endpoints = TronEndpoints(fullNodes: ["nile": ["https://node.fuzz.example", "https://node2.fuzz.example"]], history: ["nile": ["https://index.fuzz.example"]])335 let client = TronClient(network: .nile, endpoints: endpoints, transport: StubTransport(body: body, status: 200), pacing: .unthrottled)336 let limit = UInt64(Int64.max)337 let id = tronFuzzTransactions().first?.txIDHex ?? String(repeating: "ab", count: 32)338 fuzzAwait {339 do {340 switch fuzzSelector(selector, 12) {341 case 0:342 let account = try await client.account(tronFuzzOwner)343 FuzzOutcome.note(account.isActivated ? (account.isContract ? "contract" : "account") : "unactivated")344 fuzzCheck(account.address == tronFuzzOwner && account.balanceSun <= limit && (account.isActivated || (account.balanceSun == 0 && !account.isContract)), "account out of its rules")345 case 1:346 let r = try await client.resources(tronFuzzOwner)347 fuzzCheck(r.freeBandwidth <= r.freeNetLimit && r.stakedBandwidth <= r.netLimit && r.energy <= r.energyLimit, "resources left above their limits")348 case 2:349 let block = try await client.latestBlock()350 fuzzCheck(block.id.count == 32 && Bytes(block.id[0..<8]) == Endian.be64(block.number) && block.refBlockBytes.count == 2 && block.refBlockHash.count == 8, "block reference")351 do {352 try await client.verifyChain()353 FuzzOutcome.note("genesis")354 fuzzCheck(block.number == 0 && block.idHex == TronNetwork.nile.genesisBlockID, "another chain verified as Nile")355 } catch {356 FuzzOutcome.note("not-genesis")357 }358 case 3:359 let p = try await client.chainParameters()360 fuzzCheck(p.bandwidthPriceSun > 0 && p.energyPriceSun > 0 && p.maximumFeeLimitSun > 0, "a price of zero accepted")361 fuzzCheck([p.bandwidthPriceSun, p.energyPriceSun, p.accountActivationFeeSun, p.createAccountFeeSun, p.createAccountBandwidthRate, p.maximumFeeLimitSun, p.memoFeeSun].allSatisfy { $0 <= limit },362 "a chain parameter beyond int64")363 case 4:364 let r = try await client.constantCall(owner: tronFuzzOwner, contract: tronFuzzToken, data: ERC20.decimalsSelector)365 FuzzOutcome.note(r.succeeded ? "call-ok" : "call-failed")366 fuzzCheck(r.output.count <= 8192 && tronFuzzClean(r.message), "constant call result out of bounds")367 if let d = try? await client.tokenDecimals(tronFuzzToken) { fuzzCheck(d >= 0 && d <= 77 && r.succeeded, "decimals") }368 if let s = try? await client.tokenSymbol(tronFuzzToken) { fuzzCheck(!s.isEmpty && s.count <= 64 && tronFuzzClean(s) && r.succeeded, "symbol") }369 if let b = try? await client.tokenBalance(token: tronFuzzToken, owner: tronFuzzOwner) { fuzzCheck(r.output.count == 32 && UInt256(bigEndian: r.output) == b, "balance") }370 let simulation = try await client.simulateTokenTransfer(token: tronFuzzToken, from: tronFuzzOwner, to: tronFuzzRecipient, amount: UInt256(1))371 // whatever the node estimates, the planner keeps the fee limit under its ceiling372 let parameters = TronChainParameters(bandwidthPriceSun: 1_000, energyPriceSun: 420, accountActivationFeeSun: 1_000_000, createAccountFeeSun: 100_000, createAccountBandwidthRate: 1,373 maximumFeeLimitSun: 15_000_000_000, memoFeeSun: 1_000_000)374 if let reference = TronBlockReference(number: 5, id: Endian.be64(5) + Bytes(repeating: 1, count: 24), timestamp: tronFuzzNow) {375 let state = TronSendPlanner.ChainState(network: .nile, parameters: parameters, reference: reference, nowMilliseconds: tronFuzzNow)376 let plan = try? TronSendPlanner().planTokenTransfer(377 state: state, sender: TronAccount(address: tronFuzzOwner, isActivated: true, balanceSun: limit, isContract: false), resources: .none,378 recipient: TronAccount(address: tronFuzzRecipient, isActivated: true, balanceSun: 0, isContract: false),379 token: TronAccount(address: tronFuzzToken, isActivated: true, balanceSun: 0, isContract: true), tokenBalance: UInt256(10), amount: UInt256(1), simulation: simulation)380 if let plan {381 FuzzOutcome.note("planned")382 fuzzCheck(plan.feeLimitSun <= 100_000_000 && plan.transaction.feeLimit == plan.feeLimitSun && simulation.succeeded && simulation.energyUsed > 0, "fee limit above the ceiling")383 }384 }385 case 5:386 let status = try await client.transactionStatus(id: id)387 FuzzOutcome.note(status.state.rawValue)388 fuzzCheck(status.txID == id && !status.irreversible, "status of another transaction")389 if let tx = status.transaction { fuzzCheck(tx.txIDHex == id, "a transaction that does not hash to the id asked for") }390 for text in [status.contractResult, status.receiptResult, status.message] { fuzzCheck(text.map { tronFuzzClean($0) } ?? true, "server text not cleaned") }391 if status.state == .notFound || status.state == .pending { fuzzCheck(status.feeSun == 0 && status.blockNumber == nil, "figures for a transaction without a receipt") }392 case 6:393 let page = try await client.transactions(of: tronFuzzOwner, limit: 20)394 FuzzOutcome.note("history\(min(page.items.count, 3))")395 fuzzCheck(page.items.count <= 20, "more entries than asked for")396 for t in page.items {397 fuzzCheck(TronClient.isTxID(t.txID) && (t.kind == .trx || t.kind == .other) && t.token == nil, "native history entry")398 fuzzCheck(t.contractType.map { tronFuzzClean($0) } ?? true, "contract type text")399 }400 fuzzCheck(page.nextFingerprint.map { TronClient.isFingerprint($0) } ?? true, "fingerprint")401 case 7:402 let page = try await client.tokenTransfers(of: tronFuzzOwner, token: rngFreeBool(selector) ? tronFuzzToken : nil, limit: 200)403 FuzzOutcome.note("transfers\(min(page.items.count, 3))")404 fuzzCheck(page.items.count <= TronClient.maximumPageSize, "more entries than asked for")405 for t in page.items {406 fuzzCheck(TronClient.isTxID(t.txID) && t.kind == .trc20 && t.token != nil && t.to != nil, "token history entry")407 fuzzCheck((t.tokenDecimals ?? 0) >= 0 && (t.tokenDecimals ?? 0) <= 77 && (t.tokenSymbol.map { $0.count <= 16 && tronFuzzClean($0) } ?? true), "token metadata of the index")408 }409 case 8:410 guard let tx = tronFuzzTransactions().first, let signed = try? tx.sign(privateKey: tronFuzzKey) else { return }411 switch try await client.broadcast(signed) {412 case .accepted(let txID), .alreadyKnown(let txID):413 FuzzOutcome.note("accepted")414 fuzzCheck(txID == signed.txIDHex, "the id of another transaction was reported as broadcast")415 case .rejected(let code, let message):416 FuzzOutcome.note("rejected")417 fuzzCheck(tronFuzzClean(code) && tronFuzzClean(message), "refusal text not cleaned")418 }419 case 9:420 let raw = try await client.nodeBuiltTransfer(from: tronFuzzOwner, to: tronFuzzRecipient, amountSun: 1)421 fuzzCheck(!raw.isEmpty && raw.count <= TronTransaction.maximumRawDataBytes, "node-built bytes out of bounds")422 // for comparison only: decoded strictly, never signed as received423 if let tx = try? TronTransaction.decode(rawData: raw) { fuzzCheck(tx.rawData == raw, "node-built transaction is not canonical") }424 case 10:425 let r = try await client.referenceBlock()426 // the same answer from both nodes: one confirmation, never more than the other nodes427 fuzzCheck(r.confirmations == 1 && r.block.id.count == 32, "reference block confirmations")428 let accepted = try await client.acceptsReference(refBlockBytes: r.block.refBlockBytes, refBlockHash: r.block.refBlockHash)429 FuzzOutcome.note(accepted ? "accepts" : "refuses")430 default:431 guard let json = TronJSON.parse(body) else {432 FuzzOutcome.note("not-json")433 return434 }435 fuzzCheck(TronJSON.parse(json.serialized) == json, "JSON does not survive writing and reading")436 if let v = json.uint64 {437 // read exactly: the digits as written (a text may carry leading zeros), never through a floating-point number438 let written = json.string ?? String(decoding: body, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)439 fuzzCheck(written.utf8.count <= 20 && written.utf8.allSatisfy { $0 >= 0x30 && $0 <= 0x39 } && UInt64(written) == v, "an integer was not read exactly")440 }441 fuzzCheck(tronFuzzClean(TronClient.message(json)) && tronFuzzClean(TronClient.clean(json.string ?? "")), "message cleaning")442 }443 FuzzOutcome.note("ok")444 } catch let e as NetworkError {445 FuzzOutcome.note(error: e)446 if case .http(_, let text) = e { fuzzCheck(text.count <= 200, "error text out of bounds") }447 if case .rpc(_, let text) = e { fuzzCheck(tronFuzzClean(text, limit: 400), "node error text not cleaned") }448 } catch {449 FuzzOutcome.note(error: error)450 }451 }452 },453 FuzzTarget(454 "tron-abi", "TRC-20 ABI as the TRON module uses it: call data of a TriggerSmartContract, uint256 and string return data",455 maxLength: 400,456 tokens: [[0xa9, 0x05, 0x9c, 0xbb], [0x09, 0x5e, 0xa7, 0xb3], [0x70, 0xa0, 0x82, 0x31], Bytes(repeating: 0, count: 12), Bytes(repeating: 0xff, count: 32), UInt256(32).bytes32, UInt256(4).bytes32],457 seeds: tronABISeeds458 ) { input in459 guard let selector = input.first else { return }460 let data = Bytes(input.dropFirst())461 switch selector % 3 {462 case 0:463 let call = TronTriggerSmartContract(owner: tronFuzzOwner, contract: tronFuzzToken, data: data)464 switch call.trc20Call {465 case .transfer(let to, let amount)?:466 FuzzOutcome.note("transfer")467 fuzzCheck(data == ERC20.transfer(to: to, amount: amount) && data.count == 68, "transfer call data is not canonical")468 case .approve(let spender, let amount)?:469 FuzzOutcome.note("approve")470 fuzzCheck(data == ERC20.approve(spender: spender, amount: amount) && data.count == 68, "approve call data is not canonical")471 case nil:472 FuzzOutcome.note("other")473 }474 // TRX or a TRC-10 token attached: never a plain token call475 fuzzCheck(TronTriggerSmartContract(owner: tronFuzzOwner, contract: tronFuzzToken, callValue: 1, data: data).trc20Call == nil, "a call with TRX attached shown as a token transfer")476 fuzzCheck(TronTriggerSmartContract(owner: tronFuzzOwner, contract: tronFuzzToken, data: data, callTokenValue: 1).trc20Call == nil, "a call with a token attached shown as a token transfer")477 // through the encoding: the review of the bytes says the same478 if let tx = try? TronTransaction(refBlockBytes: [0, 1], refBlockHash: Bytes(repeating: 0, count: 8), expiration: 2, timestamp: 1, feeLimit: 1, contract: .triggerSmartContract(call)),479 let back = try? TronTransaction.decode(rawData: tx.rawData) {480 fuzzCheck(back == tx && TronTransactionReview(back).requiresBlindSigning == (call.trc20Call == nil), "review through the encoding")481 } else {482 fuzzFail("a contract call does not survive its encoding")483 }484 case 1:485 if let v = ERC20.decodeUInt(data) {486 FuzzOutcome.note("uint")487 fuzzCheck(data.count == 32 && v.bytes32 == data, "uint256 return data")488 } else {489 FuzzOutcome.note("not-uint")490 }491 default:492 if let s = ERC20.decodeString(data) {493 FuzzOutcome.note("string")494 fuzzCheck(!s.isEmpty && s.count <= 64 && tronFuzzClean(s, limit: 64), "string return data out of bounds")495 } else {496 FuzzOutcome.note("not-string")497 }498 }499 },500 FuzzTarget(501 "tron-review", "Unsigned TRON bytes on a cold device: the review shows what the bytes hold; the signature is refused outside the wallet's rules (owner, blind signing, fee limit, validity) and covers exactly the reviewed bytes",502 maxLength: 1024,503 dictionary: ["type.googleapis.com/protocol.TransferContract", "type.googleapis.com/protocol.TriggerSmartContract"],504 tokens: [[0x0a, 0x02], [0x22, 0x08], [0x40], [0x52], [0x5a], [0x70], [0x90, 0x01], [0x08, 0x01], [0x08, 0x1f], [0x28, 0x02], [0xa9, 0x05, 0x9c, 0xbb], [0x09, 0x5e, 0xa7, 0xb3],505 [0x80, 0x90, 0xbb, 0xba, 0xd6, 0xad, 0xa3, 0x03], [0x80, 0x00]],506 seeds: tronReviewSeeds507 ) { input in508 guard let w = MCFuzzWallet.shared, let me = TronAddress(w.profile.tronAddress ?? "") else { return }509 let network = "tron-nile"510 let text = "qyvtx1|u|\(network)|\(Hex.encode(input))"511 fuzzAwait {512 let review: ColdTransactionReview513 do {514 review = try await w.service.reviewColdTransaction([text])515 } catch {516 FuzzOutcome.note(error: error)517 fuzzCheck((try? TronTransaction.decode(rawData: input))?.owner.map { $0 != me } ?? true, "a canonical transaction of this account was not reviewed")518 return519 }520 guard case .tron(let decoded) = review.body, let tx = try? TronTransaction.decode(rawData: input) else { fuzzFail("a TRON review of bytes that do not decode") }521 fuzzCheck(decoded == TronTransactionReview(tx) && decoded.rawData == input && review.chain.id.rawValue == network, "the review is not the review of these bytes")522 fuzzCheck(decoded.owner == nil || decoded.owner == me, "a transaction of another account was reviewed")523 fuzzCheck(review.requiresBlindSigning == decoded.requiresBlindSigning && review.summary.count <= 40 && review.summary.allSatisfy { $0.unicodeScalars.count <= 20_000 }, "summary")524 fuzzCheck(review.warnings.contains { $0.id == "tron.network-not-bound" }, "a test-network review does not say that the bytes name no network")525 switch decoded.action {526 case .trxTransfer(_, let to, _): fuzzCheck(review.summary.contains { $0.contains(to.base58) }, "the recipient is not shown")527 case .trc20Transfer(_, let token, let to, _): fuzzCheck(review.summary.contains { $0.contains(to.base58) } && review.summary.contains { $0.contains(token.base58) }, "recipient or token not shown")528 case .trc20Approve(_, let token, let spender, let amount):529 fuzzCheck(review.summary.contains { $0.contains(spender.base58) } && review.summary.contains { $0.contains(token.base58) }, "spender or token not shown")530 if ERC20.isUnlimited(amount) { fuzzCheck(review.warnings.contains { $0.id == "tron.unlimited-approval" && $0.isCritical }, "unlimited approval not flagged") }531 case .contractCall, .unknownContract: fuzzCheck(review.warnings.contains { $0.id == "blind-signing" && $0.isCritical }, "blind signing not flagged")532 }533 FuzzOutcome.note("reviewed")534 // the signature, without the blind-signing flag535 do {536 let signed = try await w.service.signColdTransaction([text])537 FuzzOutcome.note("signed")538 fuzzCheck(!decoded.requiresBlindSigning && tx.owner == me, "signed blind, or for another owner")539 fuzzCheck(tx.feeLimit <= 100_000_000, "a fee limit above 100 TRX was signed")540 fuzzCheck(tx.expiration > tronFuzzNow && tx.expiration - tronFuzzNow <= 3_900_000, "a transaction outside the validity window was signed")541 let parts = signed.export.text.split(separator: "|").map(String.init)542 guard parts.count == 4, parts[0] == "qyvtx1", parts[1] == "s", parts[2] == network, let bytes = Hex.decode(parts[3]), let envelope = try? SignedTronTransaction.decode(bytes) else {543 fuzzFail("the signed export is not a signed TRON envelope")544 }545 fuzzCheck(envelope.transaction.rawData == input && (try? envelope.signers()) == [me] && signed.id == tx.txIDHex, "the signature does not cover the reviewed bytes")546 } catch {547 FuzzOutcome.note("sign-" + String(String(describing: error).prefix(24)))548 }549 }550 },551]552553/// A choice that depends on the input only (no generator in a harness).554func rngFreeBool(_ byte: UInt8) -> Bool { byte & 0x20 != 0 }555