forked from Gaunt/extractor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnem_extract.py
1075 lines (887 loc) · 37.1 KB
/
nem_extract.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
"""NEM Extractor Script"""
import argparse
import glob
import functools
import msgpack
import os
import pandas as pd
import re
import struct
import sys
from binascii import hexlify, unhexlify
from tqdm import tqdm
from state import XYMStateMap
from util import encode_address, public_key_to_address
# describe the fixed structure of block entity bytes for unpacking
HEADER_FORMAT = {
'size': 'I',
'reserved_1': 'I',
'signature': '64s',
'signer_public_key': '32s',
'reserved_2': 'I',
'version': 'B',
'network': 'B',
'type': '2s',
'height': 'Q',
'timestamp': 'Q',
'difficulty': 'Q',
'generation_hash_proof': '80s',
'previous_block_hash': '32s',
'transactions_hash': '32s',
'receipts_hash': '32s',
'state_hash': '32s',
'beneficiary_address': '24s',
'fee_multiplier': 'I'}
HEADER_LEN = 372
DB_OFFSET_BYTES = 800
FOOTER_FORMAT = {
'reserved': 'I'}
FOOTER_LEN = 4
IMPORTANCE_FOOTER_FORMAT = {
'voting_eligible_accounts_count': 'I',
'harvesting_eligible_accounts_count': 'Q',
'total_voting_balance': 'Q',
'previous_importance_block_hash': '32s'}
IMPORTANCE_FOOTER_LEN = 52
TX_H_FORMAT = {
'size': 'I',
'reserved_1': 'I',
'signature': '64s',
'signer_public_key': '32s',
'reserved_2': 'I',
'version': 'B',
'network': 'B',
'type': '2s',
'max_fee': 'Q',
'deadline': 'Q',}
TX_H_LEN = 128
EMBED_TX_H_FORMAT = {
'size': 'I',
'reserved_1': 'I',
'signer_public_key': '32s',
'reserved_2': 'I',
'version': 'B',
'network': 'B',
'type': '2s',}
EMBED_TX_H_LEN = 48
SUBCACHE_MERKLE_ROOT_FORMAT = {
'account_state': '32s',
'namespace': '32s',
'mosaic': '32s',
'multisig': '32s',
'hash_lock_info': '32s',
'secret_lock_info': '32s',
'account_restriction': '32s',
'mosaic_restriction': '32s',
'metadata': '32s'}
TX_HASH_FORMAT = {
'entity_hash': '32s',
'merkle_component_hash': '32s'}
TX_HASH_LEN = 64
RECEIPT_SOURCE_FORMAT = {
'primary_id': 'I',
'secondary_id': 'I'}
RECEIPT_SOURCE_LEN = 8
RECEIPT_FORMAT = {
'size': 'I',
'version': 'H',
'type': 'H'}
RECEIPT_LEN = 8
ADDRESS_RESOLUTION_FORMAT = {
'primary_id': 'I',
'secondary_id': 'I',
'resolved': '24s' }
ADDRESS_RESOLUTION_LEN = 32
MOSAIC_RESOLUTION_FORMAT = {
'primary_id': 'I',
'secondary_id': 'I',
'resolved': 'Q' }
MOSAIC_RESOLUTION_LEN = 16
TX_NAME_MAP = {
b'414c': 'Account Key Link',
b'424c': 'Node Key Link',
b'4141': 'Aggregate Complete',
b'4241': 'Aggregate Bonded',
b'4143': 'Voting Key Link',
b'4243': 'Vrf Key Link',
b'414d': 'Mosaic Definition',
b'424d': 'Mosaic Supply Change',
b'414e': 'Namespace Registration',
b'424e': 'Address Alias',
b'434e': 'Mosaic Alias',
b'4144': 'Account Metadata',
b'4244': 'Mosaic Metadata',
b'4344': 'Namespace Metadata',
b'4155': 'Multisig Account Modification',
b'4148': 'Hash Lock',
b'4152': 'Secret Lock',
b'4252': 'Secret Proof',
b'4150': 'Account Address Restriction',
b'4250': 'Account Mosaic Restriction',
b'4350': 'Account Operation Restriction',
b'4151': 'Mosaic Global Restriction',
b'4251': 'Mosaic Address Restriction',
b'4154': 'Transfer'}
def fmt_unpack(buffer,struct_format):
"""Unpack buffer of bytes into dict based on format specification"""
return dict(
zip(
struct_format.keys(),
struct.unpack('<'+''.join(struct_format.values()),buffer)
)
)
def deserialize_header(header_data):
"""Produce a python dict from a raw xym header blob
Parameters
----------
header_data : bytes
Byte array containing serialized header
Returns
-------
header: dict
Dict containing block header field keys and primitive or bytes values
"""
header = fmt_unpack(header_data,HEADER_FORMAT)
for k,v in HEADER_FORMAT.items():
if k == 'type':
header[k] = hexlify(header[k][::-1])
elif k == 'beneficiary_address':
header[k] = encode_address(header[k])
elif v[-1] == 's':
header[k] = hexlify(header[k])
header['harvester'] = public_key_to_address(unhexlify(header['signer_public_key']))
return header
def deserialize_footer(footer_data,header):
"""Produce a nested python dict from a raw xym footer blob
Parameters
----------
footer_data : bytes
Byte array containing serialized footer
header: dict
Deserialized header dict as produced by :func:`deserialize_header`
Returns
-------
footer: dict
Dict containing block footer field keys and primitive or bytes values
as well as a list of deserialized transaction dicts
"""
# parse static footer fields
if header['type'] == b'8043': #nemesis
footer = fmt_unpack(footer_data[:IMPORTANCE_FOOTER_LEN],IMPORTANCE_FOOTER_FORMAT)
i = IMPORTANCE_FOOTER_LEN
elif header['type'] == b'8143': #normal
footer = fmt_unpack(footer_data[:FOOTER_LEN],FOOTER_FORMAT)
i = FOOTER_LEN
elif header['type'] == b'8243': #importance
footer = fmt_unpack(footer_data[:IMPORTANCE_FOOTER_LEN],IMPORTANCE_FOOTER_FORMAT)
i = IMPORTANCE_FOOTER_LEN
else:
raise ValueError(f"Unknown Block Type Encountered: {header['type']}")
# parse transactions
tx_data = []
tx_count = 0
statement_count = 0
total_fee = 0
while i < len(footer_data):
tx_header = fmt_unpack(footer_data[i:i+TX_H_LEN],TX_H_FORMAT)
tx_header['id'] = statement_count + 1 #tx ids are 1-based
tx_header['signature'] = hexlify(tx_header['signature'])
tx_header['signer_public_key'] = hexlify(tx_header['signer_public_key'])
tx_header['type'] = hexlify(tx_header['type'][::-1])
tx_header['payload'] = deserialize_tx_payload(footer_data[i+TX_H_LEN:i+tx_header['size']],tx_header['type'])
tx_data.append(tx_header)
total_fee += min(tx_header['max_fee'],tx_header['size'] * header['fee_multiplier'])
tx_count += (1+tx_header['payload']['embedded_tx_count']) if 'embedded_tx_count' in tx_header['payload'] else 1
statement_count += 1
i += tx_header['size'] + (8 - tx_header['size']) %8
footer['total_fee'] = total_fee
footer['statement_count'] = statement_count
footer['tx_count'] = tx_count
footer['transactions'] = tx_data
return footer
def deserialize_tx_payload(payload_data,payload_type):
"""Produce a nested python dict from a raw xym statemet payload
Parameters
----------
payload_data : bytes
Byte array containing serialized tx payload
payload_type: bytes
Byte array containing the hex representation of the type field from
the transaction header associated with payload
Returns
-------
payload: dict
Dict containing tx payload field keys and primitive or bytes values. In
the case of aggregate transactions, will include a list containing dict
representations of deserialized embedded transactions.
"""
#Account Link
if payload_type == b'414c': #AccountKeyLinkTransaction
schema = {
'linked_public_key' : '32s',
'link_action' : 'B'
}
payload = fmt_unpack(payload_data,schema)
elif payload_type == b'424c': #NodeKeyLinkTransaction
schema = {
'linked_public_key' : '32s',
'link_action' : 'B'
}
payload = fmt_unpack(payload_data,schema)
# Aggregate
elif payload_type == b'4141': #AggregateCompleteTransaction
schema = {
'transactions_hash' : '32s',
'payload_size' : 'I',
'aggregate_complete_transaction_reserved_1' : 'I'
}
i = 40
payload = fmt_unpack(payload_data[:i],schema)
e_tx_count = 0
e_tx_data = []
while i < 8 + payload['payload_size']:
e_tx_header = fmt_unpack(payload_data[i:i+EMBED_TX_H_LEN],EMBED_TX_H_FORMAT)
e_tx_header['id'] = e_tx_count + 1 #tx ids are 1-based
e_tx_header['signer_public_key'] = hexlify(e_tx_header['signer_public_key'])
e_tx_header['type'] = hexlify(e_tx_header['type'][::-1])
e_tx_header['payload'] = deserialize_tx_payload(payload_data[i+EMBED_TX_H_LEN:i+e_tx_header['size']],e_tx_header['type'])
e_tx_data.append(e_tx_header)
e_tx_count += 1
i += e_tx_header['size'] + (8 - e_tx_header['size']) %8
payload['embedded_tx_count'] = e_tx_count
payload['embedded_transactions'] = e_tx_data
payload['cosignatures'] = payload_data[i:]
elif payload_type == b'4241': #AggregateBondedTransaction
schema = {
'transactions_hash' : '32s',
'payload_size' : 'I',
'aggregate_complete_transaction_reserved_1' : 'I'
}
i = 40
payload = fmt_unpack(payload_data[:i],schema)
e_tx_count = 0
e_tx_data = []
while i < 8 + payload['payload_size']:
e_tx_header = fmt_unpack(payload_data[i:i+EMBED_TX_H_LEN],EMBED_TX_H_FORMAT)
e_tx_header['id'] = e_tx_count + 1 #tx ids are 1-based
e_tx_header['signer_public_key'] = hexlify(e_tx_header['signer_public_key'])
e_tx_header['type'] = hexlify(e_tx_header['type'][::-1])
e_tx_header['payload'] = deserialize_tx_payload(payload_data[i+EMBED_TX_H_LEN:i+e_tx_header['size']],e_tx_header['type'])
e_tx_data.append(e_tx_header)
e_tx_count += 1
i += e_tx_header['size'] + (8 - e_tx_header['size']) %8
payload['embedded_tx_count'] = e_tx_count
payload['embedded_transactions'] = e_tx_data
payload['cosignatures'] = payload_data[i:]
#Core
elif payload_type == b'4143': #VotingKeyLinkTransaction
schema = {
'linked_public_key' : '32s',
'start_point' : 'I',
'end_point' : 'I',
'link_action' : 'B'
}
payload = fmt_unpack(payload_data,schema)
elif payload_type == b'4243': #VrfKeyLinkTransaction
schema = {
'linked_public_key' : '32s',
'link_action' : 'B'
}
payload = fmt_unpack(payload_data,schema)
#Mosaic
elif payload_type == b'414d': #MosaicDefinitionTransaction
schema = {
'id' : 'Q',
'duration' : 'Q',
'nonce' : 'I',
'flags' : 'B',
'divisibility' : 'B'
}
payload = fmt_unpack(payload_data,schema)
elif payload_type == b'424d': #MosaicSupplyChangeTransaction
schema = {
'mosaic_id' : 'Q',
'delta' : 'Q',
'action' : 'B',
}
payload = fmt_unpack(payload_data,schema)
#Namespace
elif payload_type == b'414e': #NamespaceRegistrationTransaction
schema = {
'identifier' : 'Q',
'id' : 'Q',
'registration_type' : 'B',
'name_size' : 'B',
}
payload = fmt_unpack(payload_data[:18],schema)
payload['name'] = payload_data[18:]
if payload['registration_type'] == 0:
payload['duration'] = payload['identifier']
elif payload['registration_type'] == 1:
payload['parent_id'] = payload['identifier']
else:
raise ValueError(f'Unknown registration type for Namespace RegistrationTransaction: {payload["registration_type"]}')
del payload['identifier']
elif payload_type == b'424e': #AddressAliasTransaction
schema = {
'namespace_id' : 'Q',
'address' : '24s',
'alias_action' : 'B'
}
payload = fmt_unpack(payload_data,schema)
elif payload_type == b'434e': #MosaicAliasTransaction
schema = {
'namespace_id' : 'Q',
'mosaid_id' : 'Q',
'alias_action' : 'B'
}
payload = fmt_unpack(payload_data,schema)
#Metadata
elif payload_type == b'4144': #AccountMetadataTransaction
schema = {
'target_address' : '24s',
'scoped_metadata_key' : 'Q',
'value_size_delta': 'H',
'value_size': 'H',
}
payload = fmt_unpack(payload_data[:36],schema)
payload['target_address'] = encode_address(payload['target_address'])
payload['value'] = payload_data[36:]
elif payload_type == b'4244': #MosaicMetadataTransaction
schema = {
'target_address' : '24s',
'scoped_metadata_key' : 'Q',
'target_mosaic_id' : 'Q',
'value_size_delta': 'H',
'value_size': 'H',
}
payload = fmt_unpack(payload_data[:44],schema)
payload['target_address'] = encode_address(payload['target_address'])
payload['value'] = payload_data[44:]
elif payload_type == b'4344': #NamespaceMetadataTransaction
schema = {
'target_address' : '24s',
'scoped_metadata_key' : 'Q',
'target_namespace_id' : 'Q',
'value_size_delta': 'H',
'value_size': 'H',
}
payload = fmt_unpack(payload_data[:44],schema)
payload['target_address'] = encode_address(payload['target_address'])
payload['value'] = payload_data[44:]
#Multisignature
elif payload_type == b'4155': #MultisigAccountModificationTransaction
schema = {
'min_removal_delta' : 'B',
'min_approval_delta' : 'b',
'address_additions_count' : 'B',
'address_deletions_count' : 'B',
'multisig_account_modificaion_transacion_body_reserved_1' : 'I'
}
payload = fmt_unpack(payload_data[:8],schema)
i = 8
if payload['address_additions_count'] > 0:
payload['address_additions'] = struct.unpack('<' + '24s'*payload['address_additions_count'], payload_data[i:i+payload['address_additions_count']*24])
i += payload['address_additions_count']*24
else: payload['address_additions'] = []
if payload['address_deletions_count'] > 0:
payload['address_deletions'] = struct.unpack('<' + '24s'*payload['address_deletions_count'], payload_data[i:i+payload['address_deletions_count']*24])
else: payload['address_deletions'] = []
#Hash Lock
elif payload_type == b'4148': #HashLockTransaction
schema = {
'reserved_1' : '8s', # NOT in the schema but shows up in the data ?!?
'mosaic' : 'Q',
'duration' : 'Q',
'hash' : '32s'
}
payload = fmt_unpack(payload_data,schema)
#Secret Lock
elif payload_type == b'4152': #SecretLockTransaction
schema = {
'recipient_address' : '24s',
'secret' : '32s',
'mosaic_id' : 'Q',
'amount' : 'Q',
'duration' : 'Q',
'hash_algorithm' : 'B'
}
payload = fmt_unpack(payload_data,schema)
payload['recipient_address'] = encode_address(payload['recipient_address'])
elif payload_type == b'4252': #SecretProofTransaction
schema = {
'recipient_address' : '24s',
'secret' : '32s',
'proof_size' : 'H',
'hash_algorithm' : 'B',
}
payload = fmt_unpack(payload_data[:59],schema)
payload['recipient_address'] = encode_address(payload['recipient_address'])
payload['proof'] = payload_data[59:]
#Account restriction
elif payload_type == b'4150': #AccountAddressRestrictionTransaction
schema = {
'restriction_type' : 'H',
'restriction_additions_count' : 'B',
'restriction_deletions_count' : 'B',
'account_restriction_transaction_body_reserved_1' : 'I',
}
payload = fmt_unpack(payload_data[:8],schema)
i = 8
if payload['restriction_additions_count'] > 0:
payload['restriction_additions'] = struct.unpack('<' + '24s'*payload['restriction_additions_count'], payload_data[i:i+payload['restriction_additions_count']*24])
i += payload['restriction_additions_count']*24
else: payload['restriction_additions'] = []
if payload['restriction_deletions_count'] > 0:
payload['restriction_deletions'] = struct.unpack('<' + '24s'*payload['restriction_deletions_count'], payload_data[i:i+payload['restriction_deletions_count']*24])
else: payload['restriction_deletions'] = []
elif payload_type == b'4250': #AccountMosaicRestrictionTransaction
schema = {
'restriction_type' : 'H',
'restriction_additions_count' : 'B',
'restriction_deletions_count' : 'B',
'account_restriction_transaction_body_reserved_1' : 'I',
}
payload = fmt_unpack(payload_data[:8],schema)
i = 8
if payload['restriction_additions_count'] > 0:
payload['restriction_additions'] = struct.unpack('<' + 'Q'*payload['restriction_additions_count'], payload_data[i:i+payload['restriction_additions_count']*8])
i += payload['restriction_additions_count']*8
else: payload['restriction_additions'] = []
if payload['restriction_deletions_count'] > 0:
payload['restriction_deletions'] = struct.unpack('<' + 'Q'*payload['restriction_deletions_count'], payload_data[i:i+payload['restriction_deletions_count']*8])
else: payload['restriction_deletions'] = []
elif payload_type == b'4350': #AccountOperationRestrictionTransaction
schema = {
'restriction_type' : 'H',
'restriction_additions_count' : 'B',
'restriction_deletions_count' : 'B',
'account_restriction_transaction_body_reserved_1' : 'I',
}
payload = fmt_unpack(payload_data[:8],schema)
i = 8
if payload['restriction_additions_count'] > 0:
payload['restriction_additions'] = struct.unpack('<' + '2s'*payload['restriction_additions_count'], payload_data[i:i+payload['restriction_additions_count']*2])
i += payload['restriction_additions_count']*2
else: payload['restriction_additions'] = []
if payload['restriction_deletions_count'] > 0:
payload['restriction_deletions'] = struct.unpack('<' + '2s'*payload['restriction_deletions_count'], payload_data[i:i+payload['restriction_deletions_count']*24])
else: payload['restriction_deletions'] = []
#Mosaic restriction
elif payload_type == b'4151': #MosaicGlobalRestrictionTransaction
schema = {
'mosaic_id' : 'Q',
'reference_mosaic_id' : 'Q',
'restriction_key' : 'Q',
'previous_restriction_value' : 'Q',
'new_restriction_value' : 'Q',
'previous_restriction_type' : 'B',
'new_restriction_type' : 'B'
}
payload = fmt_unpack(payload_data,schema)
elif payload_type == b'4251': #MosaicAddressRestrictionTransaction
schema = {
'mosaic_id' : 'Q',
'restriction_key' : 'Q',
'previous_restriction_value' : 'Q',
'new_restriction_value' : 'Q',
'target_address' : '24s'
}
payload = fmt_unpack(payload_data,schema)
payload['target_address'] = encode_address(payload['target_address'])
#Transfer
elif payload_type == b'4154': #TransferTransaction
schema = {
'recipient_address' : '24s',
'message_size' : 'H',
'mosaics_count' : 'B',
'transfer_transaction_body_reserved_1' : 'I',
'transfer_transaction_body_reserved_2' : 'B',
}
payload = fmt_unpack(payload_data[:32],schema)
i = 32
payload['mosaics'] = []
for _ in range(payload['mosaics_count']):
mosaic = {}
mosaic['mosaic_id'] = struct.unpack('<Q',payload_data[i:i+8])[0]
mosaic['amount'] = struct.unpack('<Q',payload_data[i+8:i+16])[0]
payload['mosaics'].append(mosaic)
i += 16
payload['message'] = payload_data[-payload['message_size']:]
payload['recipient_address'] = encode_address(payload['recipient_address'])
else:
raise ValueError(f"Unknown Tx payload type encountered: {payload_type}")
return payload
def deserialize_receipt_payload(receipt_data,receipt_type):
"""Produce a nested python dict from a raw receipt payload
Parameters
----------
receipt_data : bytes
Byte array containing serialized receipt payload
receipt_type: bytes
Byte array containing the hex representation of the type field from
the receipt header
Returns
-------
receipt: dict
Dict containing receipt payload field keys and primitive or bytes values
"""
# Reserved
if receipt_type == 0x0000: # reserved receipt
payload = None
# Balance Transfer
elif receipt_type == 0x124D: # mosaic rental fee receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
'sender_address' : '24s',
'recipient_address' : '24s'
}
payload = fmt_unpack(receipt_data,schema)
payload['sender_address'] = encode_address(payload['sender_address'])
payload['recipient_address'] = encode_address(payload['recipient_address'])
elif receipt_type == 0x134E: # namespace rental fee receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
'sender_address' : '24s',
'recipient_address' : '24s'
}
payload = fmt_unpack(receipt_data,schema)
payload['sender_address'] = encode_address(payload['sender_address'])
payload['recipient_address'] = encode_address(payload['recipient_address'])
# Balance Change (Credit)
elif receipt_type == 0x2143: # harvest fee receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
'target_address' : '24s',
}
payload = fmt_unpack(receipt_data,schema)
payload['target_address'] = encode_address(payload['target_address'])
elif receipt_type == 0x2248: # lock hash completed receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
'target_address' : '24s',
}
payload = fmt_unpack(receipt_data,schema)
payload['target_address'] = encode_address(payload['target_address'])
elif receipt_type == 0x2348: # lock hash expired receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
'target_address' : '24s',
}
payload = fmt_unpack(receipt_data,schema)
payload['target_address'] = encode_address(payload['target_address'])
elif receipt_type == 0x2252: # lock secret completed receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
'target_address' : '24s',
}
payload = fmt_unpack(receipt_data,schema)
payload['target_address'] = encode_address(payload['target_address'])
elif receipt_type == 0x2352: # lock secret expired receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
'target_address' : '24s',
}
payload = fmt_unpack(receipt_data,schema)
payload['target_address'] = encode_address(payload['target_address'])
# Balance Change (Debit)
elif receipt_type == 0x3148: # lock hash created receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
'target_address' : '24s',
}
payload = fmt_unpack(receipt_data,schema)
payload['target_address'] = encode_address(payload['target_address'])
elif receipt_type == 0x3152: # lock secret created receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
'target_address' : '24s',
}
payload = fmt_unpack(receipt_data,schema)
payload['target_address'] = encode_address(payload['target_address'])
# Artifact Expiry
elif receipt_type == 0x414D: # mosaic expired receipt
schema = {
'mosaic_id' : 'Q'
}
payload = fmt_unpack(receipt_data,schema)
elif receipt_type == 0x414E: # namespace expired receipt
schema = {
'mosaic_id' : 'Q'
}
payload = fmt_unpack(receipt_data,schema)
elif receipt_type == 0x424E: # namespace deleted receipt
schema = {
'mosaic_id' : 'Q'
}
payload = fmt_unpack(receipt_data,schema)
# Inflation
elif receipt_type == 0x5143: # inflation receipt
schema = {
'mosaic_id' : 'Q',
'amount' : 'Q',
}
payload = fmt_unpack(receipt_data,schema)
# Transaction Statement
elif receipt_type == 0xE143: # transaction group receipt
receipt_source = fmt_unpack(receipt_data[:RECEIPT_SOURCE_LEN], RECEIPT_SOURCE_FORMAT)
i = RECEIPT_SOURCE_LEN
receipt_count = struct.unpack("<I", receipt_data[i:i+4])[0]
i += 4
payload = {'receipt_source': receipt_source, 'receipts': [] }
for k in range(receipt_count):
receipt = fmt_unpack(receipt_data[i:i + RECEIPT_LEN], RECEIPT_FORMAT)
receipt['payload'] = deserialize_receipt_payload(receipt_data[i + RECEIPT_LEN:i + receipt['size']],receipt['type'])
i += receipt['size']
payload['receipts'].append(receipt)
else:
raise ValueError(f"Unknown receipt payload type encountered: {hex(receipt_type)}")
return payload
def deserialize_transaction_statements(stmt_data, i):
"""Produce a list of statements from a buffer of transaction statement data
Parameters
----------
stmt_data : bytes
Byte array containing serialized transaction statements
i: int
Starting index into byte array
Returns
-------
i: int
Final index value after deserializing transaction statements
statements: list
List of dicts containing deserialized transaction statements
"""
count = struct.unpack("<I", stmt_data[i:i+4])
i += 4
statements = []
for j in range(count[0]):
receipt_source = fmt_unpack(stmt_data[i:i + RECEIPT_SOURCE_LEN], RECEIPT_SOURCE_FORMAT)
i += RECEIPT_SOURCE_LEN
receipt_count = struct.unpack("<I", stmt_data[i:i+4])[0]
i += 4
statement = { 'receipt_source': receipt_source, 'receipts': [] }
for k in range(receipt_count):
receipt = fmt_unpack(stmt_data[i:i + RECEIPT_LEN], RECEIPT_FORMAT)
receipt['payload'] = deserialize_receipt_payload(stmt_data[i + RECEIPT_LEN:i + receipt['size']],receipt['type'])
i += receipt['size']
statement['receipts'].append(receipt)
statements.append(statement)
return i, statements
def deserialize_address_resolution_statements(stmt_data, i):
"""Produce a list of statements from a buffer of address resolution data
Parameters
----------
stmt_data : bytes
Byte array containing serialized address resolution statements
i: int
Starting index into byte array
Returns
-------
i: int
Final index value after deserializing address resolution statements
statements: list
List of dicts containing deserialized address resolution statements
"""
count = struct.unpack("<I", stmt_data[i:i+4])
i += 4
statements = []
for j in range(count[0]):
key = struct.unpack('24s', stmt_data[i:i+24])[0]
i += 24
resolution_count = struct.unpack("<I", stmt_data[i:i+4])[0]
i += 4
statement = { 'key': key, 'resolutions': [] }
for k in range(resolution_count):
address_resolution = fmt_unpack(stmt_data[i:i + ADDRESS_RESOLUTION_LEN], ADDRESS_RESOLUTION_FORMAT)
i += ADDRESS_RESOLUTION_LEN
statement['resolutions'].append(address_resolution)
statements.append(statement)
return i, statements
def deserialize_mosaic_resolution_statements(stmt_data, i):
"""Produce a list of statements from a buffer of mosaic resolution data
Parameters
----------
stmt_data : bytes
Byte array containing serialized mosaic resolution statements
i: int
Starting index into byte array
Returns
-------
i: int
Final index value after deserializing mosaic resolution statements
statements: list
List of dicts containing deserialized mosaic resolution statements
"""
count = struct.unpack("<I", stmt_data[i:i+4])
i += 4
statements = []
for j in range(count[0]):
key = struct.unpack('<Q', stmt_data[i:i+8])[0]
i += 8
resolution_count = struct.unpack("<I", stmt_data[i:i+4])[0]
i += 4
statement = { 'key': key, 'resolutions': [] }
for k in range(resolution_count):
mosaic_resolution = fmt_unpack(stmt_data[i:i + MOSAIC_RESOLUTION_LEN], MOSAIC_RESOLUTION_FORMAT)
i += MOSAIC_RESOLUTION_LEN
statement['resolutions'].append(mosaic_resolution)
statements.append(statement)
return i, statements
def get_statement_paths(statement_extension='.stmt', block_dir='./data'):
"""Collect a list of valid statement paths for analysis"""
statement_paths = glob.glob(os.path.join(block_dir,'**','*'+statement_extension),recursive=True)
statement_format_pattern = re.compile('[0-9]{5}'+statement_extension)
statement_paths = sorted(list(filter(lambda x: statement_format_pattern.match(os.path.basename(x)),statement_paths)))
return statement_paths
def deserialize_statements(statement_paths, db_offset_bytes=DB_OFFSET_BYTES):
"""Generator accepting statement paths and yielding deserialization results
Parameters
----------
statement_paths: list[str]
List of files containing statements to be deserialized
db_offset_bytes: int, optional
Number of pad bytes to be ignored at the head of each serialized
statement file
Yields
------
stmt_height: int
Block height of yielded statements
statements: dict
Data for transaction, address resolution, and mosaic resolution statements
path: str
File from which statements were deserialized
"""
stmt_height = 0
statement_paths_ = tqdm(statement_paths)
for path in statement_paths_:
statements = {
'transaction_statements':{},
'address_resolution_statements': {},
'mosaic_resolution_statements': {}
}
statement_paths_.set_description(f"processing statement file: {path}")
with open(path,mode='rb') as f:
stmt_data = f.read()
i = db_offset_bytes
while i < len(stmt_data):
# TODO: statement deserialization can probably be inlined efficiently or at least aggregated into one function
i, transaction_statements = deserialize_transaction_statements(stmt_data, i)
i, address_resolution_statements = deserialize_address_resolution_statements(stmt_data, i)
i, mosaic_resolution_statements = deserialize_mosaic_resolution_statements(stmt_data, i)
stmt_height += 1
statements['transaction_statements'] = transaction_statements
statements['address_resolution_statements'] = address_resolution_statements
statements['mosaic_resolution_statements'] = mosaic_resolution_statements
yield stmt_height, statements, path
def get_block_stats(block):
"""Extract summary data from a block and flatten for tabular manipulation"""
data = block['header'].copy()
data['statement_count'] = block['footer']['statement_count']
data['tx_count'] = block['footer']['tx_count']
data['total_fee'] = block['footer']['total_fee']
return data
def main(args):
block_format_pattern = re.compile('[0-9]{5}'+args.block_extension)
block_paths = glob.glob(os.path.join(args.block_dir,'**','*'+args.block_extension),recursive=True)
block_paths = tqdm(sorted(list(filter(lambda x: block_format_pattern.match(os.path.basename(x)),block_paths))))
blocks = []
for path in block_paths:
block_paths.set_description(f"processing block file: {path}")
with open(path,mode='rb') as f:
blk_data = f.read()
i = args.db_offset_bytes
while i < len(blk_data):
# get fixed length data
header = deserialize_header(blk_data[i:i+HEADER_LEN])
footer = deserialize_footer(blk_data[i+HEADER_LEN:i+header['size']],header)
i += header['size']
block_hash, generation_hash = struct.unpack('<32s32s',blk_data[i:i+64])
i += 64
# get transaction hashes
num_tx_hashes = struct.unpack('I',blk_data[i:i+4])[0]
i += 4
tx_hashes = None
if args.save_tx_hashes:
tx_hashes = []
for _ in range(num_tx_hashes):
tx_hashes.append(fmt_unpack(blk_data[i:i+TX_HASH_LEN],TX_HASH_FORMAT))
i += TX_HASH_LEN
else:
i += num_tx_hashes * TX_HASH_LEN
# get sub cache merkle roots
root_hash_len = struct.unpack('I',blk_data[i:i+4])[0] * 32
i += 4
merkle_roots = None
if args.save_subcache_merkle_roots:
merkle_roots = fmt_unpack(blk_data[i:i+root_hash_len],SUBCACHE_MERKLE_ROOT_FORMAT)
i += root_hash_len
blocks.append({
'header':header,
'footer':footer,
'block_hash':block_hash,
'tx_hashes':tx_hashes,
'subcache_merkle_roots':merkle_roots
})