From 4fd0a75ec4c6079e4b805f9683fda44b2e06e7f1 Mon Sep 17 00:00:00 2001 From: Jason Date: Thu, 22 Aug 2024 14:23:55 +0200 Subject: [PATCH] chore: code formatting --- Bitkit/BitkitApp.swift | 15 +++---- Bitkit/Constants/Env.swift | 37 ++++++++-------- Bitkit/ContentView.swift | 4 +- Bitkit/Extensions/HexBytes.swift | 4 +- Bitkit/Models/LnPeer.swift | 8 ++-- Bitkit/Models/WalletNetwork.swift | 8 ++-- Bitkit/Services/BlocktankService.swift | 17 ++++---- Bitkit/Services/LightningService.swift | 39 ++++++++--------- Bitkit/Services/MigrationsService.swift | 20 +++++---- Bitkit/Services/OnChainService.swift | 21 +++++----- Bitkit/Utilities/Errors.swift | 15 ++++--- Bitkit/Utilities/Keychain.swift | 28 ++++++------- Bitkit/Utilities/Logger.swift | 4 +- Bitkit/Utilities/ScenePhase.swift | 6 +-- Bitkit/Utilities/StartupHandler.swift | 6 +-- Bitkit/ViewModels/LightningViewModel.swift | 14 +++---- Bitkit/ViewModels/OnChainViewModel.swift | 4 +- Bitkit/ViewModels/ViewModel.swift | 6 +-- Bitkit/Views/Onboarding/WelcomeView.swift | 8 ++-- Bitkit/Views/Settings/LogView.swift | 8 ++-- Bitkit/Views/Wallets/HomeView.swift | 17 ++++---- BitkitNotification/NotificationService.swift | 44 +++++++++----------- BitkitTests/BitkitTests.swift | 2 - BitkitTests/KeychainTests.swift | 19 ++++----- BitkitTests/LdkMigration.swift | 16 ++++--- BitkitUITests/BitkitUITests.swift | 1 - BitkitUITests/BitkitUITestsLaunchTests.swift | 1 - 27 files changed, 179 insertions(+), 193 deletions(-) diff --git a/Bitkit/BitkitApp.swift b/Bitkit/BitkitApp.swift index 24073f1e..869a58c0 100644 --- a/Bitkit/BitkitApp.swift +++ b/Bitkit/BitkitApp.swift @@ -8,29 +8,30 @@ import SwiftUI class AppDelegate: NSObject, UIApplicationDelegate { - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { UNUserNotificationCenter.current().delegate = self return true } } -extension AppDelegate : UNUserNotificationCenterDelegate { +extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, - withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) + { let userInfo = notification.request.content.userInfo Logger.debug(userInfo, context: "push notification received while app is in the foreground") - //If we want to display the native notification to the user while the app is open we need to call this with options - //Unlikely we will need to as the background operation would have been aborted and we would have nothint to show + // If we want to display the native notification to the user while the app is open we need to call this with options + // Unlikely we will need to as the background operation would have been aborted and we would have nothint to show completionHandler([]) // completionHandler([[.banner, .badge, .sound]]) } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Task { - //If this fails we can try again later as the token is cached here + // If this fails we can try again later as the token is cached here try? await BlocktankService.shared.registerDevice(deviceToken: deviceToken.map { String(format: "%02hhx", $0) }.joined()) } } @@ -43,7 +44,7 @@ extension AppDelegate : UNUserNotificationCenterDelegate { let userInfo = response.notification.request.content.userInfo Logger.debug(userInfo, context: "app opened from push notification") - //TODO: if user tapped on an incoming tx we should open it on that tx view + // TODO: if user tapped on an incoming tx we should open it on that tx view completionHandler() } } diff --git a/Bitkit/Constants/Env.swift b/Bitkit/Constants/Env.swift index d6dd4e6c..a32b0f32 100644 --- a/Bitkit/Constants/Env.swift +++ b/Bitkit/Constants/Env.swift @@ -5,30 +5,31 @@ // Created by Jason van den Berg on 2024/07/01. // -import Foundation import BitcoinDevKit +import Foundation -struct Env { +enum Env { static let isPreview = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" static let isTestFlight = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" static let isUnitTest = ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil - //{Team ID}.{Keychain Group} + // {Team ID}.{Keychain Group} static let keychainGroup = "KYH47R284B.to.bitkit" -#if targetEnvironment(simulator) - static let isSim = true -#else - static let isSim = false -#endif + #if targetEnvironment(simulator) + static let isSim = true + #else + static let isSim = false + #endif -#if DEBUG - static let isDebug = true -#else - static let isDebug = false -#endif + #if DEBUG + static let isDebug = true + #else + static let isDebug = false + #endif - //MARK: wallet services + // MARK: wallet services + static let network: WalletNetwork = .regtest static let defaultWalletWordCount: WordCount = .words12 static let onchainWalletStopGap = UInt64(20) @@ -37,8 +38,8 @@ struct Env { switch network { case .regtest: return "https://electrs-regtest.synonym.to" - //cargo run --release --bin electrs -- -vvv --jsonrpc-import --daemon-rpc-addr 127.0.0.1:18443 --cookie polaruser:polarpass - //return "http://127.0.0.1:3000" + // cargo run --release --bin electrs -- -vvv --jsonrpc-import --daemon-rpc-addr 127.0.0.1:18443 --cookie polaruser:polarpass + // return "http://127.0.0.1:3000" case .bitcoin: fatalError("Bitcoin network not implemented") case .testnet: @@ -49,7 +50,7 @@ struct Env { } static var appStorageUrl: URL { - //App group so files can be shared with extensions + // App group so files can be shared with extensions guard let documentsDirectory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.bitkit") else { fatalError("Could not find documents directory") } @@ -108,7 +109,7 @@ struct Env { switch network { case .regtest: return [ - //Staging Blocktank node + // Staging Blocktank node .init(nodeId: "03b9a456fb45d5ac98c02040d39aec77fa3eeb41fd22cf40b862b393bcfc43473a", address: "35.233.47.252:9400") ] case .bitcoin: diff --git a/Bitkit/ContentView.swift b/Bitkit/ContentView.swift index 2fef4697..e5339a13 100644 --- a/Bitkit/ContentView.swift +++ b/Bitkit/ContentView.swift @@ -9,7 +9,7 @@ import SwiftUI struct ContentView: View { @StateObject var viewModel = ViewModel.shared - + var body: some View { VStack { if viewModel.walletExists == nil { @@ -29,7 +29,7 @@ struct ContentView: View { .onAppear { viewModel.setWalletExistsState() } - .handleLightningStateOnScenePhaseChange() //Will stop and start LN node as needed + .handleLightningStateOnScenePhaseChange() // Will stop and start LN node as needed } } diff --git a/Bitkit/Extensions/HexBytes.swift b/Bitkit/Extensions/HexBytes.swift index b95fa9c7..b3e66902 100644 --- a/Bitkit/Extensions/HexBytes.swift +++ b/Bitkit/Extensions/HexBytes.swift @@ -16,13 +16,13 @@ extension Data { extension StringProtocol { var hexaData: Data { .init(hexa) } var hexaBytes: [UInt8] { .init(hexa) } - + private var hexa: UnfoldSequence { sequence(state: startIndex) { startIndex in guard startIndex < endIndex else { return nil } let endIndex = index(startIndex, offsetBy: 2, limitedBy: endIndex) ?? endIndex defer { startIndex = endIndex } - return UInt8(self[startIndex.. Void)? = nil) { Task { @@ -259,29 +261,22 @@ extension LightningService { let event = await node.nextEventAsync() onEvent?(event) - //TODO actual event handler + // TODO: actual event handler switch event { case .paymentSuccessful(paymentId: let paymentId, paymentHash: let paymentHash, feePaidMsat: let feePaidMsat): Logger.info("βœ… Payment successful: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash) feePaidMsat: \(feePaidMsat ?? 0)") - break case .paymentFailed(paymentId: let paymentId, paymentHash: let paymentHash, reason: let reason): Logger.info("❌ Payment failed: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash) reason: \(reason.debugDescription)") - break case .paymentReceived(paymentId: let paymentId, paymentHash: let paymentHash, amountMsat: let amountMsat): Logger.info("πŸ€‘ Payment received: paymentId: \(paymentId ?? "?") paymentHash: \(paymentHash) amountMsat: \(amountMsat)") - break case .paymentClaimable(paymentId: let paymentId, paymentHash: let paymentHash, claimableAmountMsat: let claimableAmountMsat, claimDeadline: let claimDeadline): Logger.info("🫰 Payment claimable: paymentId: \(paymentId) paymentHash: \(paymentHash) claimableAmountMsat: \(claimableAmountMsat)") - break case .channelPending(channelId: let channelId, userChannelId: let userChannelId, formerTemporaryChannelId: let formerTemporaryChannelId, counterpartyNodeId: let counterpartyNodeId, fundingTxo: let fundingTxo): Logger.info("⏳ Channel pending: channelId: \(channelId) userChannelId: \(userChannelId) formerTemporaryChannelId: \(formerTemporaryChannelId) counterpartyNodeId: \(counterpartyNodeId) fundingTxo: \(fundingTxo)") - break case .channelReady(channelId: let channelId, userChannelId: let userChannelId, counterpartyNodeId: let counterpartyNodeId): Logger.info("πŸ‘ Channel ready: channelId: \(channelId) userChannelId: \(userChannelId) counterpartyNodeId: \(counterpartyNodeId ?? "?")") - break case .channelClosed(channelId: let channelId, userChannelId: let userChannelId, counterpartyNodeId: let counterpartyNodeId, reason: let reason): Logger.info("β›” Channel closed: channelId: \(channelId) userChannelId: \(userChannelId) counterpartyNodeId: \(counterpartyNodeId ?? "?") reason: \(reason.debugDescription)") - break } node.eventHandled() diff --git a/Bitkit/Services/MigrationsService.swift b/Bitkit/Services/MigrationsService.swift index 9f4588d0..22a151a1 100644 --- a/Bitkit/Services/MigrationsService.swift +++ b/Bitkit/Services/MigrationsService.swift @@ -6,8 +6,8 @@ // import Foundation +import LightningDevKit // TODO: remove this when we no longer need it to read funding_tx and index from monitors import SQLite -import LightningDevKit //TODO remove this when we no longer need it to read funding_tx and index from monitors class MigrationsService { static var shared = MigrationsService() @@ -15,14 +15,15 @@ class MigrationsService { private init() {} } -//MARK: Migrations for RN Bitkit to Swift Bitkit +// MARK: Migrations for RN Bitkit to Swift Bitkit + extension MigrationsService { func ldkToLdkNode(walletIndex: Int, seed: Data, manager: Data, monitors: [Data]) throws { Logger.info("Migrating LDK to LDKNode") let ldkStorage = Env.ldkStorage(walletIndex: walletIndex) let sqlFilePath = ldkStorage.appendingPathComponent("ldk_node_data.sqlite").path - //Create path if doesn't exist + // Create path if doesn't exist let fileManager = FileManager.default var isDir: ObjCBool = true if !fileManager.fileExists(atPath: ldkStorage.path, isDirectory: &isDir) { @@ -32,7 +33,7 @@ extension MigrationsService { Logger.debug(sqlFilePath, context: "SQLIte file path") - //Can't migrate if data currently exists + // Can't migrate if data currently exists guard !fileManager.fileExists(atPath: sqlFilePath) else { throw AppError(serviceError: .ldkNodeSqliteAlreadyExists) } @@ -53,8 +54,8 @@ extension MigrationsService { t.column(valueCol) }) - //TODO: use create statement directly from LDK-node instead - //CREATE TABLE IF NOT EXISTS {} ( + // TODO: use create statement directly from LDK-node instead + // CREATE TABLE IF NOT EXISTS {} ( // primary_namespace TEXT NOT NULL, // secondary_namespace TEXT DEFAULT \"\" NOT NULL, // key TEXT NOT NULL CHECK (key <> ''), @@ -66,7 +67,7 @@ extension MigrationsService { Logger.debug(rowid, context: "Inserted manager") let seconds = UInt64(NSDate().timeIntervalSince1970) - let nanoSeconds = UInt32.init(truncating: NSNumber(value: seconds * 1000 * 1000)) + let nanoSeconds = UInt32(truncating: NSNumber(value: seconds * 1000 * 1000)) let keysManager = KeysManager( seed: [UInt8](seed), startingTimeSecs: seconds, @@ -74,8 +75,9 @@ extension MigrationsService { ) for monitor in monitors { - //MARK: get funding_tx and index using plain LDK - //https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#definition-of-channel_id + // MARK: get funding_tx and index using plain LDK + + // https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#definition-of-channel_id guard let channelMonitor = Bindings.readThirtyTwoBytesChannelMonitor(ser: [UInt8](monitor), argA: keysManager.asEntropySource(), argB: keysManager.asSignerProvider()).getValue()?.1 else { Logger.error("Could not read channel monitor using readThirtyTwoBytesChannelMonitor") throw AppError(serviceError: .ldkToLdkNodeMigration) diff --git a/Bitkit/Services/OnChainService.swift b/Bitkit/Services/OnChainService.swift index 16e229dd..ef1ad25c 100644 --- a/Bitkit/Services/OnChainService.swift +++ b/Bitkit/Services/OnChainService.swift @@ -5,8 +5,8 @@ // Created by Jason van den Berg on 2024/07/01. // -import Foundation import BitcoinDevKit +import Foundation class OnChainService { private var wallet: Wallet? @@ -29,9 +29,9 @@ class OnChainService { currentWalletIndex = walletIndex - let secretKey = DescriptorSecretKey( + let secretKey = try DescriptorSecretKey( network: Env.network.bdkNetwork, - mnemonic: try Mnemonic.fromString(mnemonic: mnemonic), + mnemonic: Mnemonic.fromString(mnemonic: mnemonic), password: passphrase ) @@ -64,14 +64,14 @@ class OnChainService { Logger.info("Onchain wallet created") - //Clear memory + // Clear memory mnemonic = "" passphrase = nil } func stop() { Logger.debug("Stopping on chain wallet...") - self.wallet = nil + wallet = nil Logger.info("On chain wallet stopped") } @@ -115,7 +115,7 @@ class OnChainService { let update = try self.esploraClient.sync(syncRequest: request, parallelRequests: 5) try wallet.applyUpdate(update: update) - //TODO: persist wallet?? + // TODO: persist wallet?? } hasSynced = true @@ -135,11 +135,11 @@ class OnChainService { let request = wallet.startFullScan() let update = try self.esploraClient.fullScan( fullScanRequest: request, - stopGap: Env.onchainWalletStopGap, + stopGap: Env.onchainWalletStopGap, parallelRequests: Env.esploraParallelRequests ) try wallet.applyUpdate(update: update) - //TODO: persist wallet once BDK is updated to beta release + // TODO: persist wallet once BDK is updated to beta release } hasSynced = true @@ -148,8 +148,9 @@ class OnChainService { } } -//MARK: UI Helpers (Published via OnChainViewModel) +// MARK: UI Helpers (Published via OnChainViewModel) + extension OnChainService { - //TODO catch errors? + // TODO: catch errors? var balance: Balance? { hasSynced ? wallet?.getBalance() : nil } } diff --git a/Bitkit/Utilities/Errors.swift b/Bitkit/Utilities/Errors.swift index 27d033eb..f9e4b423 100644 --- a/Bitkit/Utilities/Errors.swift +++ b/Bitkit/Utilities/Errors.swift @@ -5,9 +5,9 @@ // Created by Jason van den Berg on 2024/07/04. // +import BitcoinDevKit import Foundation import LDKNode -import BitcoinDevKit enum CustomServiceError: Error { case nodeNotSetup @@ -103,12 +103,12 @@ struct AppError: LocalizedError { private init(bdkError: Error) { message = "Onchain wallet error" debugMessage = bdkError.localizedDescription - //TODO support all message types in switch case - //CalculateFeeError - //CannotConnectError - //DescriptorError - //EsploraError - //PersistenceError + // TODO: support all message types in switch case + // CalculateFeeError + // CannotConnectError + // DescriptorError + // EsploraError + // PersistenceError Logger.error("\(message) [\(debugMessage ?? "")]", context: "BdkError") } @@ -156,7 +156,6 @@ struct AppError: LocalizedError { case .AlreadyRunning(message: let ldkMessage): message = "Node is already running" debugMessage = ldkMessage - break; case .NotRunning(message: let ldkMessage): message = "Node is not running" debugMessage = ldkMessage diff --git a/Bitkit/Utilities/Keychain.swift b/Bitkit/Utilities/Keychain.swift index 709bf60a..ee76819a 100644 --- a/Bitkit/Utilities/Keychain.swift +++ b/Bitkit/Utilities/Keychain.swift @@ -12,7 +12,7 @@ enum KeychainEntryType { case bip39Mnemonic(index: Int) case bip39Passphrase(index: Int) - //TODO: allow for reading keychain entries from RN wallet and then migrate them if needed + // TODO: allow for reading keychain entries from RN wallet and then migrate them if needed var storageKey: String { switch self { @@ -34,9 +34,9 @@ class Keychain { kSecAttrAccount as String: key.storageKey, kSecValueData as String: data, kSecAttrAccessGroup as String: Env.keychainGroup - ] as [String : Any] + ] as [String: Any] - //Don't allow accidentally overwriting keys + // Don't allow accidentally overwriting keys guard try load(key: key) == nil else { Logger.error("Key \(key.storageKey) already exists in keychain. Explicity delete key before attempting to update value.", context: "Keychain") throw KeychainError.failedToSaveAlreadyExists @@ -49,7 +49,7 @@ class Keychain { throw KeychainError.failedToSave } - //Sanity check on save + // Sanity check on save guard var storedValue = try load(key: key) else { Logger.error("Failed to load \(key.storageKey) after saving", context: "Keychain") throw KeychainError.failedToSave @@ -59,7 +59,7 @@ class Keychain { Logger.error("Saved \(key.storageKey) does not match loaded value", context: "Keychain") throw KeychainError.failedToSave } - storedValue = Data() //Clear memory + storedValue = Data() // Clear memory Logger.info("Saved \(key.storageKey)", context: "Keychain") } @@ -77,7 +77,7 @@ class Keychain { kSecClass as String: kSecClassGenericPassword as String, kSecAttrAccount as String: key.storageKey, kSecAttrAccessGroup as String: Env.keychainGroup - ] as [String : Any] + ] as [String: Any] let status = SecItemDelete(query as CFDictionary) @@ -92,11 +92,11 @@ class Keychain { class func exists(key: KeychainEntryType) throws -> Bool { var value = try load(key: key) let exists = value != nil - value = Data() //Clear memory + value = Data() // Clear memory return exists } - //TODO throws if fails but return nil if not found + // TODO: throws if fails but return nil if not found class func load(key: KeychainEntryType) throws -> Data? { let query = [ kSecClass as String: kSecClassGenericPassword, @@ -104,9 +104,9 @@ class Keychain { kSecReturnData as String: kCFBooleanTrue!, kSecMatchLimit as String: kSecMatchLimitOne, kSecAttrAccessGroup as String: Env.keychainGroup - ] as [String : Any] + ] as [String: Any] - var dataTypeRef: AnyObject? = nil + var dataTypeRef: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &dataTypeRef) @@ -148,7 +148,7 @@ class Keychain { var storageKeys = [String]() if lastResultCode == noErr { - let array = result as? Array> + let array = result as? [[String: Any]] for item in array! { if let key = item[kSecAttrAccount as String] as? String { storageKeys.append(key) @@ -160,8 +160,8 @@ class Keychain { } class func wipeEntireKeychain() throws { - //TODO remove check in the future when safe to do so or required by the UI - guard (Env.isDebug || Env.isUnitTest) && Env.network == .regtest else { + // TODO: remove check in the future when safe to do so or required by the UI + guard Env.isDebug || Env.isUnitTest, Env.network == .regtest else { Logger.error("Wiping keychain is only allowed in debug mode for regtest", context: "Keychain") throw KeychainError.keychainWipeNotAllowed } @@ -172,7 +172,7 @@ class Keychain { kSecClass as String: kSecClassGenericPassword as String, kSecAttrAccount as String: key, kSecAttrAccessGroup as String: Env.keychainGroup - ] as [String : Any] + ] as [String: Any] SecItemDelete(query as CFDictionary) Logger.info("Deleted \(key) from keychain") diff --git a/Bitkit/Utilities/Logger.swift b/Bitkit/Utilities/Logger.swift index a32647b9..fd4ac4ba 100644 --- a/Bitkit/Utilities/Logger.swift +++ b/Bitkit/Utilities/Logger.swift @@ -9,7 +9,7 @@ import Foundation class Logger { private init() {} - static let queue = DispatchQueue (label: "bitkit.log", qos: .utility) + static let queue = DispatchQueue(label: "bitkit.log", qos: .utility) static func info(_ message: Any, context: String = "", file: String = #file, function: String = #function, line: Int = #line) { handle("INFOℹ️: \(message)", context: context, file: file, function: function, line: line) @@ -42,7 +42,7 @@ class Logger { print(line) queue.async { - //TODO write to file + // TODO: write to file } } } diff --git a/Bitkit/Utilities/ScenePhase.swift b/Bitkit/Utilities/ScenePhase.swift index 5a1c3396..1b047858 100644 --- a/Bitkit/Utilities/ScenePhase.swift +++ b/Bitkit/Utilities/ScenePhase.swift @@ -7,12 +7,12 @@ import SwiftUI -fileprivate struct HandleLightningStateOnScenePhaseChange: ViewModifier { +private struct HandleLightningStateOnScenePhaseChange: ViewModifier { @StateObject var viewModel = ViewModel.shared @ObservedObject var lnViewModel = LightningViewModel.shared @Environment(\.scenePhase) var scenePhase - let sleepTime: UInt64 = 5_00_000_000 // 0.5 seconds + let sleepTime: UInt64 = 500_000_000 // 0.5 seconds func body(content: Content) -> some View { content @@ -95,6 +95,6 @@ extension View { /// Stops and restarts lightning node when the app enters the background and foreground /// - Returns: View func handleLightningStateOnScenePhaseChange() -> some View { - self.modifier(HandleLightningStateOnScenePhaseChange()) + modifier(HandleLightningStateOnScenePhaseChange()) } } diff --git a/Bitkit/Utilities/StartupHandler.swift b/Bitkit/Utilities/StartupHandler.swift index 0e6c7aa0..f4f2abca 100644 --- a/Bitkit/Utilities/StartupHandler.swift +++ b/Bitkit/Utilities/StartupHandler.swift @@ -5,8 +5,8 @@ // Created by Jason van den Berg on 2024/07/31. // -import SwiftUI import BitcoinDevKit +import SwiftUI class StartupHandler { private init() {} @@ -52,9 +52,9 @@ class StartupHandler { /// - bip39Passphrase: optional bip39 passphrase /// - walletIndex: wallet index, defaults to zero for first static func restoreWallet(mnemonic: String, bip39Passphrase: String?, walletIndex: Int = 0) throws { - _ = try Mnemonic.fromString(mnemonic: mnemonic) //Check it's valid + _ = try Mnemonic.fromString(mnemonic: mnemonic) // Check it's valid - //TODO validate word count also? + // TODO: validate word count also? try Keychain.saveString(key: .bip39Mnemonic(index: walletIndex), str: mnemonic) if let bip39Passphrase { diff --git a/Bitkit/ViewModels/LightningViewModel.swift b/Bitkit/ViewModels/LightningViewModel.swift index 89d0d03c..ab431ce2 100644 --- a/Bitkit/ViewModels/LightningViewModel.swift +++ b/Bitkit/ViewModels/LightningViewModel.swift @@ -5,8 +5,8 @@ // Created by Jason van den Berg on 2024/06/28. // -import SwiftUI import LDKNode +import SwiftUI enum NodeState { case stopped @@ -47,7 +47,7 @@ class LightningViewModel: ObservableObject { syncState() try await LightningService.shared.setup(walletIndex: walletIndex) try await LightningService.shared.start(onEvent: { _ in - //On every lightning event just sync UI + // On every lightning event just sync UI Task { @MainActor in self.syncState() } @@ -56,7 +56,7 @@ class LightningViewModel: ObservableObject { state = .running syncState() - //Always sync on start but don't need to wait for this + // Always sync on start but don't need to wait for this Task { @MainActor in try await sync() } @@ -78,7 +78,7 @@ class LightningViewModel: ObservableObject { syncState() guard state == .running else { - //Not really required to throw an error here + // Not really required to throw an error here Logger.warn("Can't sync when node is not running. Current state: \(state.debugState)") return } @@ -115,9 +115,9 @@ class LightningViewModel: ObservableObject { extension NodeStatus { var debugState: String { var debug = """ -Running: \(isRunning ? "βœ…" : "❌") -Current best block \(currentBestBlock.height) -""" + Running: \(isRunning ? "βœ…" : "❌") + Current best block \(currentBestBlock.height) + """ if let latestWalletSyncTimestamp { debug += "\nLast synced \(Date(timeIntervalSince1970: TimeInterval(latestWalletSyncTimestamp)).description)\n" diff --git a/Bitkit/ViewModels/OnChainViewModel.swift b/Bitkit/ViewModels/OnChainViewModel.swift index c59a0d30..c1577f54 100644 --- a/Bitkit/ViewModels/OnChainViewModel.swift +++ b/Bitkit/ViewModels/OnChainViewModel.swift @@ -5,8 +5,8 @@ // Created by Jason van den Berg on 2024/07/01. // -import SwiftUI import BitcoinDevKit +import SwiftUI @MainActor class OnChainViewModel: ObservableObject { @@ -21,7 +21,7 @@ class OnChainViewModel: ObservableObject { try await OnChainService.shared.setup(walletIndex: walletIndex) syncState() - //Always sync on start but don't need to wait for this + // Always sync on start but don't need to wait for this Task { @MainActor in try await sync() } diff --git a/Bitkit/ViewModels/ViewModel.swift b/Bitkit/ViewModels/ViewModel.swift index fa6b0f58..8ee8bfd1 100644 --- a/Bitkit/ViewModels/ViewModel.swift +++ b/Bitkit/ViewModels/ViewModel.swift @@ -10,15 +10,15 @@ import SwiftUI @MainActor class ViewModel: ObservableObject { @Published var walletExists: Bool? = nil - + private init() {} public static var shared = ViewModel() - + func setWalletExistsState() { do { walletExists = try Keychain.exists(key: .bip39Mnemonic(index: 0)) } catch { - //TODO show error + // TODO: show error Logger.error(error) } } diff --git a/Bitkit/Views/Onboarding/WelcomeView.swift b/Bitkit/Views/Onboarding/WelcomeView.swift index 050e7947..e4d8880b 100644 --- a/Bitkit/Views/Onboarding/WelcomeView.swift +++ b/Bitkit/Views/Onboarding/WelcomeView.swift @@ -18,7 +18,7 @@ struct RestoreView: View { Text("Restore Wallet") .font(.largeTitle) - Form() { + Form { TextField("BIP39 Mnemonic", text: $bip39Mnemonic) TextField("BIP39 Passphrase", text: Binding( @@ -31,10 +31,10 @@ struct RestoreView: View { Button("Restore Wallet") { do { _ = try StartupHandler.restoreWallet(mnemonic: bip39Mnemonic, bip39Passphrase: bip39Passphrase) - //TODO: handle full sync here before revealing the UI so balances are pre populated + // TODO: handle full sync here before revealing the UI so balances are pre populated viewModel.setWalletExistsState() } catch { - //TODO: show a error to user + // TODO: show a error to user Logger.error(error) } } @@ -71,7 +71,7 @@ struct WelcomeView: View { _ = try StartupHandler.createNewWallet(bip39Passphrase: bip39Passphrase) viewModel.setWalletExistsState() } catch { - //TODO: show a error to user + // TODO: show a error to user Logger.error(error) } } diff --git a/Bitkit/Views/Settings/LogView.swift b/Bitkit/Views/Settings/LogView.swift index 8903b5f4..9ba47355 100644 --- a/Bitkit/Views/Settings/LogView.swift +++ b/Bitkit/Views/Settings/LogView.swift @@ -9,7 +9,7 @@ import SwiftUI struct LogView: View { @State var lines: [String] = [] - + var body: some View { List { ForEach(lines, id: \.self) { line in @@ -25,14 +25,14 @@ struct LogView: View { loadLog() } } - + func loadLog() { let dir = Env.ldkStorage(walletIndex: LightningService.shared.currentWalletIndex) let fileURL = dir.appendingPathComponent("ldk_node_latest.log") - + do { let text = try String(contentsOf: fileURL, encoding: .utf8) - lines = text.components(separatedBy: "\n").map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) }) + lines = text.components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } } catch { lines = ["Failed to load log file"] } diff --git a/Bitkit/Views/Wallets/HomeView.swift b/Bitkit/Views/Wallets/HomeView.swift index e4443705..d041f25a 100644 --- a/Bitkit/Views/Wallets/HomeView.swift +++ b/Bitkit/Views/Wallets/HomeView.swift @@ -43,8 +43,8 @@ struct HomeView: View { Section("Blocktank") { Button("Register for notifications") { - StartupHandler.requestPushNotificationPermision { granted, error in - //If granted AppDelegate will receive the token and handle registration + StartupHandler.requestPushNotificationPermision { _, error in + // If granted AppDelegate will receive the token and handle registration if let error { Logger.error(error, context: "Failed to request push notification permission") } @@ -53,7 +53,7 @@ struct HomeView: View { Button("Self test") { Task { - sleep(2) //Chance to background the app + sleep(2) // Chance to background the app do { try await BlocktankService.shared.selfTest() } catch { @@ -105,7 +105,6 @@ struct HomeView: View { Text(channel.isChannelReady ? "🟒" : "πŸ”΄") Text(channel.isUsable ? "🟒" : "πŸ”΄") } - } .onLongPressGesture { Task { @@ -113,9 +112,7 @@ struct HomeView: View { try await LightningService.shared.closeChannel(userChannelId: channel.userChannelId, counterpartyNodeId: channel.counterpartyNodeId) Logger.info("Channel closed") try await lnViewModel.sync() - } catch { - - } + } catch {} } } } @@ -167,10 +164,10 @@ struct HomeView: View { return } do { - //Delete storage (for current wallet only) + // Delete storage (for current wallet only) try await onChainViewModel.wipeWallet() try await lnViewModel.wipeWallet() - //Delete entire keychain + // Delete entire keychain try Keychain.wipeEntireKeychain() viewModel.setWalletExistsState() } catch { @@ -200,7 +197,7 @@ struct HomeView: View { try await group.waitForAll() } } catch { - //TODO show an error + // TODO: show an error } } .sheet(isPresented: $showLogs) { diff --git a/BitkitNotification/NotificationService.swift b/BitkitNotification/NotificationService.swift index a651ab37..c652794b 100644 --- a/BitkitNotification/NotificationService.swift +++ b/BitkitNotification/NotificationService.swift @@ -5,37 +5,37 @@ // Created by Jason van den Berg on 2024/07/03. // -import UserNotifications import LDKNode +import UserNotifications class NotificationService: UNNotificationServiceExtension { - let walletIndex = 0 //Assume first wallet for now + let walletIndex = 0 // Assume first wallet for now var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler - bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) + self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) Task { do { - try await LightningService.shared.setup(walletIndex: walletIndex) //Assume first wallet for now + try await LightningService.shared.setup(walletIndex: self.walletIndex) // Assume first wallet for now try await LightningService.shared.start { event in self.handleLdkEvent(event: event) } } catch { - bestAttemptContent?.title = "Lightning error" - bestAttemptContent?.body = error.localizedDescription + self.bestAttemptContent?.title = "Lightning error" + self.bestAttemptContent?.body = error.localizedDescription Logger.error(error, context: "failed to setup node in notification service") - dumpLdkLogs() - await deliver() + self.dumpLdkLogs() + await self.deliver() } } } - + func handleLdkEvent(event: Event) { switch event { case .paymentReceived(paymentId: let paymentId, paymentHash: let paymentHash, amountMsat: let amountMsat): @@ -44,31 +44,27 @@ class NotificationService: UNNotificationServiceExtension { Task { await self.deliver() } - break case .channelPending(channelId: let channelId, userChannelId: let userChannelId, formerTemporaryChannelId: let formerTemporaryChannelId, counterpartyNodeId: let counterpartyNodeId, fundingTxo: let fundingTxo): self.bestAttemptContent?.title = "Channel Opened" self.bestAttemptContent?.body = "Pending" - //Don't deliver, give a chance for channelReady event to update the content - break + // Don't deliver, give a chance for channelReady event to update the content case .channelReady(channelId: let channelId, userChannelId: let userChannelId, counterpartyNodeId: let counterpartyNodeId): self.bestAttemptContent?.title = "Channel ready" self.bestAttemptContent?.body = "Usable" Task { await self.deliver() } - break case .channelClosed(channelId: let channelId, userChannelId: let userChannelId, counterpartyNodeId: let counterpartyNodeId, reason: let reason): self.bestAttemptContent?.title = "Channel closed" - self.bestAttemptContent?.body = reason.debugDescription //TODO: Reason string + self.bestAttemptContent?.body = reason.debugDescription // TODO: Reason string Task { await self.deliver() } + case .paymentSuccessful: break - case .paymentSuccessful(_, _, _): - break - case .paymentFailed(_, _, _): + case .paymentFailed: break - case .paymentClaimable(_, _, _, _): + case .paymentClaimable: break } } @@ -76,22 +72,22 @@ class NotificationService: UNNotificationServiceExtension { func deliver() async { try? await LightningService.shared.stop() - if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { - //TODO: Stop LDK + if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { + // TODO: Stop LDK contentHandler(bestAttemptContent) } } func dumpLdkLogs() { - let dir = Env.ldkStorage(walletIndex: walletIndex) + let dir = Env.ldkStorage(walletIndex: self.walletIndex) let fileURL = dir.appendingPathComponent("ldk_node_latest.log") do { let text = try String(contentsOf: fileURL, encoding: .utf8) - let lines = text.components(separatedBy: "\n").map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) }) + let lines = text.components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } print("*****LDK-NODE LOG******") - lines.suffix(20).forEach { line in + for line in lines.suffix(20) { print(line) } } catch { @@ -102,7 +98,7 @@ class NotificationService: UNNotificationServiceExtension { override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. - if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { + if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } diff --git a/BitkitTests/BitkitTests.swift b/BitkitTests/BitkitTests.swift index b0cb2596..b01b9230 100644 --- a/BitkitTests/BitkitTests.swift +++ b/BitkitTests/BitkitTests.swift @@ -8,7 +8,6 @@ import XCTest final class BitkitTests: XCTestCase { - override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } @@ -31,5 +30,4 @@ final class BitkitTests: XCTestCase { // Put the code you want to measure the time of here. } } - } diff --git a/BitkitTests/KeychainTests.swift b/BitkitTests/KeychainTests.swift index 6f3d4e67..be44d210 100644 --- a/BitkitTests/KeychainTests.swift +++ b/BitkitTests/KeychainTests.swift @@ -8,7 +8,6 @@ import XCTest final class KeychainTests: XCTestCase { - override func setUpWithError() throws { try Keychain.wipeEntireKeychain() } @@ -21,29 +20,29 @@ final class KeychainTests: XCTestCase { let testMnemonic = "test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999)) test\(Int.random(in: 0...99999))" let testPassphrase = "testpasshrase\(Int.random(in: 0...99999))" - //Write + // Write try Keychain.saveString(key: .bip39Mnemonic(index: 0), str: testMnemonic) try Keychain.saveString(key: .bip39Passphrase(index: 0), str: testPassphrase) - //Read + // Read XCTAssertEqual(try Keychain.loadString(key: .bip39Mnemonic(index: 0)), testMnemonic) XCTAssertEqual(try Keychain.loadString(key: .bip39Passphrase(index: 0)), testPassphrase) - //Not allowed to overwrite existing key + // Not allowed to overwrite existing key XCTAssertThrowsError(try Keychain.saveString(key: .bip39Mnemonic(index: 0), str: testMnemonic)) XCTAssertThrowsError(try Keychain.saveString(key: .bip39Passphrase(index: 0), str: testMnemonic)) - //Test deleting + // Test deleting try Keychain.delete(key: .bip39Mnemonic(index: 0)) try Keychain.delete(key: .bip39Passphrase(index: 0)) - //Write multiple wallets + // Write multiple wallets for i in 0...5 { try Keychain.saveString(key: .bip39Mnemonic(index: i), str: "\(testMnemonic) index\(i)") try Keychain.saveString(key: .bip39Passphrase(index: i), str: "\(testPassphrase) index\(i)") } - //Check all keys are saved correctly + // Check all keys are saved correctly let listedKeys = Keychain.getAllKeyChainStorageKeys() XCTAssertEqual(listedKeys.count, 12) for i in 0...5 { @@ -51,16 +50,16 @@ final class KeychainTests: XCTestCase { XCTAssertTrue(listedKeys.contains("bip39_passphrase_\(i)")) } - //Check each value + // Check each value for i in 0...5 { XCTAssertEqual(try Keychain.loadString(key: .bip39Mnemonic(index: i)), "\(testMnemonic) index\(i)") XCTAssertEqual(try Keychain.loadString(key: .bip39Passphrase(index: i)), "\(testPassphrase) index\(i)") } - //Wipe + // Wipe try Keychain.wipeEntireKeychain() - //Check all keys are gone + // Check all keys are gone let listedKeysAfterWipe = Keychain.getAllKeyChainStorageKeys() XCTAssertEqual(listedKeysAfterWipe.count, 0) } diff --git a/BitkitTests/LdkMigration.swift b/BitkitTests/LdkMigration.swift index 104d6802..6e0da472 100644 --- a/BitkitTests/LdkMigration.swift +++ b/BitkitTests/LdkMigration.swift @@ -10,9 +10,7 @@ import XCTest final class LdkMigrationTests: XCTestCase { let walletIndex = 0 - override func setUpWithError() throws { - - } + override func setUpWithError() throws {} override func tearDownWithError() throws { dumpLdkLogs() @@ -43,14 +41,14 @@ final class LdkMigrationTests: XCTestCase { try MigrationsService.shared.ldkToLdkNode( walletIndex: 0, - seed: try Data(contentsOf: seedFile), - manager: try Data(contentsOf: managerFile), + seed: Data(contentsOf: seedFile), + manager: Data(contentsOf: managerFile), monitors: [ - try Data(contentsOf: channelFile) + Data(contentsOf: channelFile) ] ) - //TODO restore first from words + // TODO: restore first from words try await LightningService.shared.setup(walletIndex: walletIndex) try await LightningService.shared.start() @@ -69,9 +67,9 @@ final class LdkMigrationTests: XCTestCase { guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else { return } - let lines = text.components(separatedBy: "\n").map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) }) + let lines = text.components(separatedBy: "\n").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } print("*****LDK-NODE LOG******") - lines.suffix(20).forEach { line in + for line in lines.suffix(20) { print(line) } print("*****END LOG******") diff --git a/BitkitUITests/BitkitUITests.swift b/BitkitUITests/BitkitUITests.swift index 7d5e17ef..6db3ade7 100644 --- a/BitkitUITests/BitkitUITests.swift +++ b/BitkitUITests/BitkitUITests.swift @@ -8,7 +8,6 @@ import XCTest final class BitkitUITests: XCTestCase { - override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. diff --git a/BitkitUITests/BitkitUITestsLaunchTests.swift b/BitkitUITests/BitkitUITestsLaunchTests.swift index 15236f28..5256766d 100644 --- a/BitkitUITests/BitkitUITestsLaunchTests.swift +++ b/BitkitUITests/BitkitUITestsLaunchTests.swift @@ -8,7 +8,6 @@ import XCTest final class BitkitUITestsLaunchTests: XCTestCase { - override class var runsForEachTargetApplicationUIConfiguration: Bool { true }