-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
stage_txlookup.go
387 lines (344 loc) · 12 KB
/
stage_txlookup.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
// 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"
"encoding/binary"
"fmt"
"math/big"
"time"
"github.com/erigontech/erigon-lib/kv/rawdbv3"
"github.com/erigontech/erigon-lib/log/v3"
"github.com/erigontech/erigon/eth/stagedsync/stages"
"github.com/erigontech/erigon-lib/chain"
libcommon "github.com/erigontech/erigon-lib/common"
"github.com/erigontech/erigon-lib/common/hexutility"
"github.com/erigontech/erigon-lib/etl"
"github.com/erigontech/erigon-lib/kv"
"github.com/erigontech/erigon/core/rawdb"
"github.com/erigontech/erigon/ethdb/prune"
"github.com/erigontech/erigon/polygon/bor/borcfg"
bortypes "github.com/erigontech/erigon/polygon/bor/types"
"github.com/erigontech/erigon/turbo/services"
)
type TxLookupCfg struct {
db kv.RwDB
prune prune.Mode
tmpdir string
borConfig *borcfg.BorConfig
blockReader services.FullBlockReader
}
func StageTxLookupCfg(
db kv.RwDB,
prune prune.Mode,
tmpdir string,
borConfigInterface chain.BorConfig,
blockReader services.FullBlockReader,
) TxLookupCfg {
var borConfig *borcfg.BorConfig
if borConfigInterface != nil {
borConfig = borConfigInterface.(*borcfg.BorConfig)
}
return TxLookupCfg{
db: db,
prune: prune,
tmpdir: tmpdir,
borConfig: borConfig,
blockReader: blockReader,
}
}
func SpawnTxLookup(s *StageState, tx kv.RwTx, toBlock uint64, cfg TxLookupCfg, 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 := s.LogPrefix()
endBlock, err := s.ExecutionAt(tx)
if err != nil {
return err
}
if s.BlockNumber > endBlock { // Erigon will self-heal (download missed blocks) eventually
return nil
}
if toBlock > 0 {
endBlock = min(endBlock, toBlock)
}
startBlock := s.BlockNumber
if cfg.prune.History.Enabled() {
pruneTo := cfg.prune.History.PruneTo(endBlock)
if startBlock < pruneTo {
startBlock = pruneTo
if err = s.UpdatePrune(tx, pruneTo); err != nil { // prune func of this stage will use this value to prevent all ancient blocks traversal
return err
}
}
}
if cfg.blockReader.FrozenBlocks() > startBlock {
// Snapshot .idx files already have TxLookup index - then no reason iterate over them here
startBlock = cfg.blockReader.FrozenBlocks()
if err = s.UpdatePrune(tx, startBlock); err != nil { // prune func of this stage will use this value to prevent all ancient blocks traversal
return err
}
}
if startBlock > 0 {
startBlock++
}
// etl.Transform uses ExtractEndKey as exclusive bound, therefore endBlock + 1
if err = txnLookupTransform(logPrefix, tx, startBlock, endBlock+1, ctx, cfg, logger); err != nil {
return fmt.Errorf("txnLookupTransform: %w", err)
}
if cfg.borConfig != nil {
if err = borTxnLookupTransform(logPrefix, tx, startBlock, endBlock+1, ctx.Done(), cfg, logger); err != nil {
return fmt.Errorf("borTxnLookupTransform: %w", err)
}
}
if err = s.Update(tx, endBlock); err != nil {
return err
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}
// txnLookupTransform - [startKey, endKey)
func txnLookupTransform(logPrefix string, tx kv.RwTx, blockFrom, blockTo uint64, ctx context.Context, cfg TxLookupCfg, logger log.Logger) (err error) {
data := make([]byte, 16)
return etl.Transform(logPrefix, tx, kv.HeaderCanonical, kv.TxLookup, cfg.tmpdir, func(k, v []byte, next etl.ExtractNextFunc) error {
blocknum, blockHash := binary.BigEndian.Uint64(k), libcommon.CastToHash(v)
body, err := cfg.blockReader.BodyWithTransactions(ctx, tx, blockHash, blocknum)
if err != nil {
return err
}
if body == nil { // tolerate such an error, because likely it's corner-case - and not critical one
log.Warn(fmt.Sprintf("[%s] transform: empty block body %d, hash %x", logPrefix, blocknum, v))
return nil
}
firstTxNumInBlock, err := rawdbv3.TxNums.Min(tx, blocknum)
if err != nil {
return err
}
if firstTxNumInBlock == 0 {
log.Warn(fmt.Sprintf("[%s] transform: empty txnum %d, hash %x", logPrefix, firstTxNumInBlock, v))
return nil
}
binary.BigEndian.PutUint64(data[:8], blocknum)
for i, txn := range body.Transactions {
binary.BigEndian.PutUint64(data[8:], firstTxNumInBlock+uint64(i)+1)
if err := next(k, txn.Hash().Bytes(), data); err != nil {
return err
}
}
return nil
}, etl.IdentityLoadFunc, etl.TransformArgs{
Quit: ctx.Done(),
ExtractStartKey: hexutility.EncodeTs(blockFrom),
ExtractEndKey: hexutility.EncodeTs(blockTo),
LogDetailsExtract: func(k, v []byte) (additionalLogArguments []interface{}) {
return []interface{}{"block", binary.BigEndian.Uint64(k)}
},
}, logger)
}
// txnLookupTransform - [startKey, endKey)
func borTxnLookupTransform(logPrefix string, tx kv.RwTx, blockFrom, blockTo uint64, quitCh <-chan struct{}, cfg TxLookupCfg, logger log.Logger) error {
bigNum := new(big.Int)
return etl.Transform(logPrefix, tx, kv.HeaderCanonical, kv.BorTxLookup, cfg.tmpdir, func(k, v []byte, next etl.ExtractNextFunc) error {
blocknum, blockHash := binary.BigEndian.Uint64(k), libcommon.CastToHash(v)
blockNumBytes := bigNum.SetUint64(blocknum).Bytes()
// we add state sync transactions every bor Sprint amount of blocks
if cfg.borConfig.IsSprintStart(blocknum) && rawdb.HasBorReceipts(tx, blocknum) {
txnHash := bortypes.ComputeBorTxHash(blocknum, blockHash)
if err := next(k, txnHash.Bytes(), blockNumBytes); err != nil {
return err
}
}
return nil
}, etl.IdentityLoadFunc, etl.TransformArgs{
Quit: quitCh,
ExtractStartKey: hexutility.EncodeTs(blockFrom),
ExtractEndKey: hexutility.EncodeTs(blockTo),
LogDetailsExtract: func(k, v []byte) (additionalLogArguments []interface{}) {
return []interface{}{"block", binary.BigEndian.Uint64(k)}
},
}, logger)
}
func UnwindTxLookup(u *UnwindState, s *StageState, tx kv.RwTx, cfg TxLookupCfg, ctx context.Context, logger log.Logger) (err error) {
u.UnwindPoint = max(u.UnwindPoint, cfg.blockReader.FrozenBlocks()) // protect from unwind behind files
if s.BlockNumber <= u.UnwindPoint {
return nil
}
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
// end key needs to be s.BlockNumber + 1 and not s.BlockNumber, because
// the keys in BlockBody table always have hash after the block number
blockFrom, blockTo := u.UnwindPoint+1, s.BlockNumber+1
smallestInDB := cfg.blockReader.FrozenBlocks()
blockFrom, blockTo = max(blockFrom, smallestInDB), max(blockTo, smallestInDB)
// etl.Transform uses ExtractEndKey as exclusive bound, therefore blockTo + 1
if err := deleteTxLookupRange(tx, s.LogPrefix(), blockFrom, blockTo+1, ctx, cfg, logger); err != nil {
return fmt.Errorf("unwind TxLookUp: %w", err)
}
if cfg.borConfig != nil {
if err := deleteBorTxLookupRange(tx, s.LogPrefix(), blockFrom, blockTo+1, ctx, cfg, logger); err != nil {
return fmt.Errorf("unwind BorTxLookUp: %w", err)
}
}
if err := u.Done(tx); err != nil {
return err
}
if !useExternalTx {
if err := tx.Commit(); err != nil {
return err
}
}
return nil
}
func PruneTxLookup(s *PruneState, tx kv.RwTx, cfg TxLookupCfg, ctx context.Context, logger log.Logger) (err error) {
logPrefix := s.LogPrefix()
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
blockFrom := s.PruneProgress
if blockFrom == 0 {
firstNonGenesisHeader, err := rawdbv3.SecondKey(tx, kv.Headers)
if err != nil {
return err
}
if firstNonGenesisHeader != nil {
blockFrom = binary.BigEndian.Uint64(firstNonGenesisHeader)
} else {
execProgress, err := stageProgress(tx, nil, stages.Senders)
if err != nil {
return err
}
blockFrom = execProgress
}
}
var blockTo uint64
var pruneBor bool
// Forward stage doesn't write anything before PruneTo point
if cfg.prune.History.Enabled() {
blockTo = cfg.prune.History.PruneTo(s.ForwardProgress)
pruneBor = true
} else {
blockTo = cfg.blockReader.CanPruneTo(s.ForwardProgress)
}
pruneTimeout := time.Hour // aggressive pruning at non-chain-tip
if !s.CurrentSyncCycle.IsInitialCycle {
pruneTimeout = 250 * time.Millisecond
// can't prune much on non-chain-tip: because tx_lookup has crypto-hashed-keys. 1 block producing hundreds of random deletes: ~2pages updated per delete
blockTo = min(blockTo, blockFrom+10)
}
if blockFrom < blockTo {
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
t := time.Now()
var pruneBlockNum = blockFrom
for ; pruneBlockNum < blockTo; pruneBlockNum++ {
select {
case <-logEvery.C:
logger.Info(fmt.Sprintf("[%s] progress", logPrefix), "blockNum", pruneBlockNum)
default:
}
err = deleteTxLookupRange(tx, logPrefix, pruneBlockNum, pruneBlockNum+1, ctx, cfg, logger)
if err != nil {
return fmt.Errorf("prune TxLookUp: %w", err)
}
if cfg.borConfig != nil && pruneBor {
if err = deleteBorTxLookupRange(tx, logPrefix, pruneBlockNum, pruneBlockNum+1, ctx, cfg, logger); err != nil {
return fmt.Errorf("prune BorTxLookUp: %w", err)
}
}
if time.Since(t) > pruneTimeout {
break
}
}
if err = s.DoneAt(tx, pruneBlockNum); err != nil {
return err
}
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}
// deleteTxLookupRange - [blockFrom, blockTo)
func deleteTxLookupRange(tx kv.RwTx, logPrefix string, blockFrom, blockTo uint64, ctx context.Context, cfg TxLookupCfg, logger log.Logger) (err error) {
err = etl.Transform(logPrefix, tx, kv.HeaderCanonical, kv.TxLookup, cfg.tmpdir, func(k, v []byte, next etl.ExtractNextFunc) error {
blocknum, blockHash := binary.BigEndian.Uint64(k), libcommon.CastToHash(v)
body, err := cfg.blockReader.BodyWithTransactions(ctx, tx, blockHash, blocknum)
if err != nil {
return err
}
if body == nil {
log.Debug("TxLookup pruning, empty block body", "height", blocknum)
return nil
}
for _, txn := range body.Transactions {
if err := next(k, txn.Hash().Bytes(), nil); err != nil {
return err
}
}
return nil
}, etl.IdentityLoadFunc, etl.TransformArgs{
Quit: ctx.Done(),
ExtractStartKey: hexutility.EncodeTs(blockFrom),
ExtractEndKey: hexutility.EncodeTs(blockTo),
LogDetailsExtract: func(k, v []byte) (additionalLogArguments []interface{}) {
return []interface{}{"block", binary.BigEndian.Uint64(k)}
},
}, logger)
if err != nil {
return err
}
return nil
}
// deleteTxLookupRange - [blockFrom, blockTo)
func deleteBorTxLookupRange(tx kv.RwTx, logPrefix string, blockFrom, blockTo uint64, ctx context.Context, cfg TxLookupCfg, logger log.Logger) error {
return etl.Transform(logPrefix, tx, kv.HeaderCanonical, kv.BorTxLookup, cfg.tmpdir, func(k, v []byte, next etl.ExtractNextFunc) error {
blocknum, blockHash := binary.BigEndian.Uint64(k), libcommon.CastToHash(v)
borTxHash := bortypes.ComputeBorTxHash(blocknum, blockHash)
if err := next(k, borTxHash.Bytes(), nil); err != nil {
return err
}
return nil
}, etl.IdentityLoadFunc, etl.TransformArgs{
Quit: ctx.Done(),
ExtractStartKey: hexutility.EncodeTs(blockFrom),
ExtractEndKey: hexutility.EncodeTs(blockTo),
LogDetailsExtract: func(k, v []byte) (additionalLogArguments []interface{}) {
return []interface{}{"block", binary.BigEndian.Uint64(k)}
},
}, logger)
}