Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : Sources/QyvoraWallet/PaymentRequests.swift8// Module : Qyvora Wallet9// 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 QyvoraCore4344/// What a scanned or pasted text is, as far as its form tells. Pure: no wallet, no network.45///46/// A payment request is attacker-controlled input: it arrives from a QR code someone else printed or from a link.47/// The rules here keep it from doing anything the user does not see (QYV-APP-101):48/// - only what the send form displays is taken (recipient, amount, token, public note); labels, messages, gas and49/// fee parameters and everything else are dropped;50/// - a request the wallet cannot honour entirely is refused as a whole (`unsupported`) instead of being filled in51/// partly: a required parameter it does not know (`req-…`, BIP-21), a function call other than a token transfer52/// (ERC-681), a chain identifier that is not a number, an amount that is not a plain decimal number, a note longer53/// than the form shows;54/// - lengths are bounded before anything is parsed;55/// - the scheme decides the family (`Payment.matches`): a `bitcoin:` request is never offered on another coin, even56/// where the address would be valid there (test networks share address forms; a legacy Bitcoin Cash address is a57/// Bitcoin address).58/// Addresses are not judged here: the wallet service validates them (`checkAddress`), chain by chain.59public enum WalletScanParser {60 /// A payment request: `bitcoin:`, `litecoin:`, `dogecoin:`, `bitcoincash:`, `ethereum:`, `solana:` or `tron:`.61 public struct Payment: Hashable, Sendable {62 public let scheme: String63 public var address: String64 /// Decimal amount of the asset ("0.01"), when the request carries one in that form.65 public var amount: String?66 /// Amount in base units (EIP-681 `value` and `uint256`), to be scaled with the decimals of the asset.67 public var baseAmount: String?68 /// EIP-155 chain identifier named by an `ethereum:` request.69 public var evmChainID: UInt64?70 /// Token contract or mint named by the request.71 public var token: String?72 public var memo: String?7374 public init(scheme: String, address: String) {75 self.scheme = scheme76 self.address = address77 }7879 /// True when a request of this scheme can be paid on `chain`: the family of the scheme, and for an80 /// `ethereum:` request that names a chain identifier, that very network.81 public func matches(_ chain: ChainDescriptor) -> Bool {82 switch scheme {83 case "bitcoin": return chain.mainCounterpart == .bitcoin84 case "litecoin": return chain.mainCounterpart == .litecoin85 case "dogecoin": return chain.mainCounterpart == .dogecoin86 case "bitcoincash": return chain.mainCounterpart == .bitcoinCash87 case "ethereum": return chain.family == .evm && (evmChainID == nil || evmChainID == chain.evmChainID)88 case "solana": return chain.family == .solana89 case "tron": return chain.family == .tron90 default: return false91 }92 }93 }9495 public enum Content: Equatable, Sendable {96 case payment(Payment)97 /// A payment request the wallet does not honour, with the reason to show. Nothing of it is used.98 case unsupported(String)99 /// Anything else: possibly a bare address.100 case text(String)101 case signedTransaction102 case unsignedTransaction103 case watchOnlyPackage104 case identity105 case transferPackage106 }107108 public static let schemes = ["bitcoin", "litecoin", "dogecoin", "bitcoincash", "ethereum", "solana", "tron"]109110 /// Longest payment request read (a QR code holds less than 3 000 characters).111 public static let maximumRequestLength = 2_048112 /// Longest address part of a request (the longest address form the wallet knows is under 100 characters).113 public static let maximumAddressLength = 130114 /// Longest public note taken from a request: what the note field of the send form shows without scrolling.115 public static let maximumMemoLength = 120116117 public static func parse(_ raw: String) -> Content {118 let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)119 if text.hasPrefix("qyvtx1|s|") { return .signedTransaction }120 if text.hasPrefix("qyvtx1|u|") { return .unsignedTransaction }121 if text.hasPrefix("qyvora-id:") { return .identity }122 if text.hasPrefix("{"), text.contains("qyvora-watch-only") { return .watchOnlyPackage }123 if text.hasPrefix("{"), text.contains("qyvora/transfer") { return .transferPackage }124 // a PSBT in base64 ("psbt" + 0xff) or a raw EVM transaction: only a signed one can be used on this device125 if text.hasPrefix("cHNidP") { return .signedTransaction }126 if text.hasPrefix("0x"), text.count > 100, text.dropFirst(2).allSatisfy(\.isHexDigit) { return .signedTransaction }127 guard let colon = text.firstIndex(of: ":") else { return .text(text) }128 let scheme = text[..<colon].lowercased()129 guard schemes.contains(scheme) else { return .text(text) }130 guard text.utf8.count <= maximumRequestLength else { return .unsupported("This payment request is longer than any QYVORA reads. Nothing was taken from it.") }131 var rest = String(text[text.index(after: colon)...])132 if rest.hasPrefix("//") { rest.removeFirst(2) }133 let parts = rest.split(separator: "?", maxSplits: 1, omittingEmptySubsequences: false).map(String.init)134 var path = parts.first ?? ""135 guard !path.isEmpty else { return .text(text) }136 var query = [String: String]()137 if parts.count == 2 {138 guard let items = URLComponents(string: "q://q?" + parts[1])?.queryItems, items.count <= 16 else {139 return .unsupported("The parameters of this payment request cannot be read. Nothing was taken from it.")140 }141 for item in items {142 let name = item.name.lowercased()143 // BIP-21: a parameter marked as required that the wallet does not know makes the request invalid144 if name.hasPrefix("req-") {145 return .unsupported("This payment request requires something QYVORA does not support (\"\(name.prefix(24))\"). Nothing was taken from it: ask for a plain address.")146 }147 guard query[name] == nil else {148 return .unsupported("This payment request gives \"\(name.prefix(24))\" twice. Nothing was taken from it.")149 }150 if let value = item.value { query[name] = value }151 }152 }153 var payment = Payment(scheme: scheme, address: path)154 if let memo = query["memo"], !memo.isEmpty {155 guard memo.count <= maximumMemoLength, !memo.unicodeScalars.contains(where: { $0.properties.generalCategory == .control || $0.properties.generalCategory == .format }) else {156 return .unsupported("This payment request carries a public note that is too long or holds invisible characters. Nothing was taken from it.")157 }158 payment.memo = memo159 }160 /// An amount the request states and the wallet cannot read is not dropped: the request is refused.161 func amount(_ key: String, _ read: (String?) -> String?) -> (value: String?, bad: Bool) {162 guard let stated = query[key] else { return (nil, false) }163 let value = read(stated)164 return (value, value == nil)165 }166 let unreadableAmount = Content.unsupported("The amount of this payment request is not a plain number. Nothing was taken from it.")167 switch scheme {168 case "ethereum":169 if path.hasPrefix("pay-") { path.removeFirst(4) }170 var function: String?171 if let slash = path.firstIndex(of: "/") {172 function = String(path[path.index(after: slash)...])173 path = String(path[..<slash])174 }175 if let at = path.firstIndex(of: "@") {176 guard let id = UInt64(path[path.index(after: at)...]) else {177 return .unsupported("The network named by this payment request is not a chain identifier. Nothing was taken from it.")178 }179 payment.evmChainID = id180 path = String(path[..<at])181 }182 if function == "transfer", let to = query["address"] {183 // EIP-681 token transfer: the path names the contract, the query the beneficiary184 payment.token = path185 payment.address = to186 let stated = amount("uint256", plainDigits)187 if stated.bad { return unreadableAmount }188 payment.baseAmount = stated.value189 } else if function != nil {190 // any other function call: the wallet does not build calls from a link191 return .unsupported("This request asks the wallet to call a contract function, not to make a payment. QYVORA does not build contract calls from a code or a link.")192 } else {193 payment.address = path194 let stated = amount("value", plainDigits)195 if stated.bad { return unreadableAmount }196 payment.baseAmount = stated.value197 if let chain = query["chainid"] {198 guard let id = UInt64(chain), payment.evmChainID == nil || payment.evmChainID == id else {199 return .unsupported("The network named by this payment request is not a chain identifier. Nothing was taken from it.")200 }201 payment.evmChainID = id202 }203 }204 case "solana":205 let stated = amount("amount", decimal)206 if stated.bad { return unreadableAmount }207 payment.amount = stated.value208 payment.token = query["spl-token"]209 case "bitcoincash":210 payment.address = "bitcoincash:" + path211 let stated = amount("amount", decimal)212 if stated.bad { return unreadableAmount }213 payment.amount = stated.value214 default:215 let stated = amount("amount", decimal)216 if stated.bad { return unreadableAmount }217 payment.amount = stated.value218 }219 guard payment.address.count <= maximumAddressLength, (payment.token?.count ?? 0) <= maximumAddressLength else {220 return .unsupported("The address of this payment request is longer than any address QYVORA knows. Nothing was taken from it.")221 }222 return .payment(payment)223 }224225 private static func plainDigits(_ text: String?) -> String? {226 guard let text, !text.isEmpty, text.count <= 78, text.allSatisfy({ $0.isASCII && $0.isNumber }) else { return nil }227 return text228 }229230 private static func decimal(_ text: String?) -> String? {231 guard let text, !text.isEmpty, text.count <= 40, text.allSatisfy({ ($0.isASCII && $0.isNumber) || $0 == "." }), text.filter({ $0 == "." }).count <= 1,232 text.contains(where: \.isNumber) else { return nil }233 return text234 }235}236