forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stage_execute.go
765 lines (683 loc) · 22.9 KB
/
stage_execute.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
package stagedsync
import (
"context"
"encoding/binary"
"errors"
"fmt"
"runtime"
"time"
"github.com/c2h5oh/datasize"
"github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/cmp"
"github.com/ledgerwatch/erigon-lib/common/length"
"github.com/ledgerwatch/erigon-lib/etl"
"github.com/ledgerwatch/erigon-lib/kv"
libstate "github.com/ledgerwatch/erigon-lib/state"
"github.com/ledgerwatch/erigon/eth/ethconfig/estimate"
"github.com/ledgerwatch/log/v3"
commonold "github.com/ledgerwatch/erigon/common"
ecom "github.com/ledgerwatch/erigon/common"
"github.com/ledgerwatch/erigon/common/changeset"
"github.com/ledgerwatch/erigon/common/dbutils"
"github.com/ledgerwatch/erigon/common/math"
"github.com/ledgerwatch/erigon/consensus"
"github.com/ledgerwatch/erigon/core"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/state"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/core/types/accounts"
"github.com/ledgerwatch/erigon/core/vm"
"github.com/ledgerwatch/erigon/eth/calltracer"
"github.com/ledgerwatch/erigon/eth/stagedsync/stages"
"github.com/ledgerwatch/erigon/ethdb"
"github.com/ledgerwatch/erigon/ethdb/olddb"
"github.com/ledgerwatch/erigon/ethdb/prune"
"github.com/ledgerwatch/erigon/node/nodecfg/datadir"
"github.com/ledgerwatch/erigon/params"
"github.com/ledgerwatch/erigon/turbo/services"
"github.com/ledgerwatch/erigon/turbo/shards"
"github.com/ledgerwatch/erigon/turbo/snapshotsync"
"github.com/ledgerwatch/erigon/turbo/stages/headerdownload"
)
const (
logInterval = 20 * time.Second
// stateStreamLimit - don't accumulate state changes if jump is bigger than this amount of blocks
stateStreamLimit uint64 = 1_000
)
type HasChangeSetWriter interface {
ChangeSetWriter() *state.ChangeSetWriter
}
type ChangeSetHook func(blockNum uint64, wr *state.ChangeSetWriter)
type WithSnapshots interface {
Snapshots() *snapshotsync.RoSnapshots
}
type ExecuteBlockCfg struct {
db kv.RwDB
batchSize datasize.ByteSize
prune prune.Mode
changeSetHook ChangeSetHook
chainConfig *params.ChainConfig
engine consensus.Engine
vmConfig *vm.Config
badBlockHalt bool
stateStream bool
accumulator *shards.Accumulator
blockReader services.FullBlockReader
hd *headerdownload.HeaderDownload
dirs datadir.Dirs
historyV3 bool
workersCount int
genesis *core.Genesis
agg *libstate.Aggregator22
}
func StageExecuteBlocksCfg(
db kv.RwDB,
pm prune.Mode,
batchSize datasize.ByteSize,
changeSetHook ChangeSetHook,
chainConfig *params.ChainConfig,
engine consensus.Engine,
vmConfig *vm.Config,
accumulator *shards.Accumulator,
stateStream bool,
badBlockHalt bool,
historyV3 bool,
dirs datadir.Dirs,
blockReader services.FullBlockReader,
hd *headerdownload.HeaderDownload,
genesis *core.Genesis,
workersCount int,
agg *libstate.Aggregator22,
) ExecuteBlockCfg {
return ExecuteBlockCfg{
db: db,
prune: pm,
batchSize: batchSize,
changeSetHook: changeSetHook,
chainConfig: chainConfig,
engine: engine,
vmConfig: vmConfig,
dirs: dirs,
accumulator: accumulator,
stateStream: stateStream,
badBlockHalt: badBlockHalt,
blockReader: blockReader,
hd: hd,
genesis: genesis,
historyV3: historyV3,
workersCount: workersCount,
agg: agg,
}
}
func executeBlock(
block *types.Block,
tx kv.RwTx,
batch ethdb.Database,
cfg ExecuteBlockCfg,
vmConfig vm.Config, // emit copy, because will modify it
writeChangesets bool,
writeReceipts bool,
writeCallTraces bool,
initialCycle bool,
stateStream bool,
effectiveEngine consensus.Engine,
) error {
blockNum := block.NumberU64()
stateReader, stateWriter, err := newStateReaderWriter(batch, tx, block, writeChangesets, cfg.accumulator, initialCycle, stateStream)
if err != nil {
return err
}
// where the magic happens
getHeader := func(hash commonold.Hash, number uint64) *types.Header {
h, _ := cfg.blockReader.Header(context.Background(), tx, hash, number)
return h
}
getTracer := func(txIndex int, txHash ecom.Hash) (vm.Tracer, error) {
return vm.NewStructLogger(&vm.LogConfig{}), nil
}
callTracer := calltracer.NewCallTracer()
vmConfig.Debug = true
vmConfig.Tracer = callTracer
var receipts types.Receipts
var stateSyncReceipt *types.Receipt
var execRs *core.EphemeralExecResult
_, isPoSa := cfg.engine.(consensus.PoSA)
isBor := cfg.chainConfig.Bor != nil
getHashFn := core.GetHashFn(block.Header(), getHeader)
if isPoSa {
execRs, err = core.ExecuteBlockEphemerallyForBSC(cfg.chainConfig, &vmConfig, getHashFn, cfg.engine, block, stateReader, stateWriter, epochReader{tx: tx}, chainReader{config: cfg.chainConfig, tx: tx, blockReader: cfg.blockReader}, getTracer)
} else if isBor {
execRs, err = core.ExecuteBlockEphemerallyBor(cfg.chainConfig, &vmConfig, getHashFn, cfg.engine, block, stateReader, stateWriter, epochReader{tx: tx}, chainReader{config: cfg.chainConfig, tx: tx, blockReader: cfg.blockReader}, getTracer)
} else {
execRs, err = core.ExecuteBlockEphemerally(cfg.chainConfig, &vmConfig, getHashFn, cfg.engine, block, stateReader, stateWriter, epochReader{tx: tx}, chainReader{config: cfg.chainConfig, tx: tx, blockReader: cfg.blockReader}, getTracer)
}
if err != nil {
return err
}
receipts = execRs.Receipts
stateSyncReceipt = execRs.StateSyncReceipt
if writeReceipts {
if err = rawdb.AppendReceipts(tx, blockNum, receipts); err != nil {
return err
}
if stateSyncReceipt != nil && stateSyncReceipt.Status == types.ReceiptStatusSuccessful {
if err := rawdb.WriteBorReceipt(tx, block.Hash(), block.NumberU64(), stateSyncReceipt); err != nil {
return err
}
}
}
if cfg.changeSetHook != nil {
if hasChangeSet, ok := stateWriter.(HasChangeSetWriter); ok {
cfg.changeSetHook(blockNum, hasChangeSet.ChangeSetWriter())
}
}
if writeCallTraces {
return callTracer.WriteToDb(tx, block, *cfg.vmConfig)
}
return nil
}
func newStateReaderWriter(
batch ethdb.Database,
tx kv.RwTx,
block *types.Block,
writeChangesets bool,
accumulator *shards.Accumulator,
initialCycle bool,
stateStream bool,
) (state.StateReader, state.WriterWithChangeSets, error) {
var stateReader state.StateReader
var stateWriter state.WriterWithChangeSets
stateReader = state.NewPlainStateReader(batch)
if !initialCycle && stateStream {
txs, err := rawdb.RawTransactionsRange(tx, block.NumberU64(), block.NumberU64())
if err != nil {
return nil, nil, err
}
accumulator.StartChange(block.NumberU64(), block.Hash(), txs, false)
} else {
accumulator = nil
}
if writeChangesets {
stateWriter = state.NewPlainStateWriter(batch, tx, block.NumberU64()).SetAccumulator(accumulator)
} else {
stateWriter = state.NewPlainStateWriterNoHistory(batch).SetAccumulator(accumulator)
}
return stateReader, stateWriter, nil
}
// ================ Erigon3 ================
func ExecBlock22(s *StageState, u Unwinder, tx kv.RwTx, toBlock uint64, ctx context.Context, cfg ExecuteBlockCfg, initialCycle bool) (err error) {
workersCount := cfg.workersCount
//workersCount := 2
if !initialCycle {
workersCount = 1
}
cfg.agg.SetWorkers(cmp.Max(1, runtime.NumCPU()/2))
if initialCycle && s.BlockNumber == 0 {
reconstituteToBlock, found, err := reconstituteBlock(cfg.agg, cfg.db, tx)
if err != nil {
return err
}
if found && reconstituteToBlock > s.BlockNumber+1 {
reconWorkers := estimate.ReconstituteState.Workers()
log.Info(fmt.Sprintf("[%s] Blocks execution, reconstitution", s.LogPrefix()), "from", s.BlockNumber, "to", reconstituteToBlock)
if err := ReconstituteState(ctx, s, cfg.dirs, reconWorkers, cfg.batchSize, cfg.db, cfg.blockReader, log.New(), cfg.agg, cfg.engine, cfg.chainConfig, cfg.genesis); err != nil {
return err
}
}
}
prevStageProgress, err := senderStageProgress(tx, cfg.db)
if err != nil {
return err
}
logPrefix := s.LogPrefix()
var to = prevStageProgress
if toBlock > 0 {
to = cmp.Min(prevStageProgress, toBlock)
}
if to <= s.BlockNumber {
return nil
}
if to > s.BlockNumber+16 {
log.Info(fmt.Sprintf("[%s] Blocks execution", logPrefix), "from", s.BlockNumber, "to", to)
}
rs := state.NewState22()
if err := Exec3(ctx, s, workersCount, cfg.batchSize, cfg.db, tx, rs,
cfg.blockReader, log.New(), cfg.agg, cfg.engine,
to,
cfg.chainConfig, cfg.genesis); err != nil {
return err
}
return nil
}
// reconstituteBlock - First block which is not covered by the history snapshot files
func reconstituteBlock(agg *libstate.Aggregator22, db kv.RoDB, tx kv.Tx) (n uint64, ok bool, err error) {
if tx == nil {
if err = db.View(context.Background(), func(tx kv.Tx) error {
ok, n, err = rawdb.TxNums.FindBlockNum(tx, agg.EndTxNumMinimax())
return err
}); err != nil {
return
}
} else {
ok, n, err = rawdb.TxNums.FindBlockNum(tx, agg.EndTxNumMinimax())
}
return
}
func unwindExec3(u *UnwindState, s *StageState, tx kv.RwTx, ctx context.Context, cfg ExecuteBlockCfg) (err error) {
cfg.agg.SetLogPrefix(s.LogPrefix())
rs := state.NewState22()
// unwind all txs of u.UnwindPoint block. 1 txn in begin/end of block - system txs
txNum, err := rawdb.TxNums.Min(tx, u.UnwindPoint+1)
if err != nil {
return err
}
if err := rs.Unwind(ctx, tx, txNum, cfg.agg, cfg.accumulator); err != nil {
return fmt.Errorf("State22.Unwind: %w", err)
}
if err := rs.Flush(tx); err != nil {
return fmt.Errorf("State22.Flush: %w", err)
}
if err := rawdb.TruncateReceipts(tx, u.UnwindPoint+1); err != nil {
return fmt.Errorf("truncate receipts: %w", err)
}
if err := rawdb.TruncateBorReceipts(tx, u.UnwindPoint+1); err != nil {
return fmt.Errorf("truncate bor receipts: %w", err)
}
if err := rawdb.DeleteNewerEpochs(tx, u.UnwindPoint+1); err != nil {
return fmt.Errorf("delete newer epochs: %w", err)
}
return nil
}
func senderStageProgress(tx kv.Tx, db kv.RoDB) (prevStageProgress uint64, err error) {
if tx != nil {
prevStageProgress, err = stages.GetStageProgress(tx, stages.Senders)
if err != nil {
return prevStageProgress, err
}
} else {
if err = db.View(context.Background(), func(tx kv.Tx) error {
prevStageProgress, err = stages.GetStageProgress(tx, stages.Senders)
if err != nil {
return err
}
return nil
}); err != nil {
return prevStageProgress, err
}
}
return prevStageProgress, nil
}
// ================ Erigon3 End ================
func SpawnExecuteBlocksStage(s *StageState, u Unwinder, tx kv.RwTx, toBlock uint64, ctx context.Context, cfg ExecuteBlockCfg, initialCycle bool, quiet bool) (err error) {
if cfg.historyV3 {
return ExecBlock22(s, u, tx, toBlock, ctx, cfg, initialCycle)
}
quit := ctx.Done()
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(context.Background())
if err != nil {
return err
}
defer tx.Rollback()
}
prevStageProgress, errStart := stages.GetStageProgress(tx, stages.Senders)
if errStart != nil {
return errStart
}
nextStageProgress, err := stages.GetStageProgress(tx, stages.HashState)
if err != nil {
return err
}
nextStagesExpectData := nextStageProgress > 0 // Incremental move of next stages depend on fully written ChangeSets, Receipts, CallTraceSet
logPrefix := s.LogPrefix()
var to = prevStageProgress
if toBlock > 0 {
to = cmp.Min(prevStageProgress, toBlock)
}
if to <= s.BlockNumber {
return nil
}
if !quiet && to > s.BlockNumber+16 {
log.Info(fmt.Sprintf("[%s] Blocks execution", logPrefix), "from", s.BlockNumber, "to", to)
}
stateStream := !initialCycle && cfg.stateStream && to-s.BlockNumber < stateStreamLimit
// changes are stored through memory buffer
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
stageProgress := s.BlockNumber
logBlock := stageProgress
logTx, lastLogTx := uint64(0), uint64(0)
logTime := time.Now()
var gas uint64 // used for logs
var currentStateGas uint64 // used for batch commits of state
// Transform batch_size limit into Ggas
gasState := uint64(cfg.batchSize) * uint64(datasize.KB) * 2
var stoppedErr error
effectiveEngine := cfg.engine
if asyncEngine, ok := effectiveEngine.(consensus.AsyncEngine); ok {
asyncEngine = asyncEngine.WithExecutionContext(ctx)
effectiveEngine = asyncEngine.(consensus.Engine)
}
var batch ethdb.DbWithPendingMutations
// state is stored through ethdb batches
batch = olddb.NewHashBatch(tx, quit, cfg.dirs.Tmp)
// avoids stacking defers within the loop
defer func() {
batch.Rollback()
}()
Loop:
for blockNum := stageProgress + 1; blockNum <= to; blockNum++ {
if stoppedErr = common.Stopped(quit); stoppedErr != nil {
break
}
blockHash, err := rawdb.ReadCanonicalHash(tx, blockNum)
if err != nil {
return err
}
block, _, err := cfg.blockReader.BlockWithSenders(ctx, tx, blockHash, blockNum)
if err != nil {
return err
}
if block == nil {
log.Error(fmt.Sprintf("[%s] Empty block", logPrefix), "blocknum", blockNum)
break
}
lastLogTx += uint64(block.Transactions().Len())
// Incremental move of next stages depend on fully written ChangeSets, Receipts, CallTraceSet
writeChangeSets := nextStagesExpectData || blockNum > cfg.prune.History.PruneTo(to)
writeReceipts := nextStagesExpectData || blockNum > cfg.prune.Receipts.PruneTo(to)
writeCallTraces := nextStagesExpectData || blockNum > cfg.prune.CallTraces.PruneTo(to)
if err = executeBlock(block, tx, batch, cfg, *cfg.vmConfig, writeChangeSets, writeReceipts, writeCallTraces, initialCycle, stateStream, effectiveEngine); err != nil {
if !errors.Is(err, context.Canceled) {
log.Warn(fmt.Sprintf("[%s] Execution failed", logPrefix), "block", blockNum, "hash", block.Hash().String(), "err", err)
if cfg.hd != nil {
cfg.hd.ReportBadHeaderPoS(blockHash, block.ParentHash())
}
if cfg.badBlockHalt {
return err
}
}
u.UnwindTo(blockNum-1, block.Hash())
break Loop
}
stageProgress = blockNum
shouldUpdateProgress := batch.BatchSize() >= int(cfg.batchSize)
if shouldUpdateProgress {
log.Info("Committed State", "gas reached", currentStateGas, "gasTarget", gasState)
currentStateGas = 0
if err = batch.Commit(); err != nil {
return err
}
if !useExternalTx {
if err = s.Update(tx, stageProgress); err != nil {
return err
}
if err = tx.Commit(); err != nil {
return err
}
tx, err = cfg.db.BeginRw(context.Background())
if err != nil {
return err
}
// TODO: This creates stacked up deferrals
defer tx.Rollback()
}
batch = olddb.NewHashBatch(tx, quit, cfg.dirs.Tmp)
}
gas = gas + block.GasUsed()
currentStateGas = currentStateGas + block.GasUsed()
select {
default:
case <-logEvery.C:
logBlock, logTx, logTime = logProgress(logPrefix, logBlock, logTime, blockNum, logTx, lastLogTx, gas, float64(currentStateGas)/float64(gasState), batch)
gas = 0
tx.CollectMetrics()
syncMetrics[stages.Execution].Set(blockNum)
}
}
if err = s.Update(batch, stageProgress); err != nil {
return err
}
if err = batch.Commit(); err != nil {
return fmt.Errorf("batch commit: %w", err)
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
if !quiet {
log.Info(fmt.Sprintf("[%s] Completed on", logPrefix), "block", stageProgress)
}
return stoppedErr
}
func logProgress(logPrefix string, prevBlock uint64, prevTime time.Time, currentBlock uint64, prevTx, currentTx uint64, gas uint64, gasState float64, batch ethdb.DbWithPendingMutations) (uint64, uint64, time.Time) {
currentTime := time.Now()
interval := currentTime.Sub(prevTime)
speed := float64(currentBlock-prevBlock) / (float64(interval) / float64(time.Second))
speedTx := float64(currentTx-prevTx) / (float64(interval) / float64(time.Second))
speedMgas := float64(gas) / 1_000_000 / (float64(interval) / float64(time.Second))
var m runtime.MemStats
common.ReadMemStats(&m)
var logpairs = []interface{}{
"number", currentBlock,
"blk/s", fmt.Sprintf("%.1f", speed),
"tx/s", fmt.Sprintf("%.1f", speedTx),
"Mgas/s", fmt.Sprintf("%.1f", speedMgas),
"gasState", fmt.Sprintf("%.2f", gasState),
}
if batch != nil {
logpairs = append(logpairs, "batch", common.ByteCount(uint64(batch.BatchSize())))
}
logpairs = append(logpairs, "alloc", common.ByteCount(m.Alloc), "sys", common.ByteCount(m.Sys))
log.Info(fmt.Sprintf("[%s] Executed blocks", logPrefix), logpairs...)
return currentBlock, currentTx, currentTime
}
func UnwindExecutionStage(u *UnwindState, s *StageState, tx kv.RwTx, ctx context.Context, cfg ExecuteBlockCfg, initialCycle bool) (err error) {
if u.UnwindPoint >= s.BlockNumber {
return nil
}
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(context.Background())
if err != nil {
return err
}
defer tx.Rollback()
}
logPrefix := u.LogPrefix()
log.Info(fmt.Sprintf("[%s] Unwind Execution", logPrefix), "from", s.BlockNumber, "to", u.UnwindPoint)
if err = unwindExecutionStage(u, s, tx, ctx, cfg, initialCycle); 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 unwindExecutionStage(u *UnwindState, s *StageState, tx kv.RwTx, ctx context.Context, cfg ExecuteBlockCfg, initialCycle bool) error {
logPrefix := s.LogPrefix()
stateBucket := kv.PlainState
storageKeyLength := length.Addr + length.Incarnation + length.Hash
var accumulator *shards.Accumulator
if !initialCycle && cfg.stateStream && s.BlockNumber-u.UnwindPoint < stateStreamLimit {
accumulator = cfg.accumulator
hash, err := rawdb.ReadCanonicalHash(tx, u.UnwindPoint)
if err != nil {
return fmt.Errorf("read canonical hash of unwind point: %w", err)
}
txs, err := rawdb.RawTransactionsRange(tx, u.UnwindPoint, s.BlockNumber)
if err != nil {
return err
}
accumulator.StartChange(u.UnwindPoint, hash, txs, true)
}
if cfg.historyV3 {
return unwindExec3(u, s, tx, ctx, cfg)
}
changes := etl.NewCollector(logPrefix, cfg.dirs.Tmp, etl.NewOldestEntryBuffer(etl.BufferOptimalSize))
defer changes.Close()
errRewind := changeset.RewindData(tx, s.BlockNumber, u.UnwindPoint, changes, ctx.Done())
if errRewind != nil {
return fmt.Errorf("getting rewind data: %w", errRewind)
}
if err := changes.Load(tx, stateBucket, func(k, v []byte, table etl.CurrentTableReader, next etl.LoadNextFunc) error {
if len(k) == 20 {
if len(v) > 0 {
var acc accounts.Account
if err := acc.DecodeForStorage(v); err != nil {
return err
}
// Fetch the code hash
recoverCodeHashPlain(&acc, tx, k)
var address commonold.Address
copy(address[:], k)
// cleanup contract code bucket
original, err := state.NewPlainStateReader(tx).ReadAccountData(address)
if err != nil {
return fmt.Errorf("read account for %x: %w", address, err)
}
if original != nil {
// clean up all the code incarnations original incarnation and the new one
for incarnation := original.Incarnation; incarnation > acc.Incarnation && incarnation > 0; incarnation-- {
err = tx.Delete(kv.PlainContractCode, dbutils.PlainGenerateStoragePrefix(address[:], incarnation))
if err != nil {
return fmt.Errorf("writeAccountPlain for %x: %w", address, err)
}
}
}
newV := make([]byte, acc.EncodingLengthForStorage())
acc.EncodeForStorage(newV)
if accumulator != nil {
accumulator.ChangeAccount(address, acc.Incarnation, newV)
}
if err := next(k, k, newV); err != nil {
return err
}
} else {
if accumulator != nil {
var address commonold.Address
copy(address[:], k)
accumulator.DeleteAccount(address)
}
if err := next(k, k, nil); err != nil {
return err
}
}
return nil
}
if accumulator != nil {
var address commonold.Address
var incarnation uint64
var location commonold.Hash
copy(address[:], k[:length.Addr])
incarnation = binary.BigEndian.Uint64(k[length.Addr:])
copy(location[:], k[length.Addr+length.Incarnation:])
log.Debug(fmt.Sprintf("un ch st: %x, %d, %x, %x\n", address, incarnation, location, common.Copy(v)))
accumulator.ChangeStorage(address, incarnation, location, common.Copy(v))
}
if len(v) > 0 {
if err := next(k, k[:storageKeyLength], v); err != nil {
return err
}
} else {
if err := next(k, k[:storageKeyLength], nil); err != nil {
return err
}
}
return nil
}, etl.TransformArgs{Quit: ctx.Done()}); err != nil {
return err
}
if err := changeset.Truncate(tx, u.UnwindPoint+1); err != nil {
return err
}
if err := rawdb.TruncateReceipts(tx, u.UnwindPoint+1); err != nil {
return fmt.Errorf("truncate receipts: %w", err)
}
if err := rawdb.TruncateBorReceipts(tx, u.UnwindPoint+1); err != nil {
return fmt.Errorf("truncate bor receipts: %w", err)
}
if err := rawdb.DeleteNewerEpochs(tx, u.UnwindPoint+1); err != nil {
return fmt.Errorf("delete newer epochs: %w", err)
}
// Truncate CallTraceSet
keyStart := dbutils.EncodeBlockNumber(u.UnwindPoint + 1)
c, err := tx.RwCursorDupSort(kv.CallTraceSet)
if err != nil {
return err
}
defer c.Close()
for k, _, err := c.Seek(keyStart); k != nil; k, _, err = c.NextNoDup() {
if err != nil {
return err
}
err = c.DeleteCurrentDuplicates()
if err != nil {
return err
}
}
return nil
}
func recoverCodeHashPlain(acc *accounts.Account, db kv.Tx, key []byte) {
var address commonold.Address
copy(address[:], key)
if acc.Incarnation > 0 && acc.IsEmptyCodeHash() {
if codeHash, err2 := db.GetOne(kv.PlainContractCode, dbutils.PlainGenerateStoragePrefix(address[:], acc.Incarnation)); err2 == nil {
copy(acc.CodeHash[:], codeHash)
}
}
}
func PruneExecutionStage(s *PruneState, tx kv.RwTx, cfg ExecuteBlockCfg, ctx context.Context, initialCycle bool) (err error) {
logPrefix := s.LogPrefix()
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
if cfg.prune.History.Enabled() {
if err = rawdb.PruneTableDupSort(tx, kv.AccountChangeSet, logPrefix, cfg.prune.History.PruneTo(s.ForwardProgress), logEvery, ctx); err != nil {
return err
}
if err = rawdb.PruneTableDupSort(tx, kv.StorageChangeSet, logPrefix, cfg.prune.History.PruneTo(s.ForwardProgress), logEvery, ctx); err != nil {
return err
}
}
if cfg.prune.Receipts.Enabled() {
if err = rawdb.PruneTable(tx, kv.Receipts, cfg.prune.Receipts.PruneTo(s.ForwardProgress), ctx, math.MaxInt32); err != nil {
return err
}
if err = rawdb.PruneTable(tx, kv.BorReceipts, cfg.prune.Receipts.PruneTo(s.ForwardProgress), ctx, math.MaxUint32); err != nil {
return err
}
// LogIndex.Prune will read everything what not pruned here
if err = rawdb.PruneTable(tx, kv.Log, cfg.prune.Receipts.PruneTo(s.ForwardProgress), ctx, math.MaxInt32); err != nil {
return err
}
}
if cfg.prune.CallTraces.Enabled() {
if err = rawdb.PruneTableDupSort(tx, kv.CallTraceSet, logPrefix, cfg.prune.CallTraces.PruneTo(s.ForwardProgress), logEvery, ctx); err != nil {
return err
}
}
if err = s.Done(tx); err != nil {
return err
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}