1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
|
/*
* This file is part of GNU Taler, ©2022-23 Taler Systems S.A.
* See LICENSE.md
*/
/**
* @author Marc Stibane
* @author Iván Ávalos
*/
import SwiftUI // FOUNDATION has no AppStorage
import AnyCodable
import FTalerWalletcore
import SymLog
import os
import LocalConsole
/// Delegate for the wallet backend.
protocol WalletBackendDelegate {
/// Called when the backend interface receives a message it does not know how to handle.
func walletBackendReceivedUnknownMessage(_ walletCore: WalletCore, message: String)
}
// MARK: -
/// An interface to the wallet backend.
class WalletCore: QuickjsMessageHandler {
public static let shared = try! WalletCore() // will (and should) crash on failure
private let symLog = SymLogC()
private var queue: DispatchQueue
private var semaphore: DispatchSemaphore
private let quickjs: Quickjs
private var requestsMade: UInt // counter for array of completion closures
private var completions: [UInt : (Date, (UInt, Date, Data?, WalletBackendResponseError?) -> Void)] = [:]
var delegate: WalletBackendDelegate?
var versionInfo: VersionInfo? // shown in SettingsView
var developDelay: Bool? // if set in SettingsView will delay wallet-core after each action
var isObserving: Int
var isLogging: Bool
let logger = Logger(subsystem: "net.taler.gnu", category: "WalletCore")
private struct FullRequest: Encodable {
let operation: String
let id: UInt
let args: AnyEncodable
}
private struct FullResponse: Decodable {
let type: String
let operation: String
let id: UInt
let result: AnyCodable
}
struct FullError: Decodable {
let type: String
let operation: String
let id: UInt
let error: WalletBackendResponseError
}
var lastError: FullError?
struct ResponseOrNotification: Decodable {
let type: String
let operation: String?
let id: UInt?
let result: AnyCodable?
let error: WalletBackendResponseError?
let payload: AnyCodable?
}
struct Payload: Decodable {
let type: String
let id: String?
let reservePub: String?
let event: [String: AnyCodable]?
}
deinit {
logger.log("shutdown Quickjs")
// TODO: send shutdown message to talerWalletInstance
// quickjs.waitStopped()
}
init() throws {
isObserving = 0
isLogging = false
logger.info("init Quickjs")
requestsMade = 0
queue = DispatchQueue(label: "net.taler.myQueue", attributes: .concurrent)
semaphore = DispatchSemaphore(value: 1)
quickjs = Quickjs()
quickjs.messageHandler = self
logger.log("Quickjs running")
}
}
// MARK: - completionHandler functions
extension WalletCore {
private func handleError(_ decoded: ResponseOrNotification) throws {
guard let requestId = decoded.id else {
logger.error("didn't find requestId in error response")
// TODO: show error alert
throw WalletBackendError.deserializationError
}
guard let (timeSent, completion) = completions[requestId] else {
logger.error("requestId \(requestId, privacy: .public) not in list")
// TODO: show error alert
throw WalletBackendError.deserializationError
}
completions[requestId] = nil
if let walletError = decoded.error { // wallet-core sent an error message
do {
let jsonData = try JSONEncoder().encode(walletError)
logger.error("wallet-core sent back an error for request \(requestId, privacy: .public)")
symLog.log("id:\(requestId) \(walletError)")
completion(requestId, timeSent, jsonData, walletError)
} catch { // JSON encoding of response.result failed / should never happen
symLog.log(decoded)
logger.error("cannot encode wallet-core Error")
completion(requestId, timeSent, nil, WalletCore.parseFailureError())
}
} else { // JSON decoding of error message failed
completion(requestId, timeSent, nil, WalletCore.parseFailureError())
}
}
private func handleResponse(_ decoded: ResponseOrNotification) throws {
guard let requestId = decoded.id else {
logger.error("didn't find requestId in response")
symLog.log(decoded) // TODO: .error
throw WalletBackendError.deserializationError
}
guard let (timeSent, completion) = completions[requestId] else {
logger.error("requestId \(requestId, privacy: .public) not in list")
throw WalletBackendError.deserializationError
}
completions[requestId] = nil
guard let result = decoded.result else {
logger.error("requestId \(requestId, privacy: .public) got no result")
throw WalletBackendError.deserializationError
}
do {
let jsonData = try JSONEncoder().encode(result)
symLog.log("id:\(requestId) \(result)")
// logger.info(result) TODO: log result
completion(requestId, timeSent, jsonData, nil)
} catch { // JSON encoding of response.result failed / should never happen
symLog.log(result) // TODO: .error
completion(requestId, timeSent, nil, WalletCore.parseResponseError())
}
}
@MainActor
private func postNotificationM(_ aName: NSNotification.Name,
object anObject: Any? = nil,
userInfo: [AnyHashable: Any]? = nil) async {
NotificationCenter.default.post(name: aName, object: anObject, userInfo: userInfo)
}
private func postNotification(_ aName: NSNotification.Name,
object anObject: Any? = nil,
userInfo: [AnyHashable: Any]? = nil) {
Task { // runs on MainActor
await postNotificationM(aName, object: anObject, userInfo: userInfo)
// logger.info("Notification sent: \(aName.rawValue, privacy: .public)")
}
}
private func handlePendingProcessed(_ payload: Payload) throws {
guard let id = payload.id else { throw WalletBackendError.deserializationError }
let pendingOp = Notification.Name.PendingOperationProcessed.rawValue
if id.hasPrefix("exchange-update:") {
// Bla Bla Bla
} else if id.hasPrefix("refresh:") {
// Bla Bla Bla
} else if id.hasPrefix("purchase:") {
// TODO: handle purchase
// symLog.log("\(pendingOp): \(id)")
} else if id.hasPrefix("withdraw:") {
// TODO: handle withdraw
// symLog.log("\(pendingOp): \(id)")
} else if id.hasPrefix("peer-pull-credit:") {
// TODO: handle peer-pull-credit
// symLog.log("\(pendingOp): \(id)")
} else if id.hasPrefix("peer-push-debit:") {
// TODO: handle peer-push-debit
// symLog.log("\(pendingOp): \(id)")
} else {
// TODO: handle other pending-operation-processed
logger.log("❗️ \(pendingOp, privacy: .public): \(id, privacy: .public)") // this is a new pendingOp I haven't seen before
}
}
@MainActor private func handleStateTransition(_ jsonData: Data) throws {
do {
let decoded = try JSONDecoder().decode(TransactionTransition.self, from: jsonData)
guard decoded.newTxState != decoded.oldTxState else {
// TODO: Same state usually means that an error is transmitted
logger.info("No State change: \(decoded.transactionId, privacy: .private(mask: .hash))")
return
}
if decoded.errorInfo == nil {
postNotification(.Error, userInfo: [NOTIFICATIONERROR: decoded.errorInfo])
}
let components = decoded.transactionId.components(separatedBy: ":")
if components.count >= 3 { // txn:$txtype:$uid
if let type = TransactionType(rawValue: components[1]) {
guard type != .refresh else { return }
let newMajor = decoded.newTxState.major
let newMinor = decoded.newTxState.minor
switch newMajor {
case .done:
logger.info("Done: \(decoded.transactionId, privacy: .private(mask: .hash))")
if type.isWithdrawal {
Controller.shared.playSound(2) // payment_received only for withdrawals
} else if !type.isIncoming {
Controller.shared.playSound(1) // payment_sent for all outgoing tx
}
postNotification(.TransactionDone, userInfo: [TRANSACTIONTRANSITION: decoded])
return
case .aborting:
if let newMinor {
if newMinor == .refreshExpired {
logger.warning("RefreshExpired: \(decoded.transactionId, privacy: .private(mask: .hash))")
Controller.shared.playSound(0)
postNotification(.TransactionExpired, userInfo: [TRANSACTIONTRANSITION: decoded])
return
}
}
logger.warning("Unknown aborting: \(decoded.transactionId, privacy: .private(mask: .hash))")
postNotification(.TransactionStateTransition, userInfo: [TRANSACTIONTRANSITION: decoded])
case .expired:
logger.warning("Expired: \(decoded.transactionId, privacy: .private(mask: .hash))")
Controller.shared.playSound(0)
postNotification(.TransactionExpired, userInfo: [TRANSACTIONTRANSITION: decoded])
return
case .pending:
if let newMinor {
if newMinor == .ready {
logger.log("PendingReady: \(decoded.transactionId, privacy: .private(mask: .hash))")
postNotification(.PendingReady, userInfo: [TRANSACTIONTRANSITION: decoded])
return
} else if newMinor == .exchangeWaitReserve // user did confirm on bank website
|| newMinor == .withdrawCoins { // coin-withdrawal has started
// logger.log("DismissSheet: \(decoded.transactionId, privacy: .private(mask: .hash))")
postNotification(.DismissSheet, userInfo: [TRANSACTIONTRANSITION: decoded])
return
} else if newMinor == .kyc { // user did confirm on bank website, but KYC is needed
logger.log("KYCrequired: \(decoded.transactionId, privacy: .private(mask: .hash))")
postNotification(.KYCrequired, userInfo: [TRANSACTIONTRANSITION: decoded])
return
}
logger.log("Pending:\(newMinor.rawValue, privacy: .public) \(decoded.transactionId, privacy: .private(mask: .hash))")
} else {
logger.log("Pending: \(decoded.transactionId, privacy: .private(mask: .hash))")
}
postNotification(.TransactionStateTransition, userInfo: [TRANSACTIONTRANSITION: decoded])
default:
if let newMinor {
logger.warning("\(newMajor.rawValue, privacy: .public):\(newMinor.rawValue, privacy: .public) \(decoded.transactionId, privacy: .private(mask: .hash))")
} else {
logger.warning("\(newMajor.rawValue, privacy: .public): \(decoded.transactionId, privacy: .private(mask: .hash))")
}
postNotification(.TransactionStateTransition, userInfo: [TRANSACTIONTRANSITION: decoded])
} // switch
} // type
} // 3 components
} catch { // rethrows
symLog.log(jsonData) // TODO: .error
throw WalletBackendError.deserializationError
}
}
@MainActor private func handleNotification(_ anyCodable: AnyCodable?) throws {
guard let anyPayload = anyCodable else { throw WalletBackendError.deserializationError }
do {
let jsonData = try JSONEncoder().encode(anyPayload)
let payload = try JSONDecoder().decode(Payload.self, from: jsonData)
switch payload.type {
case Notification.Name.TransactionStateTransition.rawValue:
symLog.log(anyPayload)
try handleStateTransition(jsonData)
case Notification.Name.PendingOperationProcessed.rawValue:
try handlePendingProcessed(payload)
case Notification.Name.BalanceChange.rawValue:
symLog.log(anyPayload)
postNotification(.BalanceChange)
case Notification.Name.ExchangeAdded.rawValue:
symLog.log(anyPayload)
postNotification(.ExchangeAdded)
case Notification.Name.ReserveNotYetFound.rawValue:
if let reservePub = payload.reservePub {
let userInfo = ["reservePub" : reservePub]
// postNotification(.ReserveNotYetFound, userInfo: userInfo) // TODO: remind User to confirm withdrawal
} // else { throw WalletBackendError.deserializationError } shouldn't happen, but if it does just ignore it
case Notification.Name.ProposalAccepted.rawValue: // "proposal-accepted":
symLog.log(anyPayload)
postNotification(.ProposalAccepted, userInfo: nil)
case Notification.Name.ProposalDownloaded.rawValue: // "proposal-downloaded":
symLog.log(anyPayload)
postNotification(.ProposalDownloaded, userInfo: nil)
case Notification.Name.TaskObservabilityEvent.rawValue,
Notification.Name.RequestObservabilityEvent.rawValue:
symLog.log(anyPayload)
if isObserving != 0 {
let timestamp = TalerDater.dateString()
if let event = payload.event, let json = event.toJSON() {
let type = event["type"]?.value as? String
let eventID = event["id"]?.value as? String
observe(json: json,
type: type,
eventID: eventID,
timestamp: timestamp)
}
}
// TODO: remove these once wallet-core doesn't send them anymore
// case "refresh-started", "refresh-melted",
// "refresh-revealed", "refresh-unwarranted":
// break
default:
print("\n❗️ WalletCore.swift:251 Notification: ", anyPayload, "\n") // this is a new notification I haven't seen before
break
}
} catch let error {
symLog.log("Error \(error) parsing notification: \(anyPayload)") // TODO: .error
postNotification(.Error, userInfo: [NOTIFICATIONERROR: error])
// TODO: if DevMode then should log into file for user
}
}
@MainActor func handleLog(message: String) {
if isLogging {
let consoleManager = LCManager.shared
consoleManager.print(message)
}
}
@MainActor func observe(json: String, type: String?, eventID: String?, timestamp: String) {
let consoleManager = LCManager.shared
if let type {
if let eventID {
consoleManager.print("\(type) \(eventID)")
} else {
consoleManager.print(type)
}
}
consoleManager.print(" \(timestamp)")
if isObserving < 0 {
consoleManager.print(json)
}
consoleManager.print("- - -")
}
/// here not only responses, but also notifications from wallet-core will be received
@MainActor func handleMessage(message: String) {
do {
var asyncDelay = 0
if let delay: Bool = developDelay { // Settings: 2 seconds delay
if delay {
asyncDelay = 2
}
}
if asyncDelay > 0 {
symLog.log(message)
symLog.log("...going to sleep for \(asyncDelay) seconds...")
sleep(UInt32(asyncDelay))
symLog.log("waking up again after \(asyncDelay) seconds, will deliver message")
}
guard let messageData = message.data(using: .utf8) else {
throw WalletBackendError.deserializationError
}
let decoded = try JSONDecoder().decode(ResponseOrNotification.self, from: messageData)
switch decoded.type {
case "error":
symLog.log(decoded) // TODO: .error
try handleError(decoded)
case "response":
try handleResponse(decoded)
case "notification":
try handleNotification(decoded.payload)
case "tunnelHttp": // TODO: Handle tunnelHttp
symLog.log("Can't handle tunnelHttp: \(decoded)") // TODO: .error
throw WalletBackendError.deserializationError
default:
symLog.log("Unknown response type: \(decoded)") // TODO: .error
throw WalletBackendError.deserializationError
}
} catch DecodingError.dataCorrupted(let context) {
print(context)
} catch DecodingError.keyNotFound(let key, let context) {
print("Key '\(key)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch DecodingError.valueNotFound(let value, let context) {
print("Value '\(value)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch DecodingError.typeMismatch(let type, let context) {
print("Type '\(type)' mismatch:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch { // TODO: ?
delegate?.walletBackendReceivedUnknownMessage(self, message: message)
}
}
private func sendRequest(request: WalletBackendRequest, completionHandler: @escaping (UInt, Date, Data?, WalletBackendResponseError?) -> Void) {
// Encode the request and send it to the backend.
queue.async {
self.semaphore.wait() // guard access to requestsMade
let requestId = self.requestsMade
let sendTime = Date.now
do {
let full = FullRequest(operation: request.operation, id: requestId, args: request.args)
// symLog.log(full)
let encoded = try JSONEncoder().encode(full)
guard let jsonString = String(data: encoded, encoding: .utf8) else { throw WalletBackendError.serializationError }
self.completions[requestId] = (sendTime, completionHandler)
self.requestsMade += 1
self.semaphore.signal() // free requestsMade
self.logger.log("sendRequest \(requestId, privacy: .public): \(request.operation, privacy: .public)")
self.quickjs.sendMessage(message: jsonString)
self.symLog.log(jsonString)
} catch { // call completion
self.semaphore.signal()
self.symLog.log(error)
completionHandler(requestId, sendTime, nil, WalletCore.serializeRequestError());
}
}
}
}
// MARK: - async / await function
extension WalletCore {
/// send async requests to wallet-core
func sendFormattedRequest<T: WalletBackendFormattedRequest> (_ request: T) async throws -> (T.Response, UInt) {
let reqData = WalletBackendRequest(operation: request.operation(),
args: AnyEncodable(request.args()))
return try await withCheckedThrowingContinuation { continuation in
sendRequest(request: reqData) { requestId, timeSent, result, error in
let timeUsed = Date.now - timeSent
let millisecs = timeUsed.milliseconds
if let error {
self.logger.error("Request \"id\":\(requestId, privacy: .public) failed after \(millisecs, privacy: .public) ms")
} else {
self.logger.info("Request \"id\":\(requestId, privacy: .public) took \(millisecs, privacy: .public) ms")
}
var err: Error? = nil
if let json = result, error == nil {
do {
let decoded = try JSONDecoder().decode(T.Response.self, from: json)
continuation.resume(returning: (decoded, requestId))
return
} catch DecodingError.dataCorrupted(let context) {
print(context)
} catch DecodingError.keyNotFound(let key, let context) {
print("Key '\(key)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch DecodingError.valueNotFound(let value, let context) {
print("Value '\(value)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch DecodingError.typeMismatch(let type, let context) {
print("Type '\(type)' mismatch:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch { // rethrows
if let jsonString = String(data: json, encoding: .utf8) {
self.symLog.log(jsonString) // TODO: .error
} else {
self.symLog.log(json) // TODO: .error
}
err = error // this will be thrown in continuation.resume(throwing:), otherwise keep nil
}
} else {
// TODO: WALLET_CORE_REQUEST_CANCELLED
if let error {
self.lastError = FullError(type: "error", operation: request.operation(), id: requestId, error: error)
} else {
self.lastError = nil
}
err = WalletBackendError.walletCoreError(error)
}
continuation.resume(throwing: err ?? TransactionDecodingError.invalidStringValue)
}
}
}
}
|