-
Notifications
You must be signed in to change notification settings - Fork 1
/
erigon_extract.c
2785 lines (2514 loc) · 79.1 KB
/
erigon_extract.c
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
/*
* erigon_extract: ETL for Nimbus-eth1 full state
* Reads an Erigon database, writes an DB file for Nimbus-eth1.
*
* Copyright (C) 2021, 2022 Jamie Lokier
*
* This file is licensed under either of "MIT license" or "Apache License,
* Version 2.0", at your option. Links to each license respectively:
* - <http://opensource.org/licenses/MIT>
* - <http://www.apache.org/licenses/LICENSE-2.0>.
*
* This file is provided without any warranty. Use at your own risk. It is
* intended that excerpts be used and changed in other programs, subject to the
* terms of the one or both of the above licenses.
*/
#include "mdbx.h"
#include <ctype.h>
#include <stdarg.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#if CALCULATE_KECCAK256
#if 0
/* https://github.com/brainhub/SHA3IUF */
#include "SHA3IUF/sha3.h"
#include "SHA3IUF/sha3.c"
static inline keccak256(byte *hash, const byte *input, size_t length)
{
sha3_context ctx;
sha3_Init256(&ctx);
sha3_SetFlags(&ctx, SHA3_FLAGS_KECCAK);
sha3_Update(&ctx, input, length);
const void *h = sha3_Finalize(&ctx);
memcpy(hash, h, 32);
}
#else
/*
* https://github.com/firefly/wallet
* About 1.2 microseconds per short hash on my system.
*/
#include "wallet/source/libs/ethers/src/keccak256.h"
#include "wallet/source/libs/ethers/src/keccak256.c"
static inline keccak256(byte *hash, const byte *input, size_t length)
{
SHA3_CTX ctx;
keccak_init(&ctx);
keccak_update(&ctx, input, length);
byte hash[32];
keccak_final(&ctx, hash);
}
#endif
#endif
static volatile sig_atomic_t stop_flag;
static void signal_handler(int sig)
{
stop_flag = 1;
}
static void setup_signal_handler(void)
{
signal(SIGPIPE, signal_handler);
signal(SIGHUP, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
}
typedef uint8_t byte;
static const char hex_chars[] = "0123456789abcdef";
static void print_bytes(const char *bytes, size_t start, size_t end)
{
while (start < end) {
byte b = bytes[start++];
putchar(hex_chars[(b >> 4) & 0x0f]);
putchar(hex_chars[b & 0x0f]);
}
}
static void print_number(const char *bytes, size_t start, size_t end)
{
while (start < end) {
if (bytes[start] != 0)
break;
start++;
}
if (start >= end) {
putchar('0');
} else if ((bytes[start] >> 4) == 0) {
putchar(hex_chars[bytes[start] & 0x0f]);
start++;
}
print_bytes(bytes, start, end);
}
static void print_mdbx_val(MDBX_val *v)
{
putchar(' ');
print_bytes(v->iov_base, 0, v->iov_len);
putchar('\n');
}
bool opt_verbose = true, opt_print = false;
const char *prog;
#define PRINT opt_print
#define CODE_PAGE_PADDING 0 /* Single value 0 */
#define CODE_BLOCK_NUMBER 1 /* Range 1..8 */
#define CODE_ADDRESS 9 /* Single value 9 */
#define CODE_ACCOUNT 10 /* Range 10..73 */
#define CODE_STORAGE 74 /* Range 74..249 */
#define CODE_INCARNATION 250 /* Single value 250 */
#define CODE_BLOCK_INLINE 251 /* Range 251..255 */
static void error(const char *func, int rc)
{
if (opt_verbose)
fprintf(stderr, "%s: %s() error %d %s\n", prog, func, rc,
mdbx_strerror(rc));
}
static uint64_t get64be(const byte *bytes)
{
uint64_t result = 0;
result = (result << 8) + *(const uint8_t *)bytes++;
result = (result << 8) + *(const uint8_t *)bytes++;
result = (result << 8) + *(const uint8_t *)bytes++;
result = (result << 8) + *(const uint8_t *)bytes++;
result = (result << 8) + *(const uint8_t *)bytes++;
result = (result << 8) + *(const uint8_t *)bytes++;
result = (result << 8) + *(const uint8_t *)bytes++;
result = (result << 8) + *(const uint8_t *)bytes++;
return result;
}
static void put64be(byte *bytes, uint64_t value)
{
*bytes++ = (byte)(value >> 56);
*bytes++ = (byte)(value >> 48);
*bytes++ = (byte)(value >> 40);
*bytes++ = (byte)(value >> 32);
*bytes++ = (byte)(value >> 24);
*bytes++ = (byte)(value >> 16);
*bytes++ = (byte)(value >> 8);
*bytes++ = (byte)value;
}
static uint64_t get64be_len(const byte *bytes, size_t len)
{
uint64_t result = 0;
for (size_t i = 0; i < 8 && i < len; i++)
result = (result << 8) + *(const uint8_t *)bytes++;
return result;
}
#define ADDRESS_LEN 20
#define BALANCE_LEN 32
#define HASH_LEN 32
#define SLOT_LEN 32
#define VALUE_LEN 32
#define BLOCK_LEN 8
#define INCARNATION_LEN 8
static const byte zero_balance[BALANCE_LEN] = { 0, };
static const byte zero_code_hash[HASH_LEN] = { 0, };
static const byte empty_code_hash[HASH_LEN] = {
0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2,
0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b,
0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70
};
struct ReaderItem {
byte address[ADDRESS_LEN];
uint64_t block;
bool is_storage;
};
struct Account {
struct ReaderItem item_base;
uint64_t nonce, incarnation;
byte balance[BALANCE_LEN], codeHash[HASH_LEN];
};
struct Storage {
struct ReaderItem item_base;
byte slot[HASH_LEN], value[VALUE_LEN];
uint64_t incarnation;
};
static int decode_account(const byte *account_bytes, size_t account_len,
MDBX_txn *txn, MDBX_dbi dbi_codeHash,
uint64_t block, const byte address[ADDRESS_LEN],
struct Account *account)
{
int rc;
byte fieldset = 0;
size_t pos = 0;
*account = (struct Account){
.item_base.is_storage = false,
.item_base.block = block,
.nonce = 0,
.incarnation = 0,
.balance = { 0, },
.codeHash = { 0, },
};
memcpy(account->item_base.address, address, ADDRESS_LEN);
if (account_len >= 1)
fieldset = account_bytes[pos++];
if (fieldset & 1) {
if (pos >= account_len)
goto err_decoding;
size_t item_len = account_bytes[pos++];
if (pos + item_len > account_len || item_len > 8)
goto err_decoding;
account->nonce = get64be_len(account_bytes + pos, item_len);
pos += item_len;
}
if (fieldset & 2) {
if (pos >= account_len)
goto err_decoding;
size_t item_len = account_bytes[pos++];
if (pos + item_len > account_len || item_len > BALANCE_LEN)
goto err_decoding;
if (item_len > 0)
memcpy(account->balance + (BALANCE_LEN - item_len), account_bytes + pos, item_len);
pos += item_len;
}
if (fieldset & 4) {
if (pos >= account_len)
goto err_decoding;
size_t item_len = account_bytes[pos++];
if (pos + item_len > account_len || item_len > 8)
goto err_decoding;
account->incarnation = get64be_len(account_bytes + pos, item_len);
pos += item_len;
}
if (fieldset & 8) {
if (pos >= account_len)
goto err_decoding;
size_t item_len = account_bytes[pos++];
if (pos + item_len > account_len || item_len != HASH_LEN)
goto err_decoding;
memcpy(account->codeHash, account_bytes + pos, item_len);
pos += item_len;
}
if (fieldset & 0xf0)
goto err_decoding;
if (pos != account_len)
goto err_decoding;
if ((!(fieldset & 8)
|| 0 == memcmp(account->codeHash, empty_code_hash, HASH_LEN)
|| 0 == memcmp(account->codeHash, zero_code_hash, HASH_LEN))
&& account->incarnation != 0) {
byte lookup_code_hash[28];
memcpy(lookup_code_hash, address, ADDRESS_LEN);
put64be(lookup_code_hash + ADDRESS_LEN, account->incarnation);
MDBX_val key, data;
key.iov_base = lookup_code_hash;
key.iov_len = sizeof(lookup_code_hash);
rc = mdbx_get(txn, dbi_codeHash, &key, &data);
if (rc == MDBX_SUCCESS) {
// Erigon code doesn't strictly say this, but the value
// should be exactly 32 bytes.
if (data.iov_len != HASH_LEN) {
rc = MDBX_INVALID;
goto err_codeHash;
}
memcpy(account->codeHash, data.iov_base, HASH_LEN);
// Erigon code doesn't strictly check this, but the
// restored hash should not be all zeros or empty code.
if (0 == memcmp(account->codeHash, empty_code_hash, HASH_LEN)
|| 0 == memcmp(account->codeHash, zero_code_hash, HASH_LEN)){
goto err_decoding;
}
} else if (rc == MDBX_NOTFOUND) {
// NOTFOUND is fine and means don't replace the code hash.
} else {
goto err_codeHash;
}
}
// Erigon code doesn't strictly check this, but zero incarnation or
// empty code hash should be represented consistently as all zeros,
// never `empty_code_hash` in this format.
if (account->incarnation == 0
? 0 != memcmp(account->codeHash, zero_code_hash, HASH_LEN)
: 0 == memcmp(account->codeHash, empty_code_hash, HASH_LEN))
goto err_decoding;
return MDBX_SUCCESS;
err_decoding:
printf(" ** DECODING_ERROR Account address=");
print_bytes(address, 0, ADDRESS_LEN);
printf("\n blob=");
print_bytes(account_bytes, 0, account_len);
printf("\n");
fprintf(stderr, "Error decoding account\n");
return MDBX_INVALID;
err_codeHash:
printf(" ** MDBX_CODE_HASH_ERROR Account address=");
print_bytes(address, 0, ADDRESS_LEN);
printf("\n blob=");
print_bytes(account_bytes, 0, account_len);
error("mdbx_cursor_get PlainCodeHash", rc);
return rc;
}
static int decode_storage(const byte *storage_bytes, size_t storage_len,
uint64_t block, const byte address[ADDRESS_LEN],
uint64_t incarnation, struct Storage *storage)
{
if (storage_len < SLOT_LEN || storage_len > SLOT_LEN + VALUE_LEN)
goto err_decoding;
*storage = (struct Storage){
.item_base.is_storage = true,
.item_base.block = block,
.incarnation = incarnation,
};
memcpy(storage->item_base.address, address, ADDRESS_LEN);
memcpy(storage->slot, storage_bytes, SLOT_LEN);
if (storage_len < SLOT_LEN + VALUE_LEN)
memset(storage->value, 0, SLOT_LEN + VALUE_LEN - storage_len);
if (storage_len > SLOT_LEN)
memcpy(storage->value + (SLOT_LEN + VALUE_LEN - storage_len),
storage_bytes + SLOT_LEN, storage_len - SLOT_LEN);
return MDBX_SUCCESS;
err_decoding:
printf(" ** DECODING_ERROR Storage blob=");
print_bytes(storage_bytes, 0, storage_len);
printf("\n");
fprintf(stderr, "Error decoding storage\n");
return MDBX_INVALID;
}
#define T_RESET "\033[m"
#define T_DIM "\033[2m"
#define T_LABEL T_DIM
#define T_BLOCK "\033[31m"
#define T_ADDR "\033[34m"
#define T_SLOT "\033[35m"
#define T_CODE "\033[33m"
#define T_ACCOUNT "\033[1;34m"
#define T_STORAGE "\033[1;35m"
static void print_file_offset(off_t offset)
{
printf(T_DIM "(file offset=%llu offset=0x%llx)" T_RESET "\n",
(unsigned long long)offset, (unsigned long long)offset);
}
static void print_block_number(uint64_t block)
{
printf(T_DIM "(set block=%llu)" T_RESET "\n", (unsigned long long)block);
}
static void print_address(const byte address[ADDRESS_LEN])
{
printf(T_DIM "(set address=");
print_bytes(address, 0, ADDRESS_LEN);
printf(")" T_RESET "\n");
}
static void print_bytecode_incarnation(uint64_t bytecode_incarnation)
{
printf(T_DIM "(bytecode_incarnation=%llu)" T_RESET "\n",
(unsigned long long)bytecode_incarnation);
}
static void print_account(const struct Account *account)
{
printf(" " T_ACCOUNT "Account" T_RESET
T_LABEL " block=" T_RESET T_BLOCK "%llu" T_RESET
T_LABEL " address=" T_RESET T_ADDR,
(unsigned long long)account->item_base.block);
print_bytes(account->item_base.address, 0, ADDRESS_LEN);
printf(T_RESET "\n "
T_LABEL " inc=" T_RESET "%llu"
T_LABEL " nonce=" T_RESET "%llu"
T_LABEL " balance=" T_RESET,
(unsigned long long)account->incarnation,
(unsigned long long)account->nonce);
print_number(account->balance, 0, BALANCE_LEN);
printf(T_RESET T_LABEL " codeHash=" T_RESET T_CODE);
if (0 == memcmp(account->codeHash, empty_code_hash, HASH_LEN)
|| 0 == memcmp(account->codeHash, zero_code_hash, HASH_LEN)) {
printf("0");
} else {
print_bytes(account->codeHash, 0, HASH_LEN);
}
printf(T_RESET "\n");
}
static void print_storage(const struct Storage *storage)
{
printf(" " T_STORAGE "Storage" T_RESET
T_LABEL " block=" T_RESET T_BLOCK "%llu" T_RESET
T_LABEL " slot=" T_RESET T_ADDR,
(unsigned long long)storage->item_base.block);
print_bytes(storage->item_base.address, 0, ADDRESS_LEN);
printf(T_RESET "/" T_SLOT);
print_bytes(storage->slot, 0, sizeof(storage->slot));
printf(T_RESET "\n "
T_LABEL " inc=" T_RESET "%llu"
T_LABEL " value=" T_RESET,
(unsigned long long)storage->incarnation);
print_number(storage->value, 0, sizeof(storage->value));
printf("\n");
}
struct File {
FILE *file;
char *buffer;
char name[1];
};
static struct File *file_open(bool for_write, const char *format, ...)
{
struct File *file;
size_t file_name_size = 256;
while (1) {
file = malloc(offsetof(struct File, name) + file_name_size);
if (!file) {
perror("malloc");
errno = ENOMEM;
return NULL;
}
va_list ap;
va_start(ap, format);
size_t size = vsnprintf(file->name, file_name_size, format, ap);
va_end(ap);
if (size < file_name_size)
break;
free(file);
file_name_size *= 2;
}
/*
* Unlink the file if it already exists, so we can make "copies" by
* hard-linking, and this code won't truncate or overwrite them.
*/
if (for_write && unlink(file->name) != 0 && errno != ENOENT) {
int save_error = errno;
perror("unlink");
errno = save_error;
return NULL;
}
file->file = fopen(file->name, for_write ? "w" : "r");
if (!file->file) {
int save_error = errno;
perror("fopen");
fprintf(stderr, "fopen: %s: While opening %s\n",
strerror(errno), file->name);
free(file);
errno = save_error;
return NULL;
}
/* Larger file buffer for slightly faster reading/writing. */
const size_t buffer_size = 262144;
file->buffer = malloc(buffer_size);
if (!file->buffer) {
perror("malloc");
fclose(file->file);
free(file);
errno = ENOMEM;
return NULL;
}
if (setvbuf(file->file, file->buffer, _IOFBF, buffer_size) != 0) {
perror("setvbuf");
free(file->buffer);
fclose(file->file);
free(file);
errno = EIO;
return NULL;
}
return file;
}
static int file_close(struct File *file, bool delete_file)
{
if (!file)
return 0;
if (delete_file)
unlink(file->name);
if (ferror(file->file)) {
/* `ferror` doesn't set `errno`. */
fclose(file->file);
fprintf(stderr, "Error processing file %s\n", file->name);
free(file->buffer);
free(file);
errno = EIO;
return -1;
}
if (fclose(file->file) != 0) {
int save_error = errno;
perror("fclose");
free(file->buffer);
free(file);
errno = save_error;
return -1;
}
free(file->buffer);
free(file);
return 0;
}
struct Writer {
struct File *file;
uint64_t count_accounts, count_storage_slots;
int strategy, page_shift;
uint64_t block, nonce, account_incarnation, storage_incarnation;
byte address[ADDRESS_LEN];
byte balance[BALANCE_LEN];
byte code_hash[HASH_LEN];
byte storage_slot[SLOT_LEN];
};
struct Reader {
struct File *file;
int strategy, page_shift;
union {
struct Account account;
struct Storage storage;
};
uint64_t block, nonce, account_incarnation, storage_incarnation;
uint64_t bytecode_incarnation;
byte address[ADDRESS_LEN];
byte balance[BALANCE_LEN];
byte code_hash[HASH_LEN];
byte storage_slot[SLOT_LEN];
};
static void writer_state_init(struct Writer *writer)
{
writer->block = 0;
writer->nonce = 0;
writer->account_incarnation = 0;
writer->storage_incarnation = 0;
memset(writer->address, 0, ADDRESS_LEN);
memset(writer->balance, 0, BALANCE_LEN);
memset(writer->code_hash, 0, HASH_LEN);
memset(writer->storage_slot, 0, SLOT_LEN);
}
static void writer_init(struct Writer *writer, struct File *file,
int strategy)
{
writer->file = file;
writer->page_shift = 0;
writer->count_accounts = 0;
writer->count_storage_slots = 0;
writer->strategy = strategy;
writer_state_init(writer);
}
static void reader_state_init(struct Reader *reader)
{
reader->block = 0;
reader->nonce = 0;
reader->account_incarnation = 0;
reader->storage_incarnation = 0;
reader->bytecode_incarnation = 0;
memset(reader->address, 0, ADDRESS_LEN);
memset(reader->balance, 0, BALANCE_LEN);
memset(reader->code_hash, 0, HASH_LEN);
memset(reader->storage_slot, 0, SLOT_LEN);
}
static void reader_init(struct Reader *reader, struct File *file,
int strategy)
{
reader->file = file;
reader->page_shift = 0;
reader->strategy = strategy;
reader_state_init(reader);
}
static void write_number(struct Writer *writer, const byte *bytes, size_t len)
{
FILE *file = writer->file->file;
size_t i;
for (i = 0; i < len; i++)
if (bytes[i] != 0)
break;
if (i == len)
putc(0, file);
else if (i + 1 == len && bytes[i] < 224)
putc(bytes[i], file);
else {
byte prefix_code = (len - i) + 223;
putc(prefix_code, file);
for (; i < len; i++)
putc(bytes[i], file);
}
}
/* Must match `write_number`. */
static void read_number(struct Reader *reader, byte *value, size_t len)
{
FILE *file = reader->file->file;
byte b = getc(file);
if (b < 224) {
memset(value, 0, len);
value[len-1] = b;
} else {
b -= 223;
if (b < len) {
memset(value, 0, len - b);
value += len - b;
len = b;
}
for (size_t i = 0; i < len; i++)
value[i] = getc(file);
}
}
static void write_u64(struct Writer *writer, uint64_t value)
{
byte bytes[8];
put64be(bytes, value);
write_number(writer, bytes, sizeof(bytes));
}
/* Must match `write_u64`. */
static uint64_t read_u64(struct Reader *reader)
{
byte bytes[8];
read_number(reader, bytes, 8);
return get64be(bytes);
}
static void write_array(struct Writer *writer, const byte *bytes, size_t len)
{
FILE *file = writer->file->file;
for (size_t i = 0; i < len; i++)
putc(bytes[i], file);
}
/* Must match `write_array`. */
static void read_array(struct Reader *reader, byte *array, size_t len)
{
FILE *file = reader->file->file;
for (size_t i = 0; i < len; i++)
array[i] = getc(file);
}
static void delta(byte *delta_out, const byte *value_in, byte *accumulator, size_t len)
{
for (int i = len-1, borrow = 1; i >= 0; i--) {
int delta = (int)value_in[i] - (int)accumulator[i] - borrow;
accumulator[i] = value_in[i];
borrow = delta < 0;
delta_out[i] = (byte)delta;
}
}
static void sum(byte *value_out, const byte *delta_in, byte *accumulator, size_t len)
{
for (int i = len-1, carry = 1; i >= 0; i--) {
int sum = (int)delta_in[i] + (int)accumulator[i] + carry;
carry = sum >= 256;
value_out[i] = accumulator[i] = (byte)sum;
}
}
static void invert(byte *bytes, size_t len)
{
for (int i = 0; i < (int)len; i++)
bytes[i] = ~bytes[i];
}
static void write_block_number(struct Writer *writer, uint64_t block)
{
if (block == writer->block)
return;
if (PRINT)
print_block_number(block);
uint64_t delta_block = block - writer->block;
if (writer->strategy == 0)
delta_block = block;
writer->block = block;
byte bytes[8];
put64be(bytes, delta_block);
size_t i;
for (i = 0; i < 7; i++)
if (bytes[i] != 0)
break;
if (i == 7 && bytes[7] <= 4 && writer->strategy >= 1) {
putc(CODE_BLOCK_INLINE + bytes[7], writer->file->file);
} else {
putc(CODE_BLOCK_NUMBER + (7 - i), writer->file->file);
for (; i < 8; i++)
putc(bytes[i], writer->file->file);
}
}
/* Must match `write_block_number`. */
static void read_block_number(struct Reader *reader, uint64_t *block_number,
byte b)
{
uint64_t encoded_block;
if (b >= CODE_BLOCK_INLINE) {
encoded_block = b - CODE_BLOCK_INLINE;
} else {
int len = (int)(b - CODE_BLOCK_NUMBER + 1);
encoded_block = 0;
for (int i = 0; i < len; i++) {
encoded_block <<= 8;
encoded_block += getc(reader->file->file);
}
}
if (reader->strategy != 0)
encoded_block += reader->block;
*block_number = encoded_block;
}
static void write_address(struct Writer *writer, const byte address[ADDRESS_LEN])
{
if (0 == memcmp(address, writer->address, ADDRESS_LEN))
return;
if (PRINT)
print_address(address);
putc(CODE_ADDRESS, writer->file->file);
write_array(writer, address, ADDRESS_LEN);
memcpy(writer->address, address, ADDRESS_LEN);
/* `write_storage` uses incarnation reference with strategy == 0 too. */
writer->account_incarnation = 0;
writer->storage_incarnation = 0;
/* New address resets some other compression values. */
if (writer->strategy >= 1) {
writer->block = 0;
writer->nonce = 0;
memset(writer->balance, 0, BALANCE_LEN);
memset(writer->code_hash, 0, HASH_LEN);
}
}
/* Must match `write_address`. */
static void read_address(struct Reader *reader, byte address[ADDRESS_LEN])
{
read_array(reader, reader->address, ADDRESS_LEN);
reader->account_incarnation = 0;
reader->storage_incarnation = 0;
if (reader->strategy >= 1) {
reader->block = 0;
reader->nonce = 0;
memset(reader->balance, 0, BALANCE_LEN);
memset(reader->code_hash, 0, HASH_LEN);
}
}
//#define SPECIAL_LOG_ADDRESS 0x00, 0x52, 0xb9, 0x4f, 0x97, 0x43, 0x12, 0x9d, 0x87, 0x78, 0x8b, 0x17, 0x75, 0x38, 0x66, 0xa5, 0x6b, 0xe2, 0x2e, 0xce
//#define SPECIAL_LOG_ADDRESS 0x05, 0x14, 0xb6, 0x31, 0x17, 0xd2, 0x93, 0x1a, 0x88, 0x48, 0xb0, 0xc5, 0x47, 0x7b, 0xb1, 0x8b, 0x65, 0xe8, 0x0e, 0x07
//#define SPECIAL_LOG_ADDRESS 0x39, 0xd2, 0xa8, 0x51, 0x4c, 0xac, 0x3b, 0xb6, 0xcb, 0x7d, 0xbd, 0x85, 0xaa, 0x3a, 0x48, 0x93, 0x78, 0x77, 0xc1, 0x3b
#ifdef SPECIAL_LOG_ADDRESS
static const byte special[ADDRESS_LEN] = { SPECIAL_LOG_ADDRESS };
#endif
static void write_block_and_address(struct Writer *writer,
const struct ReaderItem *item)
{
if (writer->strategy == 0) {
write_block_number(writer, item->block);
write_address(writer, item->address);
} else {
/* Write address first, so all block deltas work including the first. */
write_address(writer, item->address);
write_block_number(writer, item->block);
}
}
/*
* When writing an entry passes a page boundary, replace it with padding, reset
* the incremental writer state, and write the entry again. The reader can
* read from this entry without preceding ones.
*/
static bool write_check_page_boundary(struct Writer *writer, off_t file_offset)
{
if (writer->page_shift == 0)
return false;
if (((file_offset ^ ftello(writer->file->file)) >> writer->page_shift) == 0)
return false;
if (fseeko(writer->file->file, file_offset, SEEK_SET) != 0) {
perror("fseeko");
exit(EXIT_FAILURE);
}
off_t mask = ((off_t)1 << writer->page_shift) - 1;
while ((file_offset & mask) != 0) {
putc(CODE_PAGE_PADDING, writer->file->file);
file_offset++;
}
writer_state_init(writer);
return true;
}
static void write_account(struct Writer *writer, const struct Account *account)
{
writer->count_accounts++;
again:;
off_t file_offset = ftello(writer->file->file);
write_block_and_address(writer, &account->item_base);
byte flags = 0;
const byte *encoded_code_hash = account->codeHash;
bool is_zero_code_hash = false;
if (0 == memcmp(account->codeHash, zero_code_hash, HASH_LEN)
|| 0 == memcmp(account->codeHash, empty_code_hash, HASH_LEN)) {
encoded_code_hash = zero_code_hash;
is_zero_code_hash = true;
}
if (!is_zero_code_hash && account->incarnation == 0) {
/* These don't occur, so class their appearance as an error. */
print_account(account);
fflush(stdout);
fprintf(stderr, "Error: ^ Account with non-zero codeHash and zero incarnation\n");
abort();
}
#if 0
if (is_zero_code_hash && account->incarnation != 0) {
/*
* Too many of these occur in `PlainState` to list.
* Much fewer than in the history (on Goerli).
*/
print_account(account);
fflush(stdout);
fprintf(stderr, "Warning: ^ Account with zero codeHash and non-zero incarnation\n");
//abort();
}
#endif
#if 0
if (account->incarnation != 0
&& account->incarnation - writer->account_incarnation >= 3) {
/*
* Too many of these occur to list when transforming Mainnet.
* Relatively few on Goerli.
*/
print_account(account);
fflush(stdout);
fprintf(stderr, "Warning: ^ Account with delta incarnation >= 3\n");
//abort();
}
#endif
/* Nonce delta encoding alone saves ~1.5% of storage. */
uint64_t encoded_nonce, encoded_incarnation;
if (writer->strategy == 0) {
encoded_nonce = account->nonce;
encoded_incarnation = account->incarnation;
} else {
encoded_nonce = account->nonce - writer->nonce;
if (writer->strategy == 3 && is_zero_code_hash)
encoded_incarnation = account->incarnation;
else
encoded_incarnation = account->incarnation - writer->account_incarnation;
}
/* Balance delta encoding saves ~8% of storage. */
byte encoded_balance[BALANCE_LEN];
if (writer->strategy == 0) {
memcpy(encoded_balance, account->balance, BALANCE_LEN);
} else {
delta(encoded_balance, account->balance, writer->balance, BALANCE_LEN);
if (encoded_balance[0] >= (byte)0x80) {
invert(encoded_balance, BALANCE_LEN);
flags |= (1 << 5);
}
}
if (0 != memcmp(encoded_balance, zero_balance, BALANCE_LEN))
flags |= (1 << 0);
#ifdef SPECIAL_LOG_ADDRESS
static int special_counter = 0;
if (special_counter || 0 == memcmp(account->item_base.address, special, ADDRESS_LEN)) {
if (special_counter == 0)
special_counter = 10;
special_counter--;
printf("Write special case, block=%llu\n", (unsigned long long)account->item_base.block);
print_file_offset(ftello(writer->file->file));
print_account(account);
}
#endif /* SPECIAL_LOG_ADDRESS */
/*
* At mainnet block 10094566, there is a self-destruct, create, sstore
* on account 000000000000006f6502b7f2bbac8c30a3f67e9a. It has the
* effect of pairing an inc=1 account entry (from before the
* self-destruct) with inc=2 storage entries (from before the sstore).
* Later at block 10094587, the balance changes which adds the inc=2
* account entry for the create at 10094566. The sequence when address
* is the primary order, and account/state updates as at
* last-block-number:
*
* (set block=10094566)
* Account block=10094566 address=000000000000006f6502b7f2bbac8c30a3f67e9a
* inc=1 nonce=1976 balance=1 codeHash=a81d7f06c942f28e7852465c195e233d05e645893ae829822e95b4ff420d93c2
* Storage block=10094566 slot=000000000000006f6502b7f2bbac8c30a3f67e9a/0000000000000000000000000000000000000000000000000000000000005850
* inc=2 value=0
* Storage block=10094566 slot=000000000000006f6502b7f2bbac8c30a3f67e9a/0000000000000000000000003452954838762313786992245132387393331546
* inc=2 value=0
* (set block=10094587)
* Account block=10094587 address=000000000000006f6502b7f2bbac8c30a3f67e9a
* inc=2 nonce=1 balance=1 codeHash=b06895d1ddccd23a5648db366bf46ecaf7e60d6364a7974e8785d9eb5f04cc18
*
* Due to this sequence, simply delta-compressing inc results in zero
* delta for the second account entry, which doesn't match the encoding
* constraint that codeHash only changes when there is delta inc. To
* maintain the constraint, delta-compression of account inc is done
* relative to the previous account inc. This problem goes away when
* we change all account/state updates to Nimbus first-block-number
* order, and constrain storage inc ranges correctly. But that is only
* possible after merging the transposed state files.
*
* TODO: When that's done, there will be no need to encode all-zeros
* code hashes for self-destructed accounts.
*/
if (writer->strategy == 0) {
if (!is_zero_code_hash)
flags |= (1 << 1);
} else if (0 != memcmp(writer->code_hash, encoded_code_hash, HASH_LEN)) {
flags |= (1 << 1);
if (!is_zero_code_hash && encoded_incarnation == 0) {
print_account(account);
fflush(stdout);
fprintf(stderr, "Warning: ^ Change of code hash with no change of incarnation\n");
//abort();
}
}
if (writer->strategy == 2) {
if (account->balance == 0) {
flags |= (1 << 3);
flags &= ~(1 << 0);
}
if (encoded_nonce >= 1) {
flags |= (1 << 2);
}
} else {
if (encoded_nonce >= 3) {
flags |= (3 << 2);
} else {
flags |= (byte)encoded_nonce << 2;
}
}
if (writer->strategy == 0) {
if (encoded_incarnation >= 3)
flags |= (3 << 4);
else
flags |= (byte)encoded_incarnation << 4;
} else {
/*
* In account entries, in the block ranges measured (blocks
* 10-10.1M), `encoded_incarnation` was 0 in 99.865% of
* entries, 1 in 0.135% of entries, and never >= 2. It is
* rare, so there is no need for efficient inline encoding of
* >= 2, but it must be supported because multiple
* self-destruct+create pairs are allowed in the same block.
*/
if (encoded_incarnation == 1) {
flags |= (1 << 4);
} else if (encoded_incarnation != 0) {
if (PRINT)
print_bytecode_incarnation(encoded_incarnation);
putc(CODE_INCARNATION, writer->file->file);
write_u64(writer, encoded_incarnation);
}
}
if (PRINT)
print_account(account);
putc(CODE_ACCOUNT + flags, writer->file->file);