SPB Git

Repository Public

TronAuditRegressionTests.swift 29.3 KB 477 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraWalletTests/TronAuditRegressionTests.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 Testing43import QyvoraMath44import QyvoraCore45import QyvoraEthereum46import QyvoraNetworking47import QyvoraStorage48import QyvoraVault49@testable import QyvoraTron50@testable import QyvoraWallet5152/// A transport in front of the multi-chain backend that records every request as it was sent (headers and body53/// included), renames hosts before forwarding, and can answer for a node of its own.54final class RecordingTronTransport: HTTPTransport, @unchecked Sendable {55    let backend: MultiBackend56    /// Hosts answered by the TRON model of the backend (forwarded as `tron.test`).57    var nodeHosts: Set<String> = []58    /// Hosts answered by the TRON index of the backend (GET requests of a node host go there too).59    var indexHosts: Set<String> = []60    /// A node of the test's own: (path, body) → answer, nil = HTTP 404.61    var scripted: [String: @Sendable (String, Data) -> String?] = [:]62    private let lock = NSLock()63    private var log = [URLRequest]()6465    init(backend: MultiBackend) { self.backend = backend }6667    var requests: [URLRequest] { lock.withLock { log } }6869    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {70        lock.withLock { log.append(request) }71        let url = request.url!72        let host = url.host ?? ""73        if let script = scripted[host] {74            let body = script(url.path, request.httpBody ?? Data())75            return (Data((body ?? "{}").utf8), HTTPURLResponse(url: url, statusCode: body == nil ? 404 : 200, httpVersion: "HTTP/1.1", headerFields: nil)!)76        }77        if nodeHosts.contains(host) || indexHosts.contains(host) {78            var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!79            components.host = request.httpMethod == "GET" || !nodeHosts.contains(host) ? "tronindex.test" : "tron.test"80            var forwarded = URLRequest(url: components.url!)81            forwarded.httpMethod = request.httpMethod82            forwarded.httpBody = request.httpBody83            return try await backend.send(forwarded)84        }85        return try await backend.send(request)86    }87}8889/// Regression tests of the multi-chain security audit, TRON part (QYV-SVC-040 to QYV-SVC-042), and the tests the audit90/// asked for on the TronGrid API key and on the limits at signing time.91@Suite(.readsMainnetPolicy) struct TronAuditRegressionTests {92    static let trx: UInt64 = 1_000_0009394    /// A full wallet on the test phrase, TRON enabled, behind a recording transport.95    static func recordingWallet(_ configure: (RecordingTronTransport, inout ChainEndpoints) -> Void) async throws -> (service: WalletService, transport: RecordingTronTransport, clock: TestClock, directory: URL) {96        let backend = MultiBackend()97        let transport = RecordingTronTransport(backend: backend)98        let clock = TestClock()99        let directory = FileManager.default.temporaryDirectory.appendingPathComponent("qy-tron-audit-\(UUID().uuidString)")100        let store = try FileStore(root: directory)101        let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting, now: { clock.now }, monotonic: { clock.monotonic }))102        let service = try WalletService(vault: vault, fileStore: store, transport: transport, now: { clock.now }, monotonic: { clock.monotonic }, sleep: { _ in },103                                        transactionSeed: 7, backupKDF: .insecureForTesting, internalBuildAllowsMainnet: false, tronPacing: .unthrottled)104        var endpoints = MultiBackend.endpoints()105        configure(transport, &endpoints)106        try await service.setChainEndpoints(endpoints)107        backend.tron.headTimestamp = UInt64(clock.now.timeIntervalSince1970 * 1000)108        try await service.importWallet(words: Harness.abandon, password: Harness.password)109        try await service.setEnabledChains([.tron])110        backend.tron.balances[MultiHarness.tronHex(MultiHarness.tronAddress)] = 50 * trx111        return (service, transport, clock, directory)112    }113114    /// Every regular file under a directory, at any depth.115    static func regularFiles(under directory: URL) -> [URL] {116        guard let enumerator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: [.isRegularFileKey]) else { return [] }117        var out = [URL]()118        for case let file as URL in enumerator where (try? file.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true { out.append(file) }119        return out120    }121122    // MARK: QYV-SVC-040 — the reference block is cross-checked123124    /// A node that passes the genesis check and then hands out a reference block the other node does not have at that125    /// height (a block of another TRON network, for instance) used to be believed when it answered first: the126    /// transaction was built on its block. The payment is now refused before anything is built.127    @Test func aNodeThatGivesAnotherReferenceBlockStopsThePayment() async throws {128        let liarID: @Sendable (UInt64) -> String = { Hex.encode(Endian.be64($0) + Bytes(repeating: 0xcd, count: 24)) }129        let w = try await Self.recordingWallet { transport, endpoints in130            let head = transport.backend.tron.headNumber131            let now = UInt64(TestClock().now.timeIntervalSince1970 * 1000)132            transport.scripted["liar.test"] = { path, body in133                switch path {134                case "/wallet/getblockbynum":135                    return #"{"blockID":"\#(TronNetwork.nile.genesisBlockID)","block_header":{"raw_data":{"txTrieRoot":"00"}}}"#136                case "/walletsolidity/getblock":137                    return #"{"blockID":"\#(liarID(head - 19))","block_header":{"raw_data":{"timestamp":\#(now),"number":\#(head - 19)}}}"#138                default:139                    return nil140                }141            }142            endpoints.tron.fullNodes["nile"] = ["https://liar.test", "https://tron.test"]143        }144        defer { try? FileManager.default.removeItem(at: w.directory) }145        let refusal = await walletError { try await w.service.prepareSend(chain: .tronNile, asset: .native, to: tronStranger().base58, amount: UInt256(Self.trx)) }146        guard case .wrongChain(let text)? = refusal else {147            Issue.record("expected a refusal, got \(String(describing: refusal))")148            return149        }150        #expect(text.contains("different irreversible blocks"))151    }152153    /// Two nodes that agree: the review says so. One node only: the review says that nothing could be compared.154    @Test func theReviewSaysHowManyNodesVouchForTheReferenceBlock() async throws {155        let two = try await Self.recordingWallet { transport, endpoints in156            transport.nodeHosts = ["second.test"]157            endpoints.tron.fullNodes["nile"] = ["https://tron.test", "https://second.test"]158        }159        defer { try? FileManager.default.removeItem(at: two.directory) }160        let agreed = try await two.service.prepareSend(chain: .tronNile, asset: .native, to: tronStranger().base58, amount: UInt256(Self.trx))161        #expect(agreed.notes.contains("The reference block of this transaction is the same on 2 TRON nodes."))162163        let one = try await Self.recordingWallet { _, _ in }164        defer { try? FileManager.default.removeItem(at: one.directory) }165        let alone = try await one.service.prepareSend(chain: .tronNile, asset: .native, to: tronStranger().base58, amount: UInt256(Self.trx))166        #expect(alone.notes.contains { $0.hasPrefix("Only one TRON node vouched for the reference block") })167    }168169    // MARK: QYV-SVC-041 — the validity of what is signed is bounded by the wallet170171    static func transfer(amountSun: UInt64 = 5 * trx, feeLimit: UInt64 = 0, validFor seconds: Int64, clock: TestClock) throws -> TronTransaction {172        let now = UInt64(clock.now.timeIntervalSince1970 * 1000)173        let expiration = UInt64(Int64(now) + seconds * 1000)174        let owner = try #require(TronAddress(MultiHarness.tronAddress))175        return try TronTransaction(refBlockBytes: [0x12, 0x34], refBlockHash: Bytes(repeating: 0x56, count: 8), expiration: expiration,176                                   timestamp: min(now, expiration - 1), feeLimit: feeLimit,177                                   contract: .transfer(TronTransferContract(owner: owner, to: tronStranger(), amount: amountSun)))178    }179180    /// A cold device used to sign a transaction valid for as long as the protocol allows (a day): bytes that can be181    /// held back and broadcast much later, on any TRON network that has the reference block. It now signs nothing182    /// that stays valid for more than an hour (plus five minutes of clock skew), and nothing already expired.183    @Test func aColdDeviceDoesNotSignATransactionValidForMoreThanAnHour() async throws {184        // an offline device of an unaudited build signs no test-network TRON transaction at all (QYV-APP-040): the185        // bound on the validity is checked on the device that signs, which is online186        let offline = try await MultiChainSendTests.coldDevice(chains: [.tron])187        defer { offline.cleanup() }188        guard case .unauditedLimitUnverifiable? = await walletError({189            try await offline.service.signColdTransaction(["qyvtx1|u|tron-nile|\(Hex.encode(try Self.transfer(validFor: 600, clock: offline.clock).rawData))"])190        }) else {191            Issue.record("an offline device must not sign a test-network TRON transaction")192            return193        }194        let cold = try await MultiHarness.wallet(chains: [.tron])195        defer { cold.cleanup() }196        func sign(validFor seconds: Int64) async -> WalletError? {197            do {198                let tx = try Self.transfer(validFor: seconds, clock: cold.clock)199                let signed = try await cold.service.signColdTransaction(["qyvtx1|u|tron-nile|\(Hex.encode(tx.rawData))"])200                #expect(signed.id == tx.txIDHex)201                return nil202            } catch {203                return error as? WalletError ?? .signingFailed("not a WalletError: \(error)")204            }205        }206        guard case .signingFailed(let text)? = await sign(validFor: 86_400) else {207            Issue.record("a transaction valid for a day must not be signed")208            return209        }210        #expect(text.contains("more than an hour"))211        guard case .signingFailed? = await sign(validFor: 3_901) else {212            Issue.record("a transaction valid for an hour, five minutes and a second must not be signed")213            return214        }215        guard case .transactionExpired? = await sign(validFor: -10) else {216            Issue.record("an expired transaction must not be signed")217            return218        }219        #expect(await sign(validFor: 3_900) == nil)220        #expect(await sign(validFor: 1_800) == nil)221    }222223    /// The cold review of a test-network transaction says that nothing in the bytes names the network.224    @Test func theColdReviewOfATestNetworkTransactionSaysItIsNotBoundToItsNetwork() async throws {225        let cold = try await MultiChainSendTests.coldDevice(chains: [.tron])226        defer { cold.cleanup() }227        let tx = try Self.transfer(validFor: 600, clock: cold.clock)228        let review = try await cold.service.reviewColdTransaction(["qyvtx1|u|tron-nile|\(Hex.encode(tx.rawData))"])229        #expect(review.warnings.contains { $0.id == "tron.network-not-bound" && $0.isCritical && $0.message.contains("does not name its network") })230        #expect(review.signingRefusal != nil)231        #expect(review.summary.contains { $0.contains("would also be valid on TRON mainnet") })232    }233234    // MARK: QYV-SVC-042 — the burn address235236    @Test func theBurnAddressOfTheMainNetworkIsRefused() async throws {237        let h = try await MultiHarness.wallet(chains: [.tron])238        defer { h.cleanup() }239        let burn = "TLsV52sRDL79HXGGm9yzwKibb6BeruhUzy"240        #expect(TronNetwork.mainnet.burnAddress?.base58 == burn && TronNetwork.nile.burnAddress == nil && TronNetwork.shasta.burnAddress == nil)241        guard case .address(.unsupported(let text))? = await walletError({ try await h.service.checkAddress(burn, chain: .tron) }) else {242            Issue.record("the burn address must be refused on the main network")243            return244        }245        #expect(text.contains("burns fees"))246        // on a test network the same bytes are an ordinary address247        #expect(try await h.service.checkAddress(burn, chain: .tronNile).canonical == burn)248    }249250    // MARK: Limits at signing time, whatever the plan says251252    /// On every network `fee_limit` above 100 TRX is refused when signing, even for a transaction that never went253    /// through `prepareSend` (a plan built by hand, a cold payload).254    @Test func aFeeLimitAboveTheCeilingIsNotSignedOnAnyNetwork() async throws {255        let h = try await MultiHarness.wallet(chains: [.tron])256        defer { h.cleanup() }257        let owner = try #require(TronAddress(MultiHarness.tronAddress))258        let now = UInt64(h.clock.now.timeIntervalSince1970 * 1000)259        let reference = try #require(TronBlockReference(number: 7, id: Endian.be64(7) + Bytes(repeating: 1, count: 24), timestamp: now))260        func call(feeLimit: UInt64) throws -> TronTransaction {261            try TronTransaction.trc20Transfer(from: owner, token: tronStranger(0x51), to: tronStranger(), amount: UInt256(1), feeLimitSun: feeLimit,262                                              reference: reference, timestamp: now, expiration: now + 60_000)263        }264        #expect(await walletError { try await h.service.signTron(try call(feeLimit: 100_000_001), network: .nile) }265            == .tron(.feeLimitTooHigh(requiredSun: 100_000_001, capSun: 100_000_000)))266        #expect(await walletError { try await h.service.signTron(try call(feeLimit: UInt64(Int64.max)), network: .nile) }267            == .tron(.feeLimitTooHigh(requiredSun: UInt64(Int64.max), capSun: 100_000_000)))268        #expect(try await h.service.signTron(try call(feeLimit: 100_000_000), network: .nile).isSignedByOwner)269    }270271    /// A copy of a review around another plan (possible inside the module only: neither type has a public initialiser).272    static func forged(_ honest: SendReview, network: TronNetwork, transaction: TronTransaction, amount: UInt256? = nil, recipient: String? = nil) throws -> SendReview {273        guard case .tron(let details) = honest.body else { throw WalletError.invalidInput("not a TRON review") }274        let p = details.plan275        let plan = TronSendPlan(transaction: transaction, asset: p.asset, from: p.from, to: recipient.flatMap { TronAddress($0) } ?? p.to, amount: amount ?? p.amount,276                                bandwidthBytes: p.bandwidthBytes, bandwidthSource: p.bandwidthSource, bandwidthFeeSun: p.bandwidthFeeSun, energyEstimate: 0,277                                energyLimit: 0, energyAvailable: 0, energyFeeSun: 0, activationFeeSun: 0, memoFeeSun: 0, feeLimitSun: 0,278                                estimatedFeeSun: p.estimatedFeeSun, maximumFeeSun: p.maximumFeeSun, maximumDebitSun: p.maximumDebitSun, notes: [])279        return SendReview(id: UUID(), chain: honest.chain, createdAt: honest.createdAt, isMainnet: honest.isMainnet, unauditedMainnet: honest.unauditedMainnet,280                          limits: honest.limits, from: honest.from, recipient: recipient ?? honest.recipient, asset: honest.asset, amount: amount ?? honest.amount,281                          amountDecimals: honest.amountDecimals, amountSymbol: honest.amountSymbol, fee: honest.fee, totalNative: honest.totalNative, isSendMax: false,282                          warnings: [], notes: [], expiresAt: honest.expiresAt, body: .tron(TronSendDetails(network: network, plan: plan)))283    }284285    /// What is signed is what the review shows: a review whose transaction pays another recipient, another amount or286    /// carries another contract is refused before anything is signed.287    @Test func aReviewThatDoesNotMatchItsTransactionIsNotSigned() async throws {288        let h = try await MultiHarness.wallet(chains: [.tron])289        defer { h.cleanup() }290        let owner = try #require(TronAddress(MultiHarness.tronAddress))291        h.backend.tron.balances[owner.hex] = 50 * Self.trx292        let recipient = tronStranger()293        let honest = try await h.service.prepareSend(chain: .tronNile, asset: .native, to: recipient.base58, amount: UInt256(Self.trx))294        guard case .tron(let details) = honest.body else {295            Issue.record("not a TRON review")296            return297        }298        let t = details.plan.transaction299        func variant(_ contract: TronContract, feeLimit: UInt64 = 0, permission: UInt32 = 0) throws -> TronTransaction {300            try TronTransaction(refBlockBytes: t.refBlockBytes, refBlockHash: t.refBlockHash, expiration: t.expiration, timestamp: t.timestamp, feeLimit: feeLimit,301                                contract: contract, permissionID: permission)302        }303        let stale = WalletError.stalePlan("The transaction does not match its review.")304        let others: [TronTransaction] = [305            try variant(.transfer(TronTransferContract(owner: owner, to: tronStranger(0x44), amount: Self.trx))),306            try variant(.transfer(TronTransferContract(owner: owner, to: recipient, amount: Self.trx + 1))),307            try variant(.transfer(TronTransferContract(owner: owner, to: recipient, amount: Self.trx)), permission: 2),308            try variant(.triggerSmartContract(TronTriggerSmartContract(owner: owner, contract: recipient, callValue: Self.trx, data: []))),309            try variant(.triggerSmartContract(TronTriggerSmartContract(owner: owner, contract: tronStranger(0x51), data: ERC20.transfer(to: recipient.evm, amount: UInt256(Self.trx)))), feeLimit: 1),310            try variant(.unknown(type: 4, typeURL: "type.googleapis.com/protocol.VoteWitnessContract", value: [1, 2, 3])),311        ]312        for other in others {313            #expect(await walletError { try await h.service.signAndBroadcast(try Self.forged(honest, network: .nile, transaction: other)) } == stale)314        }315        #expect(h.backend.tron.broadcasts.isEmpty)316        // the honest review still goes through317        _ = try await h.service.signAndBroadcast(honest)318        #expect(h.backend.tron.broadcasts.count == 1 && h.backend.tron.broadcasts[0].transaction == t)319    }320321    // MARK: QYV-SVC-040 — a test-network transaction that the main network would accept322323    /// A TRON transaction names no network and the account is the same key everywhere: a test-network node that hands324    /// out a main-network block as reference obtains a signature that moves real funds on the main network, past the325    /// mainnet switch and the limits. Before the fix the Nile payment below was reviewed, signed and sent.326    @Test func aTestNetworkTransactionTheMainNetworkWouldAcceptIsNeverSigned() async throws {327        let h = try await MultiHarness.wallet(chains: [.tron])328        defer { h.cleanup() }329        let node = h.backend.tron330        let owner = try #require(TronAddress(MultiHarness.tronAddress))331        node.balances[owner.hex] = 50 * Self.trx332        let recipient = tronStranger()333334        // the main network has the block the Nile node gave: refused when preparing335        node.mainnetAcceptsTestReferences = true336        guard case .wrongChain(let text)? = await walletError({ try await h.service.prepareSend(chain: .tronNile, asset: .native, to: recipient.base58, amount: UInt256(Self.trx)) }) else {337            Issue.record("a Nile transaction whose reference block is a main-network block must be refused")338            return339        }340        #expect(text.contains("valid on the main network"))341        #expect(h.backend.requests.contains("POST tron-main.test/wallet/getblockbynum"))342343        // …and when signing, should the answer change in between344        node.mainnetAcceptsTestReferences = false345        let review = try await h.service.prepareSend(chain: .tronNile, asset: .native, to: recipient.base58, amount: UInt256(Self.trx))346        node.mainnetAcceptsTestReferences = true347        guard case .wrongChain? = await walletError({ try await h.service.signAndBroadcast(review) }) else {348            Issue.record("the check must be made again before signing")349            return350        }351        #expect(node.broadcasts.isEmpty)352353        // no main-network node answers: the check cannot be made, nothing is signed354        node.mainnetAcceptsTestReferences = false355        h.backend.silentHosts = ["tron-main.test"]356        guard case .network(let why)? = await walletError({ try await h.service.signAndBroadcast(review) }) else {357            Issue.record("without an answer from the main network nothing may be signed")358            return359        }360        #expect(why.contains("does not sign it") && node.broadcasts.isEmpty)361362        // the main network does not know the block: signed and sent as before363        h.backend.silentHosts = []364        _ = try await h.service.signAndBroadcast(review)365        #expect(node.broadcasts.count == 1)366    }367368    // MARK: The TronGrid API key369370    /// The key is sent in its header to TronGrid hosts only: never to a custom node, never to the history of another371    /// host, never to the price source, never in a URL or a body, and no file of the application holds it after a372    /// synchronization, a payment and a failure.373    @Test func theTronGridKeyGoesToTronGridHostsOnlyAndNowhereElse() async throws {374        let key = "5c1f0b9a-audit-KEY_0123456789abcdef"375        let w = try await Self.recordingWallet { transport, endpoints in376            transport.nodeHosts = ["nile.trongrid.io", "custom-node.example.org", "nile.trongrid.io.example.org"]377            transport.indexHosts = ["nile.trongrid.io", "index.example.org"]378            endpoints.tron.fullNodes["nile"] = ["https://custom-node.example.org", "https://nile.trongrid.io", "https://nile.trongrid.io.example.org"]379            endpoints.tron.history["nile"] = ["https://index.example.org", "https://nile.trongrid.io"]380        }381        defer { try? FileManager.default.removeItem(at: w.directory) }382        try await w.service.setTronAPIKey(key)383        try await w.service.syncTron(.nile)384        let review = try await w.service.prepareSend(chain: .tronNile, asset: .native, to: tronStranger().base58, amount: UInt256(Self.trx))385        _ = try await w.service.signAndBroadcast(review)386        // a failure whose text goes to the snapshot: the custom node first, then TronGrid, both refusing387        w.transport.backend.tron.parameters = "{}"388        let failure = await walletError { try await w.service.prepareSend(chain: .tronNile, asset: .native, to: tronStranger().base58, amount: UInt256(Self.trx)) }389        #expect(failure != nil && "\(String(describing: failure))".contains(key) == false && (failure?.userMessage.contains(key) ?? true) == false)390        try? await w.service.syncTron(.nile)391392        var toTronGrid = 0, elsewhere = 0393        for request in w.transport.requests {394            let url = try #require(request.url)395            let host = url.host ?? ""396            let headers = request.allHTTPHeaderFields ?? [:]397            #expect(url.absoluteString.contains(key) == false, "key in a URL: \(host)")398            #expect(String(decoding: request.httpBody ?? Data(), as: UTF8.self).contains(key) == false, "key in a body: \(host)")399            if host == "nile.trongrid.io" {400                toTronGrid += 1401                #expect(headers["TRON-PRO-API-KEY"] == key && url.scheme == "https")402            } else {403                elsewhere += 1404                #expect(headers.values.contains { $0.contains(key) } == false, "key sent to \(host)")405                #expect(headers.keys.contains { $0.uppercased() == "TRON-PRO-API-KEY" } == false, "key header sent to \(host)")406            }407        }408        #expect(toTronGrid > 0 && elsewhere > 0)409        let hosts = Set(w.transport.requests.compactMap { $0.url?.host })410        #expect(hosts.isSuperset(of: ["custom-node.example.org", "nile.trongrid.io", "index.example.org"]))411412        // nothing on disk holds it (the vault file holds it encrypted), nor the snapshot, nor the profile413        let files = Self.regularFiles(under: w.directory)414        for file in files {415            let data = try Data(contentsOf: file)416            #expect(data.range(of: Data(key.utf8)) == nil, "\(file.lastPathComponent)")417        }418        #expect(files.count > 0)419        let profile = await w.service.currentProfile()420        let profileText = String(decoding: try JSONEncoder().encode(profile), as: UTF8.self)421        #expect(profile.hasTronAPIKey && profileText.contains(key) == false)422        let snapshot = await w.service.chainSnapshots()423        #expect("\(snapshot)".contains(key) == false)424        let held = await w.service.tronAPIKey425        #expect("\(String(describing: held))".contains(key) == false && String(reflecting: held).contains(key) == false)426        var dumped = ""427        dump(held, to: &dumped)428        #expect(dumped.contains(key) == false)429    }430}431432// MARK: - Main network (serialised with the other tests of the process-wide policy)433434extension MainnetPolicyTests {435    /// A review cannot be built through the public API (no public initialiser, no mutable field), and a plan forged436    /// inside the module does not get an amount above the ceiling signed: the limit is read from the bytes again.437    @Test func aForgedTronPlanAboveTheCeilingIsNotSigned() async throws {438        Self.reset()439        defer { Self.reset() }440        let h = try await Self.mainnetMultiWallet(chains: [.tron], prices: [("tron", "0.25"), ("tether", "1")])441        defer { h.cleanup() }442        let me = try #require(TronAddress(MultiHarness.tronAddress))443        let recipient = tronStranger()444        h.backend.tron.balances[me.hex] = 10_000 * MultiChainSendTests.trx445        h.backend.tron.balances[recipient.hex] = 1446        try await h.service.refreshMarket()447        // 150 USD at 0.25 USD per TRX: 600 TRX448        let honest = try await h.service.prepareSend(chain: .tron, asset: .native, to: recipient.base58, amount: UInt256(100 * MultiChainSendTests.trx))449        guard case .tron(let details) = honest.body else {450            Issue.record("not a TRON review")451            return452        }453        let t = details.plan.transaction454        let big = try TronTransaction(refBlockBytes: t.refBlockBytes, refBlockHash: t.refBlockHash, expiration: t.expiration, timestamp: t.timestamp,455                                      contract: .transfer(TronTransferContract(owner: me, to: recipient, amount: 601 * MultiChainSendTests.trx)))456        // the review still shows 100 TRX and the bytes say 601: the mismatch stops it457        let mismatched = try TronAuditRegressionTests.forged(honest, network: .mainnet, transaction: big)458        #expect(await walletError { try await h.service.signAndBroadcast(mismatched) } == .stalePlan("The transaction does not match its review."))459        // a review that shows 601 TRX like its bytes: the ceiling stops it460        let consistent = try TronAuditRegressionTests.forged(honest, network: .mainnet, transaction: big, amount: UInt256(601 * MultiChainSendTests.trx))461        guard case .exceedsUnauditedLimit? = await walletError({ try await h.service.signAndBroadcast(consistent) }) else {462            Issue.record("a forged plan above the ceiling must not be signed")463            return464        }465        guard case .exceedsUnauditedLimit? = await walletError({ try await h.service.signTron(big, network: .mainnet) }) else {466            Issue.record("the signing function itself must apply the ceiling")467            return468        }469        #expect(h.backend.tron.broadcasts.isEmpty)470        // exactly at the ceiling it signs471        let atCeiling = try TronTransaction(refBlockBytes: t.refBlockBytes, refBlockHash: t.refBlockHash, expiration: t.expiration, timestamp: t.timestamp,472                                            contract: .transfer(TronTransferContract(owner: me, to: recipient, amount: 600 * MultiChainSendTests.trx)))473        #expect(try await h.service.signTron(atCeiling, network: .mainnet).isSignedByOwner)474        // a main-network payload relabelled as a test network is outside what the bytes can tell: recorded as QYV-APP-040475    }476}477
Files main
Menu

Theme