@@ -256,18 +256,51 @@ private class BDKService {
256256 private func loadWallet( descriptor: Descriptor , changeDescriptor: Descriptor ) throws {
257257 let documentsDirectoryURL = URL . documentsDirectory
258258 let walletDataDirectoryURL = documentsDirectoryURL. appendingPathComponent ( " wallet_data " )
259- try FileManager . default. ensureDirectoryExists ( at: walletDataDirectoryURL)
260- try FileManager . default. removeOldFlatFileIfNeeded ( at: documentsDirectoryURL)
261259 let persistenceBackendPath = walletDataDirectoryURL. appendingPathComponent ( " wallet.sqlite " )
262260 . path
263- let connection = try Connection ( path: persistenceBackendPath)
264- self . connection = connection
265- let wallet = try Wallet . load (
266- descriptor: descriptor,
267- changeDescriptor: changeDescriptor,
268- connection: connection
269- )
270- self . wallet = wallet
261+
262+ // Ensure the directory exists, but don't delete it
263+ try FileManager . default. ensureDirectoryExists ( at: walletDataDirectoryURL)
264+ try FileManager . default. removeOldFlatFileIfNeeded ( at: documentsDirectoryURL)
265+
266+ // If database doesn't exist, create it from the descriptors
267+ if !FileManager. default. fileExists ( atPath: persistenceBackendPath) {
268+ let connection = try Connection ( path: persistenceBackendPath)
269+ self . connection = connection
270+ let wallet = try Wallet (
271+ descriptor: descriptor,
272+ changeDescriptor: changeDescriptor,
273+ network: self . network,
274+ connection: connection
275+ )
276+ self . wallet = wallet
277+ } else {
278+ // Database exists, try to load the wallet
279+ do {
280+ let connection = try Connection ( path: persistenceBackendPath)
281+ self . connection = connection
282+ let wallet = try Wallet . load (
283+ descriptor: descriptor,
284+ changeDescriptor: changeDescriptor,
285+ connection: connection
286+ )
287+ self . wallet = wallet
288+ } catch is LoadWithPersistError {
289+ // Database is corrupted or incompatible, delete and recreate
290+ print ( " Wallet database is corrupted, recreating... " )
291+ try FileManager . default. removeItem ( atPath: persistenceBackendPath)
292+
293+ let connection = try Connection ( path: persistenceBackendPath)
294+ self . connection = connection
295+ let wallet = try Wallet (
296+ descriptor: descriptor,
297+ changeDescriptor: changeDescriptor,
298+ network: self . network,
299+ connection: connection
300+ )
301+ self . wallet = wallet
302+ }
303+ }
271304 }
272305
273306 func loadWalletFromBackup( ) throws {
0 commit comments