forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 44
/
stage_execute.go
434 lines (389 loc) · 12.6 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
// Copyright 2024 The Erigon Authors
// This file is part of Erigon.
//
// Erigon is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Erigon is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Erigon. If not, see <http://www.gnu.org/licenses/>.
package stagedsync
import (
"context"
"errors"
"fmt"
"time"
"github.com/c2h5oh/datasize"
"golang.org/x/sync/errgroup"
"github.com/erigontech/erigon/cmd/state/exec3"
"github.com/erigontech/erigon-lib/chain"
"github.com/erigontech/erigon-lib/common"
"github.com/erigontech/erigon-lib/common/datadir"
"github.com/erigontech/erigon-lib/common/dbg"
"github.com/erigontech/erigon-lib/config3"
"github.com/erigontech/erigon-lib/kv"
"github.com/erigontech/erigon-lib/kv/rawdbv3"
"github.com/erigontech/erigon-lib/kv/temporal"
"github.com/erigontech/erigon-lib/log/v3"
libstate "github.com/erigontech/erigon-lib/state"
"github.com/erigontech/erigon-lib/wrap"
"github.com/erigontech/erigon/consensus"
"github.com/erigontech/erigon/core/rawdb"
"github.com/erigontech/erigon/core/rawdb/rawdbhelpers"
"github.com/erigontech/erigon/core/state"
"github.com/erigontech/erigon/core/types"
"github.com/erigontech/erigon/core/vm"
"github.com/erigontech/erigon/eth/ethconfig"
"github.com/erigontech/erigon/eth/stagedsync/stages"
"github.com/erigontech/erigon/ethdb/prune"
"github.com/erigontech/erigon/turbo/services"
"github.com/erigontech/erigon/turbo/shards"
"github.com/erigontech/erigon/turbo/silkworm"
"github.com/erigontech/erigon/turbo/snapshotsync/freezeblocks"
)
const (
logInterval = 30 * time.Second
// stateStreamLimit - don't accumulate state changes if jump is bigger than this amount of blocks
stateStreamLimit uint64 = 1_000
)
type headerDownloader interface {
ReportBadHeaderPoS(badHeader, lastValidAncestor common.Hash)
POSSync() bool
}
type ExecuteBlockCfg struct {
db kv.RwDB
batchSize datasize.ByteSize
prune prune.Mode
chainConfig *chain.Config
notifications *shards.Notifications
engine consensus.Engine
vmConfig *vm.Config
badBlockHalt bool
stateStream bool
blockReader services.FullBlockReader
hd headerDownloader
author *common.Address
// last valid number of the stage
dirs datadir.Dirs
historyV3 bool
syncCfg ethconfig.Sync
genesis *types.Genesis
silkworm *silkworm.Silkworm
blockProduction bool
keepAllChangesets bool
applyWorker, applyWorkerMining *exec3.Worker
}
func StageExecuteBlocksCfg(
db kv.RwDB,
pm prune.Mode,
batchSize datasize.ByteSize,
chainConfig *chain.Config,
engine consensus.Engine,
vmConfig *vm.Config,
notifications *shards.Notifications,
stateStream bool,
badBlockHalt bool,
keepAllChangesets bool,
dirs datadir.Dirs,
blockReader services.FullBlockReader,
hd headerDownloader,
genesis *types.Genesis,
syncCfg ethconfig.Sync,
silkworm *silkworm.Silkworm,
) ExecuteBlockCfg {
if dirs.SnapDomain == "" {
panic("empty `dirs` variable")
}
return ExecuteBlockCfg{
db: db,
prune: pm,
batchSize: batchSize,
chainConfig: chainConfig,
engine: engine,
vmConfig: vmConfig,
dirs: dirs,
notifications: notifications,
stateStream: stateStream,
badBlockHalt: badBlockHalt,
blockReader: blockReader,
hd: hd,
genesis: genesis,
historyV3: true,
syncCfg: syncCfg,
silkworm: silkworm,
applyWorker: exec3.NewWorker(nil, log.Root(), context.Background(), false, db, nil, blockReader, chainConfig, genesis, nil, engine, dirs, false),
applyWorkerMining: exec3.NewWorker(nil, log.Root(), context.Background(), false, db, nil, blockReader, chainConfig, genesis, nil, engine, dirs, true),
keepAllChangesets: keepAllChangesets,
}
}
// ================ Erigon3 ================
func ExecBlockV3(s *StageState, u Unwinder, txc wrap.TxContainer, toBlock uint64, ctx context.Context, cfg ExecuteBlockCfg, initialCycle bool, logger log.Logger, isMining bool) (err error) {
workersCount := cfg.syncCfg.ExecWorkerCount
if !initialCycle {
workersCount = 1
}
prevStageProgress, err := senderStageProgress(txc.Tx, cfg.db)
if err != nil {
return err
}
var to = prevStageProgress
if toBlock > 0 {
to = min(prevStageProgress, toBlock)
}
if to < s.BlockNumber {
return nil
}
parallel := txc.Tx == nil
if err := ExecV3(ctx, s, u, workersCount, cfg, txc, parallel, to, logger, initialCycle, isMining); err != nil {
return err
}
return nil
}
var ErrTooDeepUnwind = errors.New("too deep unwind")
func unwindExec3(u *UnwindState, s *StageState, txc wrap.TxContainer, ctx context.Context, br services.FullBlockReader, accumulator *shards.Accumulator, logger log.Logger) (err error) {
var domains *libstate.SharedDomains
if txc.Doms == nil {
domains, err = libstate.NewSharedDomains(txc.Tx, logger)
if err != nil {
return err
}
defer domains.Close()
} else {
domains = txc.Doms
}
rs := state.NewStateV3(domains, logger)
txNumsReader := rawdbv3.TxNums.WithCustomReadTxNumFunc(freezeblocks.ReadTxNumFuncFromBlockReader(ctx, br))
// unwind all txs of u.UnwindPoint block. 1 txn in begin/end of block - system txs
txNum, err := txNumsReader.Min(txc.Tx, u.UnwindPoint+1)
if err != nil {
return err
}
t := time.Now()
var changeset *[kv.DomainLen][]libstate.DomainEntryDiff
for currentBlock := u.CurrentBlockNumber; currentBlock > u.UnwindPoint; currentBlock-- {
currentHash, ok, err := br.CanonicalHash(ctx, txc.Tx, currentBlock)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("canonical hash not found %d", currentBlock)
}
var currentKeys [kv.DomainLen][]libstate.DomainEntryDiff
currentKeys, ok, err = domains.GetDiffset(txc.Tx, currentHash, currentBlock)
if !ok {
return fmt.Errorf("domains.GetDiffset(%d, %s): not found", currentBlock, currentHash)
}
if err != nil {
return err
}
if changeset == nil {
changeset = ¤tKeys
} else {
for i := range currentKeys {
changeset[i] = libstate.MergeDiffSets(changeset[i], currentKeys[i])
}
}
}
if err := rs.Unwind(ctx, txc.Tx, u.UnwindPoint, txNum, accumulator, changeset); err != nil {
return fmt.Errorf("StateV3.Unwind(%d->%d): %w, took %s", s.BlockNumber, u.UnwindPoint, err, time.Since(t))
}
if err := rawdb.DeleteNewerEpochs(txc.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, txc wrap.TxContainer, toBlock uint64, ctx context.Context, cfg ExecuteBlockCfg, logger log.Logger) (err error) {
if dbg.StagesOnlyBlocks {
return nil
}
if err = ExecBlockV3(s, u, txc, toBlock, ctx, cfg, s.CurrentSyncCycle.IsInitialCycle, logger, false); err != nil {
return err
}
return nil
}
func blocksReadAhead(ctx context.Context, cfg *ExecuteBlockCfg, workers int, histV3 bool) (chan uint64, context.CancelFunc) {
const readAheadBlocks = 100
readAhead := make(chan uint64, readAheadBlocks)
g, gCtx := errgroup.WithContext(ctx)
for workerNum := 0; workerNum < workers; workerNum++ {
g.Go(func() (err error) {
var bn uint64
var ok bool
var tx kv.Tx
defer func() {
if tx != nil {
tx.Rollback()
}
}()
for i := 0; ; i++ {
select {
case bn, ok = <-readAhead:
if !ok {
return
}
case <-gCtx.Done():
return gCtx.Err()
}
if i%100 == 0 {
if tx != nil {
tx.Rollback()
}
tx, err = cfg.db.BeginRo(ctx)
if err != nil {
return err
}
}
if err := blocksReadAheadFunc(gCtx, tx, cfg, bn+readAheadBlocks, histV3); err != nil {
return err
}
}
})
}
return readAhead, func() {
close(readAhead)
_ = g.Wait()
}
}
func blocksReadAheadFunc(ctx context.Context, tx kv.Tx, cfg *ExecuteBlockCfg, blockNum uint64, histV3 bool) error {
block, err := cfg.blockReader.BlockByNumber(ctx, tx, blockNum)
if err != nil {
return err
}
if block == nil {
return nil
}
_, _ = cfg.engine.Author(block.HeaderNoCopy()) // Bor consensus: this calc is heavy and has cache
if histV3 {
return nil
}
return nil
}
func UnwindExecutionStage(u *UnwindState, s *StageState, txc wrap.TxContainer, ctx context.Context, cfg ExecuteBlockCfg, logger log.Logger) (err error) {
//fmt.Printf("unwind: %d -> %d\n", u.CurrentBlockNumber, u.UnwindPoint)
if u.UnwindPoint >= s.BlockNumber {
return nil
}
useExternalTx := txc.Tx != nil
if !useExternalTx {
txc.Tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer txc.Tx.Rollback()
}
logPrefix := u.LogPrefix()
logger.Info(fmt.Sprintf("[%s] Unwind Execution", logPrefix), "from", s.BlockNumber, "to", u.UnwindPoint)
unwindToLimit, ok, err := txc.Tx.(libstate.HasAggTx).AggTx().(*libstate.AggregatorRoTx).CanUnwindBeforeBlockNum(u.UnwindPoint, txc.Tx)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("%w: %d < %d", ErrTooDeepUnwind, u.UnwindPoint, unwindToLimit)
}
if err = unwindExecutionStage(u, s, txc, ctx, cfg, logger); err != nil {
return err
}
if err = u.Done(txc.Tx); err != nil {
return err
}
//dumpPlainStateDebug(tx, nil)
if !useExternalTx {
if err = txc.Tx.Commit(); err != nil {
return err
}
}
return nil
}
func unwindExecutionStage(u *UnwindState, s *StageState, txc wrap.TxContainer, ctx context.Context, cfg ExecuteBlockCfg, logger log.Logger) error {
var accumulator *shards.Accumulator
if cfg.stateStream && s.BlockNumber-u.UnwindPoint < stateStreamLimit {
accumulator = cfg.notifications.Accumulator
hash, ok, err := cfg.blockReader.CanonicalHash(ctx, txc.Tx, u.UnwindPoint)
if err != nil {
return fmt.Errorf("read canonical hash of unwind point: %w", err)
}
if !ok {
return fmt.Errorf("canonical hash not found %d", u.UnwindPoint)
}
txs, err := cfg.blockReader.RawTransactions(ctx, txc.Tx, u.UnwindPoint, s.BlockNumber)
if err != nil {
return err
}
accumulator.StartChange(u.UnwindPoint, hash, txs, true)
}
return unwindExec3(u, s, txc, ctx, cfg.blockReader, accumulator, logger)
}
func PruneExecutionStage(s *PruneState, tx kv.RwTx, cfg ExecuteBlockCfg, 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 s.ForwardProgress > config3.MaxReorgDepthV3 && !cfg.keepAllChangesets {
// (chunkLen is 8Kb) * (1_000 chunks) = 8mb
// Some blocks on bor-mainnet have 400 chunks of diff = 3mb
var pruneDiffsLimitOnChainTip = 1_000
if s.CurrentSyncCycle.IsInitialCycle {
pruneDiffsLimitOnChainTip *= 10
}
if err := rawdb.PruneTable(tx, kv.ChangeSets3, s.ForwardProgress-config3.MaxReorgDepthV3, ctx, pruneDiffsLimitOnChainTip); err != nil {
return err
}
}
mxExecStepsInDB.Set(rawdbhelpers.IdxStepsCountV3(tx) * 100)
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
// on chain-tip:
// - can prune only between blocks (without blocking blocks processing)
// - need also leave some time to prune blocks
// - need keep "fsync" time of db fast
// Means - the best is:
// - stop prune when `tx.SpaceDirty()` is big
// - and set ~500ms timeout
// because on slow disks - prune is slower. but for now - let's tune for nvme first, and add `tx.SpaceDirty()` check later https://github.com/erigontech/erigon/issues/11635
pruneTimeout := 250 * time.Millisecond
if s.CurrentSyncCycle.IsInitialCycle {
pruneTimeout = 12 * time.Hour
}
if _, err = tx.(*temporal.Tx).AggTx().(*libstate.AggregatorRoTx).PruneSmallBatches(ctx, pruneTimeout, tx); err != nil { // prune part of retired data, before commit
return err
}
if err = s.Done(tx); err != nil {
return err
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}