SPB Git

Repository Public

TransactionTests.swift 20.0 KB 283 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraTronTests/TransactionTests.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 QyvoraCore47import QyvoraEthereum48@testable import QyvoraTron4950/// Two transactions read from the Nile test network on 2026-12-05 (`/wallet/gettransactionbyid`,51/// `/wallet/gettransactioninfobyid`, `/v1/accounts/…/transactions`): public chain data, signed by third parties.52enum NileSamples {53    /// TRC-20 transfer of 1000 units of the Nile USDT contract; receipt: net_fee 346000 sun, energy 29650, SUCCESS.54    static let tokenTxID = "fe6bdc97a3934657d79edb5839ae7db9dcadce572186c2aee61d0ade882e64d8"55    static let tokenRaw = "0a02794822082c94a67aadc4829340809cf1a4a4345aae01081f12a9010a31747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e54726967676572536d617274436f6e747261637412740a1541d3682962027e721c5247a9faf7865fe4a71d5438121541eca9bc828a3005b9a3b909f2cc5c2a54794de05f2244a9059cbb00000000000000000000000007140750a55b979ee3b69f5a8d276f6589bce563000000000000000000000000000000000000000000000000000000003b9aca007090d4eda4a43490018094ebdc03"56    static let tokenSignature = "c087e2c87f0cdf205b3668c990501938334d07199a2f0531094a4555bf4680e059151c114c2e31a9c7440c75e4b08b5b483ee4fa184e3b482d7cb0c0fb27d7e501"57    static let tokenOwner = "TVF2Mp9QY7FEGTnr3DBpFLobA6jguHyMvi"58    static let tokenBandwidth = 34659    /// TRX transfer of 103205 sun; receipt: net_fee 267000 sun.60    static let trxTxID = "de88c19453b5d0e8f839b34554664d668816e8587901d82769d31b88f46892c5"61    static let trxRaw = "0a023cff22084ff8ec47939c04b640cceda3f993345a67080112630a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412320a15411fab686441481c0df7970d951fb158df04eed31312154166426c7ac3d98b29191063833345b6bc540d727818a5a60670ec98a0f99334"62    static let trxSignature = "2d3d005e9dfd66b196a171429e1dea526ceb432c80896886979fdf0ab2db009472f192b1aa67b9ac4e996d1d11856a46d0e099e2a430257056b3d4ef83baff4c00"63    static let trxBandwidth = 26764}6566func hex(_ s: String) -> Bytes { Hex.decode(s) ?? [] }6768func build(_ v: TronVectors.Transaction) throws -> TronTransaction {69    let from = try #require(TronAddress(v.from)), to = try #require(TronAddress(v.to))70    let refBytes = hex(v.refBlockBytes), refHash = hex(v.refBlockHash)71    switch v.kind {72    case "trx":73        return try TronTransaction(refBlockBytes: refBytes, refBlockHash: refHash, expiration: v.expiration, timestamp: v.timestamp,74                                   memo: Bytes((v.memo ?? "").utf8),75                                   contract: .transfer(TronTransferContract(owner: from, to: to, amount: try #require(UInt64(v.amount)))))76    case "trc20-transfer", "trc20-approve":77        let token = try #require(TronAddress(v.token ?? "")), amount = try #require(UInt256(decimal: v.amount))78        let data = v.kind == "trc20-transfer" ? ERC20.transfer(to: to.evm, amount: amount) : ERC20.approve(spender: to.evm, amount: amount)79        return try TronTransaction(refBlockBytes: refBytes, refBlockHash: refHash, expiration: v.expiration, timestamp: v.timestamp,80                                   feeLimit: v.feeLimit, contract: .triggerSmartContract(TronTriggerSmartContract(owner: from, contract: token, data: data)))81    default:82        throw TronTransaction.Error.valueOutOfRange83    }84}8586@Suite struct TronTransactionTests {87    let key = hex(TronVectors.derivation[0].privateKey)8889    /// Locally encoded `Transaction.raw` and transaction id, byte for byte against TronWeb 6.5.1.90    @Test func encodingMatchesReference() throws {91        #expect(TronVectors.transactions.count == 10)92        #expect(TronVectors.transactions.filter { $0.kind == "trx" }.count == 6)93        #expect(TronVectors.transactions.filter { $0.kind == "trc20-transfer" }.count == 3)94        for v in TronVectors.transactions {95            let tx = try build(v)96            #expect(Hex.encode(tx.rawData) == v.rawDataHex, "\(v.name)")97            #expect(tx.txIDHex == v.txID, "\(v.name)")98            #expect(tx.txID == SHA256.hash(hex(v.rawDataHex)))99        }100    }101102    /// The convenience builders give the same bytes as the reference.103    @Test func buildersMatchReference() throws {104        let from = try #require(TronAddress(TronVectors.derivation[0].address))105        for v in TronVectors.transactions where v.memo == nil && v.kind != "trc20-approve" {106            // a block id whose bytes 6…15 are the reference fields of the vector107            let number = UInt64(hex(v.refBlockBytes)[0]) << 8 | UInt64(hex(v.refBlockBytes)[1])108            let id = Endian.be64(number) + hex(v.refBlockHash) + Bytes(repeating: 0xee, count: 16)109            let reference = try #require(TronBlockReference(number: number, id: id, timestamp: v.timestamp))110            #expect(reference.refBlockBytes == hex(v.refBlockBytes) && reference.refBlockHash == hex(v.refBlockHash))111            let to = try #require(TronAddress(v.to))112            let tx: TronTransaction113            if v.kind == "trx" {114                tx = try .transfer(from: from, to: to, amountSun: try #require(UInt64(v.amount)), reference: reference, timestamp: v.timestamp, expiration: v.expiration)115            } else {116                tx = try .trc20Transfer(from: from, token: try #require(TronAddress(v.token ?? "")), to: to, amount: try #require(UInt256(decimal: v.amount)),117                                        feeLimitSun: v.feeLimit, reference: reference, timestamp: v.timestamp, expiration: v.expiration)118            }119            #expect(Hex.encode(tx.rawData) == v.rawDataHex, "\(v.name)")120        }121    }122123    @Test func blockReference() throws {124        // mainnet block 88590960 as read on 2026-12-05125        let id = hex("000000000547ca70d6b17c88b4254293ed8d65c1e7b6836b4178d970ab50c210")126        let r = try #require(TronBlockReference(number: 88_590_960, id: id, timestamp: 1_796_447_349_000))127        #expect(Hex.encode(r.refBlockBytes) == "ca70")128        #expect(Hex.encode(r.refBlockHash) == "d6b17c88b4254293")129        #expect(r.idHex == "000000000547ca70d6b17c88b4254293ed8d65c1e7b6836b4178d970ab50c210")130        #expect(TronBlockReference(number: 88_590_961, id: id, timestamp: 0) == nil)131        #expect(TronBlockReference(number: 88_590_960, id: Bytes(id.dropLast()), timestamp: 0) == nil)132    }133134    /// Signatures are byte-identical to TronWeb's (RFC 6979, low s, v = 27/28) and recover to the sender.135    @Test func signaturesMatchReference() throws {136        let sender = try #require(TronAddress(TronVectors.derivation[0].address))137        for v in TronVectors.transactions {138            let signed = try build(v).sign(privateKey: key)139            #expect(signed.signatures.count == 1)140            #expect(Hex.encode(signed.signatures[0]) == v.signature, "\(v.name)")141            #expect(signed.signatures[0].count == 65 && (signed.signatures[0][64] == 27 || signed.signatures[0][64] == 28))142            #expect(try signed.signers() == [sender])143            #expect(signed.isSignedByOwner)144            #expect(signed.txIDHex == v.txID)145            #expect(signed.hex == "0a" + Hex.encode(ProtoWriter.varint(UInt64(v.rawDataHex.count / 2))) + v.rawDataHex + "1241" + v.signature)146            // v = 0/1 is the other accepted form of the same signature147            let alt = try #require(SignedTronTransaction(transaction: signed.transaction, signatures: [Bytes(signed.signatures[0].dropLast()) + [signed.signatures[0][64] - 27]]))148            #expect(try alt.signers() == [sender])149            // round trip of the broadcast form150            #expect(try SignedTronTransaction.decode(signed.serialized) == signed)151        }152    }153154    @Test func signingRefusals() throws {155        let tx = try build(TronVectors.transactions[0])156        // another key than the owner's157        #expect(throws: TronTransaction.Error.signerMismatch) { try tx.sign(privateKey: hex(TronVectors.derivation[1].privateKey)) }158        #expect(throws: (any Error).self) { try tx.sign(privateKey: Bytes(repeating: 0, count: 32)) }159        #expect(throws: (any Error).self) { try tx.sign(privateKey: [1, 2, 3]) }160        // an unknown contract and an opaque contract call need an explicit decision161        let unknown = try TronTransaction(refBlockBytes: [1, 2], refBlockHash: Bytes(repeating: 3, count: 8), expiration: 2000, timestamp: 1000,162                                          contract: .unknown(type: 54, typeURL: "type.googleapis.com/protocol.FreezeBalanceV2Contract", value: [0x0a, 0x01, 0x41]))163        #expect(throws: TronTransaction.Error.blindSigningRefused) { try unknown.sign(privateKey: key) }164        #expect(try unknown.sign(privateKey: key, allowBlindSigning: true).signatures.count == 1)165        let owner = try #require(TronAddress(TronVectors.derivation[0].address))166        let opaque = try TronTransaction(refBlockBytes: [1, 2], refBlockHash: Bytes(repeating: 3, count: 8), expiration: 2000, timestamp: 1000, feeLimit: 5,167                                         contract: .triggerSmartContract(TronTriggerSmartContract(owner: owner, contract: .zero, data: [0xde, 0xad, 0xbe, 0xef])))168        #expect(throws: TronTransaction.Error.blindSigningRefused) { try opaque.sign(privateKey: key) }169        // a forged or damaged signature does not recover to the owner170        var damaged = try tx.sign(privateKey: key).signatures[0]171        damaged[10] ^= 1172        let bad = try #require(SignedTronTransaction(transaction: tx, signatures: [damaged]))173        #expect((try? bad.signers()) != [owner])174        #expect(!bad.isSignedByOwner)175        let badV = try #require(SignedTronTransaction(transaction: tx, signatures: [Bytes(damaged.dropLast()) + [5]]))176        #expect(throws: TronTransaction.Error.invalidSignature) { try badV.signers() }177        let zero = try #require(SignedTronTransaction(transaction: tx, signatures: [Bytes(repeating: 0, count: 65)]))178        #expect(throws: TronTransaction.Error.invalidSignature) { try zero.signers() }179        #expect(SignedTronTransaction(transaction: tx, signatures: [Bytes(repeating: 1, count: 64)]) == nil)180        #expect(SignedTronTransaction(transaction: tx, signatures: Array(repeating: Bytes(repeating: 1, count: 65), count: 6)) == nil)181    }182183    @Test func constructionLimits() throws {184        let a = try #require(TronAddress(TronVectors.derivation[0].address)), b = try #require(TronAddress(TronVectors.derivation[1].address))185        let c = TronContract.transfer(TronTransferContract(owner: a, to: b, amount: 1))186        let ref8 = Bytes(repeating: 3, count: 8)187        #expect(throws: TronTransaction.Error.invalidReferenceBlock) { try TronTransaction(refBlockBytes: [1], refBlockHash: ref8, expiration: 2, timestamp: 1, contract: c) }188        #expect(throws: TronTransaction.Error.invalidReferenceBlock) { try TronTransaction(refBlockBytes: [1, 2], refBlockHash: [1], expiration: 2, timestamp: 1, contract: c) }189        #expect(throws: TronTransaction.Error.invalidExpiration) { try TronTransaction(refBlockBytes: [1, 2], refBlockHash: ref8, expiration: 1, timestamp: 1, contract: c) }190        #expect(throws: TronTransaction.Error.invalidExpiration) { try TronTransaction(refBlockBytes: [1, 2], refBlockHash: ref8, expiration: 86_400_002, timestamp: 1, contract: c) }191        #expect(throws: TronTransaction.Error.valueOutOfRange) { try TronTransaction(refBlockBytes: [1, 2], refBlockHash: ref8, expiration: UInt64(Int64.max) + 1, timestamp: UInt64(Int64.max), contract: c) }192        #expect(throws: TronTransaction.Error.valueOutOfRange) { try TronTransaction(refBlockBytes: [1, 2], refBlockHash: ref8, expiration: 2, timestamp: 1, feeLimit: UInt64.max, contract: c) }193        #expect(throws: TronTransaction.Error.valueOutOfRange) {194            try TronTransaction(refBlockBytes: [1, 2], refBlockHash: ref8, expiration: 2, timestamp: 1, contract: .transfer(TronTransferContract(owner: a, to: b, amount: UInt64(Int64.max) + 1)))195        }196        #expect(throws: TronTransaction.Error.valueOutOfRange) { try TronTransaction(refBlockBytes: [1, 2], refBlockHash: ref8, expiration: 2, timestamp: 1, contract: c, permissionID: UInt32.max) }197        #expect(throws: TronTransaction.Error.memoTooLong) { try TronTransaction(refBlockBytes: [1, 2], refBlockHash: ref8, expiration: 2, timestamp: 1, memo: Bytes(repeating: 65, count: 257), contract: c) }198        #expect(try TronTransaction(refBlockBytes: [1, 2], refBlockHash: ref8, expiration: 86_400_001, timestamp: 1, memo: Bytes(repeating: 65, count: 256), contract: c).memo.count == 256)199    }200201    /// Decoding the reference bytes gives back the fields, and the review says what the transaction does.202    @Test func decodeAndReview() throws {203        let sender = try #require(TronAddress(TronVectors.derivation[0].address))204        for v in TronVectors.transactions {205            let raw = hex(v.rawDataHex)206            let tx = try TronTransaction.decode(rawData: raw)207            #expect(tx == (try build(v)))208            #expect(tx.rawData == raw)209            #expect(tx.expiration == v.expiration && tx.timestamp == v.timestamp && tx.feeLimit == v.feeLimit)210            let review = TronTransactionReview(tx)211            #expect(review.owner == sender && review.txIDHex == v.txID && review.rawData == raw)212            #expect(review.feeLimitSun == v.feeLimit && review.expiration == v.expiration && review.signatureCount == 0)213            #expect(!review.requiresBlindSigning)214            #expect(review.isExpired(atMilliseconds: v.expiration) && !review.isExpired(atMilliseconds: v.expiration - 1))215            let to = try #require(TronAddress(v.to))216            switch v.kind {217            case "trx":218                #expect(review.action == .trxTransfer(from: sender, to: to, amountSun: try #require(UInt64(v.amount))))219                #expect(review.memoText == v.memo)220                #expect(review.warnings == (v.memo == nil ? [] : [.memo]))221            case "trc20-transfer":222                #expect(review.action == .trc20Transfer(from: sender, token: try #require(TronAddress(v.token ?? "")), to: to, amount: try #require(UInt256(decimal: v.amount))))223                #expect(review.warnings.isEmpty)224            default:225                #expect(review.action == .trc20Approve(owner: sender, token: try #require(TronAddress(v.token ?? "")), spender: to, amount: try #require(UInt256(decimal: v.amount))))226            }227        }228    }229230    /// Transactions taken from the chain: id, signer and the bandwidth the network actually charged.231    @Test func onChainSamples() throws {232        let token = try TronTransaction.decode(rawData: hex(NileSamples.tokenRaw))233        #expect(token.txIDHex == NileSamples.tokenTxID)234        #expect(token.feeLimit == 1_000_000_000)235        let owner = try #require(TronAddress(NileSamples.tokenOwner))236        #expect(TronTransactionReview(token).action == .trc20Transfer(from: owner, token: try #require(TronAddress("TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf")),237                                                                       to: try #require(TronAddress(hex: "4107140750a55b979ee3b69f5a8d276f6589bce563")), amount: UInt256(1_000_000_000)))238        let signedToken = try #require(SignedTronTransaction(transaction: token, signatures: [hex(NileSamples.tokenSignature)]))239        #expect(try signedToken.signers() == [owner]) // v = 1240        #expect(signedToken.isSignedByOwner && TronTransactionReview(signedToken).warnings.isEmpty)241        #expect(token.bandwidthSize() == NileSamples.tokenBandwidth)242        #expect(signedToken.serialized.count + TronTransaction.resultOverheadBytes == NileSamples.tokenBandwidth)243244        let trx = try TronTransaction.decode(rawData: hex(NileSamples.trxRaw))245        #expect(trx.txIDHex == NileSamples.trxTxID)246        let sender = try #require(TronAddress(hex: "411fab686441481c0df7970d951fb158df04eed313"))247        #expect(TronTransactionReview(trx).action == .trxTransfer(from: sender, to: try #require(TronAddress("TKHuVq1oKVruCGLvqVexFs6dawKv6fQgFs")), amountSun: 103_205))248        let signedTrx = try #require(SignedTronTransaction(transaction: trx, signatures: [hex(NileSamples.trxSignature)]))249        #expect(try signedTrx.signers() == [sender]) // v = 0250        #expect(trx.bandwidthSize() == NileSamples.trxBandwidth)251        // a signature of another transaction is flagged252        let crossed = try #require(SignedTronTransaction(transaction: trx, signatures: [hex(NileSamples.tokenSignature)]))253        #expect(TronTransactionReview(crossed).warnings == [.notSignedByOwner])254    }255256    @Test func reviewWarnings() throws {257        let a = try #require(TronAddress(TronVectors.derivation[0].address)), b = try #require(TronAddress(TronVectors.derivation[1].address))258        let ref8 = Bytes(repeating: 3, count: 8)259        func tx(_ c: TronContract, permission: UInt32 = 0) throws -> TronTransaction {260            try TronTransaction(refBlockBytes: [1, 2], refBlockHash: ref8, expiration: 2000, timestamp: 1000, feeLimit: 7, contract: c, permissionID: permission)261        }262        let unlimited = try tx(.triggerSmartContract(TronTriggerSmartContract(owner: a, contract: b, data: ERC20.approve(spender: b.evm, amount: .max))))263        #expect(TronTransactionReview(unlimited).warnings == [.unlimitedApproval])264        // value attached to what looks like a token transfer: not shown as a token transfer265        let withValue = try tx(.triggerSmartContract(TronTriggerSmartContract(owner: a, contract: b, callValue: 5, data: ERC20.transfer(to: b.evm, amount: UInt256(1)))))266        let r = TronTransactionReview(withValue)267        #expect(r.warnings == [.blindSigning, .valueAttachedToCall])268        #expect(r.action == .contractCall(owner: a, contract: b, callValueSun: 5, data: ERC20.transfer(to: b.evm, amount: UInt256(1)), callTokenValue: 0, tokenID: 0))269        // non-zero bytes above the address word: not a plain transfer270        var dirty = ERC20.transfer(to: b.evm, amount: UInt256(1))271        dirty[15] = 0x41272        #expect(TronTransactionReview(try tx(.triggerSmartContract(TronTriggerSmartContract(owner: a, contract: b, data: dirty)))).requiresBlindSigning)273        let unknown = try tx(.unknown(type: 4, typeURL: "type.googleapis.com/protocol.VoteWitnessContract", value: [0x0a, 0x00]), permission: 2)274        let u = TronTransactionReview(unknown)275        #expect(u.action == .unknownContract(type: 4, typeName: "VoteWitnessContract", typeURL: "type.googleapis.com/protocol.VoteWitnessContract", value: [0x0a, 0x00]))276        #expect(u.warnings == [.blindSigning, .nonOwnerPermission] && u.owner == nil)277        // unknown contracts and permission ids survive a round trip278        #expect(try TronTransaction.decode(rawData: unknown.rawData) == unknown)279        #expect(try TronTransaction.decode(rawData: withValue.rawData) == withValue)280        #expect(TronContract.typeName(7) == nil && TronContract.typeName(31) == "TriggerSmartContract")281    }282}283
Files main
Menu

Theme