Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Tests/QyvoraWalletTests/SolanaAuditRegressionTests.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 QyvoraNetworking46@testable import QyvoraSolana47@testable import QyvoraWallet4849/// Regression tests of the findings of the multi-chain security audit on the Solana send path of the wallet service.50@Suite(.readsMainnetPolicy) struct SolanaWalletAuditRegressionTests {51 static let sol: UInt64 = 1_000_000_0005253 /// QYV-SVC-022. A Solana transaction names no cluster and the account is the same key everywhere: a test-cluster54 /// endpoint that hands out a mainnet-beta blockhash obtains a signature that moves real funds on mainnet-beta,55 /// past the mainnet switch and the limits. Before the fix the devnet payment below was signed and sent.56 @Test func aTestClusterTransactionValidOnMainnetIsNeverSigned() async throws {57 let h = try await MultiChainSendTests.solanaWallet()58 defer { h.cleanup() }59 let node = h.backend.solana60 let recipient = solanaStranger()61 node.lamports[recipient.base58] = Self.sol6263 // the devnet endpoint answers with a blockhash that mainnet-beta knows: nothing is even prepared64 node.validBlockhashes = [node.blockhash]65 guard case .wrongChain(let early)? = await walletError({ try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(1_000_000)) }) else {66 Issue.record("a devnet transaction whose blockhash is valid on mainnet must not be prepared")67 return68 }69 #expect(early.contains("valid on the main network") && node.simulations == 0)70 // mainnet-beta learns the blockhash between the review and the signature: nothing is signed71 node.validBlockhashes = []72 let review = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(1_000_000))73 node.validBlockhashes = [node.blockhash]74 guard case .wrongChain(let text)? = await walletError({ try await h.service.signAndBroadcast(review) }) else {75 Issue.record("a devnet transaction whose blockhash is valid on mainnet must be refused")76 return77 }78 #expect(text.contains("valid on the main network") && node.sent.isEmpty)7980 // mainnet-beta does not know it: signed and sent as before81 node.validBlockhashes = []82 _ = try await h.service.signAndBroadcast(review)83 #expect(node.sent.count == 1)8485 // bytes signed by a cold device: they are not handed to an endpoint, not even for simulation86 let me = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))87 let message = try SolanaMessage(feePayer: me, instructions: [SolanaComputeBudget.setComputeUnitLimit(5_000), SolanaComputeBudget.setComputeUnitPrice(microLamports: 5_000),88 SolanaSystemProgram.transfer(from: me, to: recipient, lamports: 7_000_000)],89 recentBlockhash: try #require(Base58.bitcoin.decode(node.blockhash)))90 let coldSigned = try await h.service.run { try await h.service.signSolana(SolanaTransaction(message: message), network: .devnet) }91 let envelope = try QRExport.make(text: "qyvtx1|s|solana-devnet|\(try coldSigned.base64())")92 node.validBlockhashes = [node.blockhash]93 let simulations = node.simulations94 guard case .wrongChain? = await walletError({ try await h.service.broadcastSigned(envelope.frames) }) else {95 Issue.record("signed bytes valid on mainnet must not be broadcast")96 return97 }98 #expect(node.sent.count == 1 && node.simulations == simulations)99 node.validBlockhashes = []100 _ = try await h.service.broadcastSigned(envelope.frames)101 #expect(node.sent.count == 2)102103 // no mainnet-beta endpoint answers: the check cannot be made, nothing is prepared104 var endpoints = MultiBackend.endpoints()105 endpoints.solana.rpc["mainnet-beta"] = ["https://sol2.test"]106 try await h.service.setChainEndpoints(endpoints)107 h.backend.silentHosts = ["sol2.test"]108 guard case .network(let why)? = await walletError({ try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(2_000_000)) }) else {109 Issue.record("without an answer from mainnet nothing may be prepared")110 return111 }112 #expect(why.contains("did not answer") && node.sent.count == 2)113 // it answers at the review and no longer at the signature: nothing is signed114 h.backend.silentHosts = []115 let second = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(2_000_000))116 h.backend.silentHosts = ["sol2.test"]117 guard case .network? = await walletError({ try await h.service.signAndBroadcast(second) }) else {118 Issue.record("without an answer from mainnet nothing may be signed")119 return120 }121 #expect(node.sent.count == 2)122 // and with no mainnet-beta endpoint configured at all123 h.backend.silentHosts = []124 endpoints.solana.rpc["mainnet-beta"] = []125 try await h.service.setChainEndpoints(endpoints)126 guard case .network(let none)? = await walletError({ try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(3_000_000)) }) else {127 Issue.record("without a mainnet endpoint nothing may be prepared")128 return129 }130 #expect(none.contains("No Solana mainnet endpoint") && node.sent.count == 2)131 }132133 /// The forged plan of the tests below: a real plan of the planner for another amount or another recipient.134 private static func plan(from me: SolanaPublicKey, to recipient: SolanaPublicKey, lamports: UInt64, node: FakeSolana) throws -> SolanaSendPlan {135 let blockhash = SolanaBlockhash(blockhash: try #require(Base58.bitcoin.decode(node.blockhash)), lastValidBlockHeight: node.lastValidBlockHeight)136 let snapshot = SolanaChainSnapshot(senderLamports: node.lamports[me.base58] ?? 0, recipient: .system(lamports: Self.sol), systemAccountRent: 890_880,137 blockhash: blockhash)138 return try SolanaSendPlanner.plan(SolanaSendRequest(sender: me, recipient: recipient, asset: .sol, amount: .exact(lamports)), snapshot: snapshot)139 }140141 /// QYV-SVC-023. The figures of a review were the planner's, never compared with the bytes. `SolanaSendPlan`,142 /// `SolanaSendDetails` and `SendReview` cannot be built or altered through the public interface (no public143 /// initializer, constant properties); this test builds forged ones through the module-internal initializers, which144 /// is more than a caller of the library can do, and checks that the service still signs nothing that differs145 /// from what the review shows.146 @Test func aReviewThatDoesNotMatchItsBytesIsNeverSigned() async throws {147 let h = try await MultiChainSendTests.solanaWallet(lamports: 50 * Self.sol)148 defer { h.cleanup() }149 let node = h.backend.solana150 let me = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))151 let recipient = solanaStranger(), thief = solanaStranger(66)152 node.lamports[recipient.base58] = Self.sol153 node.lamports[thief.base58] = Self.sol154 let honest = try await h.service.prepareSend(chain: .solanaDevnet, asset: .native, to: recipient.base58, amount: UInt256(1_000_000))155 guard case .solana(let details) = honest.body else {156 Issue.record("a Solana body is expected")157 return158 }159 func forged(_ plan: SolanaSendPlan) async -> SendReview {160 // shows the honest payment, carries other bytes161 await h.service.makeReview(kind: .solana(.devnet), from: me.base58, recipient: recipient.base58, asset: .native, amount: UInt256(1_000_000), decimals: 9,162 symbol: "SOL", expectedFee: honest.fee.expected, maximumFee: honest.fee.maximum, feeLines: [], totalNative: honest.totalNative,163 isSendMax: false, warnings: [], notes: [], expiresAt: nil,164 body: .solana(SolanaSendDetails(network: .devnet, plan: plan, simulatedUnits: details.simulatedUnits)))165 }166 func refused(_ review: SendReview, _ what: String) async {167 guard case .stalePlan(let text)? = await walletError({ try await h.service.signAndBroadcast(review) }) else {168 Issue.record("a review that differs from its bytes must be refused (\(what))")169 return170 }171 #expect(text.contains("does not match what the review shows") && text.contains(what) && node.sent.isEmpty)172 }173 // another amount, another recipient174 await refused(await forged(try Self.plan(from: me, to: recipient, lamports: 40 * Self.sol, node: node)), "transfer")175 await refused(await forged(try Self.plan(from: me, to: thief, lamports: 1_000_000, node: node)), "transfer")176 // another fee177 let blockhash = SolanaBlockhash(blockhash: try #require(Base58.bitcoin.decode(node.blockhash)), lastValidBlockHeight: node.lastValidBlockHeight)178 let snapshot = SolanaChainSnapshot(senderLamports: 50 * Self.sol, recipient: .system(lamports: Self.sol), systemAccountRent: 890_880, blockhash: blockhash)179 let costly = try SolanaSendPlanner.plan(SolanaSendRequest(sender: me, recipient: recipient, asset: .sol, amount: .exact(1_000_000), computeUnitPrice: 1_900_000_000),180 snapshot: snapshot)181 #expect(costly.priorityFee == 9_500_000)182 await refused(await forged(costly), "fee")183 // an added instruction: the honest payment followed by a second transfer, by an approval, by an unknown program184 let base = [SolanaComputeBudget.setComputeUnitLimit(5_000), SolanaComputeBudget.setComputeUnitPrice(microLamports: 5_000),185 SolanaSystemProgram.transfer(from: me, to: recipient, lamports: 1_000_000)]186 let extras: [SolanaInstruction] = [187 SolanaSystemProgram.transfer(from: me, to: thief, lamports: 30 * Self.sol),188 SolanaInstruction(programID: SolanaProgram.token, accounts: [SolanaAccountMeta(recipient, isSigner: false, isWritable: true),189 SolanaAccountMeta(thief, isSigner: false, isWritable: false),190 SolanaAccountMeta(me, isSigner: true, isWritable: false)], data: [4] + Endian.le64(.max)),191 SolanaInstruction(programID: thief, accounts: [SolanaAccountMeta(me, isSigner: true, isWritable: true)], data: [1, 2, 3]),192 ]193 for (n, extra) in extras.enumerated() {194 let message = try SolanaMessage(feePayer: me, instructions: base + [extra], recentBlockhash: blockhash.blockhash)195 let tampered = SolanaSendPlan(transaction: SolanaTransaction(message: message), asset: .sol, amount: 1_000_000, decimals: 9, signatureFee: 5_000, priorityFee: 25,196 accountCreationCost: 0, computeUnitLimit: 5_000, computeUnitPrice: 5_000, senderLamportsAfter: 0, sourceTokenAccount: nil,197 destinationTokenAccount: nil, warnings: [], blockhash: blockhash)198 await refused(await forged(tampered), n == 2 ? "signers" : "unexpected instruction")199 }200 // the honest review is signed, and its bytes are the reviewed ones201 _ = try await h.service.signAndBroadcast(honest)202 #expect(node.sent.count == 1 && node.sent[0].message == details.plan.transaction.message)203 }204}205206/// In the serialized suite: `MainnetPolicy` is process-wide.207extension MainnetPolicyTests {208 /// The per-transaction ceiling of an unaudited build cannot be passed by handing the service a plan above it:209 /// the limit is computed from the decoded bytes at prepare, at sign (`signAndBroadcast`), in the signing function210 /// itself (`signSolana`) and before a broadcast of bytes signed elsewhere.211 @Test func aSolanaTransactionAboveTheCeilingIsNeverSignedWhateverThePlanSays() async throws {212 Self.reset()213 defer { Self.reset() }214 let h = try await Self.mainnetMultiWallet(chains: [.solana], prices: [("solana", "100"), ("usd-coin", "1")])215 defer { h.cleanup() }216 let node = h.backend.solana217 let me = try #require(SolanaPublicKey(base58: MultiHarness.solanaAddress))218 let recipient = solanaStranger()219 let sol = MultiChainSendTests.sol220 node.lamports[me.base58] = 100 * sol221 node.lamports[recipient.base58] = sol222 try await h.service.refreshMarket()223 let ceiling = WalletError.exceedsUnauditedLimit(limit: "150 USD of SOL per transaction (1.5 SOL at the current price)")224225 // 150 USD at 100 USD per SOL = 1.5 SOL. A plan for 40 SOL, wrapped in a review that says 40 SOL (consistent226 // with its bytes, so that only the ceiling can stop it): built with the module-internal initializers.227 let blockhash = SolanaBlockhash(blockhash: try #require(Base58.bitcoin.decode(node.blockhash)), lastValidBlockHeight: node.lastValidBlockHeight)228 let snapshot = SolanaChainSnapshot(senderLamports: 100 * sol, recipient: .system(lamports: sol), systemAccountRent: 890_880, blockhash: blockhash)229 let big = try SolanaSendPlanner.plan(SolanaSendRequest(sender: me, recipient: recipient, asset: .sol, amount: .exact(40 * sol)), snapshot: snapshot)230 let forged = await h.service.makeReview(kind: .solana(.mainnetBeta), from: me.base58, recipient: recipient.base58, asset: .native, amount: UInt256(40 * sol),231 decimals: 9, symbol: "SOL", expectedFee: UInt256(big.fee), maximumFee: UInt256(big.fee), feeLines: [],232 totalNative: UInt256(big.totalLamports), isSendMax: false, warnings: [], notes: [], expiresAt: nil,233 body: .solana(SolanaSendDetails(network: .mainnetBeta, plan: big, simulatedUnits: nil)))234 #expect(await walletError { try await h.service.signAndBroadcast(forged) } == ceiling)235 #expect(node.sent.isEmpty)236 // the signing function itself refuses the bytes237 #expect(await walletError { try await h.service.run { try await h.service.signSolana(big.transaction, network: .mainnetBeta) } } == ceiling)238 // one lamport above the ceiling, and a priority fee above its own ceiling239 let above = try SolanaSendPlanner.plan(SolanaSendRequest(sender: me, recipient: recipient, asset: .sol, amount: .exact(1_500_000_001)), snapshot: snapshot)240 #expect(await walletError { try await h.service.run { try await h.service.signSolana(above.transaction, network: .mainnetBeta) } } == ceiling)241 let fee = try SolanaTransaction(message: SolanaMessage(feePayer: me, instructions: [242 SolanaComputeBudget.setComputeUnitLimit(1_400_000), SolanaComputeBudget.setComputeUnitPrice(microLamports: 1_000_000_000),243 SolanaSystemProgram.transfer(from: me, to: recipient, lamports: 1_000),244 ], recentBlockhash: blockhash.blockhash))245 #expect(await walletError { try await h.service.run { try await h.service.signSolana(fee, network: .mainnetBeta) } }246 == .solana(.priorityFeeTooHigh(lamports: 1_400_000_000)))247 // at the ceiling it signs248 let at = try SolanaSendPlanner.plan(SolanaSendRequest(sender: me, recipient: recipient, asset: .sol, amount: .exact(1_500_000_000)), snapshot: snapshot)249 let signed = try await h.service.run { try await h.service.signSolana(at.transaction, network: .mainnetBeta) }250 #expect(signed.verifySignatures() && signed.message == at.transaction.message)251 #expect(node.sent.isEmpty)252 }253}254