WalletCore.swift (35496B)
1 /* 2 * This file is part of GNU Taler, ©2022-25 Taler Systems S.A. 3 * See LICENSE.md 4 */ 5 /** 6 * @author Marc Stibane 7 * @author Iván Ávalos 8 */ 9 import SwiftUI // FOUNDATION has no AppStorage 10 import AnyCodable 11 import SymLog 12 import os 13 import LocalConsole 14 15 /// Delegate for the wallet backend. 16 protocol WalletBackendDelegate { 17 /// Called when the backend interface receives a message it does not know how to handle. 18 func walletBackendReceivedUnknownMessage(_ walletCore: WalletCore, message: String) 19 } 20 21 // MARK: - 22 /// An interface to the wallet backend. 23 class WalletCore: QuickjsMessageHandler { 24 public static let shared = try! WalletCore() // will (and should) crash on failure 25 private let symLog = SymLogC() 26 27 @AppStorage("logTransactions") var logTransactions: Bool = false 28 29 private var queue: DispatchQueue 30 private var semaphore: DispatchSemaphore 31 32 private let quickjs: Quickjs 33 private var requestsMade: UInt // counter for array of completion closures 34 private var completions: [UInt : (Date, (UInt, Date, String?, Data?, TalerErrorDetail?) -> Void)] = [:] 35 var delegate: WalletBackendDelegate? 36 37 var versionInfo: VersionInfo? // shown in SettingsView 38 var nativeDB: Bool 39 var isObserving: Int 40 var isLogging: Bool 41 let logger = Logger(subsystem: "net.taler.gnu", category: "WalletCore") 42 43 private var expired: [String] = [] // save txID of expired items to not beep twice 44 45 private struct FullRequest: Encodable { 46 let operation: String 47 let id: UInt 48 let args: AnyEncodable 49 } 50 51 private struct FullResponse: Decodable { 52 let type: String 53 let operation: String 54 let id: UInt 55 let result: AnyCodable 56 } 57 58 struct FullError: Decodable { 59 let type: String 60 let operation: String 61 let id: UInt 62 let error: TalerErrorDetail 63 } 64 65 var lastError: FullError? 66 67 struct ResponseOrNotification: Decodable { 68 let type: String 69 let operation: String? 70 let id: UInt? 71 let result: AnyCodable? 72 let error: TalerErrorDetail? 73 let payload: AnyCodable? 74 } 75 76 /// the bare envelope, which still decodes when the full `ResponseOrNotification` doesn't 77 private struct ResponseHeader: Decodable { 78 let type: String 79 let id: UInt? 80 } 81 82 struct Payload: Decodable { 83 let type: String 84 let id: String? 85 let reservePub: String? 86 let isInternal: Bool? 87 let hintTransactionId: String? 88 let event: [String: AnyCodable]? 89 let exchangeBaseUrl: String? 90 let newExchangeState: ExchangeState? 91 let operation: String? // indexeddb-to-native-migration 92 let phase: String? // fixup | copy | verify | complete | failed 93 let error: TalerErrorDetail? // only when phase is "failed" 94 let step: String? // config | currencyInfo | contacts | mailboxMessages | mailboxConfigurations | contractTerms | tombstones | operationRetries | bankAccounts | globalCurrencyExchanges | globalCurrencyAuditors | exchangeBaseUrlFixups | exchangeBaseUrlMigrationLog | reserves | exchanges | exchangeDetails | exchangeSignKeys | denominationFamilies | denominations | withdrawalGroups | purchases | refreshGroups | coins | planchets | refreshSessions | coinHistory | coinAvailability | refundGroups | tokens | slates | depositGroups | recoupGroups | denomLossEvents | peerPushDebit | peerPushCredit | peerPullDebit | peerPullCredit | donationSummaries | donationPlanchets | donationReceipts | transactionsMeta | refundItems 95 let completedSteps: Int? 96 let totalSteps: Int? 97 let processedRecords: Int? 98 let totalRecords: Int? 99 let completionPercent: Int? 100 } 101 102 deinit { 103 logger.log("shutdown Quickjs") 104 // TODO: send shutdown message to talerWalletInstance 105 // quickjs.waitStopped() 106 } 107 108 init() throws { 109 nativeDB = false 110 isObserving = 0 111 isLogging = false 112 // logger.trace("init Quickjs") 113 requestsMade = 0 114 queue = DispatchQueue(label: "net.taler.myQueue", attributes: .concurrent) 115 semaphore = DispatchSemaphore(value: 1) 116 quickjs = Quickjs() 117 quickjs.messageHandler = self 118 logger.log("Quickjs running") 119 } 120 } 121 // MARK: - completionHandler functions 122 extension WalletCore { 123 /// `requestsMade` and `completions` are touched both from the request queue and from 124 /// wallet-core's message handler, thus every access must be guarded by the semaphore. 125 private func reserveRequestId() -> UInt { 126 semaphore.wait() 127 defer { semaphore.signal() } 128 let requestId = requestsMade 129 requestsMade += 1 130 return requestId 131 } 132 133 private func setCompletion(_ requestId: UInt, _ sendTime: Date, 134 _ completion: @escaping (UInt, Date, String?, Data?, TalerErrorDetail?) -> Void) { 135 semaphore.wait() 136 defer { semaphore.signal() } 137 completions[requestId] = (sendTime, completion) 138 } 139 140 /// Take the completion out of the list, so that it can never be called twice. 141 /// Whoever gets it must call it - on every path, including all error paths. 142 private func takeCompletion(_ requestId: UInt) 143 -> (Date, (UInt, Date, String?, Data?, TalerErrorDetail?) -> Void)? { 144 semaphore.wait() 145 defer { semaphore.signal() } 146 return completions.removeValue(forKey: requestId) 147 } 148 149 private func handleError(_ decoded: ResponseOrNotification, _ message: String?) throws { 150 guard let requestId = decoded.id else { 151 logger.error("didn't find requestId in error response") 152 // TODO: show error alert 153 throw WalletBackendError.deserializationError 154 } 155 guard let (timeSent, completion) = takeCompletion(requestId) else { 156 logger.error("requestId \(requestId, privacy: .public) not in list") 157 // TODO: show error alert 158 throw WalletBackendError.deserializationError 159 } 160 if let walletError = decoded.error { // wallet-core sent an error message 161 do { 162 let jsonData = try JSONEncoder().encode(walletError) 163 #if !DEBUG 164 logger.error("wallet-core sent back error \(walletError.code, privacy: .public) for request \(requestId, privacy: .public)") 165 #endif 166 completion(requestId, timeSent, message, jsonData, walletError) 167 } catch { // JSON encoding of response.result failed / should never happen 168 symLog.log(decoded) 169 logger.error("cannot encode wallet-core Error") 170 completion(requestId, timeSent, message, nil, WalletCore.parseFailureError()) 171 } 172 } else { // JSON decoding of error message failed 173 completion(requestId, timeSent, message, nil, WalletCore.parseFailureError()) 174 } 175 } 176 177 private func handleResponse(_ decoded: ResponseOrNotification, _ message: String) throws { 178 guard let requestId = decoded.id else { 179 logger.error("didn't find requestId in response") 180 symLog.log(decoded) // TODO: .error 181 throw WalletBackendError.deserializationError 182 } 183 guard let (timeSent, completion) = takeCompletion(requestId) else { 184 logger.error("requestId \(requestId, privacy: .public) not in list") 185 throw WalletBackendError.deserializationError 186 } 187 guard let result = decoded.result else { // don't throw - we own the completion now 188 logger.error("requestId \(requestId, privacy: .public) got no result") 189 completion(requestId, timeSent, message, nil, WalletCore.parseResponseError()) 190 return 191 } 192 do { 193 let jsonData = try JSONEncoder().encode(result) 194 if let operation = decoded.operation { 195 if operation == "getTransactionsV2" { 196 if logTransactions { 197 symLog.log(message) 198 } 199 } else { 200 if #available(iOS 16.0, *) { 201 let regex = #/"data:image(.*?)"/# 202 let modString = message.replacing(regex, with: "\"XXX\"") 203 symLog.log(modString) 204 } else { 205 symLog.log(message) 206 } 207 208 } 209 } 210 // logger.info(result) TODO: log result 211 completion(requestId, timeSent, message, jsonData, nil) 212 } catch { // JSON encoding of response.result failed / should never happen 213 symLog.log(result) // TODO: .error 214 completion(requestId, timeSent, message, nil, WalletCore.parseResponseError()) 215 } 216 } 217 218 @MainActor 219 private func postNotificationM(_ aName: NSNotification.Name, 220 object anObject: Any? = nil, 221 userInfo: [AnyHashable: Any]? = nil) async { 222 NotificationCenter.default.post(name: aName, object: anObject, userInfo: userInfo) 223 } 224 private func postNotification(_ aName: NSNotification.Name, 225 object anObject: Any? = nil, 226 userInfo: [AnyHashable: Any]? = nil) { 227 Task { // runs on MainActor 228 await postNotificationM(aName, object: anObject, userInfo: userInfo) 229 // logger.info("Notification sent: \(aName.rawValue, privacy: .public)") 230 } 231 } 232 233 @MainActor 234 private func handleRequestProgressError(_ jsonData: Data) throws { 235 do { 236 let decoded = try JSONDecoder().decode(RequestProgressError.self, from: jsonData) 237 DispatchQueue.main.async { 238 Controller.shared.lastProgressError = decoded 239 self.postNotification(.RequestProgressError, 240 userInfo: [NOTIFICATIONERROR: decoded]) 241 } 242 } 243 } 244 245 @MainActor 246 private func handleRequestProgressPhase(_ jsonData: Data) throws { 247 do { 248 let decoded = try JSONDecoder().decode(RequestProgressPhase.self, from: jsonData) 249 DispatchQueue.main.async { 250 Controller.shared.lastProgressPhase = decoded 251 self.postNotification(.RequestProgressPhase, 252 userInfo: [NOTIFICATIONPHASE: decoded]) 253 } 254 } 255 } 256 257 private func handlePendingProcessed(_ payload: Payload) throws { 258 guard let id = payload.id else { 259 throw WalletBackendError.deserializationError 260 } 261 let pendingOp = Notification.Name.PendingOperationProcessed.rawValue 262 if id.hasPrefix("exchange-update:") { 263 // Bla Bla Bla 264 } else if id.hasPrefix("refresh:") { 265 // Bla Bla Bla 266 } else if id.hasPrefix("purchase:") { 267 // TODO: handle purchase 268 // symLog.log("\(pendingOp): \(id)") 269 } else if id.hasPrefix("withdraw:") { 270 // TODO: handle withdraw 271 // symLog.log("\(pendingOp): \(id)") 272 } else if id.hasPrefix("peer-pull-credit:") { 273 // TODO: handle peer-pull-credit 274 // symLog.log("\(pendingOp): \(id)") 275 } else if id.hasPrefix("peer-push-debit:") { 276 // TODO: handle peer-push-debit 277 // symLog.log("\(pendingOp): \(id)") 278 } else { 279 // TODO: handle other pending-operation-processed 280 logger.log("❗️ \(pendingOp, privacy: .public): \(id, privacy: .public)") // this is a new pendingOp I haven't seen before 281 } 282 } 283 @MainActor 284 private func handleStateTransition(_ jsonData: Data) throws { 285 do { 286 let decoded = try JSONDecoder().decode(TransactionTransition.self, from: jsonData) 287 if let errorInfo = decoded.errorInfo { 288 // reload pending transaction list to add error badge 289 postNotification(.TransactionError, userInfo: [NOTIFICATIONERROR: WalletBackendError.walletCoreError(errorInfo)]) 290 } else { 291 guard decoded.newTxState != decoded.oldTxState else { 292 logger.info("handleStateTransition: No State change: \(decoded.transactionId, privacy: .private(mask: .hash))") 293 return 294 } 295 } 296 297 let components = decoded.transactionId.components(separatedBy: ":") 298 if components.count >= 3 { // txn:$txtype:$uid 299 if let type = TransactionType(rawValue: components[1]) { 300 guard type != .refresh else { return } 301 let newMajor = decoded.newTxState.major 302 let newMinor = decoded.newTxState.minor 303 let oldMinor = decoded.oldTxState?.minor 304 switch newMajor { 305 case .done: 306 logger.info("handleStateTransition: Done: \(decoded.transactionId, privacy: .private(mask: .hash))") 307 if type.isWithdrawal { 308 Controller.shared.playSound(2) // play payment_received only for withdrawals 309 } else if !type.isIncoming { 310 if !(oldMinor == .autoRefund || oldMinor == .acceptRefund) { 311 Controller.shared.playSound(1) // play payment_sent for all outgoing tx 312 } 313 } else { // incoming but not withdrawal 314 logger.info(" incoming payment done - NO sound - \(type.rawValue)") 315 } 316 postNotification(.TransactionDone, userInfo: [TRANSACTIONTRANSITION: decoded]) 317 return 318 case .aborting, .aborted: 319 logger.log("handleStateTransition: Aborting: \(decoded.transactionId, privacy: .private(mask: .hash))") 320 postNotification(.TransactionStateTransition, userInfo: [TRANSACTIONTRANSITION: decoded]) 321 case .deleted: 322 logger.warning("handleStateTransition: Deleted: \(decoded.transactionId, privacy: .private(mask: .hash))") 323 postNotification(.TransactionDeleted, userInfo: [TRANSACTIONTRANSITION: decoded]) 324 case .expired: 325 logger.warning("handleStateTransition: Expired: \(decoded.transactionId, privacy: .private(mask: .hash))") 326 if let index = expired.firstIndex(of: components[2]) { 327 expired.remove(at: index) // don't beep twice 328 } else { 329 expired.append(components[2]) 330 Controller.shared.playSound(0) // beep at first sight 331 } 332 postNotification(.TransactionExpired, userInfo: [TRANSACTIONTRANSITION: decoded]) 333 case .pending: 334 if let newMinor { 335 if newMinor == .ready { 336 logger.log("handleStateTransition: PendingReady: \(decoded.transactionId, privacy: .private(mask: .hash))") 337 postNotification(.PendingReady, userInfo: [TRANSACTIONTRANSITION: decoded]) 338 return 339 } else if newMinor == .exchangeWaitReserve // user did confirm on bank website 340 || newMinor == .withdraw { // coin-withdrawal has started 341 // logger.log("DismissSheet: \(decoded.transactionId, privacy: .private(mask: .hash))") 342 postNotification(.DismissSheet, userInfo: [TRANSACTIONTRANSITION: decoded]) 343 return 344 } else if newMinor == .kyc { // user did confirm on bank website, but KYC is needed 345 logger.log("handleStateTransition: KYCrequired: \(decoded.transactionId, privacy: .private(mask: .hash))") 346 postNotification(.KYCrequired, userInfo: [TRANSACTIONTRANSITION: decoded]) 347 return 348 } 349 logger.trace("handleStateTransition: Pending:\(newMinor.rawValue, privacy: .public) \(decoded.transactionId, privacy: .private(mask: .hash))") 350 } else { 351 logger.trace("handleStateTransition: Pending: \(decoded.transactionId, privacy: .private(mask: .hash))") 352 } 353 postNotification(.TransactionStateTransition, userInfo: [TRANSACTIONTRANSITION: decoded]) 354 default: 355 if let newMinor { 356 logger.log("handleStateTransition: \(newMajor.rawValue, privacy: .public):\(newMinor.rawValue, privacy: .public) \(decoded.transactionId, privacy: .private(mask: .hash))") 357 } else { 358 logger.warning("handleStateTransition: \(newMajor.rawValue, privacy: .public): \(decoded.transactionId, privacy: .private(mask: .hash))") 359 } 360 postNotification(.TransactionStateTransition, userInfo: [TRANSACTIONTRANSITION: decoded]) 361 } // switch 362 } // type 363 } // 3 components 364 return 365 } catch DecodingError.dataCorrupted(let context) { 366 logger.error("handleStateTransition: \(context.debugDescription)") 367 } catch DecodingError.keyNotFound(let key, let context) { 368 logger.error("handleStateTransition: Key '\(key.stringValue)' not found:\(context.debugDescription)") 369 logger.error("\(context.codingPath)") 370 } catch DecodingError.valueNotFound(let value, let context) { 371 logger.error("handleStateTransition: Value '\(value)' not found:\(context.debugDescription)") 372 logger.error("\(context.codingPath)") 373 } catch DecodingError.typeMismatch(let type, let context) { 374 logger.error("handleStateTransition: Type '\(type)' mismatch:\(context.debugDescription)") 375 logger.error("\(context.codingPath)") 376 } catch let error { // rethrows 377 logger.error("handleStateTransition: \(error.localizedDescription)") 378 } 379 throw WalletBackendError.walletCoreError(nil) // TODO: error? 380 } 381 382 @MainActor private func handleNotification(_ anyCodable: AnyCodable?, _ message: String) throws { 383 guard let anyPayload = anyCodable else { 384 throw WalletBackendError.deserializationError 385 } 386 do { 387 let jsonData = try JSONEncoder().encode(anyPayload) 388 let payload = try JSONDecoder().decode(Payload.self, from: jsonData) 389 390 switch payload.type { 391 case Notification.Name.Idle.rawValue: 392 // symLog.log(message) 393 break 394 case Notification.Name.DatabaseMaintenance.rawValue: 395 symLog.log(message) 396 postNotification(.DatabaseMaintenance, userInfo: [NOTIFICATIONPAYLOAD: payload]) 397 break 398 case Notification.Name.ExchangeStateTransition.rawValue: 399 symLog.log(message) 400 if let baseUrl = payload.exchangeBaseUrl, 401 let state = payload.newExchangeState { 402 Controller.shared.updateExchange(for: baseUrl, state: state) 403 } 404 break 405 case Notification.Name.RequestProgressError.rawValue: 406 symLog.log(message) 407 try handleRequestProgressError(jsonData) 408 case Notification.Name.RequestProgressPhase.rawValue: 409 symLog.log(message) 410 try handleRequestProgressPhase(jsonData) 411 case Notification.Name.TransactionStateTransition.rawValue: 412 symLog.log(message) 413 try handleStateTransition(jsonData) 414 case Notification.Name.PendingOperationProcessed.rawValue: 415 try handlePendingProcessed(payload) 416 case Notification.Name.BalanceChange.rawValue: 417 let now = Date() 418 symLog.log(message) 419 if !(payload.isInternal ?? false) { // don't re-post internals 420 if let txID = payload.hintTransactionId { 421 if txID.contains("txn:refresh:") { 422 break // don't re-post refresh 423 } 424 } 425 postNotification(.BalanceChange, userInfo: [NOTIFICATIONTIME: now]) 426 } 427 case Notification.Name.BankAccountChange.rawValue: 428 symLog.log(message) 429 postNotification(.BankAccountChange) 430 case Notification.Name.ExchangeAdded.rawValue: 431 symLog.log(message) 432 postNotification(.ExchangeAdded) 433 case Notification.Name.ExchangeDeleted.rawValue: 434 symLog.log(message) 435 postNotification(.ExchangeDeleted) 436 case Notification.Name.ReserveNotYetFound.rawValue: 437 if let reservePub = payload.reservePub { 438 let userInfo = ["reservePub" : reservePub] 439 // postNotification(.ReserveNotYetFound, userInfo: userInfo) // TODO: remind User to confirm withdrawal 440 } // else { throw WalletBackendError.deserializationError } shouldn't happen, but if it does just ignore it 441 442 case Notification.Name.ProposalAccepted.rawValue: // "proposal-accepted": 443 symLog.log(message) 444 postNotification(.ProposalAccepted, userInfo: nil) 445 case Notification.Name.ProposalDownloaded.rawValue: // "proposal-downloaded": 446 symLog.log(message) 447 postNotification(.ProposalDownloaded, userInfo: nil) 448 case Notification.Name.TaskObservabilityEvent.rawValue, 449 Notification.Name.RequestObservabilityEvent.rawValue: 450 if isObserving != 0 { 451 symLog.log(message) 452 let timestamp = TalerDater.dateString() 453 if let event = payload.event, let json = event.toJSON() { 454 let type = event["type"]?.value as? String 455 let eventID = event["id"]?.value as? String 456 if #available(iOS 16.0, *) { 457 observe(json: json, 458 type: type, 459 eventID: eventID, 460 timestamp: timestamp) 461 } 462 } 463 } 464 // TODO: remove these once wallet-core doesn't send them anymore 465 // case "refresh-started", "refresh-melted", 466 // "refresh-revealed", "refresh-unwarranted": 467 // break 468 default: 469 logger.error("NEW Notification: \(message)") // this is a new notification I haven't seen before 470 break 471 } 472 } catch let error { 473 logger.error("Error \(error) parsing notification: \(message)") 474 postNotification(.GeneralError, userInfo: [NOTIFICATIONERROR: error]) 475 // TODO: if DevMode then should log into file for user 476 } 477 } 478 479 /// wallet-core logs from its own thread, thus hop to the main actor before the console 480 func handleLog(message: String) { 481 guard isLogging else { return } // don't flood the main queue when nobody looks 482 DispatchQueue.main.async { [self] in 483 handleLogM(message: message) 484 } 485 } 486 487 @MainActor private func handleLogM(message: String) { 488 if #available (iOS 16.0, *) { 489 if isLogging { 490 let consoleManager = LCManager.shared 491 consoleManager.print(message) 492 } 493 } 494 } 495 496 @available(iOS 16.0, *) 497 @MainActor func observe(json: String, type: String?, eventID: String?, timestamp: String) { 498 let consoleManager = LCManager.shared 499 if let type { 500 if let eventID { 501 consoleManager.print("\(type) \(eventID)") 502 } else { 503 consoleManager.print(type) 504 } 505 } 506 consoleManager.print(" \(timestamp)") 507 if isObserving < 0 { 508 consoleManager.print(json) 509 } 510 consoleManager.print("- - -") 511 } 512 513 /// A message we could not decode may still be the answer to a pending request. 514 /// Fail that request, otherwise it would wait for an answer which never comes. 515 private func failPendingRequest(_ messageData: Data, _ message: String) { 516 guard let header = try? JSONDecoder().decode(ResponseHeader.self, from: messageData), 517 header.type == "response" || header.type == "error", 518 let requestId = header.id, 519 let (timeSent, completion) = takeCompletion(requestId) 520 else { return } 521 logger.error("undecodable \(header.type, privacy: .public) for request \(requestId, privacy: .public)") 522 completion(requestId, timeSent, message, nil, WalletCore.parseFailureError()) 523 } 524 525 /// wallet-core calls this from its own thread, thus hop to the main actor 526 func handleMessage(message: String) { 527 DispatchQueue.main.async { [self] in 528 handleMessageM(message: message) 529 } 530 } 531 532 /// here not only responses, but also notifications from wallet-core will be received 533 @MainActor private func handleMessageM(message: String) { 534 do { 535 guard let messageData = message.data(using: .utf8) else { 536 throw WalletBackendError.deserializationError 537 } 538 do { 539 let decoded = try JSONDecoder().decode(ResponseOrNotification.self, from: messageData) 540 switch decoded.type { 541 case "error": 542 symLog.log("\"id\":\(decoded.id ?? 0) \(message)") 543 try handleError(decoded, message) 544 case "response": 545 // symLog.log(message) 546 try handleResponse(decoded, message) 547 case "notification": 548 // symLog.log(message) 549 try handleNotification(decoded.payload, message) 550 case "tunnelHttp": // TODO: Handle tunnelHttp 551 symLog.log("Can't handle tunnelHttp: \(message)") // TODO: .error 552 throw WalletBackendError.deserializationError 553 default: 554 symLog.log("Unknown response type: \(message)") // TODO: .error 555 throw WalletBackendError.deserializationError 556 } 557 } catch { // e.g. a TalerErrorDetail from a remote server which doesn't decode 558 failPendingRequest(messageData, message) // never leave a request hanging 559 throw error 560 } 561 } catch DecodingError.dataCorrupted(let context) { 562 logger.error("\(context.debugDescription)") 563 } catch DecodingError.keyNotFound(let key, let context) { 564 logger.error("Key '\(key.stringValue)' not found:\(context.debugDescription)") 565 logger.error("\(context.codingPath)") 566 } catch DecodingError.valueNotFound(let value, let context) { 567 logger.error("Value '\(value)' not found:\(context.debugDescription)") 568 logger.error("\(context.codingPath)") 569 } catch DecodingError.typeMismatch(let type, let context) { 570 logger.error("Type '\(type)' mismatch:\(context.debugDescription)") 571 logger.error("\(context.codingPath)") 572 } catch let error { 573 logger.error("\(error.localizedDescription)") 574 // Anything that is not a DecodingError means we could not classify the 575 // message at all (e.g. tunnelHttp, or an unknown "type"). A second 576 // `catch` after this one would be unreachable, so notify from here. 577 delegate?.walletBackendReceivedUnknownMessage(self, message: message) 578 } 579 } 580 581 private func encodeAndSend(_ request: WalletBackendRequest, completionHandler: @escaping (UInt, Date, String?, Data?, TalerErrorDetail?) -> Void) { 582 // Encode the request and send it to the backend. 583 let operation = request.operation 584 queue.async { 585 let requestId = self.reserveRequestId() 586 let sendTime = Date.now 587 do { 588 let full = FullRequest(operation: operation, id: requestId, args: request.args) 589 // symLog.log(full) 590 let encoded = try JSONEncoder().encode(full) 591 guard let jsonString = String(data: encoded, encoding: .utf8) else { throw WalletBackendError.serializationError } 592 let args = try JSONEncoder().encode(request.args) 593 if let jsonArgs = String(data: args, encoding: .utf8) { 594 if operation == "getTransactionsV2" { 595 if self.logTransactions { 596 self.logger.trace("🔴\"id\":\(requestId, privacy: .public) \(operation, privacy: .public)\(jsonArgs, privacy: .auto)") 597 } 598 } else { 599 self.logger.log("🔴\"id\":\(requestId, privacy: .public) \(operation, privacy: .public)\(jsonArgs, privacy: .auto)") 600 } 601 } else { // should NEVER happen since the whole request was already successfully encoded and stringified 602 self.logger.log("🔴\"id\":\(requestId, privacy: .public) \(operation, privacy: .public) 🔴 Error: jsonArgs") 603 } 604 // register only after everything which can throw did succeed, but before 605 // sending - the answer may arrive before sendMessage() even returns 606 self.setCompletion(requestId, sendTime, completionHandler) 607 self.quickjs.sendMessage(message: jsonString) 608 // self.symLog.log(jsonString) 609 } catch { // call completion - nothing was registered, thus nobody else will 610 self.logger.error("\(error.localizedDescription)") 611 // self.symLog.log(error) 612 completionHandler(requestId, sendTime, nil, nil, WalletCore.serializeRequestError()); 613 } 614 } 615 } 616 } 617 // MARK: - async / await function 618 extension WalletCore { 619 /// send async requests to wallet-core 620 func sendFormattedRequest<T: WalletBackendFormattedRequest> (_ request: T, asJSON: Bool = false) async throws -> (T.Response, UInt) { 621 let reqData = WalletBackendRequest(operation: request.operation, 622 args: AnyEncodable(request.args())) 623 return try await withCheckedThrowingContinuation { continuation in 624 encodeAndSend(reqData) { [self] requestId, timeSent, message, result, error in 625 let timeUsed = Date.now - timeSent 626 let millisecs = timeUsed.milliseconds 627 if let error { 628 logger.error("Request \"id\":\(requestId, privacy: .public) failed after \(millisecs, privacy: .public) ms, error: \(error.code, privacy: .public)") 629 } else { 630 #if DEBUG 631 if millisecs > (nativeDB ? 20 : 50) { 632 logger.info("Request \"id\":\(requestId, privacy: .public) took \(millisecs, privacy: .public) ms") 633 } 634 #endif 635 } 636 var err: Error? = nil 637 if let json = result, error == nil { 638 do { 639 if asJSON { 640 if let message, let response = message as? T.Response { 641 continuation.resume(returning: (response, requestId)) 642 } else { 643 continuation.resume(throwing: TransactionDecodingError.invalidStringValue) 644 } 645 } else { 646 let decoded = try JSONDecoder().decode(T.Response.self, from: json) 647 continuation.resume(returning: (decoded, requestId)) 648 } 649 return 650 } catch DecodingError.dataCorrupted(let context) { 651 logger.error("\(context.debugDescription)") 652 err = DecodingError.dataCorrupted(context) 653 } catch DecodingError.keyNotFound(let key, let context) { 654 logger.error("Key '\(key.stringValue)' not found:\(context.debugDescription)") 655 logger.error("\(context.codingPath)") 656 err = DecodingError.keyNotFound(key, context) 657 } catch DecodingError.valueNotFound(let value, let context) { 658 logger.error("Value '\(value)' not found:\(context.debugDescription)") 659 logger.error("\(context.codingPath)") 660 err = DecodingError.valueNotFound(value, context) 661 } catch DecodingError.typeMismatch(let type, let context) { 662 logger.error("Type '\(type)' mismatch:\(context.debugDescription)") 663 logger.error("\(context.codingPath)") 664 err = DecodingError.typeMismatch(type, context) 665 } catch { // rethrows 666 if let jsonString = String(data: json, encoding: .utf8) { 667 symLog.log(jsonString) // TODO: .error 668 } else { 669 symLog.log(json) // TODO: .error 670 } 671 err = error // this will be thrown in continuation.resume(throwing:), otherwise keep nil 672 } 673 } else if let error { 674 // TODO: WALLET_CORE_REQUEST_CANCELLED 675 lastError = FullError(type: "error", operation: request.operation, id: requestId, error: error) 676 err = WalletBackendError.walletCoreError(error) 677 } else { // both result and error are nil 678 lastError = nil 679 } 680 continuation.resume(throwing: err ?? TransactionDecodingError.invalidStringValue) 681 } 682 } 683 } 684 }