/
encoding.py
1055 lines (831 loc) · 33.2 KB
/
encoding.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 logging
from pathlib import Path
from typing import Any, Callable, Dict, List, Mapping, Optional, Union
import marshmallow
import webargs
from eth_utils import to_checksum_address
from marshmallow import Schema, fields, post_load, validates_schema
from marshmallow.exceptions import ValidationError
from webargs.compat import MARSHMALLOW_VERSION_INFO
from rotkehlchen.assets.asset import Asset, EthereumToken
from rotkehlchen.balances.manual import ManuallyTrackedBalance
from rotkehlchen.chain.bitcoin import is_valid_btc_address
from rotkehlchen.chain.ethereum.manager import EthereumManager
from rotkehlchen.chain.manager import AVAILABLE_MODULES
from rotkehlchen.constants.misc import ZERO
from rotkehlchen.db.settings import ModifiableDBSettings
from rotkehlchen.errors import DeserializationError, UnknownAsset
from rotkehlchen.exchanges.kraken import KrakenAccountType
from rotkehlchen.exchanges.manager import SUPPORTED_EXCHANGES
from rotkehlchen.fval import FVal
from rotkehlchen.serialization.deserialize import (
deserialize_asset_amount,
deserialize_fee,
deserialize_hex_color_code,
deserialize_location,
deserialize_price,
deserialize_timestamp,
deserialize_trade_pair,
deserialize_trade_type,
)
from rotkehlchen.typing import (
ApiKey,
ApiSecret,
AssetAmount,
ChecksumEthAddress,
ExternalService,
ExternalServiceApiCredentials,
Fee,
HexColorCode,
Location,
Price,
SupportedBlockchain,
Timestamp,
TradePair,
TradeType,
)
from rotkehlchen.utils.misc import ts_now
log = logging.getLogger(__name__)
class DelimitedOrNormalList(webargs.fields.DelimitedList):
"""This is equal to DelimitedList in webargs v5.6.0
Essentially accepting either a delimited string or a list-like object
We introduce it due to them implementing https://github.com/marshmallow-code/webargs/issues/423
"""
def __init__(
self,
cls_or_instance: Any,
*,
_delimiter: Optional[str] = None,
**kwargs: Any,
) -> None:
super().__init__(cls_or_instance, **kwargs)
def _deserialize(
self,
value: Union[List[str], str],
attr: str,
data: Dict[str, Any],
**kwargs: Any,
) -> List[Any]:
"""Adjusting code for _deserialize so that it also works for list-like objects
Adjusting code from
https://github.com/marshmallow-code/webargs/blob/dev/src/webargs/fields.py#L71
so that it uses the list-like detection seen in
https://github.com/marshmallow-code/webargs/blob/f1ae764973b6492e3c69109060c95240b7cc3d41/src/webargs/fields.py#L69
which was removed as part of https://github.com/marshmallow-code/webargs/issues/423
"""
try:
ret = (
value
if marshmallow.utils.is_iterable_but_not_string(value)
else value.split(self.delimiter) # type: ignore
)
except AttributeError:
if MARSHMALLOW_VERSION_INFO[0] < 3:
self.fail("invalid")
else:
raise self.make_error("invalid")
return super(webargs.fields.DelimitedList, self)._deserialize(ret, attr, data, **kwargs)
class TimestampField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> Timestamp:
try:
timestamp = deserialize_timestamp(value)
except DeserializationError as e:
raise ValidationError(str(e))
return timestamp
class ColorField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> HexColorCode:
try:
color_code = deserialize_hex_color_code(value)
except DeserializationError as e:
raise ValidationError(str(e))
return color_code
class TaxFreeAfterPeriodField(fields.Field):
def _deserialize(
self,
value: int,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> int:
try:
value = int(value)
except ValueError:
raise ValidationError(f'{value} is not a valid integer')
if value < -1:
raise ValidationError(
'The taxfree_after_period value can not be negative, except for '
'the value of -1 to disable the setting',
)
if value == 0:
raise ValidationError('The taxfree_after_period value can not be set to zero')
return value
class KrakenAccountTypeField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> KrakenAccountType:
try:
acc_type = KrakenAccountType.deserialize(value)
except DeserializationError:
raise ValidationError(f'{value} is not a valid kraken account type')
return acc_type
class AmountField(fields.Field):
@staticmethod
def _serialize(
value: AssetAmount,
attr: str, # pylint: disable=unused-argument
obj: Any, # pylint: disable=unused-argument
**_kwargs: Any,
) -> str:
return str(value)
def _deserialize(
self,
value: Union[str, int],
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> AssetAmount:
try:
amount = deserialize_asset_amount(value)
except DeserializationError as e:
raise ValidationError(str(e))
return amount
class PositiveOrZeroAmountField(AmountField):
def _deserialize(
self,
value: Union[str, int],
attr: Optional[str],
data: Optional[Mapping[str, Any]],
**kwargs: Any,
) -> AssetAmount:
amount = super()._deserialize(value, attr, data, **kwargs)
if amount < ZERO:
raise ValidationError(f'Negative amount {value} given. Amount should be >= 0')
return amount
class PositiveAmountField(AmountField):
def _deserialize(
self,
value: Union[str, int],
attr: Optional[str],
data: Optional[Mapping[str, Any]],
**kwargs: Any,
) -> AssetAmount:
amount = super()._deserialize(value, attr, data, **kwargs)
if amount <= ZERO:
raise ValidationError(f'Non-positive amount {value} given. Amount should be > 0')
return amount
class PriceField(fields.Field):
@staticmethod
def _serialize(
value: FVal,
attr: str, # pylint: disable=unused-argument
obj: Any, # pylint: disable=unused-argument
**_kwargs: Any,
) -> str:
return str(value)
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> Price:
try:
price = deserialize_price(value)
except DeserializationError as e:
raise ValidationError(str(e))
return price
class FeeField(fields.Field):
@staticmethod
def _serialize(
value: Fee,
attr: str, # pylint: disable=unused-argument
obj: Any, # pylint: disable=unused-argument
**_kwargs: Any,
) -> str:
return str(value)
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> Fee:
try:
fee = deserialize_fee(value)
except DeserializationError as e:
raise ValidationError(str(e))
return fee
class BlockchainField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> SupportedBlockchain:
if value in ('btc', 'BTC'):
blockchain = SupportedBlockchain.BITCOIN
elif value in ('eth', 'ETH'):
blockchain = SupportedBlockchain.ETHEREUM
else:
raise ValidationError(f'Unrecognized value {value} given for blockchain name')
return blockchain
class AssetField(fields.Field):
@staticmethod
def _serialize(
value: Asset,
attr: str, # pylint: disable=unused-argument
obj: Any, # pylint: disable=unused-argument
**_kwargs: Any,
) -> str:
return str(value.identifier)
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> Asset:
try:
asset = Asset(value)
except (DeserializationError, UnknownAsset) as e:
raise ValidationError(str(e))
return asset
class FiatAssetField(AssetField):
def _deserialize(
self,
value: str,
attr: Optional[str],
data: Optional[Mapping[str, Any]],
**kwargs: Any,
) -> Asset:
asset = super()._deserialize(value, attr, data, **kwargs)
if not asset.is_fiat():
raise ValidationError(f'Asset {asset.identifier} is not a FIAT asset')
return asset
class EthereumTokenAssetField(AssetField):
@staticmethod
def _serialize( # type: ignore
value: EthereumToken,
attr: str, # pylint: disable=unused-argument
obj: Any, # pylint: disable=unused-argument
**_kwargs: Any,
) -> str:
return str(value.identifier)
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> Asset:
try:
token = EthereumToken(value)
except (DeserializationError, UnknownAsset) as e:
raise ValidationError(str(e))
return token
class TradeTypeField(fields.Field):
@staticmethod
def _serialize(
value: TradeType,
attr: str, # pylint: disable=unused-argument
obj: Any, # pylint: disable=unused-argument
**_kwargs: Any,
) -> str:
return str(value)
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> TradeType:
try:
trade_type = deserialize_trade_type(value)
except DeserializationError as e:
raise ValidationError(str(e))
return trade_type
class TradePairField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> TradePair:
if not isinstance(value, str):
raise ValidationError(f'Provided non-string trade pair value {value}')
try:
trade_pair = deserialize_trade_pair(value)
except DeserializationError as e:
raise ValidationError(str(e))
return trade_pair
class LocationField(fields.Field):
@staticmethod
def _serialize(
value: Location,
attr: str, # pylint: disable=unused-argument
obj: Any, # pylint: disable=unused-argument
**_kwargs: Any,
) -> str:
return str(value)
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> Location:
try:
location = deserialize_location(value)
except DeserializationError as e:
raise ValidationError(str(e))
return location
class ExternalServiceNameField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> ExternalService:
if not isinstance(value, str):
raise ValidationError('External service name should be a string')
service = ExternalService.serialize(value)
if not service:
raise ValidationError(f'External service {value} is not known')
return service
class ExchangeNameField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> str:
if not isinstance(value, str):
raise ValidationError('Exchange name should be a string')
if value not in SUPPORTED_EXCHANGES:
raise ValidationError(f'Exchange {value} is not supported')
return value
class ApiKeyField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> ApiKey:
if not isinstance(value, str):
raise ValidationError('Given API Key should be a string')
return ApiKey(value)
class ApiSecretField(fields.Field):
@staticmethod
def _serialize(
value: ApiSecret,
attr: str, # pylint: disable=unused-argument
obj: Any, # pylint: disable=unused-argument
**_kwargs: Any,
) -> str:
return str(value.decode())
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> ApiSecret:
if not isinstance(value, str):
raise ValidationError('Given API Secret should be a string')
return ApiSecret(value.encode())
class DirectoryField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> Path:
path = Path(value)
if not path.exists():
raise ValidationError(f'Given path {value} does not exist')
if not path.is_dir():
raise ValidationError(f'Given path {value} is not a directory')
return path
class FileField(fields.Field):
def _deserialize(
self,
value: str,
attr: Optional[str], # pylint: disable=unused-argument
data: Optional[Mapping[str, Any]], # pylint: disable=unused-argument
**_kwargs: Any,
) -> Path:
if not isinstance(value, str):
raise ValidationError('Provided non string type for filepath')
path = Path(value)
if not path.exists():
raise ValidationError(f'Given path {value} does not exist')
if not path.is_file():
raise ValidationError(f'Given path {value} is not a file')
return path
class AsyncTasksQuerySchema(Schema):
task_id = fields.Integer(strict=True, missing=None)
class TradesQuerySchema(Schema):
from_timestamp = TimestampField(missing=Timestamp(0))
to_timestamp = TimestampField(missing=ts_now)
location = LocationField(missing=None)
class TradeSchema(Schema):
timestamp = TimestampField(required=True)
location = LocationField(required=True)
pair = TradePairField(required=True)
trade_type = TradeTypeField(required=True)
amount = PositiveAmountField(required=True)
rate = PriceField(required=True)
fee = FeeField(required=True)
fee_currency = AssetField(required=True)
link = fields.String(missing='')
notes = fields.String(missing='')
class FiatBalancesSchema(Schema):
balances = fields.Dict(
keys=FiatAssetField(),
values=PositiveOrZeroAmountField(),
required=True,
)
class ManuallyTrackedBalanceSchema(Schema):
asset = AssetField(required=True)
label = fields.String(required=True)
amount = PositiveAmountField(required=True)
location = LocationField(required=True)
tags = fields.List(fields.String(), missing=None)
@post_load # type: ignore
def make_manually_tracked_balances( # pylint: disable=no-self-use
self,
data: Dict[str, Any],
**_kwargs: Any,
) -> ManuallyTrackedBalance:
return ManuallyTrackedBalance(**data)
class ManuallyTrackedBalancesSchema(Schema):
balances = fields.List(fields.Nested(ManuallyTrackedBalanceSchema), required=True)
class ManuallyTrackedBalancesDeleteSchema(Schema):
labels = fields.List(fields.String(required=True), required=True)
class TradePatchSchema(TradeSchema):
trade_id = fields.String(required=True)
class TradeDeleteSchema(Schema):
trade_id = fields.String(required=True)
class TagSchema(Schema):
name = fields.String(required=True)
description = fields.String(missing=None)
background_color = ColorField(required=True)
foreground_color = ColorField(required=True)
class TagEditSchema(Schema):
name = fields.String(required=True)
description = fields.String(missing=None)
background_color = ColorField(missing=None)
foreground_color = ColorField(missing=None)
class TagDeleteSchema(Schema):
name = fields.String(required=True)
class ModifiableSettingsSchema(Schema):
"""This is the Schema for the settings that can be modified via the API"""
premium_should_sync = fields.Bool(missing=None)
include_crypto2crypto = fields.Bool(missing=None)
anonymized_logs = fields.Bool(missing=None)
submit_usage_analytics = fields.Bool(missing=None)
ui_floating_precision = fields.Integer(
strict=True,
validate=webargs.validate.Range(
min=0,
max=8,
error='Floating numbers precision in the UI must be between 0 and 8',
),
missing=None,
)
taxfree_after_period = TaxFreeAfterPeriodField(missing=None)
balance_save_frequency = fields.Integer(
strict=True,
validate=webargs.validate.Range(
min=1,
error='The number of hours after which balances should be saved should be >= 1',
),
missing=None,
)
include_gas_costs = fields.Bool(missing=None)
# TODO: Add some validation to this field
historical_data_start = fields.String(missing=None)
# TODO: Add some validation to this field
# even though it gets validated since we try to connect to it
eth_rpc_endpoint = fields.String(missing=None)
main_currency = FiatAssetField(missing=None)
# TODO: Add some validation to this field
date_display_format = fields.String(missing=None)
kraken_account_type = KrakenAccountTypeField(missing=None)
active_modules = fields.List(fields.String(), missing=None)
@validates_schema # type: ignore
def validate_settings_schema( # pylint: disable=no-self-use
self,
data: Dict[str, Any],
**_kwargs: Any,
) -> None:
if data['active_modules'] is not None:
for module in data['active_modules']:
if module not in AVAILABLE_MODULES:
raise ValidationError(
message=f'{module} is not a valid module',
field_name='active_modules',
)
@post_load # type: ignore
def transform_data( # pylint: disable=no-self-use
self,
data: Dict[str, Any],
**_kwargs: Any,
) -> Any:
return ModifiableDBSettings(
premium_should_sync=data['premium_should_sync'],
include_crypto2crypto=data['include_crypto2crypto'],
anonymized_logs=data['anonymized_logs'],
ui_floating_precision=data['ui_floating_precision'],
taxfree_after_period=data['taxfree_after_period'],
balance_save_frequency=data['balance_save_frequency'],
include_gas_costs=data['include_gas_costs'],
historical_data_start=data['historical_data_start'],
eth_rpc_endpoint=data['eth_rpc_endpoint'],
main_currency=data['main_currency'],
date_display_format=data['date_display_format'],
submit_usage_analytics=data['submit_usage_analytics'],
kraken_account_type=data['kraken_account_type'],
active_modules=data['active_modules'],
)
class EditSettingsSchema(Schema):
settings = fields.Nested(ModifiableSettingsSchema, required=True)
class BaseUserSchema(Schema):
name = fields.String(required=True)
password = fields.String(required=True)
class UserActionSchema(Schema):
name = fields.String(required=True)
# All the fields below are not needed for logout/modification so are not required=True
password = fields.String(missing=None)
sync_approval = fields.String(
missing='unknown',
validate=webargs.validate.OneOf(choices=('unknown', 'yes', 'no')),
)
action = fields.String(
validate=webargs.validate.OneOf(choices=('login', 'logout')),
missing=None,
)
premium_api_key = fields.String(missing='')
premium_api_secret = fields.String(missing='')
@validates_schema # type: ignore
def validate_user_action_schema( # pylint: disable=no-self-use
self,
data: Dict[str, Any],
**_kwargs: Any,
) -> None:
if data['action'] == 'login':
if data['password'] is None:
raise ValidationError('Missing password field for login')
elif data['action'] is None:
if data['premium_api_key'] == '' or data['premium_api_secret'] == '':
raise ValidationError(
'Without an action premium api key and secret must be provided',
)
class UserPasswordChangeSchema(Schema):
name = fields.String(required=True)
current_password = fields.String(required=True)
new_password = fields.String(required=True)
class UserPremiumKeyRemoveSchema(Schema):
name = fields.String(required=True)
class NewUserSchema(BaseUserSchema):
premium_api_key = fields.String(missing='')
premium_api_secret = fields.String(missing='')
initial_settings = fields.Nested(ModifiableSettingsSchema, missing=None)
class AllBalancesQuerySchema(Schema):
async_query = fields.Boolean(missing=False)
save_data = fields.Boolean(missing=False)
ignore_cache = fields.Boolean(missing=False)
class ExternalServiceSchema(Schema):
name = ExternalServiceNameField(required=True)
api_key = fields.String(required=True)
@post_load # type: ignore
def make_external_service( # pylint: disable=no-self-use
self,
data: Dict[str, Any],
**_kwargs: Any,
) -> ExternalServiceApiCredentials:
"""Used when encoding an external resource given in via the API"""
return ExternalServiceApiCredentials(service=data['name'], api_key=data['api_key'])
class ExternalServicesResourceAddSchema(Schema):
services = fields.List(fields.Nested(ExternalServiceSchema), required=True)
class ExternalServicesResourceDeleteSchema(Schema):
services = fields.List(ExternalServiceNameField(), required=True)
class ExchangesResourceAddSchema(Schema):
name = ExchangeNameField(required=True)
api_key = ApiKeyField(required=True)
api_secret = ApiSecretField(required=True)
passphrase = fields.String(missing=None)
class ExchangesResourceRemoveSchema(Schema):
name = ExchangeNameField(required=True)
class ExchangeBalanceQuerySchema(Schema):
name = ExchangeNameField(missing=None)
async_query = fields.Boolean(missing=False)
ignore_cache = fields.Boolean(missing=False)
class ExchangeTradesQuerySchema(Schema):
name = ExchangeNameField(missing=None)
from_timestamp = TimestampField(missing=Timestamp(0))
to_timestamp = TimestampField(missing=ts_now)
async_query = fields.Boolean(missing=False)
class BlockchainBalanceQuerySchema(Schema):
blockchain = BlockchainField(missing=None)
async_query = fields.Boolean(missing=False)
ignore_cache = fields.Boolean(missing=False)
class StatisticsAssetBalanceSchema(Schema):
asset = AssetField(required=True)
from_timestamp = TimestampField(missing=Timestamp(0))
to_timestamp = TimestampField(missing=ts_now)
class StatisticsValueDistributionSchema(Schema):
distribution_by = fields.String(
required=True,
validate=webargs.validate.OneOf(choices=('location', 'asset')),
)
class HistoryProcessingSchema(Schema):
from_timestamp = TimestampField(missing=Timestamp(0))
to_timestamp = TimestampField(missing=ts_now)
async_query = fields.Boolean(missing=False)
class HistoryExportingSchema(Schema):
directory_path = DirectoryField(required=True)
class EthTokensSchema(Schema):
eth_tokens = fields.List(EthereumTokenAssetField(), required=True)
async_query = fields.Boolean(missing=False)
class BlockchainAccountDataSchema(Schema):
address = fields.String(required=True)
label = fields.String(missing=None)
tags = fields.List(fields.String(), missing=None)
class BlockchainAccountsGetSchema(Schema):
blockchain = BlockchainField(required=True)
def _validate_blockchain_account_schemas(
data: Dict[str, Any],
address_getter: Callable,
) -> None:
"""Validates schema input for the PUT/PATCH/DELETE on blockchain account data"""
# Make sure no duplicates addresses are given
given_addresses = set()
# Make sure ethereum addresses are checksummed
if data['blockchain'] == SupportedBlockchain.ETHEREUM:
for account_data in data['accounts']:
address_string = address_getter(account_data)
if not address_string.endswith('.eth'):
# Make sure that given value is an ethereum address
try:
address = to_checksum_address(address_string)
except (ValueError, TypeError):
raise ValidationError(
f'Given value {address_string} is not an ethereum address',
field_name='address',
)
else:
# else it's ENS name and will be checked in the transformation step and not here
address = address_string
if address in given_addresses:
raise ValidationError(
f'Address {address} appears multiple times in the request data',
field_name='address',
)
given_addresses.add(address)
# Make sure bitcoin addresses are valid
elif data['blockchain'] == SupportedBlockchain.BITCOIN:
for account_data in data['accounts']:
address = address_getter(account_data)
if not is_valid_btc_address(address):
raise ValidationError(
f'Given value {address} is not a valid bitcoin address',
field_name='address',
)
if address in given_addresses:
raise ValidationError(
f'Address {address} appears multiple times in the request data',
field_name='address',
)
given_addresses.add(address)
def _transform_eth_address(
ethereum: EthereumManager, given_address: str) -> ChecksumEthAddress:
try:
address = to_checksum_address(given_address)
except ValueError:
# Validation will only let .eth names come here.
# So let's see if it resolves to anything
resolved_address = ethereum.ens_lookup(given_address)
if resolved_address is None:
raise ValidationError(
f'Given ENS address {given_address} could not be resolved',
field_name='address',
)
else:
address = to_checksum_address(resolved_address)
log.info(f'Resolved ENS {given_address} to {address}')
return address
class BlockchainAccountsPatchSchema(Schema):
blockchain = BlockchainField(required=True)
accounts = fields.List(fields.Nested(BlockchainAccountDataSchema), required=True)
def __init__(self, ethereum_manager: EthereumManager):
super().__init__()
self.ethereum_manager = ethereum_manager
@validates_schema # type: ignore
def validate_schema( # pylint: disable=no-self-use
self,
data: Dict[str, Any],
**_kwargs: Any,
) -> None:
_validate_blockchain_account_schemas(data, lambda x: x['address'])
@post_load # type: ignore
def transform_data( # pylint: disable=no-self-use
self,
data: Dict[str, Any],
**_kwargs: Any,
) -> Any:
if data['blockchain'] == SupportedBlockchain.ETHEREUM:
for idx, account in enumerate(data['accounts']):
data['accounts'][idx]['address'] = _transform_eth_address(
ethereum=self.ethereum_manager,
given_address=account['address'],
)
return data
class BlockchainAccountsPutSchema(BlockchainAccountsPatchSchema):
async_query = fields.Boolean(missing=False)
class BlockchainAccountsDeleteSchema(Schema):
blockchain = BlockchainField(required=True)
accounts = fields.List(fields.String(), required=True)
async_query = fields.Boolean(missing=False)
def __init__(self, ethereum_manager: EthereumManager):
super().__init__()
self.ethereum_manager = ethereum_manager
@validates_schema # type: ignore
def validate_blockchain_accounts_delete_schema( # pylint: disable=no-self-use
self,
data: Dict[str, Any],
**_kwargs: Any,
) -> None:
_validate_blockchain_account_schemas(data, lambda x: x)
@post_load # type: ignore
def transform_data( # pylint: disable=no-self-use
self,
data: Dict[str, Any],
**_kwargs: Any,
) -> Any:
if data['blockchain'] == SupportedBlockchain.ETHEREUM:
data['accounts'] = [
_transform_eth_address(self.ethereum_manager, x) for x in data['accounts']
]
return data
class IgnoredAssetsSchema(Schema):
assets = fields.List(AssetField(), required=True)