-
-
Notifications
You must be signed in to change notification settings - Fork 575
/
Copy pathrest.py
5135 lines (4607 loc) · 211 KB
/
rest.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 datetime
import json
import logging
import os
import sys
import tempfile
import traceback
from collections import defaultdict
from collections.abc import Callable, Sequence
from http import HTTPStatus
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Optional, get_args, overload
from zipfile import BadZipFile, ZipFile
import gevent
from flask import Response, make_response, send_file
from gevent.event import Event
from gevent.lock import Semaphore
from marshmallow.exceptions import ValidationError
from pysqlcipher3 import dbapi2 as sqlcipher
from web3.exceptions import BadFunctionCallOutput
from werkzeug.datastructures import FileStorage
from rotkehlchen.accounting.constants import (
ACCOUNTING_EVENTS_ICONS,
EVENT_CATEGORY_DETAILS,
EVENT_CATEGORY_MAPPINGS,
FREE_PNL_EVENTS_LIMIT,
FREE_REPORTS_LOOKUP_LIMIT,
)
from rotkehlchen.accounting.debugimporter.json import DebugHistoryImporter
from rotkehlchen.accounting.entry_type_mappings import ENTRY_TYPE_MAPPINGS
from rotkehlchen.accounting.export.csv import (
FILENAME_HISTORY_EVENTS_CSV,
FILENAME_SKIPPED_EXTERNAL_EVENTS_CSV,
CSVWriteError,
dict_to_csv_file,
)
from rotkehlchen.accounting.pot import AccountingPot
from rotkehlchen.accounting.structures.balance import Balance, BalanceType
from rotkehlchen.accounting.structures.processed_event import AccountingEventExportType
from rotkehlchen.accounting.structures.types import ActionType
from rotkehlchen.api.v1.schemas import TradeSchema
from rotkehlchen.api.v1.types import IncludeExcludeFilterData
from rotkehlchen.assets.asset import (
Asset,
AssetWithNameAndType,
AssetWithOracles,
CustomAsset,
EvmToken,
FiatAsset,
)
from rotkehlchen.assets.resolver import AssetResolver
from rotkehlchen.assets.types import ASSET_TYPES_EXCLUDED_FOR_USERS, AssetType
from rotkehlchen.balances.manual import (
ManuallyTrackedBalance,
add_manually_tracked_balances,
edit_manually_tracked_balances,
get_manually_tracked_balances,
remove_manually_tracked_balances,
)
from rotkehlchen.chain.accounts import SingleBlockchainAccountData
from rotkehlchen.chain.bitcoin.xpub import XpubManager
from rotkehlchen.chain.ethereum.airdrops import check_airdrops, fetch_airdrops_metadata
from rotkehlchen.chain.ethereum.defi.protocols import DEFI_PROTOCOLS
from rotkehlchen.chain.ethereum.modules.convex.convex_cache import (
query_convex_data,
save_convex_data_to_cache,
)
from rotkehlchen.chain.ethereum.modules.eth2.constants import FREE_VALIDATORS_LIMIT
from rotkehlchen.chain.ethereum.modules.eth2.structures import PerformanceStatusFilter
from rotkehlchen.chain.ethereum.modules.liquity.constants import CPT_LIQUITY
from rotkehlchen.chain.ethereum.modules.liquity.statistics import get_stats as get_liquity_stats
from rotkehlchen.chain.ethereum.modules.makerdao.cache import (
query_ilk_registry_and_maybe_update_cache,
)
from rotkehlchen.chain.ethereum.modules.nft.structures import NftLpHandling
from rotkehlchen.chain.ethereum.modules.yearn.utils import query_yearn_vaults
from rotkehlchen.chain.ethereum.utils import try_download_ens_avatar
from rotkehlchen.chain.evm.accounting.aggregator import EVMAccountingAggregators
from rotkehlchen.chain.evm.decoding.curve.curve_cache import (
query_curve_data,
save_curve_data_to_cache,
)
from rotkehlchen.chain.evm.decoding.gearbox.gearbox_cache import (
query_gearbox_data,
save_gearbox_data_to_cache,
)
from rotkehlchen.chain.evm.decoding.monerium.constants import CPT_MONERIUM
from rotkehlchen.chain.evm.decoding.velodrome.velodrome_cache import (
query_velodrome_like_data,
save_velodrome_data_to_cache,
)
from rotkehlchen.chain.evm.names import find_ens_mappings, search_for_addresses_names
from rotkehlchen.chain.evm.types import EvmlikeAccount, WeightedNode
from rotkehlchen.chain.zksync_lite.constants import ZKL_IDENTIFIER
from rotkehlchen.constants import ONE
from rotkehlchen.constants.assets import A_USD
from rotkehlchen.constants.limits import (
FREE_ASSET_MOVEMENTS_LIMIT,
FREE_HISTORY_EVENTS_LIMIT,
FREE_TRADES_LIMIT,
FREE_USER_NOTES_LIMIT,
)
from rotkehlchen.constants.misc import (
AIRDROPS_TOLERANCE,
AVATARIMAGESDIR_NAME,
DEFAULT_MAX_LOG_BACKUP_FILES,
DEFAULT_MAX_LOG_SIZE_IN_MB,
DEFAULT_SQL_VM_INSTRUCTIONS_CB,
HTTP_STATUS_INTERNAL_DB_ERROR,
IMAGESDIR_NAME,
ZERO,
)
from rotkehlchen.constants.prices import ZERO_PRICE
from rotkehlchen.constants.resolver import ChainID
from rotkehlchen.constants.timing import ENS_AVATARS_REFRESH
from rotkehlchen.data_import.manager import DataImportSource
from rotkehlchen.db.accounting_rules import DBAccountingRules, query_missing_accounting_rules
from rotkehlchen.db.addressbook import DBAddressbook
from rotkehlchen.db.calendar import CalendarEntry, CalendarFilterQuery, DBCalendar, ReminderEntry
from rotkehlchen.db.constants import (
HISTORY_MAPPING_KEY_STATE,
HISTORY_MAPPING_STATE_CUSTOMIZED,
LINKABLE_ACCOUNTING_PROPERTIES,
LINKABLE_ACCOUNTING_SETTINGS_NAME,
)
from rotkehlchen.db.custom_assets import DBCustomAssets
from rotkehlchen.db.ens import DBEns
from rotkehlchen.db.evmtx import DBEvmTx
from rotkehlchen.db.filtering import (
AccountingRulesFilterQuery,
AddressbookFilterQuery,
AssetMovementsFilterQuery,
AssetsFilterQuery,
CustomAssetsFilterQuery,
DBFilterQuery,
Eth2DailyStatsFilterQuery,
EvmEventFilterQuery,
EvmTransactionsFilterQuery,
HistoryBaseEntryFilterQuery,
HistoryEventFilterQuery,
LevenshteinFilterQuery,
LocationAssetMappingsFilterQuery,
NFTFilterQuery,
ReportDataFilterQuery,
TradesFilterQuery,
UserNotesFilterQuery,
)
from rotkehlchen.db.history_events import DBHistoryEvents
from rotkehlchen.db.queried_addresses import QueriedAddresses
from rotkehlchen.db.reports import DBAccountingReports
from rotkehlchen.db.search_assets import search_assets_levenshtein
from rotkehlchen.db.settings import ModifiableDBSettings
from rotkehlchen.db.snapshots import DBSnapshot
from rotkehlchen.db.unresolved_conflicts import DBRemoteConflicts
from rotkehlchen.db.utils import DBAssetBalance, LocationData
from rotkehlchen.errors.api import (
AuthenticationError,
IncorrectApiKeyFormat,
PremiumApiError,
PremiumAuthenticationError,
PremiumPermissionError,
RotkehlchenPermissionError,
)
from rotkehlchen.errors.asset import UnknownAsset, UnsupportedAsset
from rotkehlchen.errors.misc import (
AccountingError,
AlreadyExists,
DBSchemaError,
DBUpgradeError,
EthSyncError,
GreenletKilledError,
InputError,
ModuleInactive,
RemoteError,
SystemPermissionError,
TagConstraintError,
)
from rotkehlchen.errors.price import NoPriceForGivenTimestamp, PriceQueryUnsupportedAsset
from rotkehlchen.errors.serialization import DeserializationError
from rotkehlchen.exchanges.constants import ALL_SUPPORTED_EXCHANGES
from rotkehlchen.exchanges.data_structures import Trade
from rotkehlchen.exchanges.utils import query_binance_exchange_pairs
from rotkehlchen.externalapis.github import Github
from rotkehlchen.externalapis.monerium import init_monerium
from rotkehlchen.fval import FVal
from rotkehlchen.globaldb.assets_management import export_assets_from_file, import_assets_from_file
from rotkehlchen.globaldb.cache import (
globaldb_delete_general_cache_values,
globaldb_get_general_cache_values,
globaldb_set_general_cache_values,
)
from rotkehlchen.globaldb.handler import GlobalDBHandler
from rotkehlchen.globaldb.updates import ASSETS_VERSION_KEY
from rotkehlchen.globaldb.utils import set_token_spam_protocol
from rotkehlchen.history.events.structures.base import (
HistoryBaseEntryType,
get_event_type_identifier,
)
from rotkehlchen.history.events.structures.evm_event import EvmProduct
from rotkehlchen.history.events.structures.types import HistoryEventSubType, HistoryEventType
from rotkehlchen.history.events.utils import history_event_to_staking_for_api
from rotkehlchen.history.price import PriceHistorian
from rotkehlchen.history.skipped import (
export_skipped_external_events,
get_skipped_external_events_summary,
reprocess_skipped_external_events,
)
from rotkehlchen.history.types import NOT_EXPOSED_SOURCES, HistoricalPrice, HistoricalPriceOracle
from rotkehlchen.icons import (
check_if_image_is_cached,
create_image_response,
maybe_create_image_response,
)
from rotkehlchen.inquirer import CurrentPriceOracle, Inquirer
from rotkehlchen.logging import RotkehlchenLogsAdapter
from rotkehlchen.premium.premium import PremiumCredentials
from rotkehlchen.rotkehlchen import Rotkehlchen
from rotkehlchen.serialization.serialize import process_result, process_result_list
from rotkehlchen.tasks.utils import query_missing_prices_of_base_entries
from rotkehlchen.types import (
AVAILABLE_MODULES_MAP,
EVM_CHAIN_IDS_WITH_TRANSACTIONS,
EVM_CHAIN_IDS_WITH_TRANSACTIONS_TYPE,
EVM_EVMLIKE_LOCATIONS,
SPAM_PROTOCOL,
SUPPORTED_BITCOIN_CHAINS,
SUPPORTED_CHAIN_IDS,
SUPPORTED_EVM_CHAINS_TYPE,
SUPPORTED_EVM_EVMLIKE_CHAINS,
SUPPORTED_EVM_EVMLIKE_CHAINS_TYPE,
SUPPORTED_EVMLIKE_CHAINS_TYPE,
SUPPORTED_SUBSTRATE_CHAINS,
AddressbookEntry,
AddressbookType,
ApiKey,
ApiSecret,
AssetAmount,
BTCAddress,
CacheType,
ChainType,
ChecksumEvmAddress,
Eth2PubKey,
EvmlikeChain,
EVMTxHash,
ExternalService,
ExternalServiceApiCredentials,
Fee,
HexColorCode,
HistoryEventQueryType,
ListOfBlockchainAddresses,
Location,
LocationAssetMappingDeleteEntry,
LocationAssetMappingUpdateEntry,
ModuleName,
OptionalChainAddress,
Price,
SubstrateAddress,
SupportedBlockchain,
Timestamp,
TradeType,
UserNote,
)
from rotkehlchen.utils.misc import combine_dicts, ts_ms_to_sec, ts_now
from rotkehlchen.utils.snapshots import parse_import_snapshot_data
from rotkehlchen.utils.version_check import get_current_version
if TYPE_CHECKING:
from rotkehlchen.chain.bitcoin.xpub import XpubData
from rotkehlchen.chain.ethereum.manager import EthereumManager
from rotkehlchen.chain.evm.accounting.structures import BaseEventSettings
from rotkehlchen.chain.evm.manager import EvmManager
from rotkehlchen.db.dbhandler import DBHandler
from rotkehlchen.db.drivers.gevent import DBCursor
from rotkehlchen.exchanges.kraken import KrakenAccountType
from rotkehlchen.history.events.structures.base import HistoryBaseEntry
logger = logging.getLogger(__name__)
log = RotkehlchenLogsAdapter(logger)
OK_RESULT = {'result': True, 'message': ''}
def _wrap_in_ok_result(result: Any, status_code: HTTPStatus | None = None) -> dict[str, Any]:
result = {'result': result, 'message': ''}
if status_code:
result['status_code'] = status_code
return result
def _wrap_in_result(result: Any, message: str) -> dict[str, Any]:
return {'result': result, 'message': message}
def wrap_in_fail_result(message: str, status_code: HTTPStatus | None = None) -> dict[str, Any]:
result: dict[str, Any] = {'result': None, 'message': message}
if status_code:
result['status_code'] = status_code
return result
def api_response(
result: dict[str, Any],
status_code: HTTPStatus = HTTPStatus.OK,
log_result: bool = True,
) -> Response:
if status_code == HTTPStatus.NO_CONTENT:
assert not result, 'Provided 204 response with non-zero length response'
data = ''
else:
data = json.dumps(result)
response = make_response(
(
data,
status_code,
{
'mimetype': 'application/json',
'Content-Type': 'application/json',
'rotki-log-result': log_result, # popped by after request callback
}),
)
return response
def make_response_from_dict(response_data: dict[str, Any]) -> Response:
result = response_data.get('result')
message = response_data.get('message', '')
status_code = response_data.get('status_code', HTTPStatus.OK)
return api_response(
result=process_result(_wrap_in_result(result=result, message=message)),
status_code=status_code,
)
def async_api_call() -> Callable:
"""
This is a decorator that should be used with endpoints that can be called asynchronously.
It reads `async_query` argument from the wrapped function to determine whether to call
asynchronously or not. Defaults to synchronous mode.
Endpoints that it wraps must return a dictionary with result, message and optionally a
status code.
This decorator reads the dictionary and transforms it to a Reponse object.
"""
def wrapper(func: Callable[..., dict[str, Any]]) -> Callable[..., Response]:
def inner(rest_api: 'RestAPI', async_query: bool = False, **kwargs: Any) -> Response:
response: dict[str, Any]
if async_query is True:
return rest_api._query_async(
command=func,
**kwargs,
)
response = func(rest_api, **kwargs)
if isinstance(response, Response): # the case of returning a file in a async response
return response
return make_response_from_dict(response)
return inner
return wrapper
def login_lock() -> Callable:
"""
This is a decorator that uses the login lock at RestAPI to avoid a race condition between
async tasks using the user unlock logic.
"""
def wrapper(func: Callable[..., Response]) -> Callable[..., Response]:
def inner(rest_api: 'RestAPI', **kwargs: Any) -> Response:
with rest_api.login_lock:
return func(rest_api, **kwargs)
return inner
return wrapper
class RestAPI:
""" The Object holding the logic that runs inside all the API calls"""
def __init__(self, rotkehlchen: Rotkehlchen) -> None:
self.rotkehlchen = rotkehlchen
self.stop_event = Event()
mainloop_greenlet = self.rotkehlchen.start()
mainloop_greenlet.link_exception(self._handle_killed_greenlets)
# Greenlets that will be waited for when we shutdown (just main loop)
self.waited_greenlets = [mainloop_greenlet]
self.task_lock = Semaphore()
self.login_lock = Semaphore()
self.task_id = 0
self.task_results: dict[int, Any] = {}
self.trade_schema = TradeSchema()
# - Private functions not exposed to the API
def _new_task_id(self) -> int:
with self.task_lock:
task_id = self.task_id
self.task_id += 1
return task_id
def _write_task_result(self, task_id: int, result: Any) -> None:
with self.task_lock:
self.task_results[task_id] = result
def _handle_killed_greenlets(self, greenlet: gevent.Greenlet) -> None:
if not greenlet.exception:
log.warning('handle_killed_greenlets without an exception')
return
try:
task_id = greenlet.task_id
task_str = f'Greenlet for task {task_id}'
except AttributeError:
task_id = None
task_str = 'Main greenlet'
if isinstance(greenlet.exception, GreenletKilledError):
log.debug(
f'Greenlet for task id {task_id} with name {task_str} was killed. '
f'{greenlet.exception!s}',
)
# Setting empty message to signify that the death of the greenlet is expected.
self._write_task_result(task_id, {'result': None, 'message': ''})
return
log.error(
f'{task_str} dies with exception: {greenlet.exception}.\n'
f'Exception Name: {greenlet.exc_info[0]}\n'
f'Exception Info: {greenlet.exc_info[1]}\n'
f'Traceback:\n {"".join(traceback.format_tb(greenlet.exc_info[2]))}',
)
# also write an error for the task result if it's not the main greenlet
if task_id is not None:
result = {
'result': None,
'message': f'The backend query task died unexpectedly: {greenlet.exception!s}',
}
self._write_task_result(task_id, result)
def _do_query_async(self, command: Callable, task_id: int, **kwargs: Any) -> None:
log.debug(f'Async task with task id {task_id} started')
result = command(self, **kwargs)
self._write_task_result(task_id, result)
def _query_async(self, command: Callable, **kwargs: Any) -> Response:
task_id = self._new_task_id()
greenlet = gevent.spawn(
self._do_query_async,
command,
task_id,
**kwargs,
)
greenlet.task_id = task_id
greenlet.link_exception(self._handle_killed_greenlets)
self.rotkehlchen.api_task_greenlets.append(greenlet)
return api_response(_wrap_in_ok_result({'task_id': task_id}), status_code=HTTPStatus.OK)
# - Public functions not exposed via the rest api
def stop(self) -> None:
self.rotkehlchen.shutdown()
log.debug('Waiting for greenlets')
gevent.wait(self.waited_greenlets)
log.debug('Waited for greenlets. Killing all other greenlets')
gevent.killall(self.rotkehlchen.api_task_greenlets)
self.rotkehlchen.api_task_greenlets.clear()
log.debug('Shutdown completed')
logging.shutdown()
self.stop_event.set()
# - Public functions exposed via the rest api
def set_settings(self, settings: ModifiableDBSettings) -> Response:
success, message = self.rotkehlchen.set_settings(settings)
if not success:
return api_response(wrap_in_fail_result(message), status_code=HTTPStatus.CONFLICT)
with self.rotkehlchen.data.db.conn.read_ctx() as cursor:
new_settings = process_result(self.rotkehlchen.get_settings(cursor))
cache = self.rotkehlchen.data.db.get_cache_for_api(cursor)
result_dict = {'result': new_settings | cache, 'message': ''}
return api_response(result=result_dict, status_code=HTTPStatus.OK)
def get_settings(self) -> Response:
with self.rotkehlchen.data.db.conn.read_ctx() as cursor:
settings = process_result(self.rotkehlchen.get_settings(cursor))
cache = self.rotkehlchen.data.db.get_cache_for_api(cursor)
result_dict = _wrap_in_ok_result(settings | cache)
return api_response(result=result_dict, status_code=HTTPStatus.OK)
def query_tasks_outcome(self, task_id: int | None) -> Response:
if task_id is None:
# If no task id is given return list of all pending and completed tasks
completed = []
pending = []
for greenlet in self.rotkehlchen.api_task_greenlets:
task_id = greenlet.task_id
if task_id in self.task_results:
completed.append(task_id)
else:
pending.append(task_id)
result = _wrap_in_ok_result({'pending': pending, 'completed': completed})
return api_response(result=result, status_code=HTTPStatus.OK)
with self.task_lock:
for idx, greenlet in enumerate(self.rotkehlchen.api_task_greenlets):
if greenlet.task_id == task_id:
if task_id in self.task_results:
# Task has completed and we just got the outcome
function_response = self.task_results.pop(int(task_id), None)
# The result of the original request
result = function_response['result']
# The message of the original request
message = function_response['message']
status_code = function_response.get('status_code')
ret = {'result': result, 'message': message}
returned_task_result = {
'status': 'completed',
'outcome': process_result(ret),
}
if status_code:
returned_task_result['status_code'] = status_code
result_dict = {
'result': returned_task_result,
'message': '',
}
# Also remove the greenlet from the api tasks
self.rotkehlchen.api_task_greenlets.pop(idx) # mutation is fine since we get out of the loop right here # noqa: B909, E501
return api_response(result=result_dict, status_code=HTTPStatus.OK)
# else task is still pending and the greenlet is running
result_dict = {
'result': {'status': 'pending', 'outcome': None},
'message': f'The task with id {task_id} is still pending',
}
return api_response(result=result_dict, status_code=HTTPStatus.OK)
# The task has not been found
result_dict = {
'result': {'status': 'not-found', 'outcome': None},
'message': f'No task with id {task_id} found',
}
return api_response(result=result_dict, status_code=HTTPStatus.NOT_FOUND)
def delete_async_task(self, task_id: int) -> Response:
"""Tries to find and cancel the async task with the given task id"""
with self.task_lock:
for idx, greenlet in enumerate(self.rotkehlchen.api_task_greenlets): # noqa: B007 # var used right after loop
if (
greenlet.dead is False and
getattr(greenlet, 'task_id', None) == task_id
):
log.debug(f'Killing api task greenlet with {task_id=}')
greenlet.kill(exception=GreenletKilledError('Killed due to api request'))
break
else: # greenlet not found
return api_response(wrap_in_fail_result(f'Did not cancel task with id {task_id} because it could not be found'), status_code=HTTPStatus.NOT_FOUND) # noqa: E501
self.rotkehlchen.api_task_greenlets.pop(idx) # also pop from greenlets
return api_response(OK_RESULT, status_code=HTTPStatus.OK)
@async_api_call()
def get_exchange_rates(self, given_currencies: list[AssetWithOracles]) -> dict[str, Any]:
currencies = given_currencies
fiat_currencies: list[FiatAsset] = []
asset_rates = {}
for asset in currencies:
if asset.is_fiat():
fiat_currencies.append(asset.resolve_to_fiat_asset())
continue
usd_price = Inquirer.find_usd_price(asset)
if usd_price == ZERO_PRICE:
asset_rates[asset] = ZERO_PRICE
else:
asset_rates[asset] = Price(ONE / usd_price)
asset_rates.update(Inquirer.get_fiat_usd_exchange_rates(fiat_currencies)) # type: ignore # type narrowing does not work here
return _wrap_in_ok_result(process_result(asset_rates))
@async_api_call()
def query_all_balances(
self,
save_data: bool,
ignore_errors: bool,
ignore_cache: bool,
) -> dict[str, Any]:
result = self.rotkehlchen.query_balances(
requested_save_data=save_data,
save_despite_errors=ignore_errors,
ignore_cache=ignore_cache,
)
return {'result': result, 'message': ''}
def _return_external_services_response(self) -> Response:
credentials_list = self.rotkehlchen.data.db.get_all_external_service_credentials()
response_dict: dict[str, Any] = {}
for credential in credentials_list:
name, key_info = credential.serialize_for_api()
if (chain := credential.service.get_chain_for_etherscan()) is not None:
if 'etherscan' not in response_dict:
response_dict['etherscan'] = {}
response_dict['etherscan'][chain.to_name()] = key_info
else:
response_dict[name] = key_info
return api_response(_wrap_in_ok_result(response_dict), status_code=HTTPStatus.OK)
def get_external_services(self) -> Response:
return self._return_external_services_response()
def add_external_services(self, services: list[ExternalServiceApiCredentials]) -> Response:
if self.rotkehlchen.premium is None and ExternalService.MONERIUM in {x.service for x in services}: # noqa: E501
return api_response(
wrap_in_fail_result('You can only use monerium with rotki premium'),
status_code=HTTPStatus.FORBIDDEN,
)
self.rotkehlchen.data.db.add_external_service_credentials(services)
return self._return_external_services_response()
def delete_external_services(self, services: list[ExternalService]) -> Response:
self.rotkehlchen.data.db.delete_external_service_credentials(services)
return self._return_external_services_response()
def get_exchanges(self) -> Response:
return api_response(
_wrap_in_ok_result(self.rotkehlchen.exchange_manager.get_connected_exchanges_info()),
status_code=HTTPStatus.OK,
)
def setup_exchange(
self,
name: str,
location: Location,
api_key: ApiKey,
api_secret: ApiSecret,
passphrase: str | None,
kraken_account_type: Optional['KrakenAccountType'],
binance_markets: list[str] | None,
) -> Response:
result = None
status_code = HTTPStatus.OK
msg = ''
result, msg = self.rotkehlchen.setup_exchange(
name=name,
location=location,
api_key=api_key,
api_secret=api_secret,
passphrase=passphrase,
kraken_account_type=kraken_account_type,
binance_selected_trade_pairs=binance_markets,
)
if not result:
result = None
status_code = HTTPStatus.CONFLICT
return api_response(_wrap_in_result(result, msg), status_code=status_code)
def edit_exchange(
self,
name: str,
location: Location,
new_name: str | None,
api_key: ApiKey | None,
api_secret: ApiSecret | None,
passphrase: str | None,
kraken_account_type: Optional['KrakenAccountType'],
binance_markets: list[str] | None,
) -> Response:
edited, msg = self.rotkehlchen.exchange_manager.edit_exchange(
name=name,
location=location,
new_name=new_name,
api_key=api_key,
api_secret=api_secret,
passphrase=passphrase,
kraken_account_type=kraken_account_type,
binance_selected_trade_pairs=binance_markets,
)
result: bool | None = True
status_code = HTTPStatus.OK
if not edited:
result = None
status_code = HTTPStatus.CONFLICT
return api_response(_wrap_in_result(result, msg), status_code=status_code)
def remove_exchange(self, name: str, location: Location) -> Response:
result: bool | None
result, message = self.rotkehlchen.exchange_manager.delete_exchange(
name=name,
location=location,
)
status_code = HTTPStatus.OK
if not result:
result = None
status_code = HTTPStatus.CONFLICT
return api_response(_wrap_in_result(result, message), status_code=status_code)
def _query_all_exchange_balances(self, ignore_cache: bool) -> dict[str, Any]:
final_balances = {}
error_msg = ''
for exchange_obj in self.rotkehlchen.exchange_manager.iterate_exchanges():
balances, msg = exchange_obj.query_balances(ignore_cache=ignore_cache)
if balances is None:
error_msg += msg
else:
location_str = str(exchange_obj.location)
if location_str not in final_balances:
final_balances[location_str] = balances
else: # multiple exchange of same type. Combine balances
final_balances[location_str] = combine_dicts(
final_balances[location_str],
balances,
)
if final_balances == {}:
result = None
status_code = HTTPStatus.CONFLICT
else:
result = final_balances
status_code = HTTPStatus.OK
return {'result': result, 'message': error_msg, 'status_code': status_code}
@async_api_call()
def query_exchange_balances(self, location: Location | None, ignore_cache: bool) -> dict[str, Any]: # noqa: E501
if location is None:
# Query all exchanges
return self._query_all_exchange_balances(ignore_cache=ignore_cache)
# else query only the specific exchange
exchanges_list = self.rotkehlchen.exchange_manager.connected_exchanges.get(location)
if exchanges_list is None:
return {
'result': None,
'message': f'Could not query balances for {location!s} since it is not registered',
'status_code': HTTPStatus.CONFLICT,
}
balances: dict[AssetWithOracles, Balance] = {}
for exchange in exchanges_list:
result, msg = exchange.query_balances(ignore_cache=ignore_cache)
if result is None:
return {
'result': result,
'message': msg,
'status_code': HTTPStatus.CONFLICT,
}
balances = combine_dicts(balances, result)
return {
'result': balances,
'message': '',
'status_code': HTTPStatus.OK,
}
def get_supported_chains(self) -> Response:
result = []
for blockchain in SupportedBlockchain:
data = {
'id': blockchain.serialize(),
'name': str(blockchain),
'type': blockchain.get_chain_type().serialize(),
'native_token': blockchain.get_native_token_id(),
'image': blockchain.get_image_name(),
}
if blockchain.is_evm() is True:
data['evm_chain_name'] = blockchain.to_chain_id().to_name()
result.append(data)
return api_response(_wrap_in_ok_result(result), status_code=HTTPStatus.OK)
@async_api_call()
def query_blockchain_balances(
self,
blockchain: SupportedBlockchain | None,
ignore_cache: bool,
) -> dict[str, Any]:
msg = ''
status_code = HTTPStatus.OK
result = None
try:
balances = self.rotkehlchen.chains_aggregator.query_balances(
blockchain=blockchain,
ignore_cache=ignore_cache,
)
except EthSyncError as e:
msg = str(e)
status_code = HTTPStatus.CONFLICT
except RemoteError as e:
msg = str(e)
status_code = HTTPStatus.BAD_GATEWAY
else:
result = balances.serialize()
return {'result': result, 'message': msg, 'status_code': status_code}
@async_api_call()
def get_trades(
self,
only_cache: bool,
filter_query: TradesFilterQuery,
include_ignored_trades: bool,
) -> dict[str, Any]:
try:
trades, filter_total_found = self.rotkehlchen.history_querying_manager.query_trades(
filter_query=filter_query,
only_cache=only_cache,
)
except RemoteError as e:
return {'result': None, 'message': str(e), 'status_code': HTTPStatus.BAD_GATEWAY}
trades_result = []
for trade in trades:
serialized_trade = self.trade_schema.dump(trade)
serialized_trade['trade_id'] = trade.identifier
trades_result.append(serialized_trade)
with self.rotkehlchen.data.db.conn.read_ctx() as cursor:
mapping = self.rotkehlchen.data.db.get_ignored_action_ids(cursor, ActionType.TRADE)
ignored_ids = mapping.get(ActionType.TRADE, set())
entries_result = []
for entry in trades_result:
is_trade_ignored = entry['trade_id'] in ignored_ids
if include_ignored_trades is False and is_trade_ignored is True:
continue
entries_result.append(
{'entry': entry, 'ignored_in_accounting': is_trade_ignored},
)
result = {
'entries': entries_result,
'entries_found': filter_total_found,
'entries_total': self.rotkehlchen.data.db.get_entries_count(
cursor=cursor,
entries_table='trades',
),
'entries_limit': FREE_TRADES_LIMIT if self.rotkehlchen.premium is None else -1,
}
return {'result': result, 'message': '', 'status_code': HTTPStatus.OK}
def add_trade(
self,
timestamp: Timestamp,
location: Location,
base_asset: Asset,
quote_asset: Asset,
trade_type: TradeType,
amount: AssetAmount,
rate: Price,
fee: Fee | None,
fee_currency: Asset | None,
link: str | None,
notes: str | None,
) -> Response:
trade = Trade(
timestamp=timestamp,
location=location,
base_asset=base_asset,
quote_asset=quote_asset,
trade_type=trade_type,
amount=amount,
rate=rate,
fee=fee,
fee_currency=fee_currency,
link=link,
notes=notes,
)
with self.rotkehlchen.data.db.user_write() as cursor:
self.rotkehlchen.data.db.add_trades(cursor, [trade])
# For the outside world we should also add the trade identifier
result_dict = self.trade_schema.dump(trade)
result_dict['trade_id'] = trade.identifier
result_dict = _wrap_in_ok_result(result_dict)
return api_response(result_dict, status_code=HTTPStatus.OK)
def edit_trade(
self,
trade_id: str,
timestamp: Timestamp,
location: Location,
base_asset: Asset,
quote_asset: Asset,
trade_type: TradeType,
amount: AssetAmount,
rate: Price,
fee: Fee | None,
fee_currency: Asset | None,
link: str | None,
notes: str | None,
) -> Response:
trade = Trade(
timestamp=timestamp,
location=location,
base_asset=base_asset,
quote_asset=quote_asset,
trade_type=trade_type,
amount=amount,
rate=rate,
fee=fee,
fee_currency=fee_currency,
link=link,
notes=notes,
)
with self.rotkehlchen.data.db.user_write() as cursor:
result, msg = self.rotkehlchen.data.db.edit_trade(cursor, old_trade_id=trade_id, trade=trade) # noqa: E501
if not result:
return api_response(wrap_in_fail_result(msg), status_code=HTTPStatus.CONFLICT)
# For the outside world we should also add the trade identifier
result_dict = self.trade_schema.dump(trade)
result_dict['trade_id'] = trade.identifier
result_dict = _wrap_in_ok_result(result_dict)
return api_response(result_dict, status_code=HTTPStatus.OK)
def delete_trades(self, trades_ids: list[str]) -> Response:
try:
with self.rotkehlchen.data.db.user_write() as cursor:
self.rotkehlchen.data.db.delete_trades(cursor, trades_ids)
except InputError as e:
return api_response(wrap_in_fail_result(str(e)), status_code=HTTPStatus.CONFLICT)
return api_response(_wrap_in_ok_result(True), status_code=HTTPStatus.OK)
@async_api_call()
def get_asset_movements(
self,
filter_query: AssetMovementsFilterQuery,
only_cache: bool,
) -> dict[str, Any]:
msg = ''
status_code = HTTPStatus.OK
result = None
try:
movements, filter_total_found = self.rotkehlchen.history_querying_manager.query_asset_movements( # noqa: E501
filter_query=filter_query,
only_cache=only_cache,
)
except RemoteError as e:
return {'result': None, 'message': str(e), 'status_code': HTTPStatus.BAD_GATEWAY}
serialized_movements = process_result_list([x.serialize() for x in movements])
limit = FREE_ASSET_MOVEMENTS_LIMIT if self.rotkehlchen.premium is None else -1
with self.rotkehlchen.data.db.conn.read_ctx() as cursor:
mapping = self.rotkehlchen.data.db.get_ignored_action_ids(cursor, ActionType.ASSET_MOVEMENT) # noqa: E501
ignored_ids = mapping.get(ActionType.ASSET_MOVEMENT, set())
entries_result = [{
'entry': x,
'ignored_in_accounting': x['identifier'] in ignored_ids,
} for x in serialized_movements]
result = {
'entries': entries_result,
'entries_total': self.rotkehlchen.data.db.get_entries_count(cursor, 'asset_movements'), # noqa: E501
'entries_found': filter_total_found,
'entries_limit': limit,
}
return {'result': result, 'message': msg, 'status_code': status_code}
def add_history_event(self, event: 'HistoryBaseEntry') -> Response:
db = DBHistoryEvents(self.rotkehlchen.data.db)
with self.rotkehlchen.data.db.user_write() as cursor:
try:
identifier = db.add_history_event(
write_cursor=cursor,
event=event,
mapping_values={
HISTORY_MAPPING_KEY_STATE: HISTORY_MAPPING_STATE_CUSTOMIZED,
},
)
except sqlcipher.DatabaseError as e: # pylint: disable=no-member
error_msg = f'Failed to add event to the DB due to a DB error: {e!s}'
return api_response(wrap_in_fail_result(error_msg), status_code=HTTPStatus.CONFLICT) # noqa: E501
if identifier is None:
error_msg = 'Failed to add event to the DB. It already exists'
return api_response(wrap_in_fail_result(error_msg), status_code=HTTPStatus.CONFLICT)
# success
result_dict = _wrap_in_ok_result({'identifier': identifier})
return api_response(result_dict, status_code=HTTPStatus.OK)
def edit_history_event(self, event: 'HistoryBaseEntry') -> Response:
db = DBHistoryEvents(self.rotkehlchen.data.db)
result, msg = db.edit_history_event(event)
if result is False:
return api_response(wrap_in_fail_result(msg), status_code=HTTPStatus.CONFLICT)
return api_response(OK_RESULT, status_code=HTTPStatus.OK)
def delete_history_events(self, identifiers: list[int], force_delete: bool) -> Response:
db = DBHistoryEvents(self.rotkehlchen.data.db)
error_msg = db.delete_history_events_by_identifier(