From 64cd816a8290ccc65648a112ba87c533a7a76636 Mon Sep 17 00:00:00 2001 From: ThomasV Date: Fri, 23 Jun 2023 15:20:46 +0200 Subject: [PATCH] json_db: recover corrupt db from incomplete file appends --- electrum/json_db.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/electrum/json_db.py b/electrum/json_db.py index 11b30e341..16e82a620 100644 --- a/electrum/json_db.py +++ b/electrum/json_db.py @@ -238,6 +238,8 @@ class JsonDB(Logger): except Exception: if r := self.maybe_load_ast_data(s): data, patches = r, [] + elif r := self.maybe_load_incomplete_data(s): + data, patches = r, [] else: raise WalletFileException("Cannot read wallet file. (parsing failed)") if not isinstance(data, dict): @@ -269,6 +271,21 @@ class JsonDB(Logger): data[key] = value return data + def maybe_load_incomplete_data(self, s): + n = s.count('{') - s.count('}') + i = len(s) + while n > 0 and i > 0: + i = i - 1 + if s[i] == '{': + n = n - 1 + if s[i] == '}': + n = n + 1 + if n == 0: + s = s[0:i] + assert s[-2:] == ',\n' + self.logger.info('found incomplete data {s[i:]}') + return self.load_data(s[0:-2]) + def set_modified(self, b): with self.lock: self._modified = b