1
0

Separate WalletDB from storage upgrades.

Make sure that WalletDB.data is always a StoredDict.
Perform db upgrades in a separate class, since they
operate on a dict object.
This commit is contained in:
ThomasV
2023-08-18 15:13:33 +02:00
parent af2b0f758d
commit b5bc5ff9ed
10 changed files with 159 additions and 146 deletions

View File

@@ -34,8 +34,6 @@ from .logging import Logger
if TYPE_CHECKING:
from .storage import WalletStorage
JsonDBJsonEncoder = util.MyEncoder
def modifier(func):
def wrapper(self, *args, **kwargs):
with self.lock:
@@ -168,24 +166,28 @@ class StoredDict(dict):
class JsonDB(Logger):
def __init__(self, data, storage=None):
def __init__(self, s: str, storage=None, encoder=None):
Logger.__init__(self)
self.lock = threading.RLock()
self.storage = storage
self.encoder = encoder
self._modified = False
# load data
if data:
self.load_data(data)
else:
self.data = {}
data = self.load_data(s)
# convert to StoredDict
self.data = StoredDict(data, self, [])
def load_data(self, s):
def load_data(self, s:str) -> dict:
""" overloaded in wallet_db """
if s == '':
return {}
try:
self.data = json.loads(s)
data = json.loads(s)
except Exception:
raise WalletFileException("Cannot read wallet file. (parsing failed)")
if not isinstance(self.data, dict):
if not isinstance(data, dict):
raise WalletFileException("Malformed wallet file (not dict)")
return data
def set_modified(self, b):
with self.lock:
@@ -204,8 +206,8 @@ class JsonDB(Logger):
@modifier
def put(self, key, value):
try:
json.dumps(key, cls=JsonDBJsonEncoder)
json.dumps(value, cls=JsonDBJsonEncoder)
json.dumps(key, cls=self.encoder)
json.dumps(value, cls=self.encoder)
except Exception:
self.logger.info(f"json error: cannot save {repr(key)} ({repr(value)})")
return False
@@ -235,7 +237,7 @@ class JsonDB(Logger):
self.data,
indent=4 if human_readable else None,
sort_keys=bool(human_readable),
cls=JsonDBJsonEncoder,
cls=self.encoder,
)
def _should_convert_to_stored_dict(self, key) -> bool: