-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathbase.py
3157 lines (2410 loc) · 110 KB
/
base.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
# Python Substrate Interface Library
#
# Copyright 2018-2021 Stichting Polkascan (Polkascan Foundation).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
from functools import lru_cache
from hashlib import blake2b
import binascii
import json
import logging
import re
import requests
from typing import Optional
from websocket import create_connection, WebSocketConnectionClosedException
from scalecodec.base import ScaleDecoder, ScaleBytes, RuntimeConfigurationObject, ScaleType
from scalecodec.types import GenericCall, GenericExtrinsic, Extrinsic, LogDigest
from scalecodec.type_registry import load_type_registry_preset
from scalecodec.updater import update_type_registries
from .key import extract_derive_path
from .utils.caching import block_dependent_lru_cache
from .utils.hasher import blake2_256, two_x64_concat, xxh128, blake2_128, blake2_128_concat, identity
from .exceptions import SubstrateRequestException, ConfigurationError, StorageFunctionNotFound, BlockNotFound, \
ExtrinsicNotFound
from .constants import *
from .utils.ss58 import ss58_decode, ss58_encode, is_valid_ss58_address
from bip39 import bip39_to_mini_secret, bip39_generate
import sr25519
import ed25519
__all__ = ['Keypair', 'KeypairType', 'SubstrateInterface', 'ExtrinsicReceipt', 'logger']
logger = logging.getLogger(__name__)
class KeypairType:
ED25519 = 0
SR25519 = 1
class Keypair:
def __init__(self, ss58_address=None, public_key=None, private_key=None, ss58_format=None,
address_type=None, seed_hex=None,
crypto_type=KeypairType.SR25519):
"""
Allows generation of Keypairs from a variety of input combination, such as a public/private key combination, a
mnemonic or a uri containing soft and hard derivation paths. With these Keypairs data can be signed and verified
Parameters
----------
ss58_address: Substrate address
public_key: hex string or bytes of public_key key
private_key: hex string or bytes of private key
ss58_format: Substrate address format, default = 42
address_type: (deprecated) replaced by ss58_format
seed_hex: hex string of seed
crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair
"""
self.crypto_type = crypto_type
self.seed_hex = seed_hex
self.derive_path = None
if ss58_address and not public_key:
public_key = ss58_decode(ss58_address, valid_ss58_format=ss58_format)
if not public_key:
raise ValueError('No SS58 formatted address or public key provided')
if type(public_key) is bytes:
public_key = public_key.hex()
public_key = '0x{}'.format(public_key.replace('0x', ''))
if len(public_key) != 66:
raise ValueError('Public key should be 32 bytes long')
if address_type is not None:
warnings.warn("Keyword 'address_type' will be replaced by 'ss58_format'", DeprecationWarning)
ss58_format = address_type
self.ss58_format = ss58_format
if not ss58_address:
ss58_address = ss58_encode(public_key, ss58_format=ss58_format)
self.public_key = public_key
self.ss58_address = ss58_address
if private_key:
if type(private_key) is bytes:
private_key = private_key.hex()
private_key = '0x{}'.format(private_key.replace('0x', ''))
if self.crypto_type == KeypairType.SR25519 and len(private_key) != 130:
raise ValueError('Secret key should be 64 bytes long')
self.private_key = private_key
self.mnemonic = None
@classmethod
def generate_mnemonic(cls, words=12):
"""
Generates a new seed phrase with given amount of words (default 12)
Parameters
----------
words: The amount of words to generate, valid values are 12, 15, 18, 21 and 24
Returns
-------
Seed phrase
"""
return bip39_generate(words)
@classmethod
def create_from_mnemonic(cls, mnemonic, ss58_format=42, address_type=None, crypto_type=KeypairType.SR25519):
"""
Create a Keypair for given memonic
Parameters
----------
mnemonic: Seed phrase
ss58_format: Substrate address format
address_type: (deprecated)
crypto_type: Use `KeypairType.SR25519` or `KeypairType.ED25519` cryptography for generating the Keypair
Returns
-------
Keypair
"""
seed_array = bip39_to_mini_secret(mnemonic, "")
if address_type is not None:
warnings.warn("Keyword 'address_type' will be replaced by 'ss58_format'", DeprecationWarning)
ss58_format = address_type
keypair = cls.create_from_seed(
seed_hex=binascii.hexlify(bytearray(seed_array)).decode("ascii"),
ss58_format=ss58_format,
crypto_type=crypto_type
)
keypair.mnemonic = mnemonic
return keypair
@classmethod
def create_from_seed(
cls, seed_hex: str, ss58_format: Optional[int] = 42, address_type=None, crypto_type=KeypairType.SR25519
) -> 'Keypair':
"""
Create a Keypair for given seed
Parameters
----------
seed_hex: hex string of seed
ss58_format: Substrate address format
address_type: (deprecated)
crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair
Returns
-------
Keypair
"""
if address_type is not None:
warnings.warn("Keyword 'address_type' will be replaced by 'ss58_format'", DeprecationWarning)
ss58_format = address_type
if crypto_type == KeypairType.SR25519:
public_key, private_key = sr25519.pair_from_seed(bytes.fromhex(seed_hex.replace('0x', '')))
elif crypto_type == KeypairType.ED25519:
private_key, public_key = ed25519.ed_from_seed(bytes.fromhex(seed_hex.replace('0x', '')))
else:
raise ValueError('crypto_type "{}" not supported'.format(crypto_type))
public_key = public_key.hex()
private_key = private_key.hex()
ss58_address = ss58_encode(f'0x{public_key}', ss58_format)
return cls(
ss58_address=ss58_address, public_key=public_key, private_key=private_key,
ss58_format=ss58_format, crypto_type=crypto_type, seed_hex=seed_hex
)
@classmethod
def create_from_uri(
cls, suri: str, ss58_format: Optional[int] = 42, address_type=None, crypto_type=KeypairType.SR25519
) -> 'Keypair':
"""
Creates Keypair for specified suri in following format: `<mnemonic>/<soft-path>//<hard-path>`
Parameters
----------
suri:
ss58_format: Substrate address format
address_type: (deprecated)
crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair
Returns
-------
Keypair
"""
if address_type is not None:
warnings.warn("Keyword 'address_type' will be replaced by 'ss58_format'", DeprecationWarning)
ss58_format = address_type
if suri and suri.startswith('/'):
suri = DEV_PHRASE + suri
suri_regex = re.match(r'^(?P<phrase>\w+( \w+)*)(?P<path>(//?[^/]+)*)(///(?P<password>.*))?$', suri)
suri_parts = suri_regex.groupdict()
if suri_parts['password']:
raise NotImplementedError("Passwords in suri not supported")
derived_keypair = cls.create_from_mnemonic(
suri_parts['phrase'], ss58_format=ss58_format, crypto_type=crypto_type
)
if suri_parts['path'] != '':
derived_keypair.derive_path = suri_parts['path']
if crypto_type not in [KeypairType.SR25519]:
raise NotImplementedError('Derivation paths for this crypto type not supported')
derive_junctions = extract_derive_path(suri_parts['path'])
child_pubkey = bytes.fromhex(derived_keypair.public_key[2:])
child_privkey = bytes.fromhex(derived_keypair.private_key[2:])
for junction in derive_junctions:
if junction.is_hard:
_, child_pubkey, child_privkey = sr25519.hard_derive_keypair(
(junction.chain_code, child_pubkey, child_privkey),
b''
)
else:
_, child_pubkey, child_privkey = sr25519.derive_keypair(
(junction.chain_code, child_pubkey, child_privkey),
b''
)
derived_keypair = Keypair(public_key=child_pubkey, private_key=child_privkey, ss58_format=ss58_format)
return derived_keypair
@classmethod
def create_from_private_key(
cls, private_key, public_key=None, ss58_address=None, ss58_format=None, crypto_type=KeypairType.SR25519,
address_type=None
):
"""
Creates Keypair for specified public/private keys
Parameters
----------
private_key: hex string or bytes of private key
public_key: hex string or bytes of public key
ss58_address: Substrate address
ss58_format: Substrate address format, default = 42
address_type: (deprecated)
crypto_type: Use KeypairType.SR25519 or KeypairType.ED25519 cryptography for generating the Keypair
Returns
-------
Keypair
"""
if address_type is not None:
warnings.warn("Keyword 'address_type' will be replaced by 'ss58_format'", DeprecationWarning)
ss58_format = address_type
return cls(
ss58_address=ss58_address, public_key=public_key, private_key=private_key,
ss58_format=ss58_format, crypto_type=crypto_type
)
def sign(self, data):
"""
Creates a signature for given data
Parameters
----------
data: data to sign in `Scalebytes`, bytes or hex string format
Returns
-------
signature in hex string format
"""
if type(data) is ScaleBytes:
data = bytes(data.data)
elif data[0:2] == '0x':
data = bytes.fromhex(data[2:])
else:
data = data.encode()
if not self.private_key:
raise ConfigurationError('No private key set to create signatures')
if self.crypto_type == KeypairType.SR25519:
signature = sr25519.sign((bytes.fromhex(self.public_key[2:]), bytes.fromhex(self.private_key[2:])), data)
elif self.crypto_type == KeypairType.ED25519:
signature = ed25519.ed_sign(bytes.fromhex(self.public_key[2:]), bytes.fromhex(self.private_key[2:]), data)
else:
raise ConfigurationError("Crypto type not supported")
return "0x{}".format(signature.hex())
def verify(self, data, signature):
"""
Verifies data with specified signature
Parameters
----------
data: data to be verified in `Scalebytes`, bytes or hex string format
signature: signature in bytes or hex string format
Returns
-------
True if data is signed with this Keypair, otherwise False
"""
if type(data) is ScaleBytes:
data = bytes(data.data)
elif data[0:2] == '0x':
data = bytes.fromhex(data[2:])
else:
data = data.encode()
if type(signature) is str and signature[0:2] == '0x':
signature = bytes.fromhex(signature[2:])
if type(signature) is not bytes:
raise TypeError("Signature should be of type bytes or a hex-string")
if self.crypto_type == KeypairType.SR25519:
return sr25519.verify(signature, data, bytes.fromhex(self.public_key[2:]))
elif self.crypto_type == KeypairType.ED25519:
return ed25519.ed_verify(signature, data, bytes.fromhex(self.public_key[2:]))
else:
raise ConfigurationError("Crypto type not supported")
def __repr__(self):
return '<Keypair (ss58_address={})>'.format(self.ss58_address)
class SubstrateInterface:
def __init__(self, url=None, websocket=None, ss58_format=None, type_registry=None, type_registry_preset=None,
cache_region=None, address_type=None, runtime_config=None, use_remote_preset=False, ws_options=None,
auto_discover=True):
"""
A specialized class in interfacing with a Substrate node.
Parameters
----------
url: the URL to the substrate node, either in format https://127.0.0.1:9933 or wss://127.0.0.1:9944
ss58_format: The address type which account IDs will be SS58-encoded to Substrate addresses. Defaults to 42, for Kusama the address type is 2
type_registry: A dict containing the custom type registry in format: {'types': {'customType': 'u32'},..}
type_registry_preset: The name of the predefined type registry shipped with the SCALE-codec, e.g. kusama
cache_region: a Dogpile cache region as a central store for the metadata cache
use_remote_preset: When True preset is downloaded from Github master, otherwise use files from local installed scalecodec package
ws_options: dict of options to pass to the websocket-client create_connection function
"""
if (not url and not websocket) or (url and websocket):
raise ValueError("Either 'url' or 'websocket' must be provided")
if address_type is not None:
warnings.warn("Keyword 'address_type' will be replaced by 'ss58_format'", DeprecationWarning)
ss58_format = address_type
# Initialize lazy loading variables
self.__version = None
self.__name = None
self.__properties = None
self.__chain = None
self.__token_decimals = None
self.__token_symbol = None
self.__ss58_format = None
self.cache_region = cache_region
self.ss58_format = ss58_format
self.type_registry_preset = type_registry_preset
self.type_registry = type_registry
self.request_id = 1
self.url = url
self.websocket = None
# Websocket connection options
self.ws_options = ws_options or {}
if 'max_size' not in self.ws_options:
self.ws_options['max_size'] = 2 ** 32
if 'read_limit' not in self.ws_options:
self.ws_options['read_limit'] = 2 ** 32
if 'write_limit' not in self.ws_options:
self.ws_options['write_limit'] = 2 ** 32
self.__rpc_message_queue = []
if self.url and (self.url[0:6] == 'wss://' or self.url[0:5] == 'ws://'):
self.connect_websocket()
elif websocket:
self.websocket = websocket
self.mock_extrinsics = None
self.default_headers = {
'content-type': "application/json",
'cache-control': "no-cache"
}
self.metadata_decoder = None
self.runtime_version = None
self.transaction_version = None
self.block_hash = None
self.block_id = None
self.metadata_cache = {}
self.type_registry_cache = {}
if not runtime_config:
runtime_config = RuntimeConfigurationObject(ss58_format=self.ss58_format)
self.runtime_config = runtime_config
self.debug = False
self.config = {
'use_remote_preset': use_remote_preset,
'auto_discover': auto_discover
}
self.reload_type_registry(use_remote_preset=use_remote_preset, auto_discover=auto_discover)
def connect_websocket(self):
if self.url and (self.url[0:6] == 'wss://' or self.url[0:5] == 'ws://'):
self.debug_message("Connecting to {} ...".format(self.url))
self.websocket = create_connection(
self.url,
**self.ws_options
)
def close(self):
if self.websocket:
self.debug_message("Closing websocket connection")
self.websocket.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def debug_message(self, message):
logger.debug(message)
def rpc_request(self, method, params, result_handler=None):
"""
Method that handles the actual RPC request to the Substrate node. The other implemented functions eventually
use this method to perform the request.
Parameters
----------
result_handler: Callback function that processes the result received from the node
method: method of the JSONRPC request
params: a list containing the parameters of the JSONRPC request
Returns
-------
a dict with the parsed result of the request.
"""
request_id = self.request_id
self.request_id += 1
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": request_id
}
self.debug_message('RPC request #{}: "{}"'.format(request_id, method))
if self.websocket:
try:
self.websocket.send(json.dumps(payload))
update_nr = 0
json_body = None
subscription_id = None
while json_body is None:
self.__rpc_message_queue.append(json.loads(self.websocket.recv()))
for message in self.__rpc_message_queue:
# Check if result message is matching request ID
if 'id' in message and message['id'] == request_id:
self.__rpc_message_queue.remove(message)
# Check if response has error
if 'error' in message:
raise SubstrateRequestException(message['error'])
# If result handler is set, pass result through and loop until handler return value is set
if callable(result_handler):
# Set subscription ID and only listen to messages containing this ID
subscription_id = message['result']
self.debug_message(f"Websocket subscription [{subscription_id}] created")
else:
json_body = message
# Check if message is meant for this subscription
elif 'params' in message and message['params']['subscription'] == subscription_id:
self.__rpc_message_queue.remove(message)
self.debug_message(f"Websocket result [{subscription_id} #{update_nr}]: {message}")
# Call result_handler with message for processing
callback_result = result_handler(message, update_nr, subscription_id)
if callback_result is not None:
json_body = callback_result
update_nr += 1
except WebSocketConnectionClosedException:
if self.url:
# Try to reconnect websocket and retry rpc_request
self.debug_message("Connection Closed; Trying to reconnecting...")
self.connect_websocket()
return self.rpc_request(method=method, params=params, result_handler=result_handler)
else:
# websocket connection is externally created, re-raise exception
raise
else:
if result_handler:
raise ConfigurationError("Result handlers only available for websockets (ws://) connections")
response = requests.request("POST", self.url, data=json.dumps(payload), headers=self.default_headers)
if response.status_code != 200:
raise SubstrateRequestException(
"RPC request failed with HTTP status code {}".format(response.status_code))
json_body = response.json()
# Check if response has error
if 'error' in json_body:
raise SubstrateRequestException(json_body['error'])
return json_body
@property
def name(self):
if self.__name is None:
self.__name = self.rpc_request("system_name", []).get('result')
return self.__name
@property
def properties(self):
if self.__properties is None:
self.__properties = self.rpc_request("system_properties", []).get('result')
return self.__properties
@property
def chain(self):
if self.__chain is None:
self.__chain = self.rpc_request("system_chain", []).get('result')
return self.__chain
@property
def version(self):
if self.__version is None:
self.__version = self.rpc_request("system_version", []).get('result')
return self.__version
@property
def token_decimals(self):
if self.__token_decimals is None:
self.__token_decimals = self.properties.get('tokenDecimals')
return self.__token_decimals
@token_decimals.setter
def token_decimals(self, value):
if type(value) is not int and value is not None:
raise TypeError('Token decimals must be an int')
self.__token_decimals = value
@property
def token_symbol(self):
if self.__token_symbol is None:
if self.properties:
self.__token_symbol = self.properties.get('tokenSymbol')
else:
self.__token_symbol = 'UNIT'
return self.__token_symbol
@token_symbol.setter
def token_symbol(self, value):
self.__token_symbol = value
@property
def ss58_format(self):
if self.__ss58_format is None:
if self.properties:
self.__ss58_format = self.properties.get('ss58Format')
else:
self.__ss58_format = 42
return self.__ss58_format
@ss58_format.setter
def ss58_format(self, value):
if type(value) is not int and value is not None:
raise TypeError('ss58_format must be an int')
self.__ss58_format = value
def implements_scaleinfo(self) -> Optional[bool]:
if self.metadata_decoder:
return self.metadata_decoder.portable_registry is not None
def get_chain_head(self):
"""
A pass-though to existing JSONRPC method `chain_getHead`
Returns
-------
"""
response = self.rpc_request("chain_getHead", [])
if response is not None:
if 'error' in response:
raise SubstrateRequestException(response['error']['message'])
return response.get('result')
def get_chain_finalised_head(self):
"""
A pass-though to existing JSONRPC method `chain_getFinalisedHead`
Returns
-------
"""
response = self.rpc_request("chain_getFinalisedHead", [])
if response is not None:
if 'error' in response:
raise SubstrateRequestException(response['error']['message'])
return response.get('result')
def get_chain_block(self, block_hash=None, block_id=None, metadata_decoder=None):
"""
A pass-though to existing JSONRPC method `chain_getBlock`. For a decoded version see `get_runtime_block()`
Parameters
----------
block_hash
block_id
metadata_decoder
Returns
-------
"""
warnings.warn("'get_chain_block' will be replaced by 'get_block'", DeprecationWarning)
if block_id:
block_hash = self.get_block_hash(block_id)
response = self.rpc_request("chain_getBlock", [block_hash])
if 'error' in response:
raise SubstrateRequestException(response['error']['message'])
else:
result = response.get('result')
if self.mock_extrinsics:
# Extend extrinsics with mock_extrinsics for e.g. performance tests
result['block']['extrinsics'].extend(self.mock_extrinsics)
# Decode extrinsics
if metadata_decoder:
result['block']['header']['number'] = int(result['block']['header']['number'], 16)
for idx, extrinsic_data in enumerate(result['block']['extrinsics']):
extrinsic_decoder = Extrinsic(
data=ScaleBytes(extrinsic_data),
metadata=metadata_decoder,
runtime_config=self.runtime_config
)
extrinsic_decoder.decode()
result['block']['extrinsics'][idx] = extrinsic_decoder.value
for idx, log_data in enumerate(result['block']['header']["digest"]["logs"]):
log_digest = LogDigest(ScaleBytes(log_data), runtime_config=self.runtime_config)
log_digest.decode()
result['block']['header']["digest"]["logs"][idx] = log_digest.value
return result
@lru_cache(maxsize=1000)
def get_block_hash(self, block_id: int) -> str:
"""
A pass-though to existing JSONRPC method `chain_getBlockHash`
Parameters
----------
block_id
Returns
-------
"""
response = self.rpc_request("chain_getBlockHash", [block_id])
if 'error' in response:
raise SubstrateRequestException(response['error']['message'])
else:
return response.get('result')
@block_dependent_lru_cache(maxsize=1000, block_arg_index=1)
def get_block_number(self, block_hash: str) -> int:
"""
A convenience method to get the block number for given block_hash
Parameters
----------
block_hash
Returns
-------
"""
response = self.rpc_request("chain_getHeader", [block_hash])
if 'error' in response:
raise SubstrateRequestException(response['error']['message'])
elif 'result' in response:
if response['result']:
return int(response['result']['number'], 16)
@block_dependent_lru_cache(maxsize=10)
def get_block_metadata(self, block_hash=None, decode=True):
"""
A pass-though to existing JSONRPC method `state_getMetadata`.
Parameters
----------
block_hash
decode: True for decoded version
Returns
-------
"""
params = None
if block_hash:
params = [block_hash]
response = self.rpc_request("state_getMetadata", params)
if 'error' in response:
raise SubstrateRequestException(response['error']['message'])
if response.get('result') and decode:
metadata_decoder = self.runtime_config.create_scale_object(
'MetadataVersioned', data=ScaleBytes(response.get('result'))
)
metadata_decoder.decode()
return metadata_decoder
return response
def get_storage_by_key(self, block_hash, storage_key):
"""
A pass-though to existing JSONRPC method `state_getStorageAt`
Parameters
----------
block_hash
storage_key
Returns
-------
"""
response = self.rpc_request("state_getStorageAt", [storage_key, block_hash])
if 'result' in response:
return response.get('result')
elif 'error' in response:
raise SubstrateRequestException(response['error']['message'])
else:
raise SubstrateRequestException("Unknown error occurred during retrieval of events")
def get_block_runtime_version(self, block_hash):
"""
Retrieve the runtime version id of given block_hash
Parameters
----------
block_hash
Returns
-------
"""
response = self.rpc_request("chain_getRuntimeVersion", [block_hash])
if 'error' in response:
raise SubstrateRequestException(response['error']['message'])
return response.get('result')
def generate_storage_hash(self, storage_module: str, storage_function: str, params: list = None,
hashers: list = None):
"""
Generate a storage key for given module/function
Parameters
----------
storage_module
storage_function
params: Parameters of the storage function, provided in scale encoded hex-bytes or ScaleBytes instances
hashers: Hashing methods used to determine storage key, defaults to 'Twox64Concat' if not provided
Returns
-------
str Hexstring respresentation of the storage key
"""
storage_hash = xxh128(storage_module.encode()) + xxh128(storage_function.encode())
if params:
for idx, param in enumerate(params):
# Get hasher assiociated with param
try:
param_hasher = hashers[idx]
except IndexError:
raise ValueError(f'No hasher found for param #{idx + 1}')
params_key = bytes()
# Convert param to bytes
if type(param) is str:
params_key += binascii.unhexlify(param)
elif type(param) is ScaleBytes:
params_key += param.data
elif isinstance(param, ScaleDecoder):
params_key += param.data.data
if not param_hasher:
param_hasher = 'Twox128'
if param_hasher == 'Blake2_256':
storage_hash += blake2_256(params_key)
elif param_hasher == 'Blake2_128':
storage_hash += blake2_128(params_key)
elif param_hasher == 'Blake2_128Concat':
storage_hash += blake2_128_concat(params_key)
elif param_hasher == 'Twox128':
storage_hash += xxh128(params_key)
elif param_hasher == 'Twox64Concat':
storage_hash += two_x64_concat(params_key)
elif param_hasher == 'Identity':
storage_hash += identity(params_key)
else:
raise ValueError('Unknown storage hasher "{}"'.format(param_hasher))
return '0x{}'.format(storage_hash)
def convert_storage_parameter(self, scale_type, value):
if scale_type == 'AccountId':
if value[0:2] != '0x':
return '0x{}'.format(ss58_decode(value, self.ss58_format))
return value
# Runtime functions used by Substrate API
def init_runtime(self, block_hash=None, block_id=None):
"""
This method is used by all other methods that deals with metadata and types defined in the type registry.
It optionally retrieves the block_hash when block_id is given and sets the applicable metadata for that
block_hash. Also it applies all the versioned types at the time of the block_hash.
Because parsing of metadata and type registry is quite heavy, the result will be cached per runtime id.
In the future there could be support for caching backends like Redis to make this cache more persistent.
Parameters
----------
block_hash
block_id
Returns
-------
"""
if block_id and block_hash:
raise ValueError('Cannot provide block_hash and block_id at the same time')
# Check if runtime state already set to current block
if (block_hash and block_hash == self.block_hash) or (block_id and block_id == self.block_id):
return
if block_id is not None:
block_hash = self.get_block_hash(block_id)
if not block_hash:
block_hash = self.get_chain_head()
self.block_hash = block_hash
self.block_id = block_id
# In fact calls and storage functions are decoded against runtime of previous block, therefor retrieve
# metadata and apply type registry of runtime of parent block
block_header = self.rpc_request('chain_getHeader', [self.block_hash])
if block_header['result'] is None:
raise BlockNotFound(f'Block not found for "{self.block_hash}"')
parent_block_hash = block_header['result']['parentHash']
if parent_block_hash == '0x0000000000000000000000000000000000000000000000000000000000000000':
runtime_block_hash = self.block_hash
else:
runtime_block_hash = parent_block_hash
runtime_info = self.get_block_runtime_version(block_hash=runtime_block_hash)
if runtime_info is None:
raise SubstrateRequestException(f"No runtime information for block '{block_hash}'")
# Check if runtime state already set to current block
if runtime_info.get("specVersion") == self.runtime_version:
return
self.runtime_version = runtime_info.get("specVersion")