SPB Git

Repository Public

MultiChainSupport.swift 24.0 KB 423 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraWalletTests/MultiChainSupport.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 QyvoraSymmetric45import QyvoraCore46import QyvoraBitcoin47import QyvoraEthereum48import QyvoraNetworking49import QyvoraStorage50import QyvoraVault51import QyvoraSolana52import QyvoraTron53@testable import QyvoraWallet5455/// A scripted Solana cluster: answers JSON-RPC in the shapes of a real node from a small model the tests edit.56final class FakeSolana: @unchecked Sendable {57    struct Mint {58        var decimals = 659        var program = SolanaTokenProgram.Kind.token60        var extensions: [String] = []61    }6263    struct TokenAccount {64        var address: String65        var mint: String66        var owner: String67        var amount: UInt6468        var program = SolanaTokenProgram.Kind.token69        var frozen = false70    }7172    var genesis = SolanaNetwork.devnet.genesisHash73    var slot: UInt64 = 5_00074    var blockHeight: UInt64 = 4_00075    var finalizedBlockHeight: UInt64 = 3_99076    var lamports: [String: UInt64] = [:]77    /// Accounts owned by another program than System (address → owner program).78    var programOwned: [String: String] = [:]79    var mints: [String: Mint] = [:]80    var tokenAccounts: [TokenAccount] = []81    var rent: [Int: UInt64] = [0: 890_880, 165: 2_039_280, 170: 2_074_080]82    var blockhash = Base58.bitcoin.encode(Bytes(repeating: 7, count: 32))83    var lastValidBlockHeight: UInt64 = 4_15084    var prioritizationFees: [UInt64] = []85    /// JSON of the `err` member of the simulation; nil for success.86    var simulationError: String?87    var simulations = 088    var sent: [SolanaTransaction] = []89    /// JSON-RPC error message of sendTransaction when set.90    var sendError: String?91    /// signature → JSON status object (as getSignatureStatuses returns it); absent = unknown to the node.92    var statuses: [String: String] = [:]93    /// JSON array returned by getSignaturesForAddress.94    var signatures = "[]"95    /// signature → getTransaction answer.96    var transactions: [String: String] = [:]97    /// method → raw JSON `result` (hostile or special answers).98    var resultOverride: [String: String] = [:]99    /// Blockhashes (base58) `isBlockhashValid` answers true for: what the main cluster would know (QYV-SVC-022).100    var validBlockhashes: Set<String> = []101102    private func accountJSON(_ address: String) -> String {103        if let mint = mints[address] {104            let extensions = mint.extensions.isEmpty ? "" : #","extensions":["# + mint.extensions.map { #"{"extension":"\#($0)","state":{}}"# }.joined(separator: ",") + "]"105            return #"{"data":{"parsed":{"info":{"decimals":\#(mint.decimals),"isInitialized":true,"supply":"1000000000000"\#(extensions)},"type":"mint"},"program":"spl-token","space":82},"executable":false,"lamports":1461600,"owner":"\#(mint.program.programID.base58)","space":82}"#106        }107        if let account = tokenAccounts.first(where: { $0.address == address }) { return tokenAccountBody(account) }108        if let owner = programOwned[address] { return #"{"data":["","base64"],"executable":false,"lamports":1000000,"owner":"\#(owner)","space":0}"# }109        if let balance = lamports[address], balance > 0 {110            return #"{"data":["","base64"],"executable":false,"lamports":\#(balance),"owner":"11111111111111111111111111111111","space":0}"#111        }112        return "null"113    }114115    private func tokenAccountBody(_ a: TokenAccount) -> String {116        let decimals = mints[a.mint]?.decimals ?? 6117        let size = a.program.associatedAccountSize118        return #"{"data":{"parsed":{"info":{"isNative":false,"mint":"\#(a.mint)","owner":"\#(a.owner)","state":"\#(a.frozen ? "frozen" : "initialized")","tokenAmount":{"amount":"\#(a.amount)","decimals":\#(decimals),"uiAmountString":"0"}},"type":"account"},"program":"spl-token","space":\#(size)},"executable":false,"lamports":\#(rent[size] ?? 2039280),"owner":"\#(a.program.programID.base58)","space":\#(size)}"#119    }120121    /// The body of the HTTP answer to one JSON-RPC request.122    func answer(_ body: Data) -> String {123        guard let request = SolanaJSON.parse(body), let method = request["method"]?.string else {124            return #"{"jsonrpc":"2.0","id":1,"error":{"code":-32700,"message":"parse error"}}"#125        }126        let params = request["params"]?.array ?? []127        func result(_ raw: String) -> String { #"{"jsonrpc":"2.0","id":1,"result":"# + raw + "}" }128        func error(_ code: Int, _ message: String) -> String { #"{"jsonrpc":"2.0","id":1,"error":{"code":\#(code),"message":"\#(message)"}}"# }129        func value(_ raw: String) -> String { result(#"{"context":{"slot":\#(slot)},"value":\#(raw)}"#) }130        if let o = resultOverride[method] { return result(o) }131        switch method {132        case "getGenesisHash": return result("\"\(genesis)\"")133        case "getSlot": return result(String(slot))134        case "getBlockHeight":135            let finalized = params.first?["commitment"]?.string == "finalized"136            return result(String(finalized ? finalizedBlockHeight : blockHeight))137        case "getBalance": return value(String(lamports[params.first?.string ?? ""] ?? 0))138        case "getMinimumBalanceForRentExemption": return result(String(rent[Int(params.first?.uint64 ?? 0)] ?? 890_880))139        case "getLatestBlockhash": return value(#"{"blockhash":"\#(blockhash)","lastValidBlockHeight":\#(lastValidBlockHeight)}"#)140        case "getAccountInfo": return value(accountJSON(params.first?.string ?? ""))141        case "getTokenAccountsByOwner":142            let owner = params.first?.string ?? "", program = params.count > 1 ? params[1]["programId"]?.string ?? "" : ""143            let items = tokenAccounts.filter { $0.owner == owner && $0.program.programID.base58 == program }144                .map { #"{"account":\#(tokenAccountBody($0)),"pubkey":"\#($0.address)"}"# }145            return value("[" + items.joined(separator: ",") + "]")146        case "getRecentPrioritizationFees":147            return result("[" + prioritizationFees.enumerated().map { #"{"slot":\#($0.offset),"prioritizationFee":\#($0.element)}"# }.joined(separator: ",") + "]")148        case "simulateTransaction":149            simulations += 1150            return value(#"{"err":\#(simulationError ?? "null"),"logs":["Program log: simulated"],"unitsConsumed":450}"#)151        case "sendTransaction":152            guard let text = params.first?.string, let tx = try? SolanaTransaction.decode(base64: text), let id = tx.id, tx.verifySignatures() else {153                return error(-32602, "invalid transaction")154            }155            if let sendError { return error(-32002, sendError) }156            sent.append(tx)157            return result("\"\(id)\"")158        case "getSignatureStatuses":159            let list = params.first?.array ?? []160            return value("[" + list.map { statuses[$0.string ?? ""] ?? "null" }.joined(separator: ",") + "]")161        case "getSignaturesForAddress": return result(signatures)162        case "getTransaction": return result(transactions[params.first?.string ?? ""] ?? "null")163        case "isBlockhashValid": return value(validBlockhashes.contains(params.first?.string ?? "") ? "true" : "false")164        default: return error(-32601, "Method not found")165        }166    }167}168169/// A scripted TRON node and history index.170final class FakeTron: @unchecked Sendable {171    struct Token {172        var decimals = 6173        var symbol = "TKN"174        var name = "Token"175        /// EVM-form owner (40 hex digits, lower case) → balance.176        var balances: [String: UInt256] = [:]177        var transferEnergy = 29_650178        /// Message of a revert of `transfer`; nil when it works.179        var revert: String?180    }181182    var genesisID = TronNetwork.nile.genesisBlockID183    var headNumber: UInt64 = 60_000_000184    var headTimestamp: UInt64 = 1_800_000_000_000185    /// hex address ("41…") → balance in sun. Present = activated.186    var balances: [String: UInt64] = [:]187    var contracts: Set<String> = []188    var resources = #"{"freeNetLimit":600,"freeNetUsed":0}"#189    var parameters = #"{"chainParameter":[{"key":"getCreateAccountFee","value":100000},{"key":"getTransactionFee","value":1000},{"key":"getCreateNewAccountFeeInSystemContract","value":1000000},{"key":"getCreateNewAccountBandwidthRate","value":1},{"key":"getEnergyFee","value":100},{"key":"getMaxFeeLimit","value":15000000000},{"key":"getMemoFee","value":1000000}]}"#190    var tokens: [String: Token] = [:]191    var broadcasts: [SignedTronTransaction] = []192    /// Answer of /wallet/broadcasthex when set (a refusal).193    var broadcastAnswer: String?194    /// transaction id → answer of gettransactioninfobyid / gettransactionbyid (head state).195    var info: [String: String] = [:]196    var byID: [String: String] = [:]197    /// Ids the irreversible state knows too.198    var solid: Set<String> = []199    var history = #"{"data":[],"success":true,"meta":{"page_size":0}}"#200    var tokenHistory = #"{"data":[],"success":true,"meta":{"page_size":0}}"#201    var historyStatus = 200202    /// The main network (host `tron-main.test`) has the very blocks the test networks hand out: what a test-network203    /// node that feeds main-network reference blocks looks like from the wallet.204    var mainnetAcceptsTestReferences = false205    /// What the index answers when it is asked for the transactions the account itself sent (`only_from=true`);206    /// nil for an index that ignores the filter and answers `history`.207    var ownHistory: String?208    /// Query string of the request being answered (set by the transport).209    var query = ""210    /// Requests that carried `only_from=true`.211    var ownHistoryRequests = 0212213    private func block(_ number: UInt64, fill: UInt8 = 0xab) -> String {214        let id = Hex.encode(Endian.be64(number) + Bytes(repeating: fill, count: 24))215        return #"{"blockID":"\#(id)","block_header":{"raw_data":{"timestamp":\#(headTimestamp),"number":\#(number)}}}"#216    }217218    func answer(method: String, path: String, body: Data, mainnet: Bool = false) -> (Int, String) {219        let json = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any]220        let asked = (json?["num"] as? NSNumber)?.uint64Value ?? 0221        // the blocks of the main network are its own, unless the test says the two chains share them222        let fill: UInt8 = mainnet && !mainnetAcceptsTestReferences ? 0x5a : 0xab223        func field(_ name: String) -> String { ((json?[name] as? String) ?? "").lowercased() }224        if method == "GET" {225            if path.hasSuffix("/transactions/trc20") { return (historyStatus, tokenHistory) }226            if path.hasSuffix("/transactions") {227                if query.contains("only_from=true") {228                    ownHistoryRequests += 1229                    if let ownHistory { return (historyStatus, ownHistory) }230                }231                return (historyStatus, history)232            }233            return (404, "{}")234        }235        switch path {236        case "/wallet/getblockbynum":237            if asked != 0 { return (200, block(asked, fill: fill)) }238            return (200, #"{"blockID":"\#(mainnet ? TronNetwork.mainnet.genesisBlockID : genesisID)","block_header":{"raw_data":{"txTrieRoot":"00"}},"transactions":[]}"#)239        case "/wallet/getblock": return (200, block(headNumber, fill: fill))240        case "/walletsolidity/getblock": return (200, block(headNumber - 19))241        case "/walletsolidity/getblockbynum": return (200, block(asked))242        case "/wallet/getaccount":243            let address = field("address")244            if contracts.contains(address) || tokens[address] != nil { return (200, #"{"type":"Contract","address":"\#(address)","balance":0}"#) }245            guard let balance = balances[address] else { return (200, "{}") }246            return (200, #"{"address":"\#(address)","balance":\#(balance)}"#)247        case "/wallet/getaccountresource": return (200, balances[field("address")] == nil ? "{}" : resources)248        case "/wallet/getchainparameters": return (200, parameters)249        case "/wallet/triggerconstantcontract":250            guard let token = tokens[field("contract_address")], let data = Hex.decode(field("data")), data.count >= 4 else {251                return (200, #"{"result":{"code":"CONTRACT_VALIDATE_ERROR","message":"Smart contract is not exist."}}"#)252            }253            func constant(_ output: String, energy: Int, failed: String? = nil) -> (Int, String) {254                let result = failed.map { #"{"result":true,"message":"\#($0)"}"# } ?? #"{"result":true}"#255                return (200, #"{"transaction":{"ret":[{\#(failed == nil ? "" : #""ret":"FAILED""#)}]},"constant_result":["\#(output)"],"result":\#(result),"energy_used":\#(energy)}"#)256            }257            let selector = Bytes(data[0..<4])258            func word(_ v: UInt256) -> String { Hex.encode(v.bytes32) }259            if selector == ERC20.decimalsSelector { return constant(word(UInt256(UInt64(token.decimals))), energy: 500) }260            if selector == ERC20.symbolSelector || selector == ERC20.nameSelector {261                let text = Bytes((selector == ERC20.symbolSelector ? token.symbol : token.name).utf8)262                let padded = text + Bytes(repeating: 0, count: (32 - text.count % 32) % 32)263                return constant(Hex.encode(UInt256(32).bytes32 + UInt256(UInt64(text.count)).bytes32 + padded), energy: 1_300)264            }265            if selector == ERC20.balanceOfSelector, data.count == 36 { return constant(word(token.balances[Hex.encode(Bytes(data[16..<36]))] ?? .zero), energy: 900) }266            if selector == ERC20.transferSelector {267                // like USDT: nothing useful is returned by a transfer that works268                return constant("", energy: token.transferEnergy, failed: token.revert)269            }270            return constant("", energy: 100, failed: "REVERT opcode executed")271        case "/wallet/broadcasthex":272            guard let bytes = Hex.decode(field("transaction")), let signed = try? SignedTronTransaction.decode(bytes), signed.isSignedByOwner else {273                return (200, #"{"code":"SIGERROR","message":"validate signature error"}"#)274            }275            if let broadcastAnswer { return (200, broadcastAnswer) }276            broadcasts.append(signed)277            return (200, #"{"result":true,"code":"SUCCESS","txid":"\#(signed.txIDHex)"}"#)278        case "/wallet/gettransactioninfobyid": return (200, info[field("value")] ?? "{}")279        case "/wallet/gettransactionbyid": return (200, byID[field("value")] ?? "{}")280        case "/walletsolidity/gettransactioninfobyid": return (200, solid.contains(field("value")) ? (info[field("value")] ?? "{}") : "{}")281        case "/walletsolidity/gettransactionbyid": return (200, solid.contains(field("value")) ? (byID[field("value")] ?? "{}") : "{}")282        default: return (404, "{}")283        }284    }285286    /// Marks a broadcast transaction as included with this receipt result.287    func include(_ signed: SignedTronTransaction, receipt: String = "SUCCESS", contractRet: String = "SUCCESS", fee: UInt64 = 0, irreversible: Bool = false) {288        let id = signed.txIDHex289        info[id] = #"{"id":"\#(id)","fee":\#(fee),"blockNumber":\#(headNumber),"blockTimeStamp":\#(headTimestamp),"receipt":{"result":"\#(receipt)","energy_usage_total":0}}"#290        byID[id] = #"{"txID":"\#(id)","raw_data_hex":"\#(Hex.encode(signed.transaction.rawData))","ret":[{"contractRet":"\#(contractRet)"}]}"#291        if irreversible { solid.insert(id) }292    }293}294295/// Every service the multi-chain wallet talks to, behind one transport. Hosts:296/// - `<name>.evm.test`: the JSON-RPC of the EVM network `name` (raw value of `EthereumNetwork`), each with its own model;297/// - `<name>.evmindex.test`: its indexer;298/// - `sol.test`, `sol2.test`: the Solana cluster; `tron.test`, `tronindex.test`: the TRON node and index;299/// - `tron-main.test`: the same TRON model seen as the main network (its genesis block, its own block ids);300/// - anything else goes to the Bitcoin / Ethereum / price backend of the 1.0 tests.301final class MultiBackend: HTTPTransport, @unchecked Sendable {302    private let lock = NSLock()303    let base = FakeBackend()304    let solana = FakeSolana()305    let tron = FakeTron()306    private var evmBackends: [String: FakeBackend] = [:]307    /// Hosts that do not answer at all.308    var silentHosts: Set<String> = []309    /// Any request is a test failure (cold mode).310    var forbidAllRequests = false311    private var log: [String] = []312    var requests: [String] { lock.withLock { log } }313314    /// The model of one EVM network (created on first use, with that network's chain identifier).315    func evm(_ network: EthereumNetwork) -> FakeBackend {316        lock.withLock {317            if let existing = evmBackends[network.rawValue] { return existing }318            let backend = FakeBackend()319            backend.chainID = network.chainID320            evmBackends[network.rawValue] = backend321            return backend322        }323    }324325    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {326        let url = request.url!327        let host = url.host ?? ""328        let line = "\(request.httpMethod ?? "GET") \(host)\(url.path)"329        let (silent, forbidden) = lock.withLock { () -> (Bool, Bool) in330            log.append(line)331            return (silentHosts.contains(host), forbidAllRequests)332        }333        if forbidden { Issue.record("network request in cold mode: \(line)") }334        if silent { throw URLError(.timedOut) }335        func reply(_ status: Int, _ body: String) -> (Data, HTTPURLResponse) {336            (Data(body.utf8), HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: nil)!)337        }338        if host == "sol.test" || host == "sol2.test" {339            return lock.withLock { reply(200, solana.answer(request.httpBody ?? Data())) }340        }341        if host == "tron.test" || host == "tronindex.test" || host == "tron-main.test" {342            return lock.withLock {343                tron.query = url.query ?? ""344                let (status, body) = tron.answer(method: request.httpMethod ?? "GET", path: url.path, body: request.httpBody ?? Data(), mainnet: host == "tron-main.test")345                return reply(status, body)346            }347        }348        for (suffix, target) in [(".evm.test", "rpc.test"), (".evmindex.test", "indexer.test")] where host.hasSuffix(suffix) {349            guard let network = EthereumNetwork(rawValue: String(host.dropLast(suffix.count))) else { throw URLError(.cannotFindHost) }350            var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!351            components.host = target352            var forwarded = request353            forwarded.url = components.url354            return try await evm(network).send(forwarded)355        }356        return try await base.send(request)357    }358359    static func endpoints() -> ChainEndpoints {360        var core = FakeBackend.endpoints361        for network in EthereumNetwork.allCases where network != .sepolia && network != .mainnet {362            core.ethereumRPC[network.rawValue] = ["https://\(network.rawValue).evm.test"]363            // as shipped: only some networks have an indexer364            core.ethereumIndexer[network.rawValue] = EVMEndpointDefaults.hasDefaultIndexer(network) ? ["https://\(network.rawValue).evmindex.test"] : []365        }366        return ChainEndpoints(core: core,367                              solana: SolanaEndpoints(rpc: ["devnet": ["https://sol.test"], "testnet": ["https://sol.test"], "mainnet-beta": ["https://sol.test"]]),368                              tron: TronEndpoints(fullNodes: ["nile": ["https://tron.test"], "shasta": ["https://tron.test"], "mainnet": ["https://tron-main.test"]],369                                                  history: ["nile": ["https://tronindex.test"], "shasta": [], "mainnet": ["https://tronindex.test"]]))370    }371}372373/// One wallet service on its own temporary directory and vault, in front of the multi-chain backend.374struct MultiHarness {375    let service: WalletService376    let vault: Vault377    let backend: MultiBackend378    let clock: TestClock379    let directory: URL380381    /// Addresses of the "abandon … about" phrase, as published by the chain modules.382    static let solanaAddress = "HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk"383    static let tronAddress = "TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH"384    static let ethereumAddress = "0x9858EfFD232B4033E47d90003D41EC34EcaEda94"385386    static func make(backend: MultiBackend = MultiBackend(), clock: TestClock = TestClock(), directory: URL? = nil, configure: Bool = true,387                     internalBuildAllowsMainnet: Bool = false) async throws -> MultiHarness {388        let dir = directory ?? FileManager.default.temporaryDirectory.appendingPathComponent("qy-multi-\(UUID().uuidString)")389        let store = try FileStore(root: dir)390        let vault = Vault(fileStore: store, keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting, now: { clock.now }, monotonic: { clock.monotonic }))391        let service = try WalletService(vault: vault, fileStore: store, transport: backend, now: { clock.now }, monotonic: { clock.monotonic }, sleep: { _ in },392                                        transactionSeed: 7, backupKDF: .insecureForTesting, internalBuildAllowsMainnet: internalBuildAllowsMainnet,393                                        tronPacing: .unthrottled)394        if configure { try await service.setChainEndpoints(MultiBackend.endpoints()) }395        // the TRON blocks of the model are "now" for the service396        backend.tron.headTimestamp = UInt64(clock.now.timeIntervalSince1970 * 1000)397        return MultiHarness(service: service, vault: vault, backend: backend, clock: clock, directory: dir)398    }399400    /// A full wallet on the test phrase with the given chains enabled (main identifiers).401    static func wallet(chains: [ChainID], backend: MultiBackend = MultiBackend()) async throws -> MultiHarness {402        let h = try await make(backend: backend)403        try await h.service.importWallet(words: Harness.abandon, password: Harness.password)404        try await h.service.setEnabledChains(chains)405        return h406    }407408    var store: FileStore { get throws { try FileStore(root: directory) } }409410    func cleanup() { try? FileManager.default.removeItem(at: directory) }411412    /// The hexadecimal ("41…") form of a TRON address, as the node API prints it.413    static func tronHex(_ base58: String) -> String { TronAddress(base58)!.hex }414}415416/// A Solana address that belongs to nobody in the tests (an Ed25519 public key).417func solanaStranger(_ n: UInt8 = 9) -> SolanaPublicKey {418    try! SolanaKeys.publicKey(privateSeed: Bytes(repeating: n, count: 32))419}420421/// A TRON address that belongs to nobody in the tests.422func tronStranger(_ n: UInt8 = 0x33) -> TronAddress { TronAddress(hash: Bytes(repeating: n, count: 20))! }423
Files main
Menu

Theme