WalletCore.swift (35351B)
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 let responseCode = walletError.code 164 logger.error("wallet-core sent back error \(walletError.code, privacy: .public), \(responseCode, privacy: .public) for request \(requestId, privacy: .public)") 165 symLog.log("id:\(requestId) \(walletError)") 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 .expired, .deleted: 322 logger.warning("handleStateTransition: Expired: \(decoded.transactionId, privacy: .private(mask: .hash))") 323 if let index = expired.firstIndex(of: components[2]) { 324 expired.remove(at: index) // don't beep twice 325 } else { 326 expired.append(components[2]) 327 Controller.shared.playSound(0) // beep at first sight 328 } 329 postNotification(.TransactionExpired, userInfo: [TRANSACTIONTRANSITION: decoded]) 330 case .pending: 331 if let newMinor { 332 if newMinor == .ready { 333 logger.log("handleStateTransition: PendingReady: \(decoded.transactionId, privacy: .private(mask: .hash))") 334 postNotification(.PendingReady, userInfo: [TRANSACTIONTRANSITION: decoded]) 335 return 336 } else if newMinor == .exchangeWaitReserve // user did confirm on bank website 337 || newMinor == .withdraw { // coin-withdrawal has started 338 // logger.log("DismissSheet: \(decoded.transactionId, privacy: .private(mask: .hash))") 339 postNotification(.DismissSheet, userInfo: [TRANSACTIONTRANSITION: decoded]) 340 return 341 } else if newMinor == .kyc { // user did confirm on bank website, but KYC is needed 342 logger.log("handleStateTransition: KYCrequired: \(decoded.transactionId, privacy: .private(mask: .hash))") 343 postNotification(.KYCrequired, userInfo: [TRANSACTIONTRANSITION: decoded]) 344 return 345 } 346 logger.trace("handleStateTransition: Pending:\(newMinor.rawValue, privacy: .public) \(decoded.transactionId, privacy: .private(mask: .hash))") 347 } else { 348 logger.trace("handleStateTransition: Pending: \(decoded.transactionId, privacy: .private(mask: .hash))") 349 } 350 postNotification(.TransactionStateTransition, userInfo: [TRANSACTIONTRANSITION: decoded]) 351 default: 352 if let newMinor { 353 logger.log("handleStateTransition: \(newMajor.rawValue, privacy: .public):\(newMinor.rawValue, privacy: .public) \(decoded.transactionId, privacy: .private(mask: .hash))") 354 } else { 355 logger.warning("handleStateTransition: \(newMajor.rawValue, privacy: .public): \(decoded.transactionId, privacy: .private(mask: .hash))") 356 } 357 postNotification(.TransactionStateTransition, userInfo: [TRANSACTIONTRANSITION: decoded]) 358 } // switch 359 } // type 360 } // 3 components 361 return 362 } catch DecodingError.dataCorrupted(let context) { 363 logger.error("handleStateTransition: \(context.debugDescription)") 364 } catch DecodingError.keyNotFound(let key, let context) { 365 logger.error("handleStateTransition: Key '\(key.stringValue)' not found:\(context.debugDescription)") 366 logger.error("\(context.codingPath)") 367 } catch DecodingError.valueNotFound(let value, let context) { 368 logger.error("handleStateTransition: Value '\(value)' not found:\(context.debugDescription)") 369 logger.error("\(context.codingPath)") 370 } catch DecodingError.typeMismatch(let type, let context) { 371 logger.error("handleStateTransition: Type '\(type)' mismatch:\(context.debugDescription)") 372 logger.error("\(context.codingPath)") 373 } catch let error { // rethrows 374 logger.error("handleStateTransition: \(error.localizedDescription)") 375 } 376 throw WalletBackendError.walletCoreError(nil) // TODO: error? 377 } 378 379 @MainActor private func handleNotification(_ anyCodable: AnyCodable?, _ message: String) throws { 380 guard let anyPayload = anyCodable else { 381 throw WalletBackendError.deserializationError 382 } 383 do { 384 let jsonData = try JSONEncoder().encode(anyPayload) 385 let payload = try JSONDecoder().decode(Payload.self, from: jsonData) 386 387 switch payload.type { 388 case Notification.Name.Idle.rawValue: 389 // symLog.log(message) 390 break 391 case Notification.Name.DatabaseMaintenance.rawValue: 392 symLog.log(message) 393 postNotification(.DatabaseMaintenance, userInfo: [NOTIFICATIONPAYLOAD: payload]) 394 break 395 case Notification.Name.ExchangeStateTransition.rawValue: 396 symLog.log(message) 397 if let baseUrl = payload.exchangeBaseUrl, 398 let state = payload.newExchangeState { 399 Controller.shared.updateExchange(for: baseUrl, state: state) 400 } 401 break 402 case Notification.Name.RequestProgressError.rawValue: 403 symLog.log(message) 404 try handleRequestProgressError(jsonData) 405 case Notification.Name.RequestProgressPhase.rawValue: 406 symLog.log(message) 407 try handleRequestProgressPhase(jsonData) 408 case Notification.Name.TransactionStateTransition.rawValue: 409 symLog.log(message) 410 try handleStateTransition(jsonData) 411 case Notification.Name.PendingOperationProcessed.rawValue: 412 try handlePendingProcessed(payload) 413 case Notification.Name.BalanceChange.rawValue: 414 let now = Date() 415 symLog.log(message) 416 if !(payload.isInternal ?? false) { // don't re-post internals 417 if let txID = payload.hintTransactionId { 418 if txID.contains("txn:refresh:") { 419 break // don't re-post refresh 420 } 421 } 422 postNotification(.BalanceChange, userInfo: [NOTIFICATIONTIME: now]) 423 } 424 case Notification.Name.BankAccountChange.rawValue: 425 symLog.log(message) 426 postNotification(.BankAccountChange) 427 case Notification.Name.ExchangeAdded.rawValue: 428 symLog.log(message) 429 postNotification(.ExchangeAdded) 430 case Notification.Name.ExchangeDeleted.rawValue: 431 symLog.log(message) 432 postNotification(.ExchangeDeleted) 433 case Notification.Name.ReserveNotYetFound.rawValue: 434 if let reservePub = payload.reservePub { 435 let userInfo = ["reservePub" : reservePub] 436 // postNotification(.ReserveNotYetFound, userInfo: userInfo) // TODO: remind User to confirm withdrawal 437 } // else { throw WalletBackendError.deserializationError } shouldn't happen, but if it does just ignore it 438 439 case Notification.Name.ProposalAccepted.rawValue: // "proposal-accepted": 440 symLog.log(message) 441 postNotification(.ProposalAccepted, userInfo: nil) 442 case Notification.Name.ProposalDownloaded.rawValue: // "proposal-downloaded": 443 symLog.log(message) 444 postNotification(.ProposalDownloaded, userInfo: nil) 445 case Notification.Name.TaskObservabilityEvent.rawValue, 446 Notification.Name.RequestObservabilityEvent.rawValue: 447 if isObserving != 0 { 448 symLog.log(message) 449 let timestamp = TalerDater.dateString() 450 if let event = payload.event, let json = event.toJSON() { 451 let type = event["type"]?.value as? String 452 let eventID = event["id"]?.value as? String 453 if #available(iOS 16.0, *) { 454 observe(json: json, 455 type: type, 456 eventID: eventID, 457 timestamp: timestamp) 458 } 459 } 460 } 461 // TODO: remove these once wallet-core doesn't send them anymore 462 // case "refresh-started", "refresh-melted", 463 // "refresh-revealed", "refresh-unwarranted": 464 // break 465 default: 466 logger.error("NEW Notification: \(message)") // this is a new notification I haven't seen before 467 break 468 } 469 } catch let error { 470 logger.error("Error \(error) parsing notification: \(message)") 471 postNotification(.GeneralError, userInfo: [NOTIFICATIONERROR: error]) 472 // TODO: if DevMode then should log into file for user 473 } 474 } 475 476 /// wallet-core logs from its own thread, thus hop to the main actor before the console 477 func handleLog(message: String) { 478 guard isLogging else { return } // don't flood the main queue when nobody looks 479 DispatchQueue.main.async { [self] in 480 handleLogM(message: message) 481 } 482 } 483 484 @MainActor private func handleLogM(message: String) { 485 if #available (iOS 16.0, *) { 486 if isLogging { 487 let consoleManager = LCManager.shared 488 consoleManager.print(message) 489 } 490 } 491 } 492 493 @available(iOS 16.0, *) 494 @MainActor func observe(json: String, type: String?, eventID: String?, timestamp: String) { 495 let consoleManager = LCManager.shared 496 if let type { 497 if let eventID { 498 consoleManager.print("\(type) \(eventID)") 499 } else { 500 consoleManager.print(type) 501 } 502 } 503 consoleManager.print(" \(timestamp)") 504 if isObserving < 0 { 505 consoleManager.print(json) 506 } 507 consoleManager.print("- - -") 508 } 509 510 /// A message we could not decode may still be the answer to a pending request. 511 /// Fail that request, otherwise it would wait for an answer which never comes. 512 private func failPendingRequest(_ messageData: Data, _ message: String) { 513 guard let header = try? JSONDecoder().decode(ResponseHeader.self, from: messageData), 514 header.type == "response" || header.type == "error", 515 let requestId = header.id, 516 let (timeSent, completion) = takeCompletion(requestId) 517 else { return } 518 logger.error("undecodable \(header.type, privacy: .public) for request \(requestId, privacy: .public)") 519 completion(requestId, timeSent, message, nil, WalletCore.parseFailureError()) 520 } 521 522 /// wallet-core calls this from its own thread, thus hop to the main actor 523 func handleMessage(message: String) { 524 DispatchQueue.main.async { [self] in 525 handleMessageM(message: message) 526 } 527 } 528 529 /// here not only responses, but also notifications from wallet-core will be received 530 @MainActor private func handleMessageM(message: String) { 531 do { 532 guard let messageData = message.data(using: .utf8) else { 533 throw WalletBackendError.deserializationError 534 } 535 do { 536 let decoded = try JSONDecoder().decode(ResponseOrNotification.self, from: messageData) 537 switch decoded.type { 538 case "error": 539 symLog.log("\"id\":\(decoded.id ?? 0) \(message)") 540 try handleError(decoded, message) 541 case "response": 542 // symLog.log(message) 543 try handleResponse(decoded, message) 544 case "notification": 545 // symLog.log(message) 546 try handleNotification(decoded.payload, message) 547 case "tunnelHttp": // TODO: Handle tunnelHttp 548 symLog.log("Can't handle tunnelHttp: \(message)") // TODO: .error 549 throw WalletBackendError.deserializationError 550 default: 551 symLog.log("Unknown response type: \(message)") // TODO: .error 552 throw WalletBackendError.deserializationError 553 } 554 } catch { // e.g. a TalerErrorDetail from a remote server which doesn't decode 555 failPendingRequest(messageData, message) // never leave a request hanging 556 throw error 557 } 558 } catch DecodingError.dataCorrupted(let context) { 559 logger.error("\(context.debugDescription)") 560 } catch DecodingError.keyNotFound(let key, let context) { 561 logger.error("Key '\(key.stringValue)' not found:\(context.debugDescription)") 562 logger.error("\(context.codingPath)") 563 } catch DecodingError.valueNotFound(let value, let context) { 564 logger.error("Value '\(value)' not found:\(context.debugDescription)") 565 logger.error("\(context.codingPath)") 566 } catch DecodingError.typeMismatch(let type, let context) { 567 logger.error("Type '\(type)' mismatch:\(context.debugDescription)") 568 logger.error("\(context.codingPath)") 569 } catch let error { 570 logger.error("\(error.localizedDescription)") 571 // Anything that is not a DecodingError means we could not classify the 572 // message at all (e.g. tunnelHttp, or an unknown "type"). A second 573 // `catch` after this one would be unreachable, so notify from here. 574 delegate?.walletBackendReceivedUnknownMessage(self, message: message) 575 } 576 } 577 578 private func encodeAndSend(_ request: WalletBackendRequest, completionHandler: @escaping (UInt, Date, String?, Data?, TalerErrorDetail?) -> Void) { 579 // Encode the request and send it to the backend. 580 queue.async { 581 let requestId = self.reserveRequestId() 582 let sendTime = Date.now 583 do { 584 let full = FullRequest(operation: request.operation, id: requestId, args: request.args) 585 // symLog.log(full) 586 let encoded = try JSONEncoder().encode(full) 587 guard let jsonString = String(data: encoded, encoding: .utf8) else { throw WalletBackendError.serializationError } 588 let args = try JSONEncoder().encode(request.args) 589 if let jsonArgs = String(data: args, encoding: .utf8) { 590 if request.operation == "getTransactionsV2" { 591 if self.logTransactions { 592 self.logger.trace("🔴\"id\":\(requestId, privacy: .public) \(request.operation, privacy: .public)\(jsonArgs, privacy: .auto)") 593 } 594 } else { 595 self.logger.log("🔴\"id\":\(requestId, privacy: .public) \(request.operation, privacy: .public)\(jsonArgs, privacy: .auto)") 596 } 597 } else { // should NEVER happen since the whole request was already successfully encoded and stringified 598 self.logger.log("🔴\"id\":\(requestId, privacy: .public) \(request.operation, privacy: .public) 🔴 Error: jsonArgs") 599 } 600 // register only after everything which can throw did succeed, but before 601 // sending - the answer may arrive before sendMessage() even returns 602 self.setCompletion(requestId, sendTime, completionHandler) 603 self.quickjs.sendMessage(message: jsonString) 604 // self.symLog.log(jsonString) 605 } catch { // call completion - nothing was registered, thus nobody else will 606 self.logger.error("\(error.localizedDescription)") 607 // self.symLog.log(error) 608 completionHandler(requestId, sendTime, nil, nil, WalletCore.serializeRequestError()); 609 } 610 } 611 } 612 } 613 // MARK: - async / await function 614 extension WalletCore { 615 /// send async requests to wallet-core 616 func sendFormattedRequest<T: WalletBackendFormattedRequest> (_ request: T, asJSON: Bool = false) async throws -> (T.Response, UInt) { 617 let reqData = WalletBackendRequest(operation: request.operation, 618 args: AnyEncodable(request.args())) 619 return try await withCheckedThrowingContinuation { continuation in 620 encodeAndSend(reqData) { [self] requestId, timeSent, message, result, error in 621 let timeUsed = Date.now - timeSent 622 let millisecs = timeUsed.milliseconds 623 if let error { 624 logger.error("Request \"id\":\(requestId, privacy: .public) failed after \(millisecs, privacy: .public) ms, error: \(error.code, privacy: .public)") 625 } else { 626 #if DEBUG 627 if millisecs > (nativeDB ? 20 : 50) { 628 logger.info("Request \"id\":\(requestId, privacy: .public) took \(millisecs, privacy: .public) ms") 629 } 630 #endif 631 } 632 var err: Error? = nil 633 if let json = result, error == nil { 634 do { 635 if asJSON { 636 if let message, let response = message as? T.Response { 637 continuation.resume(returning: (response, requestId)) 638 } else { 639 continuation.resume(throwing: TransactionDecodingError.invalidStringValue) 640 } 641 } else { 642 let decoded = try JSONDecoder().decode(T.Response.self, from: json) 643 continuation.resume(returning: (decoded, requestId)) 644 } 645 return 646 } catch DecodingError.dataCorrupted(let context) { 647 logger.error("\(context.debugDescription)") 648 err = DecodingError.dataCorrupted(context) 649 } catch DecodingError.keyNotFound(let key, let context) { 650 logger.error("Key '\(key.stringValue)' not found:\(context.debugDescription)") 651 logger.error("\(context.codingPath)") 652 err = DecodingError.keyNotFound(key, context) 653 } catch DecodingError.valueNotFound(let value, let context) { 654 logger.error("Value '\(value)' not found:\(context.debugDescription)") 655 logger.error("\(context.codingPath)") 656 err = DecodingError.valueNotFound(value, context) 657 } catch DecodingError.typeMismatch(let type, let context) { 658 logger.error("Type '\(type)' mismatch:\(context.debugDescription)") 659 logger.error("\(context.codingPath)") 660 err = DecodingError.typeMismatch(type, context) 661 } catch { // rethrows 662 if let jsonString = String(data: json, encoding: .utf8) { 663 symLog.log(jsonString) // TODO: .error 664 } else { 665 symLog.log(json) // TODO: .error 666 } 667 err = error // this will be thrown in continuation.resume(throwing:), otherwise keep nil 668 } 669 } else if let error { 670 // TODO: WALLET_CORE_REQUEST_CANCELLED 671 lastError = FullError(type: "error", operation: request.operation, id: requestId, error: error) 672 err = WalletBackendError.walletCoreError(error) 673 } else { // both result and error are nil 674 lastError = nil 675 } 676 continuation.resume(throwing: err ?? TransactionDecodingError.invalidStringValue) 677 } 678 } 679 } 680 }