Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraTronTests/ProtobufTests.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 Foundation42import QyvoraMath43import QyvoraSymmetric44import QyvoraSecp256k145import Testing46import QyvoraCore47@testable import QyvoraTron4849/// Strict decoding: what is not exactly a canonical transaction of a known shape is refused with a typed error.50/// Unknown-field policy: refused everywhere (never skipped), so that the review shows all of what is signed.51@Suite struct TronProtobufTests {52 let reference = hex(TronVectors.transactions[1].rawDataHex) // trx-100000053 let token = hex(TronVectors.transactions[6].rawDataHex) // usdt-transfer-15455 func decodeError(_ bytes: Bytes) -> TronProtobufError? {56 do {57 _ = try TronTransaction.decode(rawData: bytes)58 return nil59 } catch {60 return error61 }62 }6364 @Test func varints() throws {65 #expect(ProtoWriter.varint(0) == [0])66 #expect(ProtoWriter.varint(127) == [0x7f])67 #expect(ProtoWriter.varint(128) == [0x80, 0x01])68 #expect(ProtoWriter.varint(300) == [0xac, 0x02])69 #expect(ProtoWriter.varint(UInt64.max) == Bytes(repeating: 0xff, count: 9) + [0x01])70 for v in [UInt64(0), 1, 127, 128, 16_383, 16_384, 1 << 32, UInt64(Int64.max), UInt64.max] {71 var r = ProtoReader(ProtoWriter.varint(v))72 #expect(try r.varint() == v)73 #expect(r.isAtEnd)74 }75 func error(_ b: Bytes) -> TronProtobufError? {76 var r = ProtoReader(b)77 do {78 _ = try r.varint()79 return nil80 } catch {81 return error82 }83 }84 #expect(error([]) == .truncated)85 #expect(error([0x80]) == .truncated)86 #expect(error([0xff, 0xff, 0xff]) == .truncated)87 #expect(error(Bytes(repeating: 0xff, count: 9)) == .truncated)88 #expect(error([0x80, 0x00]) == .nonMinimalVarint)89 #expect(error([0xff, 0x80, 0x00]) == .nonMinimalVarint)90 #expect(error(Bytes(repeating: 0xff, count: 9) + [0x02]) == .varintOverflow)91 #expect(error(Bytes(repeating: 0xff, count: 9) + [0x7f]) == .varintOverflow)92 #expect(error(Bytes(repeating: 0xff, count: 10) + [0x01]) == .varintOverflow)93 #expect(error(Bytes(repeating: 0x80, count: 10) + [0x01]) == .varintOverflow)94 }9596 @Test func truncation() {97 #expect(decodeError(reference) == nil)98 // A proper prefix is refused, except where the cut falls exactly between two fields after the contract99 // (before the timestamp, before the fee limit): that is another, shorter, well-formed transaction, with100 // another id — never the reference one.101 for (bytes, boundaries) in [(reference, 1), (token, 2)] {102 var decoded = 0103 for n in 0..<bytes.count {104 let prefix = Bytes(bytes[0..<n])105 if let tx = try? TronTransaction.decode(rawData: prefix) {106 decoded += 1107 #expect(tx.rawData == prefix && tx.txID != SHA256.hash(bytes))108 #expect(tx.timestamp == 0 || tx.feeLimit == 0)109 }110 }111 #expect(decoded == boundaries)112 }113 #expect(decodeError([]) == .invalidValue(message: "Transaction.raw", field: 1))114 #expect(decodeError([0x0a]) == .truncated)115 #expect(decodeError([0x0a, 0x02, 0x26]) == .lengthOutOfBounds)116 }117118 @Test func wireTypes() {119 // fixed64 (1), groups (3, 4), fixed32 (5) and the reserved types are never accepted120 for wire in [UInt8(1), 3, 4, 5, 6, 7] {121 #expect(decodeError(reference + [UInt8(19 << 3 & 0xff) | wire, 0x01, 0, 0, 0, 0, 0, 0, 0, 0]) == .unsupportedWireType(field: 19, wireType: wire))122 }123 // ref_block_bytes as a varint, expiration as bytes, contract as a varint124 #expect(decodeError([0x08, 0x01]) == .wrongWireType(field: 1))125 #expect(decodeError([0x0a, 0x02, 0x26, 0x60, 0x42, 0x01, 0x05]) == .wrongWireType(field: 8))126 #expect(decodeError([0x58, 0x01]) == .wrongWireType(field: 11))127 // field number 0 and a field number beyond 2^29 − 1128 #expect(decodeError([0x00, 0x00]) == .invalidFieldNumber)129 #expect(decodeError([0x80, 0x80, 0x80, 0x80, 0x10, 0x00]) == .invalidFieldNumber)130 }131132 @Test func lengths() {133 // a length prefix far beyond the input, including one near 2^64134 #expect(decodeError([0x0a, 0xff, 0xff, 0xff, 0xff, 0x0f]) == .lengthOutOfBounds)135 #expect(decodeError([0x0a] + Bytes(repeating: 0xff, count: 9) + [0x01]) == .lengthOutOfBounds)136 #expect(decodeError([0x0a, 0x03, 0x26, 0x60]) == .lengthOutOfBounds)137 // reference fields of the wrong size138 #expect(decodeError([0x0a, 0x03, 0x26, 0x60, 0x01]) == .invalidValue(message: "Transaction.raw", field: 1))139 #expect(decodeError([0x0a, 0x02, 0x26, 0x60, 0x22, 0x01, 0x01]) == .invalidValue(message: "Transaction.raw", field: 4))140 // an input larger than the accepted size is refused before any parsing141 #expect(decodeError(Bytes(repeating: 0x0a, count: TronTransaction.maximumRawDataBytes + 1)) == .oversized)142 #expect((try? SignedTronTransaction.decode(Bytes(repeating: 0x0a, count: TronTransaction.maximumRawDataBytes + 513))) == nil)143 }144145 @Test func unknownAndDuplicateFields() throws {146 // an unknown field at each level: raw (2), ref_block_num (3), auths (9), scripts (12), a high number147 #expect(decodeError(reference + [0x10, 0x01]) == .unknownField(message: "Transaction.raw", field: 2))148 #expect(decodeError(reference + [0x18, 0x01]) == .unknownField(message: "Transaction.raw", field: 3))149 #expect(decodeError(reference + [0x4a, 0x00]) == .unknownField(message: "Transaction.raw", field: 9))150 #expect(decodeError(reference + [0x62, 0x00]) == .unknownField(message: "Transaction.raw", field: 12))151 #expect(decodeError(reference + [0xa0, 0x06, 0x01]) == .unknownField(message: "Transaction.raw", field: 100))152 // duplicates of singular fields153 #expect(decodeError(reference + [0x40, 0x01]) == .duplicateField(message: "Transaction.raw", field: 8))154 #expect(decodeError(reference + [0x0a, 0x02, 0x26, 0x60]) == .duplicateField(message: "Transaction.raw", field: 1))155 // two contracts156 let contract = try #require(try firstField(11, of: reference))157 var w = ProtoWriter()158 w.message(11, contract)159 #expect(decodeError(reference + w.bytes) == .contractCount(2))160 // no contract161 #expect(decodeError([0x0a, 0x02, 0x26, 0x60, 0x22, 0x08, 1, 2, 3, 4, 5, 6, 7, 8, 0x40, 0x05]) == .contractCount(0))162 }163164 /// The fields of a message, to rebuild variants of the reference transaction.165 func fields(_ data: Bytes) throws -> [(UInt32, ProtoReader.Value)] {166 var r = ProtoReader(data)167 var out = [(UInt32, ProtoReader.Value)]()168 while let f = try r.next() { out.append((f.field, f.value)) }169 return out170 }171172 func firstField(_ number: UInt32, of data: Bytes) throws -> Bytes? {173 for (n, v) in try fields(data) where n == number {174 if case .bytes(let b) = v { return b }175 }176 return nil177 }178179 func write(_ fields: [(UInt32, ProtoReader.Value)]) -> Bytes {180 var w = ProtoWriter()181 for (n, v) in fields {182 switch v {183 case .varint(let x): w.bytes += ProtoWriter.varint(UInt64(n) << 3) + ProtoWriter.varint(x)184 case .bytes(let b): w.message(n, b)185 }186 }187 return w.bytes188 }189190 /// The reference raw data with its contract message, `Any` wrapper or inner contract replaced.191 func rebuilt(contract: ((inout [(UInt32, ProtoReader.Value)]) -> Void)? = nil, any: ((inout [(UInt32, ProtoReader.Value)]) -> Void)? = nil,192 inner: ((inout [(UInt32, ProtoReader.Value)]) -> Void)? = nil, from base: Bytes? = nil) throws -> Bytes {193 var raw = try fields(base ?? reference)194 let ci = try #require(raw.firstIndex { $0.0 == 11 })195 guard case .bytes(let cBytes) = raw[ci].1 else { return [] }196 var c = try fields(cBytes)197 let ai = try #require(c.firstIndex { $0.0 == 2 })198 guard case .bytes(let aBytes) = c[ai].1 else { return [] }199 var a = try fields(aBytes)200 let ii = try #require(a.firstIndex { $0.0 == 2 })201 guard case .bytes(let iBytes) = a[ii].1 else { return [] }202 var i = try fields(iBytes)203 inner?(&i)204 a[ii].1 = .bytes(write(i))205 any?(&a)206 c[ai].1 = .bytes(write(a))207 contract?(&c)208 raw[ci].1 = .bytes(write(c))209 return write(raw)210 }211212 @Test func nestedMessages() throws {213 // the rebuilding helper is faithful214 #expect(try rebuilt() == reference)215 #expect(try rebuilt(from: token) == token)216 // unknown fields inside the contract, the wrapper and the inner message (provider = 3, ContractName = 4)217 #expect(decodeError(try rebuilt(contract: { $0.append((3, .bytes([1]))) })) == .unknownField(message: "Transaction.Contract", field: 3))218 #expect(decodeError(try rebuilt(contract: { $0.append((4, .bytes([1]))) })) == .unknownField(message: "Transaction.Contract", field: 4))219 #expect(decodeError(try rebuilt(any: { $0.append((3, .varint(1))) })) == .unknownField(message: "Any", field: 3))220 #expect(decodeError(try rebuilt(inner: { $0.append((4, .varint(1))) })) == .unknownField(message: "TransferContract", field: 4))221 #expect(decodeError(try rebuilt(inner: { $0.append((7, .varint(1))) }, from: token)) == .unknownField(message: "TriggerSmartContract", field: 7))222 // addresses: wrong prefix, wrong length, missing223 #expect(decodeError(try rebuilt(inner: { $0[0].1 = .bytes([0x42] + Bytes(repeating: 1, count: 20)) })) == .invalidValue(message: "TransferContract", field: 1))224 #expect(decodeError(try rebuilt(inner: { $0[1].1 = .bytes(Bytes(repeating: 0x41, count: 20)) })) == .invalidValue(message: "TransferContract", field: 2))225 #expect(decodeError(try rebuilt(inner: { $0.remove(at: 0) })) == .invalidValue(message: "TransferContract", field: 1))226 #expect(decodeError(try rebuilt(inner: { $0.remove(at: 1) }, from: token)) == .invalidValue(message: "TriggerSmartContract", field: 2))227 #expect(decodeError(try rebuilt(inner: { $0[0].1 = .varint(5) })) == .wrongWireType(field: 1))228 // a negative amount (int64 −1 is ten bytes of varint), a negative expiration229 #expect(decodeError(try rebuilt(inner: { $0[2].1 = .varint(UInt64.max) })) == .negativeValue(message: "TransferContract", field: 3))230 #expect(decodeError(try rebuilt(inner: { $0[2].1 = .varint(UInt64(Int64.max) + 1) })) == .negativeValue(message: "TransferContract", field: 3))231 var raw = try fields(reference)232 raw[2].1 = .varint(UInt64.max)233 #expect(decodeError(write(raw)) == .negativeValue(message: "Transaction.raw", field: 8))234 // type and wrapper that disagree, in each direction; a wrapper that is not printable text235 #expect(decodeError(try rebuilt(contract: { $0[0].1 = .varint(31) })) == .typeURLMismatch)236 #expect(decodeError(try rebuilt(contract: { $0[0].1 = .varint(2) })) == .typeURLMismatch)237 #expect(decodeError(try rebuilt(any: { $0[0].1 = .bytes(Bytes("type.googleapis.com/protocol.TriggerSmartContract".utf8)) })) == .typeURLMismatch)238 #expect(decodeError(try rebuilt(any: { $0[0].1 = .bytes([0x74, 0x00, 0x0a]) })) == .invalidValue(message: "Any", field: 1))239 #expect(decodeError(try rebuilt(contract: { $0[0].1 = .varint(1 << 31) })) == .invalidValue(message: "Transaction.Contract", field: 1))240 #expect(decodeError(try rebuilt(contract: { $0.append((5, .varint(1 << 31))) })) == .invalidValue(message: "Transaction.Contract", field: 5))241 #expect(decodeError(try rebuilt(contract: { $0.remove(at: 1) })) == .invalidValue(message: "Transaction.Contract", field: 2))242 // a permission id is kept and shown243 let withPermission = try TronTransaction.decode(rawData: try rebuilt(contract: { $0.append((5, .varint(2))) }))244 #expect(withPermission.permissionID == 2 && TronTransactionReview(withPermission).warnings == [.nonOwnerPermission])245 }246247 /// Bytes that decode but are not the canonical encoding: the id would change when re-encoded, so they are refused.248 @Test func nonCanonical() throws {249 var raw = try fields(reference)250 // fields out of order251 raw.swapAt(0, 1)252 #expect(decodeError(write(raw)) == .nonCanonical)253 // an explicit default value (fee_limit = 0, empty memo)254 #expect(decodeError(reference + [0x90, 0x01, 0x00]) == .nonCanonical)255 var withMemo = try fields(reference)256 withMemo.insert((10, .bytes([])), at: 3)257 #expect(decodeError(write(withMemo)) == .nonCanonical)258 // a non-minimal varint for the expiration259 var padded = Bytes(reference[0..<14])260 #expect(reference[14] == 0x40)261 var i = 15262 while reference[i] & 0x80 != 0 { i += 1 }263 padded += [0x40] + reference[15..<i] + [reference[i] | 0x80, 0x00] + reference[(i + 1)...]264 #expect(decodeError(padded) == .nonMinimalVarint)265 // an explicit zero amount inside the contract266 #expect(decodeError(try rebuilt(inner: { $0[2].1 = .varint(0) })) == .nonCanonical)267 }268269 @Test func signedEnvelope() throws {270 let tx = try TronTransaction.decode(rawData: reference)271 let unsigned = try #require(SignedTronTransaction(transaction: tx, signatures: []))272 #expect(try SignedTronTransaction.decode(unsigned.serialized) == unsigned)273 let sig = Bytes(repeating: 7, count: 65)274 let two = try #require(SignedTronTransaction(transaction: tx, signatures: [sig, sig]))275 #expect(try SignedTronTransaction.decode(two.serialized).signatures.count == 2)276 func error(_ b: Bytes) -> TronProtobufError? {277 do {278 _ = try SignedTronTransaction.decode(b)279 return nil280 } catch {281 return error282 }283 }284 let good = two.serialized285 // prefixes: only the cuts between the raw data and a signature, or between the two signatures, decode286 let cuts = [unsigned.serialized.count, unsigned.serialized.count + 67]287 for n in 0..<good.count { #expect((error(Bytes(good[0..<n])) == nil) == cuts.contains(n), "prefix of \(n) bytes") }288 #expect(error([]) == .invalidValue(message: "Transaction", field: 1))289 // a signature that is not 65 bytes, six signatures, the `ret` field of a node, two raw_data290 #expect(error(unsigned.serialized + [0x12, 0x02, 1, 2]) == .invalidValue(message: "Transaction", field: 2))291 var six = unsigned.serialized292 for _ in 0..<6 { six += [0x12, 0x41] + sig }293 #expect(error(six) == .invalidValue(message: "Transaction", field: 2))294 #expect(error(good + [0x2a, 0x02, 0x18, 0x01]) == .unknownField(message: "Transaction", field: 5))295 #expect(error(unsigned.serialized + unsigned.serialized) == .duplicateField(message: "Transaction", field: 1))296 #expect(error(unsigned.serialized + [0x10, 0x01]) == .wrongWireType(field: 2))297 }298299 /// Random and mutated inputs never trap; whatever decodes re-encodes to the same bytes.300 @Test func fuzz() throws {301 var state: UInt64 = 0x9e37_79b9_7f4a_7c15302 func next() -> UInt64 {303 state ^= state << 13304 state ^= state >> 7305 state ^= state << 17306 return state307 }308 var accepted = 0309 for round in 0..<20_000 {310 var bytes: Bytes311 if round % 2 == 0 {312 bytes = (0..<Int(next() % 96)).map { _ in UInt8(truncatingIfNeeded: next()) }313 } else {314 bytes = round % 4 == 1 ? reference : token315 for _ in 0..<(1 + Int(next() % 3)) {316 let i = Int(next() % UInt64(bytes.count))317 switch next() % 3 {318 case 0: bytes[i] = UInt8(truncatingIfNeeded: next())319 case 1: bytes.remove(at: i)320 default: bytes.insert(UInt8(truncatingIfNeeded: next()), at: i)321 }322 }323 }324 if let tx = try? TronTransaction.decode(rawData: bytes) {325 accepted += 1326 #expect(tx.rawData == bytes)327 _ = TronTransactionReview(tx)328 }329 _ = try? SignedTronTransaction.decode(bytes)330 }331 // mutations that only touch a value (an amount, a hash byte) still decode: the count is not zero332 #expect(accepted > 0)333 }334}335