@@ -253,15 +253,47 @@ private class BDKService {
253253 self . wallet = wallet
254254 }
255255
256- private func loadWallet( descriptor: Descriptor , changeDescriptor: Descriptor ) throws {
257- let persister = try Persister . loadConnection ( )
258- self . persister = persister
259- let wallet = try Wallet . load (
260- descriptor: descriptor,
261- changeDescriptor: changeDescriptor,
262- persister: persister
263- )
264- self . wallet = wallet
256+ private func loadWallet( descriptor: Descriptor , changeDescriptor:
257+ Descriptor ) throws {
258+ // If database doesn't exist, create it from the descriptors
259+ if !FileManager. default. fileExists ( atPath:
260+ URL . persistenceBackendPath) {
261+ let persister = try Persister . createConnection ( )
262+ self . persister = persister
263+ let wallet = try Wallet (
264+ descriptor: descriptor,
265+ changeDescriptor: changeDescriptor,
266+ network: self . network,
267+ persister: persister
268+ )
269+ self . wallet = wallet
270+ } else {
271+ // Database exists, try to load the wallet
272+ do {
273+ let persister = try Persister . loadConnection ( )
274+ self . persister = persister
275+ let wallet = try Wallet . load (
276+ descriptor: descriptor,
277+ changeDescriptor: changeDescriptor,
278+ persister: persister
279+ )
280+ self . wallet = wallet
281+ } catch is LoadWithPersistError {
282+ // Database is corrupted or incompatible, delete and recreate
283+ print ( " Wallet database is corrupted, recreating... " )
284+ try Persister . deleteConnection ( )
285+
286+ let persister = try Persister . createConnection ( )
287+ self . persister = persister
288+ let wallet = try Wallet (
289+ descriptor: descriptor,
290+ changeDescriptor: changeDescriptor,
291+ network: self . network,
292+ persister: persister
293+ )
294+ self . wallet = wallet
295+ }
296+ }
265297 }
266298
267299 func loadWalletFromBackup( ) throws {
0 commit comments