-
-
Notifications
You must be signed in to change notification settings - Fork 494
/
dbhandler.py
3612 lines (3265 loc) · 147 KB
/
dbhandler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import logging
import os
import re
import shutil
import tempfile
from collections import defaultdict
from collections.abc import Iterator, Sequence
from contextlib import contextmanager, suppress
from pathlib import Path
from typing import Any, Literal, Optional, Unpack, cast, overload
from gevent.lock import Semaphore
from pysqlcipher3 import dbapi2 as sqlcipher
from rotkehlchen.accounting.structures.balance import BalanceType
from rotkehlchen.accounting.structures.types import ActionType
from rotkehlchen.assets.asset import Asset, AssetWithOracles, EvmToken
from rotkehlchen.assets.types import AssetType
from rotkehlchen.balances.manual import ManuallyTrackedBalance
from rotkehlchen.chain.accounts import (
BlockchainAccountData,
BlockchainAccounts,
SingleBlockchainAccountData,
)
from rotkehlchen.chain.bitcoin.hdkey import HDKey
from rotkehlchen.chain.bitcoin.xpub import (
XpubData,
XpubDerivedAddressData,
deserialize_derivation_path_for_db,
)
from rotkehlchen.chain.evm.types import NodeName, WeightedNode
from rotkehlchen.chain.substrate.types import SubstrateAddress
from rotkehlchen.chain.zksync_lite.constants import ZKSYNCLITE_TX_SAVEPREFIX
from rotkehlchen.constants import ONE, ZERO
from rotkehlchen.constants.assets import A_ETH, A_ETH2, A_USD
from rotkehlchen.constants.limits import (
FREE_ASSET_MOVEMENTS_LIMIT,
FREE_TRADES_LIMIT,
FREE_USER_NOTES_LIMIT,
)
from rotkehlchen.constants.misc import NFT_DIRECTIVE, USERDB_NAME
from rotkehlchen.constants.timing import HOUR_IN_SECONDS
from rotkehlchen.db.cache import (
AddressArgType,
DBCacheDynamic,
DBCacheStatic,
ExtraTxArgType,
LabeledLocationArgsType,
LabeledLocationIdArgsType,
)
from rotkehlchen.db.constants import (
BINANCE_MARKETS_KEY,
EVM_ACCOUNTS_DETAILS_LAST_QUERIED_TS,
EVM_ACCOUNTS_DETAILS_TOKENS,
EXTRAINTERNALTXPREFIX,
KRAKEN_ACCOUNT_TYPE_KEY,
USER_CREDENTIAL_MAPPING_KEYS,
)
from rotkehlchen.db.drivers.gevent import DBConnection, DBConnectionType, DBCursor
from rotkehlchen.db.evmtx import DBEvmTx
from rotkehlchen.db.filtering import (
AssetMovementsFilterQuery,
TradesFilterQuery,
UserNotesFilterQuery,
)
from rotkehlchen.db.loopring import DBLoopring
from rotkehlchen.db.misc import detect_sqlcipher_version
from rotkehlchen.db.schema import DB_SCRIPT_CREATE_TABLES
from rotkehlchen.db.schema_transient import DB_SCRIPT_CREATE_TRANSIENT_TABLES
from rotkehlchen.db.settings import (
DEFAULT_LAST_DATA_MIGRATION,
DEFAULT_PREMIUM_SHOULD_SYNC,
ROTKEHLCHEN_DB_VERSION,
ROTKEHLCHEN_TRANSIENT_DB_VERSION,
CachedSettings,
DBSettings,
ModifiableDBSettings,
db_settings_from_dict,
serialize_db_setting,
)
from rotkehlchen.db.upgrade_manager import DBUpgradeManager
from rotkehlchen.db.utils import (
DBAssetBalance,
DBTupleType,
LocationData,
SingleDBAssetBalance,
Tag,
combine_asset_balances,
db_tuple_to_str,
deserialize_tags_from_db,
form_query_to_filter_timestamps,
insert_tag_mappings,
is_valid_db_blockchain_account,
need_writable_cursor,
protect_password_sqlcipher,
replace_tag_mappings,
str_to_bool,
)
from rotkehlchen.errors.api import (
AuthenticationError,
IncorrectApiKeyFormat,
RotkehlchenPermissionError,
)
from rotkehlchen.errors.asset import UnknownAsset, UnsupportedAsset
from rotkehlchen.errors.misc import (
DBUpgradeError,
InputError,
SystemPermissionError,
TagConstraintError,
)
from rotkehlchen.errors.serialization import DeserializationError
from rotkehlchen.exchanges.constants import SUPPORTED_EXCHANGES
from rotkehlchen.exchanges.data_structures import AssetMovement, MarginPosition, Trade
from rotkehlchen.exchanges.kraken import KrakenAccountType
from rotkehlchen.fval import FVal
from rotkehlchen.globaldb.handler import GlobalDBHandler
from rotkehlchen.logging import RotkehlchenLogsAdapter
from rotkehlchen.premium.premium import PremiumCredentials
from rotkehlchen.serialization.deserialize import deserialize_hex_color_code, deserialize_timestamp
from rotkehlchen.types import (
EVM_CHAINS_WITH_TRANSACTIONS,
SPAM_PROTOCOL,
SUPPORTED_BITCOIN_CHAINS,
SUPPORTED_EVM_CHAINS_TYPE,
SUPPORTED_EVM_EVMLIKE_CHAINS,
SUPPORTED_EVM_EVMLIKE_CHAINS_TYPE,
SUPPORTED_EVMLIKE_CHAINS,
SUPPORTED_EVMLIKE_CHAINS_TYPE,
SUPPORTED_SUBSTRATE_CHAINS,
AnyBlockchainAddress,
ApiKey,
ApiSecret,
BTCAddress,
ChecksumEvmAddress,
ExchangeApiCredentials,
ExchangeLocationID,
ExternalService,
ExternalServiceApiCredentials,
HexColorCode,
ListOfBlockchainAddresses,
Location,
ModuleName,
SupportedBlockchain,
Timestamp,
UserNote,
)
from rotkehlchen.user_messages import MessagesAggregator
from rotkehlchen.utils.hashing import file_md5
from rotkehlchen.utils.misc import get_chunks, ts_now
from rotkehlchen.utils.serialization import rlk_jsondumps
logger = logging.getLogger(__name__)
log = RotkehlchenLogsAdapter(logger)
KDF_ITER = 64000
DBINFO_FILENAME = 'dbinfo.json'
TRANSIENT_DB_NAME = 'rotkehlchen_transient.db'
# Tuples that contain first the name of a table and then the columns that
# reference assets ids. This is used to query all assets that a user has ever owned.
TABLES_WITH_ASSETS = (
('manually_tracked_balances', 'asset'),
('trades', 'base_asset', 'quote_asset', 'fee_currency'),
('margin_positions', 'pl_currency', 'fee_currency'),
('asset_movements', 'asset', 'fee_asset'),
('timed_balances', 'currency'),
('history_events', 'asset'),
)
DB_BACKUP_RE = re.compile(r'(\d+)_rotkehlchen_db_v(\d+).backup')
# https://stackoverflow.com/questions/4814167/storing-time-series-data-relational-or-non
# http://www.sql-join.com/sql-join-types
class DBHandler:
def __init__(
self,
user_data_dir: Path,
password: str,
msg_aggregator: MessagesAggregator,
initial_settings: ModifiableDBSettings | None,
sql_vm_instructions_cb: int,
resume_from_backup: bool,
):
"""Database constructor
May raise:
- DBUpgradeError if the rotki DB version is newer than the software or
there is a DB upgrade and there is an error or if the version is older
than the one supported or if db is in a half-upgraded state and there is no backup.
- AuthenticationError if SQLCipher version problems are detected
- SystemPermissionError if the DB file's permissions are not correct
- DBSchemaError if database schema is malformed
"""
self.msg_aggregator = msg_aggregator
self.user_data_dir = user_data_dir
self.sql_vm_instructions_cb = sql_vm_instructions_cb
self.sqlcipher_version = detect_sqlcipher_version()
self.setting_to_default_type = {
'version': (int, ROTKEHLCHEN_DB_VERSION),
'last_write_ts': (int, Timestamp(0)),
'premium_should_sync': (str_to_bool, DEFAULT_PREMIUM_SHOULD_SYNC),
'main_currency': (lambda x: Asset(x).resolve(), A_USD.resolve_to_fiat_asset()),
'ongoing_upgrade_from_version': (int, None),
'last_data_migration': (int, DEFAULT_LAST_DATA_MIGRATION),
'non_syncing_exchanges': (lambda data: [ExchangeLocationID.deserialize(x) for x in json.loads(data)], []), # noqa: E501
'beacon_rpc_endpoint': (str, None),
}
self.conn: DBConnection = None # type: ignore
self.conn_transient: DBConnection = None # type: ignore
# Lock to make sure that 2 callers of get_or_create_evm_token do not go in at the same time
self.get_or_create_evm_token_lock = Semaphore()
self.password = password
self._connect()
self._check_unfinished_upgrades(resume_from_backup=resume_from_backup)
self._run_actions_after_first_connection()
with self.user_write() as cursor:
if initial_settings is not None:
self.set_settings(cursor, initial_settings)
self.update_owned_assets_in_globaldb(cursor)
self.sync_globaldb_assets(cursor)
def _check_unfinished_upgrades(self, resume_from_backup: bool) -> None:
"""
Checks the database whether there are any not finished upgrades and automatically uses a
backup if there are any. If no backup found, throws an error to the user
"""
with self.conn.read_ctx() as cursor:
try:
ongoing_upgrade_from_version = self.get_setting(
cursor=cursor,
name='ongoing_upgrade_from_version',
)
except sqlcipher.OperationalError: # pylint: disable=no-member
return # fresh database. Nothing to upgrade.
if ongoing_upgrade_from_version is None:
return # We are all good
# if there is an unfinished upgrade, check user approval to resume from backup
if resume_from_backup is False:
raise RotkehlchenPermissionError(
error_message=(
'The encrypted database is in a semi upgraded state. '
'Either resume from a backup or solve the issue manually.'
),
payload=None,
)
# If resume_from_backup is True, the user gave approval.
# Replace the db with a backup and reconnect
self.disconnect()
backup_postfix = f'rotkehlchen_db_v{ongoing_upgrade_from_version}.backup'
found_backups = list(filter(
lambda x: x[-len(backup_postfix):] == backup_postfix,
os.listdir(self.user_data_dir),
))
if len(found_backups) == 0:
raise DBUpgradeError(
f'Your encrypted database is in a half-upgraded state at '
f'v{ongoing_upgrade_from_version} and there was no backup '
'found. Please open an issue on our github or contact us in our discord server.',
)
backup_to_use = sorted(found_backups)[-1] # Use latest backup
shutil.copyfile(
self.user_data_dir / backup_to_use,
self.user_data_dir / USERDB_NAME,
)
self.msg_aggregator.add_warning(
f'Your encrypted database was in a half-upgraded state. '
f'Trying to login with a backup {backup_to_use}',
)
self._connect()
def logout(self) -> None:
self.password = ''
if self.conn is not None:
self.disconnect(conn_attribute='conn')
if self.conn_transient is not None:
self.disconnect(conn_attribute='conn_transient')
try:
dbinfo = {'sqlcipher_version': self.sqlcipher_version, 'md5_hash': self.get_md5hash()}
except (SystemPermissionError, FileNotFoundError) as e:
# If there is problems opening the DB at destruction just log and exit
log.error(f'At DB teardown could not open the DB: {e!s}')
return
Path(self.user_data_dir / DBINFO_FILENAME).write_text(rlk_jsondumps(dbinfo), encoding='utf8') # noqa: E501
def _check_settings(self) -> None:
"""Check that the non_syncing_exchanges setting only has active locations"""
with self.conn.read_ctx() as cursor:
non_syncing_exchanges = self.get_setting(
cursor=cursor,
name='non_syncing_exchanges',
)
valid_locations = [
exchange_location_id
for exchange_location_id in non_syncing_exchanges
if exchange_location_id.location in SUPPORTED_EXCHANGES
]
if len(valid_locations) != len(non_syncing_exchanges):
with self.user_write() as write_cursor:
self.set_setting(
write_cursor=write_cursor,
name='non_syncing_exchanges',
value=serialize_db_setting(
value=valid_locations,
setting='non_syncing_exchanges',
is_modifiable=True,
),
)
def _run_actions_after_first_connection(self) -> None:
"""Perform the actions that are needed after the first DB connection
Such as:
- DB Upgrades
- Create tables that are missing for new version
- sanity checks
May raise:
- AuthenticationError if a wrong password is given or if the DB is corrupt
- DBUpgradeError if there is a problem with DB upgrading or if the version
is older than the one supported.
- DBSchemaError if database schema is malformed.
"""
# Run upgrades if needed -- only for user DB
fresh_db = DBUpgradeManager(self).run_upgrades()
if fresh_db: # create tables during the first run and add the DB version
self.conn.executescript(DB_SCRIPT_CREATE_TABLES)
cursor = self.conn.cursor()
cursor.execute(
'INSERT OR REPLACE INTO settings(name, value) VALUES(?, ?)',
('version', str(ROTKEHLCHEN_DB_VERSION)),
)
# run checks on the database
self.conn.schema_sanity_check()
self._check_settings()
# This logic executes only for the transient db
self._connect(conn_attribute='conn_transient')
transient_version = 0
cursor = self.conn_transient.cursor()
with suppress(sqlcipher.DatabaseError): # pylint: disable=no-member # not created yet
result = cursor.execute('SELECT value FROM settings WHERE name=?', ('version',)).fetchone() # noqa: E501
if result is not None:
transient_version = int(result[0])
if transient_version != ROTKEHLCHEN_TRANSIENT_DB_VERSION:
# "upgrade" transient DB
tables = list(cursor.execute('select name from sqlite_master where type is "table"'))
cursor.executescript('PRAGMA foreign_keys = OFF;')
cursor.executescript(';'.join([f'DROP TABLE IF EXISTS {name[0]}' for name in tables]))
cursor.executescript('PRAGMA foreign_keys = ON;')
self.conn_transient.executescript(DB_SCRIPT_CREATE_TRANSIENT_TABLES)
cursor.execute(
'INSERT OR IGNORE INTO settings(name, value) VALUES(?, ?)',
('version', str(ROTKEHLCHEN_TRANSIENT_DB_VERSION)),
)
self.conn_transient.commit()
def get_md5hash(self, transient: bool = False) -> str:
"""Get the md5hash of the DB
May raise:
- SystemPermissionError if there are permission errors when accessing the DB
"""
assert self.conn is None, 'md5hash should be taken only with a closed DB'
if transient: # type: ignore
return file_md5(self.user_data_dir / TRANSIENT_DB_NAME)
return file_md5(self.user_data_dir / USERDB_NAME)
@overload
def get_setting(self, cursor: 'DBCursor', name: Literal['version']) -> int:
...
@overload
def get_setting(self, cursor: 'DBCursor', name: Literal['last_write_ts']) -> Timestamp:
...
@overload
def get_setting(self, cursor: 'DBCursor', name: Literal['premium_should_sync']) -> bool:
...
@overload
def get_setting(self, cursor: 'DBCursor', name: Literal['main_currency']) -> AssetWithOracles:
...
@overload
def get_setting(self, cursor: 'DBCursor', name: Literal['ongoing_upgrade_from_version']) -> int | None: # noqa: E501
...
@overload
def get_setting(self, cursor: 'DBCursor', name: Literal['last_data_migration']) -> int | None:
...
@overload
def get_setting(self, cursor: 'DBCursor', name: Literal['non_syncing_exchanges']) -> list['ExchangeLocationID']: # noqa: E501
...
@overload
def get_setting(self, cursor: 'DBCursor', name: Literal['beacon_rpc_endpoint']) -> str:
...
def get_setting(
self,
cursor: 'DBCursor',
name: Literal[
'version',
'last_write_ts',
'premium_should_sync',
'main_currency',
'ongoing_upgrade_from_version',
'last_data_migration',
'non_syncing_exchanges',
'beacon_rpc_endpoint',
],
) -> int | None | (Timestamp | (bool | AssetWithOracles)) | list['ExchangeLocationID'] | str:
deserializer, default_value = self.setting_to_default_type[name]
cursor.execute(
'SELECT value FROM settings WHERE name=?;', (name,),
)
result = cursor.fetchone()
if result is not None:
return deserializer(result[0]) # type: ignore
return default_value # type: ignore
def set_setting(
self,
write_cursor: 'DBCursor',
name: Literal[
'version',
'last_write_ts',
'premium_should_sync',
'ongoing_upgrade_from_version',
'main_currency',
'non_syncing_exchanges',
],
value: int | (Timestamp | Asset) | str,
) -> None:
write_cursor.execute(
'INSERT OR REPLACE INTO settings(name, value) VALUES(?, ?)',
(name, str(value)),
)
CachedSettings().update_entry(name, value)
def _connect(self, conn_attribute: Literal['conn', 'conn_transient'] = 'conn') -> None:
"""Connect to the DB using password
May raise:
- SystemPermissionError if we are unable to open the DB file,
probably due to permission errors
- AuthenticationError if the given password is not the right one for the DB
"""
if conn_attribute == 'conn':
fullpath = self.user_data_dir / USERDB_NAME
connection_type = DBConnectionType.USER
else:
fullpath = self.user_data_dir / TRANSIENT_DB_NAME
connection_type = DBConnectionType.TRANSIENT
try:
conn = DBConnection(
path=str(fullpath),
connection_type=connection_type,
sql_vm_instructions_cb=self.sql_vm_instructions_cb,
)
except sqlcipher.OperationalError as e: # pylint: disable=no-member
raise SystemPermissionError(
f'Could not open database file: {fullpath}. Permission errors?',
) from e
password_for_sqlcipher = protect_password_sqlcipher(self.password)
script = f'PRAGMA key="{password_for_sqlcipher}";'
if self.sqlcipher_version == 3:
script += f'PRAGMA kdf_iter={KDF_ITER};'
try:
conn.executescript(script)
conn.execute('PRAGMA foreign_keys=ON')
# Optimizations for the combined trades view
# the following will fail with DatabaseError in case of wrong password.
# If this goes away at any point it needs to be replaced by something
# that checks the password is correct at this same point in the code
conn.execute('PRAGMA cache_size = -32768')
# switch to WAL mode: https://www.sqlite.org/wal.html
conn.execute('PRAGMA journal_mode=WAL;')
except sqlcipher.DatabaseError as e: # pylint: disable=no-member
raise AuthenticationError(
'Wrong password or invalid/corrupt database for user',
) from e
setattr(self, conn_attribute, conn)
def _change_password(
self,
new_password: str,
conn_attribute: Literal['conn', 'conn_transient'],
) -> bool:
conn = getattr(self, conn_attribute, None)
if conn is None:
log.error(
f'Attempted to change password for {conn_attribute} '
f'database but no such DB connection exists',
)
return False
new_password_for_sqlcipher = protect_password_sqlcipher(new_password)
script = f'PRAGMA rekey="{new_password_for_sqlcipher}";'
if self.sqlcipher_version == 3:
script += f'PRAGMA kdf_iter={KDF_ITER};'
try:
conn.executescript(script)
except sqlcipher.OperationalError as e: # pylint: disable=no-member
log.error(
f'At change password could not re-key the open {conn_attribute} '
f'database: {e!s}',
)
return False
return True
def change_password(self, new_password: str) -> bool:
"""Changes the password for the currently logged in user"""
result = (
self._change_password(new_password, 'conn') and
self._change_password(new_password, 'conn_transient')
)
if result is True:
self.password = new_password
return result
def disconnect(self, conn_attribute: Literal['conn', 'conn_transient'] = 'conn') -> None:
conn = getattr(self, conn_attribute, None)
if conn:
conn.close()
setattr(self, conn_attribute, None)
def export_unencrypted(self, temppath: Path) -> None:
"""Export the unencrypted DB to the temppath as plaintext DB
The critical section is absolutely needed as a context switch
from inside this execute script can result in:
1. coming into this code again from another greenlet which can result
to DB plaintext already in use
2. Having a DB transaction open between the attach and detach and not
closed when we detach which will result in DB plaintext locked.
"""
with self.conn.critical_section():
# flush the wal file to have up to date information when exporting data
self.conn.execute('PRAGMA wal_checkpoint;')
self.conn.executescript(
f'ATTACH DATABASE "{temppath}" AS plaintext KEY "";'
'SELECT sqlcipher_export("plaintext");'
'DETACH DATABASE plaintext;',
)
def import_unencrypted(self, unencrypted_db_data: bytes) -> None:
"""Imports an unencrypted DB from raw data
May raise:
- DBUpgradeError if the rotki DB version is newer than the software or
there is a DB upgrade and there is an error or if the version is older
than the one supported.
- AuthenticationError if the wrong password is given
"""
self.conn.execute('PRAGMA wal_checkpoint;')
self.disconnect()
rdbpath = self.user_data_dir / USERDB_NAME
# Make copy of existing encrypted DB before removing it
shutil.copy2(
rdbpath,
self.user_data_dir / 'rotkehlchen_temp_backup.db',
)
rdbpath.unlink()
# dump the unencrypted data into a temporary file
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname: # needed on windows, see https://tinyurl.com/tmp-win-err # noqa: E501
tempdbpath = Path(tmpdirname) / 'temp.db'
tempdbpath.write_bytes(unencrypted_db_data)
# Now attach to the unencrypted DB and copy it to our DB and encrypt it
self.conn = DBConnection(
path=tempdbpath,
connection_type=DBConnectionType.USER,
sql_vm_instructions_cb=self.sql_vm_instructions_cb,
)
password_for_sqlcipher = protect_password_sqlcipher(self.password)
script = f'ATTACH DATABASE "{rdbpath}" AS encrypted KEY "{password_for_sqlcipher}";'
if self.sqlcipher_version == 3:
script += f'PRAGMA encrypted.kdf_iter={KDF_ITER};'
script += 'SELECT sqlcipher_export("encrypted");DETACH DATABASE encrypted;'
self.conn.executescript(script)
self.disconnect()
try:
self._connect()
except SystemPermissionError as e:
raise AssertionError(
f'Permission error when reopening the DB. {e!s}. Should never happen here',
) from e
self._run_actions_after_first_connection()
# all went okay, remove the original temp backup
(self.user_data_dir / 'rotkehlchen_temp_backup.db').unlink()
@contextmanager
def user_write(self) -> Iterator[DBCursor]:
"""Get a write context for the user db and after write is finished
also update the last write timestamp
"""
# TODO: Rethink this
with self.conn.write_ctx(commit_ts=True) as cursor:
yield cursor
@contextmanager
def transient_write(self) -> Iterator[DBCursor]:
"""Get a write context for the transient user db and after write is finished
also commit
"""
with self.conn_transient.write_ctx() as cursor:
yield cursor
def get_settings(self, cursor: 'DBCursor', have_premium: bool = False) -> DBSettings:
"""Aggregates settings from DB and from the given args and returns the settings object"""
cursor.execute('SELECT name, value FROM settings;')
settings_dict = {}
for q in cursor:
settings_dict[q[0]] = q[1]
# Also add the non-DB saved settings
settings_dict['have_premium'] = have_premium
return db_settings_from_dict(settings_dict, self.msg_aggregator)
def set_settings(self, write_cursor: 'DBCursor', settings: ModifiableDBSettings) -> None:
settings_dict = settings.serialize()
write_cursor.executemany(
'INSERT OR REPLACE INTO settings(name, value) VALUES(?, ?)',
list(settings_dict.items()),
)
CachedSettings().update_entries(settings)
def get_cache_for_api(self, cursor: 'DBCursor') -> dict[str, int]:
"""Returns a few key-value pairs that are used in the API
from the `key_value_cache` table of the DB. Defaults to `Timestamp(0)` if not found"""
cursor.execute(
'SELECT name, value FROM key_value_cache WHERE name IN (?,?);',
(DBCacheStatic.LAST_DATA_UPLOAD_TS.value, DBCacheStatic.LAST_BALANCE_SAVE.value),
)
db_cache = {name: int(value) for name, value in cursor}
return { # Return with default value, if needed
DBCacheStatic.LAST_BALANCE_SAVE.value: db_cache.get(DBCacheStatic.LAST_BALANCE_SAVE.value, 0), # noqa: E501
DBCacheStatic.LAST_DATA_UPLOAD_TS.value: db_cache.get(DBCacheStatic.LAST_DATA_UPLOAD_TS.value, 0), # noqa: E501
}
def get_static_cache(
self,
cursor: 'DBCursor',
name: DBCacheStatic,
) -> Timestamp | None:
"""Returns the cache value from the `key_value_cache` table of the DB
according to the given `name`. Defaults to `None` if not found"""
value = cursor.execute(
'SELECT value FROM key_value_cache WHERE name=?;', (name.value,),
).fetchone()
return None if value is None else Timestamp(int(value[0]))
def set_static_cache(
self,
write_cursor: 'DBCursor',
name: DBCacheStatic,
value: Timestamp,
) -> None:
"""Save the name-value pair of the cache with constant name
to the `key_value_cache` table of the DB"""
write_cursor.execute(
'INSERT OR REPLACE INTO key_value_cache(name, value) VALUES(?, ?)',
(name.value, value),
)
@overload
def get_dynamic_cache(
self,
cursor: 'DBCursor',
name: Literal[DBCacheDynamic.LAST_CRYPTOTX_OFFSET],
**kwargs: Unpack[LabeledLocationArgsType],
) -> int | None:
...
@overload
def get_dynamic_cache(
self,
cursor: 'DBCursor',
name: Literal[DBCacheDynamic.LAST_QUERY_TS],
**kwargs: Unpack[LabeledLocationIdArgsType],
) -> Timestamp | None:
...
@overload
def get_dynamic_cache(
self,
cursor: 'DBCursor',
name: Literal[DBCacheDynamic.LAST_QUERY_ID],
**kwargs: Unpack[LabeledLocationIdArgsType],
) -> str | None:
...
@overload
def get_dynamic_cache(
self,
cursor: 'DBCursor',
name: Literal[DBCacheDynamic.WITHDRAWALS_TS],
**kwargs: Unpack[AddressArgType],
) -> Timestamp | None:
...
@overload
def get_dynamic_cache(
self,
cursor: 'DBCursor',
name: Literal[DBCacheDynamic.WITHDRAWALS_IDX],
**kwargs: Unpack[AddressArgType],
) -> int | None:
...
@overload
def get_dynamic_cache(
self,
cursor: 'DBCursor',
name: Literal[DBCacheDynamic.EXTRA_INTERNAL_TX],
**kwargs: Unpack[ExtraTxArgType],
) -> ChecksumEvmAddress | None:
...
def get_dynamic_cache(
self,
cursor: 'DBCursor',
name: DBCacheDynamic,
**kwargs: str,
) -> int | Timestamp | str | ChecksumEvmAddress | None:
"""Returns the cache value from the `key_value_cache` table of the DB
according to the given `name` and `kwargs`. Defaults to `None` if not found."""
value = cursor.execute(
'SELECT value FROM key_value_cache WHERE name=?;', (name.get_db_key(**kwargs),),
).fetchone()
return None if value is None else name.deserialize_callback(value[0])
@overload
def set_dynamic_cache(
self,
write_cursor: 'DBCursor',
name: Literal[DBCacheDynamic.LAST_CRYPTOTX_OFFSET],
value: int,
**kwargs: Unpack[LabeledLocationArgsType],
) -> None:
...
@overload
def set_dynamic_cache(
self,
write_cursor: 'DBCursor',
name: Literal[DBCacheDynamic.LAST_QUERY_TS],
value: Timestamp,
**kwargs: Unpack[LabeledLocationIdArgsType],
) -> None:
...
@overload
def set_dynamic_cache(
self,
write_cursor: 'DBCursor',
name: Literal[DBCacheDynamic.LAST_QUERY_ID],
value: int,
**kwargs: Unpack[LabeledLocationIdArgsType],
) -> None:
...
@overload
def set_dynamic_cache(
self,
write_cursor: 'DBCursor',
name: Literal[DBCacheDynamic.WITHDRAWALS_TS],
value: Timestamp,
**kwargs: Unpack[AddressArgType],
) -> None:
...
@overload
def set_dynamic_cache(
self,
write_cursor: 'DBCursor',
name: Literal[DBCacheDynamic.WITHDRAWALS_IDX],
value: int,
**kwargs: Unpack[AddressArgType],
) -> None:
...
@overload
def set_dynamic_cache(
self,
write_cursor: 'DBCursor',
name: Literal[DBCacheDynamic.EXTRA_INTERNAL_TX],
value: ChecksumEvmAddress,
**kwargs: Unpack[ExtraTxArgType],
) -> None:
...
def set_dynamic_cache(
self,
write_cursor: 'DBCursor',
name: DBCacheDynamic,
value: int | Timestamp | ChecksumEvmAddress,
**kwargs: str,
) -> None:
"""Save the name-value pair of the cache with variable name to the `key_value_cache` table.""" # noqa: E501
write_cursor.execute(
'INSERT OR REPLACE INTO key_value_cache(name, value) VALUES(?, ?)',
(name.get_db_key(**kwargs), value),
)
@need_writable_cursor('user_write')
def add_external_service_credentials(
self,
write_cursor: 'DBCursor',
credentials: list[ExternalServiceApiCredentials],
) -> None:
write_cursor.executemany(
'INSERT OR REPLACE INTO external_service_credentials(name, api_key, api_secret) VALUES(?, ?, ?)', # noqa: E501
[c.serialize_for_db() for c in credentials],
)
def delete_external_service_credentials(self, services: list[ExternalService]) -> None:
with self.user_write() as cursor:
cursor.executemany(
'DELETE FROM external_service_credentials WHERE name=?;',
[(service.name.lower(),) for service in services],
)
def get_all_external_service_credentials(self) -> list[ExternalServiceApiCredentials]:
"""Returns a list with all the external service credentials saved in the DB"""
with self.conn.read_ctx() as cursor:
cursor.execute('SELECT name, api_key, api_secret from external_service_credentials;')
result = []
for q in cursor:
try:
service = ExternalService.deserialize(q[0])
except DeserializationError:
log.error(f'Unknown external service name "{q[0]}" found in the DB')
continue
result.append(ExternalServiceApiCredentials(
service=service,
api_key=q[1],
api_secret=q[2],
))
return result
def get_external_service_credentials(
self,
service_name: ExternalService,
) -> ExternalServiceApiCredentials | None:
"""If existing it returns the external service credentials for the given service"""
with self.conn.read_ctx() as cursor:
cursor.execute(
'SELECT api_key, api_secret from external_service_credentials WHERE name=?;',
(service_name.name.lower(),),
)
if (result := cursor.fetchone()) is None:
return None
# There can only be 1 result, since name is the primary key of the table
return ExternalServiceApiCredentials(service=service_name, api_key=result[0], api_secret=result[1]) # noqa: E501
@need_writable_cursor('user_write')
def add_to_ignored_assets(self, write_cursor: 'DBCursor', asset: Asset) -> None:
"""Add a new asset to the set of ignored assets. If the asset was already marked as
ignored then we don't do anything.
"""
write_cursor.execute(
'INSERT OR IGNORE INTO multisettings(name, value) VALUES(?, ?)',
('ignored_asset', asset.identifier),
)
def ignore_multiple_assets(self, write_cursor: 'DBCursor', assets: list[str]) -> None:
"""Add the provided identifiers to the list of ignored assets. If any asset was already
marked as ignored then we don't do anything.
"""
write_cursor.executemany(
'INSERT OR IGNORE INTO multisettings(name, value) VALUES(?, ?)',
[('ignored_asset', asset_identifier) for asset_identifier in assets],
)
def remove_from_ignored_assets(self, write_cursor: 'DBCursor', asset: Asset) -> None:
write_cursor.execute(
'DELETE FROM multisettings WHERE name="ignored_asset" AND value=?;',
(asset.identifier,),
)
@staticmethod
def _get_ignored_asset_ids(cursor: 'DBCursor', only_nfts: bool = False) -> None:
"""Executes a DB query to get the ignored asset identifiers. Modifies the cursor"""
bindings = []
query = 'SELECT value FROM multisettings WHERE name="ignored_asset" '
if only_nfts is True:
query += 'AND value LIKE ?'
bindings.append(f'{NFT_DIRECTIVE}%')
cursor.execute(query, bindings)
def get_ignored_asset_ids(self, cursor: 'DBCursor', only_nfts: bool = False) -> set[str]:
"""Gets the ignored asset ids without converting each one of them to an asset object
We used to have a heavier version which converted them to an asset but removed
it due to unnecessary roundtrips to the global DB for each asset initialization
"""
self._get_ignored_asset_ids(cursor, only_nfts)
return {x[0] for x in cursor}
def add_to_ignored_action_ids(
self,
write_cursor: 'DBCursor',
action_type: ActionType,
identifiers: list[str],
) -> None:
"""Adds a list of identifiers to be ignored for a given action type
Raises InputError in case of adding already existing ignored action
"""
tuples = [(action_type.serialize_for_db(), x) for x in identifiers]
try:
write_cursor.executemany(
'INSERT INTO ignored_actions(type, identifier) VALUES(?, ?)',
tuples,
)
except sqlcipher.IntegrityError as e: # pylint: disable=no-member
raise InputError('One of the given action ids already exists in the database') from e
def remove_from_ignored_action_ids(
self,
write_cursor: 'DBCursor',
action_type: ActionType,
identifiers: list[str],
) -> None:
"""Removes a list of identifiers to be ignored for a given action type
Raises InputError in case of removing an action that is not in the DB
"""
tuples = [(action_type.serialize_for_db(), x) for x in identifiers]
write_cursor.executemany(
'DELETE FROM ignored_actions WHERE type=? AND identifier=?;',
tuples,
)
affected_rows = write_cursor.rowcount
if affected_rows != len(identifiers):
raise InputError(
f'Tried to remove {len(identifiers) - affected_rows} '
f'ignored actions that do not exist',
)
def get_ignored_action_ids(
self,
cursor: 'DBCursor',
action_type: ActionType | None,
) -> dict[ActionType, set[str]]:
query = 'SELECT type, identifier from ignored_actions'
tuples: tuple
if action_type is None:
query += ';'
tuples = ()
else:
query += ' WHERE type=?;'
tuples = (action_type.serialize_for_db(),)
cursor.execute(query, tuples)
mapping = defaultdict(set)
for entry in cursor:
mapping[ActionType.deserialize_from_db(entry[0])].add(entry[1])
return mapping
def add_multiple_balances(self, write_cursor: 'DBCursor', balances: list[DBAssetBalance]) -> None: # noqa: E501
"""Execute addition of multiple balances in the DB"""
serialized_balances = [balance.serialize_for_db() for balance in balances]
try:
write_cursor.executemany(
'INSERT INTO timed_balances(category, timestamp, currency, amount, usd_value) '
'VALUES(?, ?, ?, ?, ?)',
serialized_balances,
)
except sqlcipher.IntegrityError as e: # pylint: disable=no-member
raise InputError(
'Adding timed_balance failed. Either unknown asset identifier '
'or an entry for the given timestamp already exists',
) from e
def delete_eth2_daily_stats(self, write_cursor: 'DBCursor') -> None: