forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stage_hashstate.go
935 lines (858 loc) · 24.4 KB
/
stage_hashstate.go
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
package stagedsync
import (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"github.com/ledgerwatch/erigon-lib/kv/dbutils"
"runtime"
"time"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/datadir"
"github.com/ledgerwatch/erigon-lib/common/dbg"
"github.com/ledgerwatch/erigon-lib/common/hexutility"
"github.com/ledgerwatch/erigon-lib/common/length"
"github.com/ledgerwatch/erigon-lib/etl"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/erigon-lib/kv/order"
"github.com/ledgerwatch/erigon-lib/kv/rawdbv3"
"github.com/ledgerwatch/erigon-lib/kv/temporal/historyv2"
"github.com/ledgerwatch/log/v3"
"golang.org/x/sync/errgroup"
"github.com/ledgerwatch/erigon/common/math"
"github.com/ledgerwatch/erigon/core/types/accounts"
"github.com/ledgerwatch/erigon/eth/ethconfig/estimate"
)
type HashStateCfg struct {
db kv.RwDB
dirs datadir.Dirs
historyV3 bool
}
func StageHashStateCfg(db kv.RwDB, dirs datadir.Dirs, historyV3 bool) HashStateCfg {
return HashStateCfg{
db: db,
dirs: dirs,
historyV3: historyV3,
}
}
func SpawnHashStateStage(s *StageState, tx kv.RwTx, cfg HashStateCfg, ctx context.Context, logger log.Logger) error {
useExternalTx := tx != nil
if !useExternalTx {
var err error
tx, err = cfg.db.BeginRw(context.Background())
if err != nil {
return err
}
defer tx.Rollback()
}
logPrefix := s.LogPrefix()
to, err := s.ExecutionAt(tx)
if err != nil {
return err
}
if s.BlockNumber == to {
// we already did hash check for this block
// we don't do the obvious `if s.BlockNumber > to` to support reorgs more naturally
return nil
}
if s.BlockNumber > to { // Erigon will self-heal (download missed blocks) eventually
log.Warn(fmt.Sprintf("[%s] promotion backwards from %d to %d", s.LogPrefix(), s.BlockNumber, to))
return nil
}
if to > s.BlockNumber+16 {
logger.Info(fmt.Sprintf("[%s] Promoting plain state", logPrefix), "from", s.BlockNumber, "to", to)
}
if s.BlockNumber == 0 { // Initial hashing of the state is performed at the previous stage
if err := PromoteHashedStateCleanly(logPrefix, tx, cfg, ctx, logger); err != nil {
return err
}
} else {
if err := promoteHashedStateIncrementally(logPrefix, s.BlockNumber, to, tx, cfg, ctx, logger); err != nil {
return err
}
}
if err = s.Update(tx, to); err != nil {
return err
}
if !useExternalTx {
if err := tx.Commit(); err != nil {
return err
}
}
return nil
}
func UnwindHashStateStage(u *UnwindState, s *StageState, tx kv.RwTx, cfg HashStateCfg, ctx context.Context, logger log.Logger) (err error) {
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
logPrefix := u.LogPrefix()
if err = unwindHashStateStageImpl(logPrefix, u, s, tx, cfg, ctx, logger); err != nil {
return err
}
if err = u.Done(tx); err != nil {
return err
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}
func unwindHashStateStageImpl(logPrefix string, u *UnwindState, s *StageState, tx kv.RwTx, cfg HashStateCfg, ctx context.Context, logger log.Logger) error {
// Currently it does not require unwinding because it does not create any Intermediate Hash records
// and recomputes the state root from scratch
prom := NewPromoter(tx, cfg.dirs, ctx, logger)
if cfg.historyV3 {
if err := prom.UnwindOnHistoryV3(logPrefix, s.BlockNumber, u.UnwindPoint, false, true); err != nil {
return err
}
if err := prom.UnwindOnHistoryV3(logPrefix, s.BlockNumber, u.UnwindPoint, false, false); err != nil {
return err
}
if err := prom.UnwindOnHistoryV3(logPrefix, s.BlockNumber, u.UnwindPoint, true, false); err != nil {
return err
}
return nil
}
if err := prom.Unwind(logPrefix, s, u, false /* storage */, true /* codes */); err != nil {
return err
}
if err := prom.Unwind(logPrefix, s, u, false /* storage */, false /* codes */); err != nil {
return err
}
if err := prom.Unwind(logPrefix, s, u, true /* storage */, false /* codes */); err != nil {
return err
}
return nil
}
func PromoteHashedStateCleanly(logPrefix string, tx kv.RwTx, cfg HashStateCfg, ctx context.Context, logger log.Logger) error {
err := promotePlainState(
logPrefix,
cfg.db,
tx,
cfg.dirs.Tmp,
ctx,
logger,
)
if err != nil {
return err
}
return etl.Transform(
logPrefix,
tx,
kv.PlainContractCode,
kv.ContractCode,
cfg.dirs.Tmp,
func(k, v []byte, next etl.ExtractNextFunc) error {
newK, err := transformContractCodeKey(k)
if err != nil {
return err
}
return next(k, newK, v)
},
etl.IdentityLoadFunc,
etl.TransformArgs{
Quit: ctx.Done(),
},
logger,
)
}
func promotePlainState(
logPrefix string,
db kv.RoDB,
tx kv.RwTx,
tmpdir string,
ctx context.Context,
logger log.Logger,
) error {
accCollector := etl.NewCollector(logPrefix, tmpdir, etl.NewSortableBuffer(etl.BufferOptimalSize), logger)
defer accCollector.Close()
accCollector.LogLvl(log.LvlTrace)
storageCollector := etl.NewCollector(logPrefix, tmpdir, etl.NewSortableBuffer(etl.BufferOptimalSize), logger)
defer storageCollector.Close()
storageCollector.LogLvl(log.LvlTrace)
transform := func(k, v []byte) ([]byte, []byte, error) {
newK, err := transformPlainStateKey(k)
return newK, v, err
}
collect := func(k, v []byte) error {
if len(k) == 32 {
return accCollector.Collect(k, v)
}
return storageCollector.Collect(k, v)
}
{ //errgroup cancelation scope
// pipeline: extract -> transform -> collect
in, out := make(chan pair, 10_000), make(chan pair, 10_000)
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
defer close(out)
return parallelTransform(ctx, in, out, transform, estimate.AlmostAllCPUs()).Wait()
})
g.Go(func() error { return collectChan(ctx, out, collect) })
g.Go(func() error { return parallelWarmup(ctx, db, kv.PlainState, 2) })
if err := extractTableToChan(ctx, tx, kv.PlainState, in, logPrefix, logger); err != nil {
// if ctx canceled, then maybe it's because of error in errgroup
//
// errgroup doesn't play with pattern where some 1 goroutine-producer is outside of errgroup
// but RwTx doesn't allow move between goroutines
if errors.Is(err, context.Canceled) {
return g.Wait()
}
return err
}
if err := g.Wait(); err != nil {
return fmt.Errorf("g.Wait: %w", err)
}
}
args := etl.TransformArgs{Quit: ctx.Done()}
if err := accCollector.Load(tx, kv.HashedAccounts, etl.IdentityLoadFunc, args); err != nil {
return fmt.Errorf("accCollector.Load: %w", err)
}
if err := storageCollector.Load(tx, kv.HashedStorage, etl.IdentityLoadFunc, args); err != nil {
return fmt.Errorf("storageCollector.Load: %w", err)
}
return nil
}
type pair struct{ k, v []byte }
func extractTableToChan(ctx context.Context, tx kv.Tx, table string, in chan pair, logPrefix string, logger log.Logger) error {
defer close(in)
logEvery := time.NewTicker(30 * time.Second)
defer logEvery.Stop()
var m runtime.MemStats
return tx.ForEach(table, nil, func(k, v []byte) error {
select { // this select can't print logs, because of
case in <- pair{k: k, v: v}:
case <-ctx.Done():
return ctx.Err()
}
select {
case <-logEvery.C:
dbg.ReadMemStats(&m)
logger.Info(fmt.Sprintf("[%s] ETL [1/2] Extracting", logPrefix), "current_prefix", hex.EncodeToString(k[:4]), "alloc", libcommon.ByteCount(m.Alloc), "sys", libcommon.ByteCount(m.Sys))
default:
}
return nil
})
}
func collectChan(ctx context.Context, out chan pair, collect func(k, v []byte) error) error {
for {
select {
case item, ok := <-out:
if !ok {
return nil
}
if err := collect(item.k, item.v); err != nil {
return fmt.Errorf("collectChan: %w", err)
}
case <-ctx.Done():
return ctx.Err()
}
}
}
func parallelTransform(ctx context.Context, in chan pair, out chan pair, transform func(k, v []byte) ([]byte, []byte, error), workers int) *errgroup.Group {
hashG, ctx := errgroup.WithContext(ctx)
for i := 0; i < workers; i++ {
hashG.Go(func() error {
for item := range in {
k, v, err := transform(item.k, item.v)
if err != nil {
return err
}
select {
case out <- pair{k: k, v: v}:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
})
}
return hashG
}
func parallelWarmup(ctx context.Context, db kv.RoDB, bucket string, workers int) error {
if db == nil || ctx == nil || workers == 0 {
return nil
}
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(workers)
for i := 0; i < 256; i++ {
i := i
g.Go(func() error {
return db.View(ctx, func(tx kv.Tx) error {
it, err := tx.Prefix(bucket, []byte{byte(i)})
if err != nil {
return err
}
for it.HasNext() {
_, _, err = it.Next()
if err != nil {
return err
}
}
return nil
})
})
}
return g.Wait()
}
func transformPlainStateKey(key []byte) ([]byte, error) {
switch len(key) {
case length.Addr:
// account
hash, err := libcommon.HashData(key)
return hash[:], err
case length.Addr + length.Incarnation + length.Hash:
// storage
addrHash, err := libcommon.HashData(key[:length.Addr])
if err != nil {
return nil, err
}
inc := binary.BigEndian.Uint64(key[length.Addr:])
secKey, err := libcommon.HashData(key[length.Addr+length.Incarnation:])
if err != nil {
return nil, err
}
compositeKey := dbutils.GenerateCompositeStorageKey(addrHash, inc, secKey)
return compositeKey, nil
default:
// no other keys are supported
return nil, fmt.Errorf("could not convert key from plain to hashed, unexpected len: %d", len(key))
}
}
func transformContractCodeKey(key []byte) ([]byte, error) {
if len(key) != length.Addr+length.Incarnation {
return nil, fmt.Errorf("could not convert code key from plain to hashed, unexpected len: %d", len(key))
}
address, incarnation := dbutils.PlainParseStoragePrefix(key)
addrHash, err := libcommon.HashData(address[:])
if err != nil {
return nil, err
}
compositeKey := dbutils.GenerateStoragePrefix(addrHash[:], incarnation)
return compositeKey, nil
}
type OldestAppearedLoad struct {
innerLoadFunc etl.LoadFunc
lastKey bytes.Buffer
}
func (l *OldestAppearedLoad) LoadFunc(k, v []byte, table etl.CurrentTableReader, next etl.LoadNextFunc) error {
if bytes.Equal(k, l.lastKey.Bytes()) {
return nil
}
l.lastKey.Reset()
//nolint:errcheck
l.lastKey.Write(k)
return l.innerLoadFunc(k, v, table, next)
}
func NewPromoter(db kv.RwTx, dirs datadir.Dirs, ctx context.Context, logger log.Logger) *Promoter {
return &Promoter{
tx: db,
ChangeSetBufSize: 256 * 1024 * 1024,
dirs: dirs,
ctx: ctx,
logger: logger,
}
}
type Promoter struct {
tx kv.RwTx
ChangeSetBufSize uint64
dirs datadir.Dirs
ctx context.Context
logger log.Logger
}
func getExtractFunc(db kv.Tx, changeSetBucket string) etl.ExtractFunc {
decode := historyv2.Mapper[changeSetBucket].Decode
return func(dbKey, dbValue []byte, next etl.ExtractNextFunc) error {
_, k, _, err := decode(dbKey, dbValue)
if err != nil {
return err
}
// ignoring value un purpose, we want the latest one and it is in PlainState
value, err := db.GetOne(kv.PlainState, k)
if err != nil {
return err
}
newK, err := transformPlainStateKey(k)
if err != nil {
return err
}
return next(dbKey, newK, value)
}
}
func getExtractCode(db kv.Tx, changeSetBucket string) etl.ExtractFunc {
decode := historyv2.Mapper[changeSetBucket].Decode
return func(dbKey, dbValue []byte, next etl.ExtractNextFunc) error {
_, k, _, err := decode(dbKey, dbValue)
if err != nil {
return err
}
value, err := db.GetOne(kv.PlainState, k)
if err != nil {
return err
}
if len(value) == 0 {
return nil
}
incarnation, err := accounts.DecodeIncarnationFromStorage(value)
if err != nil {
return err
}
if incarnation == 0 {
return nil
}
plainKey := dbutils.PlainGenerateStoragePrefix(k, incarnation)
var codeHash []byte
codeHash, err = db.GetOne(kv.PlainContractCode, plainKey)
if err != nil {
return fmt.Errorf("getFromPlainCodesAndLoad for %x, inc %d: %w", plainKey, incarnation, err)
}
if codeHash == nil {
return nil
}
newK, err := transformContractCodeKey(plainKey)
if err != nil {
return err
}
return next(dbKey, newK, codeHash)
}
}
func getUnwindExtractStorage(changeSetBucket string) etl.ExtractFunc {
decode := historyv2.Mapper[changeSetBucket].Decode
return func(dbKey, dbValue []byte, next etl.ExtractNextFunc) error {
_, k, v, err := decode(dbKey, dbValue)
if err != nil {
return err
}
newK, err := transformPlainStateKey(k)
if err != nil {
return err
}
return next(dbKey, newK, v)
}
}
func getUnwindExtractAccounts(db kv.Tx, changeSetBucket string) etl.ExtractFunc {
decode := historyv2.Mapper[changeSetBucket].Decode
return func(dbKey, dbValue []byte, next etl.ExtractNextFunc) error {
_, k, v, err := decode(dbKey, dbValue)
if err != nil {
return err
}
newK, err := transformPlainStateKey(k)
if err != nil {
return err
}
if len(v) == 0 {
return next(dbKey, newK, v)
}
var acc accounts.Account
if err = acc.DecodeForStorage(v); err != nil {
return err
}
if !(acc.Incarnation > 0 && acc.IsEmptyCodeHash()) {
return next(dbKey, newK, v)
}
if codeHash, err := db.GetOne(kv.ContractCode, dbutils.GenerateStoragePrefix(newK, acc.Incarnation)); err == nil {
copy(acc.CodeHash[:], codeHash)
} else {
return fmt.Errorf("adjusting codeHash for ks %x, inc %d: %w", newK, acc.Incarnation, err)
}
value := make([]byte, acc.EncodingLengthForStorage())
acc.EncodeForStorage(value)
return next(dbKey, newK, value)
}
}
func getCodeUnwindExtractFunc(db kv.Tx, changeSetBucket string) etl.ExtractFunc {
decode := historyv2.Mapper[changeSetBucket].Decode
return func(dbKey, dbValue []byte, next etl.ExtractNextFunc) error {
_, k, v, err := decode(dbKey, dbValue)
if err != nil {
return err
}
if len(v) == 0 {
return nil
}
var (
newK []byte
codeHash []byte
)
incarnation, err := accounts.DecodeIncarnationFromStorage(v)
if err != nil {
return err
}
if incarnation == 0 {
return nil
}
plainKey := dbutils.PlainGenerateStoragePrefix(k, incarnation)
codeHash, err = db.GetOne(kv.PlainContractCode, plainKey)
if err != nil {
return fmt.Errorf("getCodeUnwindExtractFunc: %w, key=%x", err, plainKey)
}
newK, err = transformContractCodeKey(plainKey)
if err != nil {
return err
}
return next(dbKey, newK, codeHash)
}
}
func (p *Promoter) PromoteOnHistoryV3(logPrefix string, from, to uint64, storage bool) error {
if to > from+16 {
p.logger.Info(fmt.Sprintf("[%s] Incremental promotion", logPrefix), "from", from, "to", to, "storage", storage)
}
txnFrom, err := rawdbv3.TxNums.Min(p.tx, from+1)
if err != nil {
return err
}
txnTo := uint64(math.MaxUint64)
collector := etl.NewCollector(logPrefix, p.dirs.Tmp, etl.NewSortableBuffer(etl.BufferOptimalSize), p.logger)
defer collector.Close()
if storage {
it, err := p.tx.(kv.TemporalTx).HistoryRange(kv.StorageHistory, int(txnFrom), int(txnTo), order.Asc, kv.Unlim)
if err != nil {
return err
}
for it.HasNext() {
k, _, err := it.Next()
if err != nil {
return err
}
accBytes, err := p.tx.GetOne(kv.PlainState, k[:20])
if err != nil {
return err
}
incarnation := uint64(1)
if len(accBytes) != 0 {
incarnation, err = accounts.DecodeIncarnationFromStorage(accBytes)
if err != nil {
return err
}
if incarnation == 0 {
continue
}
}
plainKey := dbutils.PlainGenerateCompositeStorageKey(k[:20], incarnation, k[20:])
newV, err := p.tx.GetOne(kv.PlainState, plainKey)
if err != nil {
return err
}
newK, err := transformPlainStateKey(plainKey)
if err != nil {
return err
}
if err := collector.Collect(newK, newV); err != nil {
return err
}
}
if err := collector.Load(p.tx, kv.HashedStorage, etl.IdentityLoadFunc, etl.TransformArgs{Quit: p.ctx.Done()}); err != nil {
return err
}
return nil
}
codeCollector := etl.NewCollector(logPrefix, p.dirs.Tmp, etl.NewSortableBuffer(etl.BufferOptimalSize), p.logger)
defer codeCollector.Close()
it, err := p.tx.(kv.TemporalTx).HistoryRange(kv.AccountsHistory, int(txnFrom), int(txnTo), order.Asc, kv.Unlim)
if err != nil {
return err
}
for it.HasNext() {
k, _, err := it.Next()
if err != nil {
return err
}
newV, err := p.tx.GetOne(kv.PlainState, k)
if err != nil {
return err
}
newK, err := transformPlainStateKey(k)
if err != nil {
return err
}
if err := collector.Collect(newK, newV); err != nil {
return err
}
//code
if len(newV) == 0 {
continue
}
incarnation, err := accounts.DecodeIncarnationFromStorage(newV)
if err != nil {
return err
}
if incarnation == 0 {
continue
}
plainKey := dbutils.PlainGenerateStoragePrefix(k, incarnation)
var codeHash []byte
codeHash, err = p.tx.GetOne(kv.PlainContractCode, plainKey)
if err != nil {
return fmt.Errorf("getFromPlainCodesAndLoad for %x, inc %d: %w", plainKey, incarnation, err)
}
if codeHash == nil {
continue
}
newCodeK, err := transformContractCodeKey(plainKey)
if err != nil {
return err
}
if err = codeCollector.Collect(newCodeK, newV); err != nil {
return err
}
}
if err := collector.Load(p.tx, kv.HashedAccounts, etl.IdentityLoadFunc, etl.TransformArgs{Quit: p.ctx.Done()}); err != nil {
return err
}
if err := codeCollector.Load(p.tx, kv.ContractCode, etl.IdentityLoadFunc, etl.TransformArgs{Quit: p.ctx.Done()}); err != nil {
return err
}
return nil
}
func (p *Promoter) Promote(logPrefix string, from, to uint64, storage, codes bool) error {
var changeSetBucket string
if storage {
changeSetBucket = kv.StorageChangeSet
} else {
changeSetBucket = kv.AccountChangeSet
}
if to > from+16 {
p.logger.Info(fmt.Sprintf("[%s] Incremental promotion", logPrefix), "from", from, "to", to, "codes", codes, "csbucket", changeSetBucket)
}
startkey := hexutility.EncodeTs(from + 1)
var loadBucket string
var extract etl.ExtractFunc
if codes {
loadBucket = kv.ContractCode
extract = getExtractCode(p.tx, changeSetBucket)
} else {
if storage {
loadBucket = kv.HashedStorage
} else {
loadBucket = kv.HashedAccounts
}
extract = getExtractFunc(p.tx, changeSetBucket)
}
if err := etl.Transform(
logPrefix,
p.tx,
changeSetBucket,
loadBucket,
p.dirs.Tmp,
extract,
etl.IdentityLoadFunc,
etl.TransformArgs{
BufferType: etl.SortableOldestAppearedBuffer,
ExtractStartKey: startkey,
Quit: p.ctx.Done(),
},
p.logger,
); err != nil {
return err
}
return nil
}
func (p *Promoter) UnwindOnHistoryV3(logPrefix string, unwindFrom, unwindTo uint64, storage, codes bool) error {
p.logger.Info(fmt.Sprintf("[%s] Unwinding started", logPrefix), "from", unwindFrom, "to", unwindTo, "storage", storage, "codes", codes)
txnFrom, err := rawdbv3.TxNums.Min(p.tx, unwindTo+1)
if err != nil {
return err
}
txnTo := uint64(math.MaxUint64)
collector := etl.NewCollector(logPrefix, p.dirs.Tmp, etl.NewOldestEntryBuffer(etl.BufferOptimalSize), p.logger)
defer collector.Close()
acc := accounts.NewAccount()
if codes {
it, err := p.tx.(kv.TemporalTx).HistoryRange(kv.AccountsHistory, int(txnFrom), int(txnTo), order.Asc, kv.Unlim)
if err != nil {
return err
}
for it.HasNext() {
k, v, err := it.Next()
if err != nil {
return err
}
if len(v) == 0 {
continue
}
if err := accounts.DeserialiseV3(&acc, v); err != nil {
return err
}
incarnation := acc.Incarnation
if incarnation == 0 {
continue
}
plainKey := dbutils.PlainGenerateStoragePrefix(k, incarnation)
codeHash, err := p.tx.GetOne(kv.PlainContractCode, plainKey)
if err != nil {
return fmt.Errorf("getCodeUnwindExtractFunc: %w, key=%x", err, plainKey)
}
newK, err := transformContractCodeKey(plainKey)
if err != nil {
return err
}
if err = collector.Collect(newK, codeHash); err != nil {
return err
}
}
return collector.Load(p.tx, kv.ContractCode, etl.IdentityLoadFunc, etl.TransformArgs{Quit: p.ctx.Done()})
}
if storage {
it, err := p.tx.(kv.TemporalTx).HistoryRange(kv.StorageHistory, int(txnFrom), int(txnTo), order.Asc, kv.Unlim)
if err != nil {
return err
}
for it.HasNext() {
k, v, err := it.Next()
if err != nil {
return err
}
val, err := p.tx.GetOne(kv.PlainState, k[:20])
if err != nil {
return err
}
incarnation := uint64(1)
if len(val) != 0 {
oldInc, _ := accounts.DecodeIncarnationFromStorage(val)
incarnation = oldInc
}
plainKey := dbutils.PlainGenerateCompositeStorageKey(k[:20], incarnation, k[20:])
newK, err := transformPlainStateKey(plainKey)
if err != nil {
return err
}
if err := collector.Collect(newK, v); err != nil {
return err
}
}
return collector.Load(p.tx, kv.HashedStorage, etl.IdentityLoadFunc, etl.TransformArgs{Quit: p.ctx.Done()})
}
it, err := p.tx.(kv.TemporalTx).HistoryRange(kv.AccountsHistory, int(txnFrom), int(txnTo), order.Asc, kv.Unlim)
if err != nil {
return err
}
for it.HasNext() {
k, v, err := it.Next()
if err != nil {
return err
}
newK, err := transformPlainStateKey(k)
if err != nil {
return err
}
if len(v) == 0 {
if err = collector.Collect(newK, nil); err != nil {
return err
}
continue
}
if err := accounts.DeserialiseV3(&acc, v); err != nil {
return err
}
if acc.Incarnation > 0 && acc.IsEmptyCodeHash() {
if codeHash, err := p.tx.GetOne(kv.ContractCode, dbutils.GenerateStoragePrefix(newK, acc.Incarnation)); err == nil {
copy(acc.CodeHash[:], codeHash)
} else {
return fmt.Errorf("adjusting codeHash for ks %x, inc %d: %w", newK, acc.Incarnation, err)
}
}
value := make([]byte, acc.EncodingLengthForStorage())
acc.EncodeForStorage(value)
if err := collector.Collect(newK, value); err != nil {
return err
}
}
return collector.Load(p.tx, kv.HashedAccounts, etl.IdentityLoadFunc, etl.TransformArgs{Quit: p.ctx.Done()})
}
func (p *Promoter) Unwind(logPrefix string, s *StageState, u *UnwindState, storage bool, codes bool) error {
var changeSetBucket string
if storage {
changeSetBucket = kv.StorageChangeSet
} else {
changeSetBucket = kv.AccountChangeSet
}
from := s.BlockNumber
to := u.UnwindPoint
p.logger.Info(fmt.Sprintf("[%s] Unwinding started", logPrefix), "from", from, "to", to, "storage", storage, "codes", codes)
startkey := hexutility.EncodeTs(to + 1)
var l OldestAppearedLoad
l.innerLoadFunc = etl.IdentityLoadFunc
var loadBucket string
var extractFunc etl.ExtractFunc
if codes {
loadBucket = kv.ContractCode
extractFunc = getCodeUnwindExtractFunc(p.tx, changeSetBucket)
} else {
if storage {
loadBucket = kv.HashedStorage
extractFunc = getUnwindExtractStorage(changeSetBucket)
} else {
loadBucket = kv.HashedAccounts
extractFunc = getUnwindExtractAccounts(p.tx, changeSetBucket)
}
}
return etl.Transform(
logPrefix,
p.tx,
changeSetBucket,
loadBucket,
p.dirs.Tmp,
extractFunc,
l.LoadFunc,
etl.TransformArgs{
BufferType: etl.SortableOldestAppearedBuffer,
ExtractStartKey: startkey,
Quit: p.ctx.Done(),
LogDetailsExtract: func(k, v []byte) (additionalLogArguments []interface{}) {
return []interface{}{"progress", etl.ProgressFromKey(k)}
},
LogDetailsLoad: func(k, v []byte) (additionalLogArguments []interface{}) {
return []interface{}{"progress", etl.ProgressFromKey(k) + 50} // loading is the second stage, from 50..100
},
},
p.logger,
)
}
func promoteHashedStateIncrementally(logPrefix string, from, to uint64, tx kv.RwTx, cfg HashStateCfg, ctx context.Context, logger log.Logger) error {
prom := NewPromoter(tx, cfg.dirs, ctx, logger)
if cfg.historyV3 {
if err := prom.PromoteOnHistoryV3(logPrefix, from, to, false); err != nil {
return err
}
if err := prom.PromoteOnHistoryV3(logPrefix, from, to, true); err != nil {
return err
}
return nil
}
if err := prom.Promote(logPrefix, from, to, false, true); err != nil {
return err
}
if err := prom.Promote(logPrefix, from, to, false, false); err != nil {
return err
}
if err := prom.Promote(logPrefix, from, to, true, false); err != nil {
return err
}
return nil
}
func PruneHashStateStage(s *PruneState, tx kv.RwTx, cfg HashStateCfg, ctx context.Context) (err error) {
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}