forked from berachain/erigon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stage_finish.go
238 lines (215 loc) · 6.09 KB
/
stage_finish.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
package stagedsync
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"time"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/hexutility"
"github.com/ledgerwatch/erigon-lib/gointerfaces"
"github.com/ledgerwatch/erigon-lib/gointerfaces/remote"
types2 "github.com/ledgerwatch/erigon-lib/gointerfaces/types"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/log/v3"
common2 "github.com/ledgerwatch/erigon/common"
"github.com/ledgerwatch/erigon/common/dbutils"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/ethdb/cbor"
"github.com/ledgerwatch/erigon/params"
"github.com/ledgerwatch/erigon/turbo/engineapi"
)
type FinishCfg struct {
db kv.RwDB
tmpDir string
forkValidator *engineapi.ForkValidator
}
func StageFinishCfg(db kv.RwDB, tmpDir string, forkValidator *engineapi.ForkValidator) FinishCfg {
return FinishCfg{
db: db,
tmpDir: tmpDir,
forkValidator: forkValidator,
}
}
func FinishForward(s *StageState, tx kv.RwTx, cfg FinishCfg, initialCycle bool) error {
useExternalTx := tx != nil
if !useExternalTx {
var err error
tx, err = cfg.db.BeginRw(context.Background())
if err != nil {
return err
}
defer tx.Rollback()
}
var executionAt uint64
var err error
if executionAt, err = s.ExecutionAt(tx); err != nil {
return err
}
if executionAt <= s.BlockNumber {
return nil
}
rawdb.WriteHeadBlockHash(tx, rawdb.ReadHeadHeaderHash(tx))
err = s.Update(tx, executionAt)
if err != nil {
return err
}
if cfg.forkValidator != nil {
cfg.forkValidator.NotifyCurrentHeight(executionAt)
}
if initialCycle {
if err := params.SetErigonVersion(tx, params.VersionKeyFinished); err != nil {
return err
}
}
if !useExternalTx {
if err := tx.Commit(); err != nil {
return err
}
}
return nil
}
func UnwindFinish(u *UnwindState, tx kv.RwTx, cfg FinishCfg, 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 err = u.Done(tx); err != nil {
return err
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}
func PruneFinish(u *PruneState, tx kv.RwTx, cfg FinishCfg, 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
}
func NotifyNewHeaders(ctx context.Context, finishStageBeforeSync uint64, finishStageAfterSync uint64, unwindTo *uint64, notifier ChainEventNotifier, tx kv.Tx) error {
t := time.Now()
if notifier == nil {
log.Trace("RPC Daemon notification channel not set. No headers notifications will be sent")
return nil
}
// Notify all headers we have (either canonical or not) in a maximum range span of 1024
var notifyFrom uint64
var isUnwind bool
if unwindTo != nil && *unwindTo != 0 && (*unwindTo) < finishStageBeforeSync {
notifyFrom = *unwindTo
isUnwind = true
} else {
heightSpan := finishStageAfterSync - finishStageBeforeSync
if heightSpan > 1024 {
heightSpan = 1024
}
notifyFrom = finishStageAfterSync - heightSpan
}
notifyFrom++
var notifyTo = notifyFrom
var notifyToHash libcommon.Hash
var headersRlp [][]byte
if err := tx.ForEach(kv.Headers, hexutility.EncodeTs(notifyFrom), func(k, headerRLP []byte) error {
if len(headerRLP) == 0 {
return nil
}
notifyTo = binary.BigEndian.Uint64(k)
var err error
if notifyToHash, err = rawdb.ReadCanonicalHash(tx, notifyTo); err != nil {
log.Warn("[Finish] failed checking if header is cannonical")
}
headerHash := libcommon.BytesToHash(k[8:])
if notifyToHash == headerHash {
headersRlp = append(headersRlp, common2.CopyBytes(headerRLP))
}
return libcommon.Stopped(ctx.Done())
}); err != nil {
log.Error("RPC Daemon notification failed", "err", err)
return err
}
if len(headersRlp) > 0 {
notifier.OnNewHeader(headersRlp)
headerTiming := time.Since(t)
t = time.Now()
if notifier.HasLogSubsriptions() {
logs, err := ReadLogs(tx, notifyFrom, isUnwind)
if err != nil {
return err
}
notifier.OnLogs(logs)
}
logTiming := time.Since(t)
log.Info("RPC Daemon notified of new headers", "from", notifyFrom-1, "to", notifyTo, "hash", notifyToHash, "header sending", headerTiming, "log sending", logTiming)
}
return nil
}
func ReadLogs(tx kv.Tx, from uint64, isUnwind bool) ([]*remote.SubscribeLogsReply, error) {
logs, err := tx.Cursor(kv.Log)
if err != nil {
return nil, err
}
defer logs.Close()
reply := make([]*remote.SubscribeLogsReply, 0)
reader := bytes.NewReader(nil)
var prevBlockNum uint64
var block *types.Block
var logIndex uint64
for k, v, err := logs.Seek(dbutils.LogKey(from, 0)); k != nil; k, v, err = logs.Next() {
if err != nil {
return nil, err
}
blockNum := binary.BigEndian.Uint64(k[:8])
if block == nil || blockNum != prevBlockNum {
logIndex = 0
prevBlockNum = blockNum
if block, err = rawdb.ReadBlockByNumber(tx, blockNum); err != nil {
return nil, err
}
}
txIndex := uint64(binary.BigEndian.Uint32(k[8:]))
txHash := block.Transactions()[txIndex].Hash()
var ll types.Logs
reader.Reset(v)
if err := cbor.Unmarshal(&ll, reader); err != nil {
return nil, fmt.Errorf("receipt unmarshal failed: %w, blocl=%d", err, blockNum)
}
for _, l := range ll {
r := &remote.SubscribeLogsReply{
Address: gointerfaces.ConvertAddressToH160(l.Address),
BlockHash: gointerfaces.ConvertHashToH256(block.Hash()),
BlockNumber: blockNum,
Data: l.Data,
LogIndex: logIndex,
Topics: make([]*types2.H256, 0, len(l.Topics)),
TransactionHash: gointerfaces.ConvertHashToH256(txHash),
TransactionIndex: txIndex,
Removed: isUnwind,
}
logIndex++
for _, topic := range l.Topics {
r.Topics = append(r.Topics, gointerfaces.ConvertHashToH256(topic))
}
reply = append(reply, r)
}
}
return reply, nil
}