summaryrefslogtreecommitdiff
path: root/TalerWallet1/Backend/WalletCore.swift
blob: e9e9ef11a89b7589f63e57554df7cbbfb4a9ff58 (plain)
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
/*
 * This file is part of GNU Taler, ©2022-23 Taler Systems S.A.
 * See LICENSE.md
 */
import SwiftUI              // FOUNDATION has no AppStorage
import AnyCodable
import FTalerWalletcore
import SymLog
import os

/// 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
    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: AnyCodable?  // should be WalletBackendResponseError?
        let payload: AnyCodable?
    }

    struct Payload: Decodable {
        let type: String
        let id: String?
        let reservePub: String?
    }

    deinit {
        logger.log("shutdown Quickjs")
    // TODO: send shutdown message to talerWalletInstance
//        quickjs.waitStopped()
    }

    init() throws {
        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)
            } catch {        // JSON encoding of response.result failed / should never happen
                symLog.log(decoded)
                logger.error("cannot encode wallet-core Error")
                // TODO: show error alert
                completion(requestId, timeSent, nil, WalletCore.parseFailureError())
            }
            // TODO: decode jsonData to WalletBackendResponseError - or HTTPError
            logger.error("wallet-core sent back an error for request \(requestId, privacy: .public)")
//            completion(requestId, timeSent, nil, walletError)
            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(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.log("Notification sent: \(aName.rawValue)")
        }
    }

    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)
            if decoded.newTxState != decoded.oldTxState {
                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 }
                        if decoded.newTxState.major == .done {
                            logger.log("Done: \(decoded.transactionId, privacy: .private(mask: .hash))")
                            Controller.shared.playSound(type.isIncoming ? 2 : 1)
                        } else if decoded.newTxState.major == .expired {
                            logger.log("Expired: \(decoded.transactionId, privacy: .private(mask: .hash))")
                            Controller.shared.playSound(0)
                        }
                        postNotification(.TransactionStateTransition,
                                         userInfo: [TRANSACTIONTRANSITION: decoded])
                    }
                }
            } else {
                // TODO: Same state usually means that an error is transmitted
                logger.log("No State change: \(decoded.transactionId, privacy: .private(mask: .hash))")
            }
        } 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)

                    // TODO: remove these once wallet-core doesn't send them anymore
//                case "reserve-registered-with-bank":
//                    symLog.log(anyPayload)
//                case "withdraw-group-finished",
//                     "pay-operation-success",
//                     "withdrawal-group-bank-confirmed",          // replaced by transaction-state-transition
//                     "withdrawal-group-reserve-ready",
//                     "waiting-for-retry",                        // Bla Bla Bla
                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
        // TODO: if DevMode then should log into file for user
        }
    }

    /// 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.symLog.log(jsonString)
                self.quickjs.sendMessage(message: 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
                self.logger.log("Request \(requestId) took \(millisecs) ms")
                var err: Error? = nil
                if let json = result {
                    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 {
                    if let error = error {
                        self.lastError = FullError(type: "error", operation: request.operation(), id: requestId, error: error)
                    } else {
                        self.lastError = nil
                    }
                    err = WalletBackendError.walletCoreError
                }
                continuation.resume(throwing: err ?? TransactionDecodingError.invalidStringValue)
            }
        }
    }
}