Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraTron/TronProtobuf.swift8// Module : Qyvora Tron9// 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 QyvoraCore4647/// Why a protobuf message was refused.48public enum TronProtobufError: Error, Equatable, Sendable {49 /// The input ends inside a varint, a tag or a length-delimited field.50 case truncated51 /// A varint longer than ten bytes, or whose value does not fit in 64 bits.52 case varintOverflow53 /// A varint carrying useless leading zero groups (0x80 0x00 for 0): one value, one encoding.54 case nonMinimalVarint55 /// Field number 0, or above 2^29 − 1.56 case invalidFieldNumber57 /// A wire type other than varint (0) and length-delimited (2): the TRON messages handled here use no other.58 case unsupportedWireType(field: UInt32, wireType: UInt8)59 /// A known field carried with the wrong wire type.60 case wrongWireType(field: UInt32)61 /// A length prefix larger than what is left of the input.62 case lengthOutOfBounds63 /// The input is larger than the accepted size.64 case oversized65 /// A field this decoder does not know in the named message. Unknown fields are refused, never skipped: what is66 /// shown for review must be the whole of what is signed.67 case unknownField(message: String, field: UInt32)68 /// A singular field present twice.69 case duplicateField(message: String, field: UInt32)70 /// An int64 field holding a negative value, where only amounts, times and limits are expected.71 case negativeValue(message: String, field: UInt32)72 /// A field with an invalid value (an address that is not 0x41 ‖ 20 bytes, a type URL that is not text…).73 case invalidValue(message: String, field: UInt32)74 /// The transaction holds no contract, or more than one (the protocol executes exactly one).75 case contractCount(Int)76 /// The type URL of the `Any` wrapper does not match the contract type.77 case typeURLMismatch78 /// The bytes decode, but are not the canonical encoding of what they decode to (fields out of order, a default79 /// value written explicitly…). Re-encoding would change the transaction id, so it is refused.80 case nonCanonical81}8283/// Minimal protobuf writer: varint (wire type 0) and length-delimited (wire type 2) fields, written in the order of84/// the calls. Proto3 rules: the callers skip default values (0, empty) so that the output is canonical.85struct ProtoWriter {86 var bytes = Bytes()8788 static func varint(_ value: UInt64) -> Bytes {89 var v = value90 var out = Bytes()91 while v >= 0x80 {92 out.append(UInt8(v & 0x7f) | 0x80)93 v >>= 794 }95 out.append(UInt8(v))96 return out97 }9899 /// A varint field; nothing when the value is 0 (proto3 default).100 mutating func varint(_ field: UInt32, _ value: UInt64) {101 guard value != 0 else { return }102 bytes += Self.varint(UInt64(field) << 3)103 bytes += Self.varint(value)104 }105106 /// A length-delimited field; nothing when it is empty (proto3 default).107 mutating func bytes(_ field: UInt32, _ value: Bytes) {108 guard !value.isEmpty else { return }109 message(field, value)110 }111112 /// A length-delimited field written even when empty (an embedded message that must be present).113 mutating func message(_ field: UInt32, _ value: Bytes) {114 bytes += Self.varint(UInt64(field) << 3 | 2)115 bytes += Self.varint(UInt64(value.count))116 bytes += value117 }118}119120/// Strict protobuf reader over one message. It accepts wire types 0 and 2 only, minimal varints only, and never121/// reads past the end of its input.122struct ProtoReader {123 enum Value: Equatable {124 case varint(UInt64)125 case bytes(Bytes)126 }127128 private let data: Bytes129 private var offset = 0130131 init(_ data: Bytes) { self.data = data }132133 var isAtEnd: Bool { offset >= data.count }134135 mutating func varint() throws(TronProtobufError) -> UInt64 {136 var result: UInt64 = 0137 var shift: UInt64 = 0138 var count = 0139 while true {140 guard offset < data.count else { throw .truncated }141 let byte = data[offset]142 offset += 1143 count += 1144 let group = UInt64(byte & 0x7f)145 // the tenth byte may only carry the top bit of a 64-bit value146 if count == 10 && group > 1 { throw .varintOverflow }147 result |= group << shift148 if byte & 0x80 == 0 {149 if count > 1 && byte == 0 { throw .nonMinimalVarint }150 return result151 }152 guard count < 10 else { throw .varintOverflow }153 shift += 7154 }155 }156157 /// The next field, or nil at the end of the message.158 mutating func next() throws(TronProtobufError) -> (field: UInt32, value: Value)? {159 guard !isAtEnd else { return nil }160 let tag = try varint()161 let number = tag >> 3162 guard number >= 1, number <= 0x1fff_ffff else { throw .invalidFieldNumber }163 let field = UInt32(number)164 switch UInt8(tag & 7) {165 case 0:166 return (field, .varint(try varint()))167 case 2:168 let length = try varint()169 guard length <= UInt64(data.count - offset) else { throw .lengthOutOfBounds }170 let end = offset + Int(length)171 defer { offset = end }172 return (field, .bytes(Bytes(data[offset..<end])))173 case let other:174 throw .unsupportedWireType(field: field, wireType: other)175 }176 }177}178179/// Field bookkeeping shared by the message decoders: wire-type checks, duplicates, signed ranges.180struct ProtoFields {181 let message: String182 private var seen = Set<UInt32>()183184 init(_ message: String) { self.message = message }185186 mutating func once(_ field: UInt32) throws(TronProtobufError) {187 guard seen.insert(field).inserted else { throw .duplicateField(message: message, field: field) }188 }189190 /// A singular int64 field that must not be negative.191 mutating func unsigned(_ field: UInt32, _ value: ProtoReader.Value) throws(TronProtobufError) -> UInt64 {192 try once(field)193 guard case .varint(let v) = value else { throw .wrongWireType(field: field) }194 guard v <= UInt64(Int64.max) else { throw .negativeValue(message: message, field: field) }195 return v196 }197198 /// A singular length-delimited field.199 mutating func bytes(_ field: UInt32, _ value: ProtoReader.Value) throws(TronProtobufError) -> Bytes {200 try once(field)201 guard case .bytes(let b) = value else { throw .wrongWireType(field: field) }202 return b203 }204205 /// A singular address field: 0x41 ‖ 20 bytes.206 mutating func address(_ field: UInt32, _ value: ProtoReader.Value) throws(TronProtobufError) -> TronAddress {207 guard let a = TronAddress(bytes: try bytes(field, value)) else { throw .invalidValue(message: message, field: field) }208 return a209 }210211 func unknown(_ field: UInt32) -> TronProtobufError { .unknownField(message: message, field: field) }212}213