SPB Git

Repository Public

TronTransaction.swift 34.0 KB 670 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraTron/TronTransaction.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 QyvoraCore46import QyvoraEthereum4748// Field numbers and wire types below are those of the TRON protocol definitions, read from49// https://github.com/tronprotocol/protocol (revision 8432beca98c52ba04c82aea0b48ae9f9f882c82a, 2026-07-17):50//51//   core/Tron.proto              message Transaction { raw raw_data = 1; repeated bytes signature = 2; repeated Result ret = 5; }52//                                message Transaction.raw { bytes ref_block_bytes = 1; int64 ref_block_num = 3;53//                                    bytes ref_block_hash = 4; int64 expiration = 8; repeated authority auths = 9;54//                                    bytes data = 10; repeated Contract contract = 11; bytes scripts = 12;55//                                    int64 timestamp = 14; int64 fee_limit = 18; }56//                                message Transaction.Contract { ContractType type = 1; google.protobuf.Any parameter = 2;57//                                    bytes provider = 3; bytes ContractName = 4; int32 Permission_id = 5; }58//                                enum ContractType { TransferContract = 1; TriggerSmartContract = 31; … }59//   core/contract/balance_contract.proto   message TransferContract { bytes owner_address = 1; bytes to_address = 2; int64 amount = 3; }60//   core/contract/smart_contract.proto     message TriggerSmartContract { bytes owner_address = 1; bytes contract_address = 2;61//                                    int64 call_value = 3; bytes data = 4; int64 call_token_value = 5; int64 token_id = 6; }62//   google/protobuf/any.proto    message Any { string type_url = 1; bytes value = 2; }63//64// Nothing of those files is vendored. Fields the wallet never writes and the network does not use (ref_block_num,65// auths, scripts, provider, ContractName) are refused when decoding.6667/// A recent block a transaction refers to (TaPoS): the transaction is only valid on a chain that contains it.68public struct TronBlockReference: Equatable, Sendable {69    public let number: UInt6470    /// 32-byte block id: the block number on eight bytes, then bytes 8…31 of the block hash.71    public let id: Bytes72    /// Block time, milliseconds since 1970.73    public let timestamp: UInt647475    /// nil unless the id is 32 bytes and starts with the block number.76    public init?(number: UInt64, id: Bytes, timestamp: UInt64) {77        guard id.count == 32, Bytes(id[0..<8]) == Endian.be64(number) else { return nil }78        self.number = number79        self.id = id80        self.timestamp = timestamp81    }8283    /// `ref_block_bytes`: bytes 6 and 7 of the block number written on eight bytes (its two low-order bytes).84    public var refBlockBytes: Bytes { Bytes(id[6..<8]) }85    /// `ref_block_hash`: bytes 8 to 15 of the block id.86    public var refBlockHash: Bytes { Bytes(id[8..<16]) }87    public var idHex: String { Hex.encode(id) }88}8990/// `TransferContract`: a transfer of TRX.91public struct TronTransferContract: Equatable, Sendable {92    public let owner: TronAddress93    public let to: TronAddress94    /// Amount in sun.95    public let amount: UInt649697    public init(owner: TronAddress, to: TronAddress, amount: UInt64) {98        self.owner = owner99        self.to = to100        self.amount = amount101    }102103    static let typeURL = "type.googleapis.com/protocol.TransferContract"104105    var encoded: Bytes {106        var w = ProtoWriter()107        w.bytes(1, owner.bytes)108        w.bytes(2, to.bytes)109        w.varint(3, amount)110        return w.bytes111    }112113    static func decode(_ data: Bytes) throws(TronProtobufError) -> TronTransferContract {114        var reader = ProtoReader(data)115        var fields = ProtoFields("TransferContract")116        var owner: TronAddress?, to: TronAddress?, amount: UInt64 = 0117        while let (field, value) = try reader.next() {118            switch field {119            case 1: owner = try fields.address(1, value)120            case 2: to = try fields.address(2, value)121            case 3: amount = try fields.unsigned(3, value)122            default: throw fields.unknown(field)123            }124        }125        guard let owner else { throw .invalidValue(message: "TransferContract", field: 1) }126        guard let to else { throw .invalidValue(message: "TransferContract", field: 2) }127        return TronTransferContract(owner: owner, to: to, amount: amount)128    }129}130131/// `TriggerSmartContract`: a call to a contract, such as a TRC-20 transfer.132public struct TronTriggerSmartContract: Equatable, Sendable {133    public let owner: TronAddress134    public let contract: TronAddress135    /// TRX sent along with the call, in sun (0 for a token transfer).136    public let callValue: UInt64137    /// ABI call data.138    public let data: Bytes139    /// TRC-10 amount sent along with the call (0 for a token transfer).140    public let callTokenValue: UInt64141    /// TRC-10 token id of `callTokenValue`.142    public let tokenID: UInt64143144    public init(owner: TronAddress, contract: TronAddress, callValue: UInt64 = 0, data: Bytes, callTokenValue: UInt64 = 0, tokenID: UInt64 = 0) {145        self.owner = owner146        self.contract = contract147        self.callValue = callValue148        self.data = data149        self.callTokenValue = callTokenValue150        self.tokenID = tokenID151    }152153    /// The TRC-20 `transfer` or `approve` call carried, when the data is exactly one of them and nothing (TRX or154    /// TRC-10) is attached to the call; nil for anything else.155    public var trc20Call: ERC20.Call? {156        guard callValue == 0, callTokenValue == 0, tokenID == 0 else { return nil }157        return ERC20.decodeCall(data)158    }159160    static let typeURL = "type.googleapis.com/protocol.TriggerSmartContract"161162    var encoded: Bytes {163        var w = ProtoWriter()164        w.bytes(1, owner.bytes)165        w.bytes(2, contract.bytes)166        w.varint(3, callValue)167        w.bytes(4, data)168        w.varint(5, callTokenValue)169        w.varint(6, tokenID)170        return w.bytes171    }172173    static func decode(_ data: Bytes) throws(TronProtobufError) -> TronTriggerSmartContract {174        var reader = ProtoReader(data)175        var fields = ProtoFields("TriggerSmartContract")176        var owner: TronAddress?, contract: TronAddress?, callValue: UInt64 = 0, callData = Bytes(), tokenValue: UInt64 = 0, tokenID: UInt64 = 0177        while let (field, value) = try reader.next() {178            switch field {179            case 1: owner = try fields.address(1, value)180            case 2: contract = try fields.address(2, value)181            case 3: callValue = try fields.unsigned(3, value)182            case 4: callData = try fields.bytes(4, value)183            case 5: tokenValue = try fields.unsigned(5, value)184            case 6: tokenID = try fields.unsigned(6, value)185            default: throw fields.unknown(field)186            }187        }188        guard let owner else { throw .invalidValue(message: "TriggerSmartContract", field: 1) }189        guard let contract else { throw .invalidValue(message: "TriggerSmartContract", field: 2) }190        return TronTriggerSmartContract(owner: owner, contract: contract, callValue: callValue, data: callData, callTokenValue: tokenValue, tokenID: tokenID)191    }192}193194/// The single contract of a transaction.195public enum TronContract: Equatable, Sendable {196    case transfer(TronTransferContract)197    case triggerSmartContract(TronTriggerSmartContract)198    /// Any other contract type (staking, voting, account permissions…): its number, the type URL of its wrapper and199    /// the undecoded message. The wallet cannot show what it does: signing it is blind signing.200    case unknown(type: UInt32, typeURL: String, value: Bytes)201202    /// Number of the contract type in `Transaction.Contract.ContractType`.203    public var type: UInt32 {204        switch self {205        case .transfer: return 1206        case .triggerSmartContract: return 31207        case .unknown(let type, _, _): return type208        }209    }210211    /// Name of a contract type in the protocol definition, when it has one.212    public static func typeName(_ type: UInt32) -> String? {213        let names: [UInt32: String] = [214            0: "AccountCreateContract", 1: "TransferContract", 2: "TransferAssetContract", 3: "VoteAssetContract",215            4: "VoteWitnessContract", 5: "WitnessCreateContract", 6: "AssetIssueContract", 8: "WitnessUpdateContract",216            9: "ParticipateAssetIssueContract", 10: "AccountUpdateContract", 11: "FreezeBalanceContract",217            12: "UnfreezeBalanceContract", 13: "WithdrawBalanceContract", 14: "UnfreezeAssetContract", 15: "UpdateAssetContract",218            16: "ProposalCreateContract", 17: "ProposalApproveContract", 18: "ProposalDeleteContract", 19: "SetAccountIdContract",219            20: "CustomContract", 30: "CreateSmartContract", 31: "TriggerSmartContract", 32: "GetContract",220            33: "UpdateSettingContract", 41: "ExchangeCreateContract", 42: "ExchangeInjectContract",221            43: "ExchangeWithdrawContract", 44: "ExchangeTransactionContract", 45: "UpdateEnergyLimitContract",222            46: "AccountPermissionUpdateContract", 48: "ClearABIContract", 49: "UpdateBrokerageContract",223            51: "ShieldedTransferContract", 52: "MarketSellAssetContract", 53: "MarketCancelOrderContract",224            54: "FreezeBalanceV2Contract", 55: "UnfreezeBalanceV2Contract", 56: "WithdrawExpireUnfreezeContract",225            57: "DelegateResourceContract", 58: "UnDelegateResourceContract", 59: "CancelAllUnfreezeV2Contract",226        ]227        return names[type]228    }229230    /// The account that must sign, when the contract is one the wallet decodes.231    public var owner: TronAddress? {232        switch self {233        case .transfer(let c): return c.owner234        case .triggerSmartContract(let c): return c.owner235        case .unknown: return nil236        }237    }238239    var typeURL: String {240        switch self {241        case .transfer: return TronTransferContract.typeURL242        case .triggerSmartContract: return TronTriggerSmartContract.typeURL243        case .unknown(_, let url, _): return url244        }245    }246247    var value: Bytes {248        switch self {249        case .transfer(let c): return c.encoded250        case .triggerSmartContract(let c): return c.encoded251        case .unknown(_, _, let value): return value252        }253    }254}255256/// An unsigned TRON transaction (`Transaction.raw`), built and serialised on the device.257///258/// The transaction id is SHA-256 of `rawData`, and it is what gets signed. The wallet only ever signs bytes it has259/// encoded itself from the fields below: a transaction received from elsewhere is decoded (`decode(rawData:)`), which260/// succeeds only when re-encoding gives the same bytes, so what is reviewed is exactly what is signed.261public struct TronTransaction: Equatable, Sendable {262    public enum Error: Swift.Error, Equatable {263        /// `ref_block_bytes` is not two bytes or `ref_block_hash` is not eight.264        case invalidReferenceBlock265        /// The expiration is not after the timestamp, or more than 24 hours after it.266        case invalidExpiration267        /// A value beyond 2^63 − 1 (the protocol counts in signed 64-bit integers), or a permission id beyond 2^31 − 1.268        case valueOutOfRange269        /// The memo is longer than `maximumMemoBytes`.270        case memoTooLong271        /// The key is not the one of the account that owns the contract.272        case signerMismatch273        /// The contract is not one the wallet decodes, and blind signing was not explicitly allowed.274        case blindSigningRefused275        /// A signature is not 65 bytes, has a recovery byte outside 0, 1, 27, 28, or does not recover to a key.276        case invalidSignature277    }278279    /// The protocol refuses a transaction whose expiration is 24 hours or more after the head block.280    public static let maximumLifetimeMilliseconds: UInt64 = 86_400_000281    /// Longest memo the wallet writes (the protocol itself only bounds the transaction size).282    public static let maximumMemoBytes = 256283    /// Largest `Transaction.raw` accepted by the decoder.284    public static let maximumRawDataBytes = 16 << 10285    /// Bytes the network adds to the serialised size of a transaction when it charges bandwidth286    /// (java-tron `Constant.MAX_RESULT_SIZE_IN_TX`).287    public static let resultOverheadBytes = 64288    /// Serialised size of one signature inside a `Transaction`: tag, length, 65 bytes.289    public static let signatureFieldBytes = 67290291    /// Two bytes: see `TronBlockReference.refBlockBytes`.292    public let refBlockBytes: Bytes293    /// Eight bytes: see `TronBlockReference.refBlockHash`.294    public let refBlockHash: Bytes295    /// Milliseconds since 1970 after which the network refuses the transaction.296    public let expiration: UInt64297    /// Milliseconds since 1970 at which the transaction was built (0 when absent).298    public let timestamp: UInt64299    /// Most sun the contract call may burn for energy (0 = absent; unused by a TRX transfer).300    public let feeLimit: UInt64301    /// Free data attached to the transaction (`raw.data`); the network charges a memo fee when it is not empty.302    public let memo: Bytes303    public let contract: TronContract304    /// `Permission_id` of the contract: 0 is the owner permission; anything else names a multi-signature permission.305    public let permissionID: UInt32306307    public init(refBlockBytes: Bytes, refBlockHash: Bytes, expiration: UInt64, timestamp: UInt64, feeLimit: UInt64 = 0,308                memo: Bytes = [], contract: TronContract, permissionID: UInt32 = 0) throws(Error) {309        guard refBlockBytes.count == 2, refBlockHash.count == 8 else { throw .invalidReferenceBlock }310        let limit = UInt64(Int64.max)311        guard expiration <= limit, timestamp <= limit, feeLimit <= limit, permissionID <= UInt32(Int32.max), contract.type <= UInt32(Int32.max) else {312            throw .valueOutOfRange313        }314        switch contract {315        case .transfer(let c): guard c.amount <= limit else { throw .valueOutOfRange }316        case .triggerSmartContract(let c): guard c.callValue <= limit, c.callTokenValue <= limit, c.tokenID <= limit else { throw .valueOutOfRange }317        case .unknown: break318        }319        guard expiration > timestamp, expiration - timestamp <= Self.maximumLifetimeMilliseconds else { throw .invalidExpiration }320        guard memo.count <= Self.maximumMemoBytes else { throw .memoTooLong }321        self.init(unchecked: refBlockBytes, refBlockHash, expiration, timestamp, feeLimit, memo, contract, permissionID)322    }323324    private init(unchecked refBlockBytes: Bytes, _ refBlockHash: Bytes, _ expiration: UInt64, _ timestamp: UInt64, _ feeLimit: UInt64,325                 _ memo: Bytes, _ contract: TronContract, _ permissionID: UInt32) {326        self.refBlockBytes = refBlockBytes327        self.refBlockHash = refBlockHash328        self.expiration = expiration329        self.timestamp = timestamp330        self.feeLimit = feeLimit331        self.memo = memo332        self.contract = contract333        self.permissionID = permissionID334    }335336    /// A TRX transfer referring to `reference`.337    public static func transfer(from: TronAddress, to: TronAddress, amountSun: UInt64, reference: TronBlockReference,338                                timestamp: UInt64, expiration: UInt64, memo: Bytes = []) throws(Error) -> TronTransaction {339        try TronTransaction(refBlockBytes: reference.refBlockBytes, refBlockHash: reference.refBlockHash, expiration: expiration,340                            timestamp: timestamp, memo: memo, contract: .transfer(TronTransferContract(owner: from, to: to, amount: amountSun)))341    }342343    /// A TRC-20 `transfer(address,uint256)` referring to `reference`. No TRX and no TRC-10 token is attached to the call.344    public static func trc20Transfer(from: TronAddress, token: TronAddress, to: TronAddress, amount: UInt256, feeLimitSun: UInt64,345                                     reference: TronBlockReference, timestamp: UInt64, expiration: UInt64) throws(Error) -> TronTransaction {346        let call = TronTriggerSmartContract(owner: from, contract: token, data: ERC20.transfer(to: to.evm, amount: amount))347        return try TronTransaction(refBlockBytes: reference.refBlockBytes, refBlockHash: reference.refBlockHash, expiration: expiration,348                                   timestamp: timestamp, feeLimit: feeLimitSun, contract: .triggerSmartContract(call))349    }350351    // MARK: Encoding352353    /// Serialised `Transaction.raw`: fields in ascending number order, default values omitted.354    public var rawData: Bytes {355        var any = ProtoWriter()356        any.bytes(1, Bytes(contract.typeURL.utf8))357        any.bytes(2, contract.value)358        var c = ProtoWriter()359        c.varint(1, UInt64(contract.type))360        c.message(2, any.bytes)361        c.varint(5, UInt64(permissionID))362        var raw = ProtoWriter()363        raw.bytes(1, refBlockBytes)364        raw.bytes(4, refBlockHash)365        raw.varint(8, expiration)366        raw.bytes(10, memo)367        raw.message(11, c.bytes)368        raw.varint(14, timestamp)369        raw.varint(18, feeLimit)370        return raw.bytes371    }372373    /// Transaction id: SHA-256 of `rawData` (32 bytes). This is the digest that is signed.374    public var txID: Bytes { SHA256.hash(rawData) }375    public var txIDHex: String { Hex.encode(txID) }376377    /// The account that must sign, when the contract is one the wallet decodes.378    public var owner: TronAddress? { contract.owner }379380    /// Bytes the network charges as bandwidth once the transaction carries `signatureCount` signatures: the serialised381    /// `Transaction` plus `resultOverheadBytes`.382    public func bandwidthSize(signatureCount: Int = 1) -> Int {383        let raw = rawData.count384        return 1 + ProtoWriter.varint(UInt64(raw)).count + raw + max(0, signatureCount) * Self.signatureFieldBytes + Self.resultOverheadBytes385    }386387    // MARK: Decoding388389    /// Decodes a `Transaction.raw`, strictly: wire types 0 and 2 only, minimal varints, no unknown field, no duplicate,390    /// no negative integer, addresses of 21 bytes with the prefix 0x41, exactly one contract whose type URL matches391    /// its type, and bytes that are the canonical encoding of the result. A contract other than `TransferContract`392    /// and `TriggerSmartContract` comes back as `.unknown` with its raw message.393    public static func decode(rawData: Bytes) throws(TronProtobufError) -> TronTransaction {394        guard rawData.count <= maximumRawDataBytes else { throw .oversized }395        var reader = ProtoReader(rawData)396        var fields = ProtoFields("Transaction.raw")397        var refBytes = Bytes(), refHash = Bytes(), expiration: UInt64 = 0, timestamp: UInt64 = 0, feeLimit: UInt64 = 0, memo = Bytes()398        var contracts = [Bytes]()399        while let (field, value) = try reader.next() {400            switch field {401            case 1: refBytes = try fields.bytes(1, value)402            case 4: refHash = try fields.bytes(4, value)403            case 8: expiration = try fields.unsigned(8, value)404            case 10: memo = try fields.bytes(10, value)405            case 11:406                guard case .bytes(let b) = value else { throw .wrongWireType(field: 11) }407                contracts.append(b)408                guard contracts.count <= 1 else { throw .contractCount(contracts.count) }409            case 14: timestamp = try fields.unsigned(14, value)410            case 18: feeLimit = try fields.unsigned(18, value)411            default: throw fields.unknown(field)412            }413        }414        guard refBytes.count == 2 else { throw .invalidValue(message: "Transaction.raw", field: 1) }415        guard refHash.count == 8 else { throw .invalidValue(message: "Transaction.raw", field: 4) }416        guard let first = contracts.first else { throw .contractCount(0) }417        let (contract, permissionID) = try decodeContract(first)418        let tx = TronTransaction(unchecked: refBytes, refHash, expiration, timestamp, feeLimit, memo, contract, permissionID)419        guard tx.rawData == rawData else { throw .nonCanonical }420        return tx421    }422423    private static func decodeContract(_ data: Bytes) throws(TronProtobufError) -> (TronContract, UInt32) {424        var reader = ProtoReader(data)425        var fields = ProtoFields("Transaction.Contract")426        var type: UInt64 = 0, parameter: Bytes?, permission: UInt64 = 0427        while let (field, value) = try reader.next() {428            switch field {429            case 1: type = try fields.unsigned(1, value)430            case 2: parameter = try fields.bytes(2, value)431            case 5: permission = try fields.unsigned(5, value)432            default: throw fields.unknown(field)433            }434        }435        guard type <= UInt64(Int32.max) else { throw .invalidValue(message: "Transaction.Contract", field: 1) }436        guard permission <= UInt64(Int32.max) else { throw .invalidValue(message: "Transaction.Contract", field: 5) }437        guard let parameter else { throw .invalidValue(message: "Transaction.Contract", field: 2) }438439        var anyReader = ProtoReader(parameter)440        var anyFields = ProtoFields("Any")441        var urlBytes = Bytes(), inner = Bytes()442        while let (field, value) = try anyReader.next() {443            switch field {444            case 1: urlBytes = try anyFields.bytes(1, value)445            case 2: inner = try anyFields.bytes(2, value)446            default: throw anyFields.unknown(field)447            }448        }449        // a type URL is printable ASCII: anything else could not be shown faithfully450        guard urlBytes.count <= 200, urlBytes.allSatisfy({ $0 >= 0x21 && $0 <= 0x7e }) else { throw .invalidValue(message: "Any", field: 1) }451        let url = String(decoding: urlBytes, as: UTF8.self)452        let contract: TronContract453        switch type {454        case 1:455            guard url == TronTransferContract.typeURL else { throw .typeURLMismatch }456            contract = .transfer(try TronTransferContract.decode(inner))457        case 31:458            guard url == TronTriggerSmartContract.typeURL else { throw .typeURLMismatch }459            contract = .triggerSmartContract(try TronTriggerSmartContract.decode(inner))460        default:461            // a known wrapper around another type number would be shown under the wrong name462            guard url != TronTransferContract.typeURL, url != TronTriggerSmartContract.typeURL else { throw .typeURLMismatch }463            contract = .unknown(type: UInt32(type), typeURL: url, value: inner)464        }465        return (contract, UInt32(permission))466    }467468    // MARK: Signing469470    /// Signs the transaction id with the key of the account that owns the contract.471    ///472    /// The signature is r ‖ s ‖ v on 65 bytes, with a deterministic nonce (RFC 6979), low s and v = 27 or 28, as473    /// TronWeb and TronLink produce (the network also accepts v = 0 or 1). The key must derive to the owner address,474    /// and the result is checked by recovering the signer before it is returned. A contract the wallet cannot decode475    /// is refused unless `allowBlindSigning` is true, in which case the owner cannot be checked.476    public func sign(privateKey: Bytes, allowBlindSigning: Bool = false) throws -> SignedTronTransaction {477        let signer = try TronAddress(publicKey: try Secp256k1.publicKey(privateKey: privateKey, compressed: false))478        if let owner {479            guard owner == signer else { throw Error.signerMismatch }480        }481        if TronTransactionReview(self).requiresBlindSigning {482            guard allowBlindSigning else { throw Error.blindSigningRefused }483        }484        let signature = try Secp256k1.sign(digest: txID, privateKey: privateKey)485        guard signature.recoveryID < 2 else { throw Error.invalidSignature }486        let signed = SignedTronTransaction(unchecked: self, signatures: [signature.compact + [27 + signature.recoveryID]])487        guard try signed.signers() == [signer] else { throw Error.invalidSignature }488        return signed489    }490}491492/// A transaction and its signatures: the `Transaction` message that is broadcast.493public struct SignedTronTransaction: Equatable, Sendable {494    /// More signatures than a permission can require (five keys at most) is refused.495    public static let maximumSignatures = 5496497    public let transaction: TronTransaction498    /// 65 bytes each: r ‖ s ‖ v.499    public let signatures: [Bytes]500501    init(unchecked transaction: TronTransaction, signatures: [Bytes]) {502        self.transaction = transaction503        self.signatures = signatures504    }505506    /// nil unless there are between zero and five signatures of 65 bytes. Their validity is checked by `signers()`.507    public init?(transaction: TronTransaction, signatures: [Bytes]) {508        guard signatures.count <= Self.maximumSignatures, signatures.allSatisfy({ $0.count == 65 }) else { return nil }509        self.init(unchecked: transaction, signatures: signatures)510    }511512    public var txID: Bytes { transaction.txID }513    public var txIDHex: String { transaction.txIDHex }514515    /// Serialised `Transaction`: field 1 = raw_data, field 2 = each signature.516    public var serialized: Bytes {517        var w = ProtoWriter()518        w.message(1, transaction.rawData)519        for s in signatures { w.message(2, s) }520        return w.bytes521    }522523    /// Lower-case hexadecimal of `serialized`: the body of `/wallet/broadcasthex`.524    public var hex: String { Hex.encode(serialized) }525526    /// The address each signature recovers to on the transaction id, in order. Throws `invalidSignature` on a527    /// signature that is malformed or recovers to nothing. v may be 0, 1, 27 or 28.528    public func signers() throws -> [TronAddress] {529        let digest = txID530        return try signatures.map { s in531            guard s.count == 65 else { throw TronTransaction.Error.invalidSignature }532            let v = s[64] >= 27 ? s[64] - 27 : s[64]533            guard v < 2, let key = try? Secp256k1.recoverPublicKey(compactSignature: Bytes(s[0..<64]), recoveryID: v, digest: digest, compressed: false),534                  Secp256k1.verify(compactSignature: Bytes(s[0..<64]), digest: digest, publicKey: key, requireLowS: false),535                  let address = try? TronAddress(publicKey: key) else { throw TronTransaction.Error.invalidSignature }536            return address537        }538    }539540    /// True when the owner of the contract is among the signers (single-signature accounts).541    public var isSignedByOwner: Bool {542        guard let owner = transaction.owner, let signers = try? signers() else { return false }543        return signers.contains(owner)544    }545546    /// Decodes a serialised `Transaction` with zero to five signatures, as strictly as `TronTransaction.decode`.547    /// The execution results a node appends (`ret`, field 5) are not part of what is signed and are refused here.548    public static func decode(_ bytes: Bytes) throws(TronProtobufError) -> SignedTronTransaction {549        guard bytes.count <= TronTransaction.maximumRawDataBytes + 512 else { throw .oversized }550        var reader = ProtoReader(bytes)551        var fields = ProtoFields("Transaction")552        var raw: Bytes?553        var signatures = [Bytes]()554        while let (field, value) = try reader.next() {555            switch field {556            case 1: raw = try fields.bytes(1, value)557            case 2:558                guard case .bytes(let s) = value else { throw .wrongWireType(field: 2) }559                guard s.count == 65, signatures.count < maximumSignatures else { throw .invalidValue(message: "Transaction", field: 2) }560                signatures.append(s)561            default: throw fields.unknown(field)562            }563        }564        guard let raw else { throw .invalidValue(message: "Transaction", field: 1) }565        let signed = SignedTronTransaction(unchecked: try TronTransaction.decode(rawData: raw), signatures: signatures)566        guard signed.serialized == bytes else { throw .nonCanonical }567        return signed568    }569}570571/// What a transaction does, for the confirmation screen and for cold mode. Built from the decoded transaction only.572public struct TronTransactionReview: Equatable, Sendable {573    public enum Action: Equatable, Sendable {574        case trxTransfer(from: TronAddress, to: TronAddress, amountSun: UInt64)575        case trc20Transfer(from: TronAddress, token: TronAddress, to: TronAddress, amount: UInt256)576        case trc20Approve(owner: TronAddress, token: TronAddress, spender: TronAddress, amount: UInt256)577        /// A contract call that is not a plain TRC-20 transfer or approval: the data is shown raw.578        case contractCall(owner: TronAddress, contract: TronAddress, callValueSun: UInt64, data: Bytes, callTokenValue: UInt64, tokenID: UInt64)579        /// A contract type the wallet does not decode: `typeName` is its name in the protocol definition, when known.580        case unknownContract(type: UInt32, typeName: String?, typeURL: String, value: Bytes)581    }582583    public enum Warning: Equatable, Sendable {584        /// The wallet cannot show what the transaction does: the caller must present it as blind signing.585        case blindSigning586        /// An approval of 2^255 or more: the spender may move every token, now and later.587        case unlimitedApproval588        /// The contract names a permission other than the owner permission (multi-signature set-up).589        case nonOwnerPermission590        /// TRX or a TRC-10 token is attached to a contract call.591        case valueAttachedToCall592        /// A memo is attached; the network charges its memo fee.593        case memo594        /// Signatures are present and none comes from the owner of the contract.595        case notSignedByOwner596    }597598    public let action: Action599    /// The account that must sign; nil for an unknown contract.600    public let owner: TronAddress?601    public let txID: Bytes602    public let rawData: Bytes603    /// Most sun the call may burn for energy (0 when absent).604    public let feeLimitSun: UInt64605    /// Milliseconds since 1970.606    public let expiration: UInt64607    /// Milliseconds since 1970 (0 when absent).608    public let timestamp: UInt64609    public let memo: Bytes610    public let permissionID: UInt32611    public let signatureCount: Int612    /// Addresses recovered from the signatures; empty when there is none or when one of them is invalid.613    public let signers: [TronAddress]614    public let warnings: [Warning]615616    public var txIDHex: String { Hex.encode(txID) }617    public var requiresBlindSigning: Bool { warnings.contains(.blindSigning) }618    public var expirationDate: Date { Date(timeIntervalSince1970: TimeInterval(expiration / 1000)) }619    public func isExpired(atMilliseconds now: UInt64) -> Bool { expiration <= now }620621    /// The memo as text, when it is printable UTF-8.622    public var memoText: String? {623        guard !memo.isEmpty, let s = String(validating: memo, as: UTF8.self),624              s.unicodeScalars.allSatisfy({ $0.value >= 0x20 && $0.value != 0x7f }) else { return nil }625        return s626    }627628    public init(_ transaction: TronTransaction) { self.init(transaction, signatures: []) }629630    public init(_ signed: SignedTronTransaction) { self.init(signed.transaction, signatures: signed.signatures, signers: (try? signed.signers()) ?? []) }631632    private init(_ tx: TronTransaction, signatures: [Bytes], signers: [TronAddress] = []) {633        var warnings = [Warning]()634        switch tx.contract {635        case .transfer(let c):636            action = .trxTransfer(from: c.owner, to: c.to, amountSun: c.amount)637        case .triggerSmartContract(let c):638            switch c.trc20Call {639            case .transfer(let to, let amount)?:640                action = .trc20Transfer(from: c.owner, token: c.contract, to: TronAddress(evm: to), amount: amount)641            case .approve(let spender, let amount)?:642                action = .trc20Approve(owner: c.owner, token: c.contract, spender: TronAddress(evm: spender), amount: amount)643                if ERC20.isUnlimited(amount) { warnings.append(.unlimitedApproval) }644            case nil:645                action = .contractCall(owner: c.owner, contract: c.contract, callValueSun: c.callValue, data: c.data,646                                       callTokenValue: c.callTokenValue, tokenID: c.tokenID)647                warnings.append(.blindSigning)648                if c.callValue != 0 || c.callTokenValue != 0 { warnings.append(.valueAttachedToCall) }649            }650        case .unknown(let type, let url, let value):651            action = .unknownContract(type: type, typeName: TronContract.typeName(type), typeURL: url, value: value)652            warnings.append(.blindSigning)653        }654        if tx.permissionID != 0 { warnings.append(.nonOwnerPermission) }655        if !tx.memo.isEmpty { warnings.append(.memo) }656        if !signatures.isEmpty, let owner = tx.owner, !signers.contains(owner) { warnings.append(.notSignedByOwner) }657        owner = tx.owner658        txID = tx.txID659        rawData = tx.rawData660        feeLimitSun = tx.feeLimit661        expiration = tx.expiration662        timestamp = tx.timestamp663        memo = tx.memo664        permissionID = tx.permissionID665        signatureCount = signatures.count666        self.signers = signers667        self.warnings = warnings668    }669}670
Files main
Menu

Theme