forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stage_tevm.go
374 lines (317 loc) · 9.1 KB
/
stage_tevm.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
package stagedsync
import (
"context"
"errors"
"fmt"
"runtime"
"time"
"github.com/c2h5oh/datasize"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/erigon/common"
"github.com/ledgerwatch/erigon/common/dbutils"
"github.com/ledgerwatch/erigon/core/state"
"github.com/ledgerwatch/erigon/core/types/accounts"
"github.com/ledgerwatch/erigon/eth/stagedsync/stages"
"github.com/ledgerwatch/erigon/ethdb"
"github.com/ledgerwatch/erigon/ethdb/olddb"
"github.com/ledgerwatch/erigon/params"
"github.com/ledgerwatch/log/v3"
)
type TranspileCfg struct {
db kv.RwDB
batchSize datasize.ByteSize
chainConfig *params.ChainConfig
}
func StageTranspileCfg(
kv kv.RwDB,
batchSize datasize.ByteSize,
chainConfig *params.ChainConfig,
) TranspileCfg {
return TranspileCfg{
db: kv,
batchSize: batchSize,
chainConfig: chainConfig,
}
}
func SpawnTranspileStage(s *StageState, tx kv.RwTx, toBlock uint64, cfg TranspileCfg, ctx context.Context) error {
var prevStageProgress uint64
var errStart error
if tx == nil {
errStart = cfg.db.View(ctx, func(tx kv.Tx) error {
prevStageProgress, errStart = stages.GetStageProgress(tx, stages.Execution)
return errStart
})
} else {
prevStageProgress, errStart = stages.GetStageProgress(tx, stages.Execution)
}
if errStart != nil {
return errStart
}
var to = prevStageProgress
if toBlock > 0 {
to = min(prevStageProgress, toBlock)
}
if to <= s.BlockNumber {
return nil
}
stageProgress := uint64(0)
logPrefix := s.LogPrefix()
if to > s.BlockNumber+16 {
log.Info(fmt.Sprintf("[%s] Contract translation", logPrefix), "from", s.BlockNumber, "to", to)
}
empty := common.Address{}
observedAddresses := map[common.Address]struct{}{
empty: {},
}
observedCodeHashes := map[common.Hash]struct{}{}
var err error
for stageProgress <= toBlock {
stageProgress, err = transpileBatch(logPrefix, stageProgress, to, cfg, tx, observedAddresses, observedCodeHashes, ctx.Done())
if err != nil {
return err
}
}
if to > s.BlockNumber+16 {
log.Info(fmt.Sprintf("[%s] Completed on", logPrefix), "block", toBlock)
}
return nil
}
func transpileBatch(logPrefix string, stageProgress, toBlock uint64, cfg TranspileCfg, tx kv.RwTx, observedAddresses map[common.Address]struct{}, observedCodeHashes map[common.Hash]struct{}, quitCh <-chan struct{}) (uint64, error) {
useExternalTx := tx != nil
var err error
if !useExternalTx {
tx, err = cfg.db.BeginRw(context.Background())
if err != nil {
return 0, err
}
defer tx.Rollback()
}
batch := olddb.NewBatch(tx, quitCh)
defer batch.Rollback()
// read contracts pending for translation
c, err := tx.CursorDupSort(kv.CallTraceSet)
if err != nil {
return 0, err
}
defer c.Close()
logTime := time.Now()
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
stateReader := state.NewPlainStateReader(batch)
var (
codeHash common.Hash
codeHashBytes []byte
addr common.Address
addrBytes []byte
acc *accounts.Account
evmContract []byte
transpiledCode []byte
ok bool
)
prevContract := stageProgress
blockKey := dbutils.EncodeBlockNumber(stageProgress)
var addressStatus []byte
for blockKey, addressStatus, err = c.SeekExact(blockKey); blockKey != nil; blockKey, addressStatus, err = c.Next() {
if err != nil {
return 0, fmt.Errorf("can't read pending code translations: %w", err)
}
select {
case <-quitCh:
return 0, libcommon.ErrStopped
case <-logEvery.C:
prevContract, logTime = logTEVMProgress(logPrefix, prevContract, logTime, stageProgress)
tx.CollectMetrics()
default:
}
stageProgress, err = dbutils.DecodeBlockNumber(blockKey)
if err != nil {
return 0, fmt.Errorf("can't read pending code translations. incorrect block key: %w", err)
}
if stageProgress > toBlock {
break
}
if addressStatus[len(addressStatus)-1]&4 == 0 {
continue
}
addrBytes = addressStatus[:len(addressStatus)-1]
addr = common.BytesToAddress(addrBytes)
_, ok = observedAddresses[addr]
if ok {
continue
}
observedAddresses[addr] = struct{}{}
acc, err = stateReader.ReadAccountData(addr)
if err != nil {
if errors.Is(err, ethdb.ErrKeyNotFound) {
continue
}
return 0, fmt.Errorf("can't read account by address %q: %w", addr, err)
}
if acc == nil {
continue
}
codeHash = acc.CodeHash
if ok = accounts.IsEmptyCodeHash(codeHash); ok {
continue
}
codeHashBytes = codeHash.Bytes()
_, ok = observedCodeHashes[codeHash]
if ok {
continue
}
observedCodeHashes[codeHash] = struct{}{}
// check if we already have TEVM code
ok, err = batch.Has(kv.ContractTEVMCode, codeHashBytes)
if err != nil && !errors.Is(err, ethdb.ErrKeyNotFound) {
return 0, fmt.Errorf("can't read code TEVM bucket by contract hash %q: %w", codeHash, err)
}
if ok && err == nil {
// already has TEVM code
continue
}
// load the contract code
evmContract, err = batch.GetOne(kv.Code, codeHashBytes)
if err != nil {
if errors.Is(err, ethdb.ErrKeyNotFound) {
continue
}
return 0, fmt.Errorf("can't read pending code translations. incorrect code hash in the bucket: %w", err)
}
if len(evmContract) == 0 {
continue
}
// call a transpiler
transpiledCode, err = transpileCode(evmContract)
if err != nil {
if errors.Is(err, ethdb.ErrKeyNotFound) {
log.Warn("cannot find EVM contract", "address", addr, "hash", codeHash)
continue
}
return 0, fmt.Errorf("contract %q cannot be translated: %w", codeHash, err)
}
// store TEVM contract code
err = batch.Put(kv.ContractTEVMCode, codeHashBytes, transpiledCode)
if err != nil {
return 0, fmt.Errorf("cannot store TEVM code %q: %w", codeHash, err)
}
if batch.BatchSize() >= int(cfg.batchSize) {
break // limit RAM usage. Break to commit batch
}
}
if err = batch.Commit(); err != nil {
return 0, fmt.Errorf("cannot commit the batch of translations on %q: %w", codeHash, err)
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return 0, fmt.Errorf("cannot commit the external transation on %q: %w", codeHash, err)
}
}
return stageProgress, nil
}
func logTEVMProgress(logPrefix string, prevContract uint64, prevTime time.Time, currentContract uint64) (uint64, time.Time) {
currentTime := time.Now()
interval := currentTime.Sub(prevTime)
speed := float64(currentContract-prevContract) / float64(interval/time.Second)
var m runtime.MemStats
runtime.ReadMemStats(&m)
var logpairs = []interface{}{
"number", currentContract,
"contracts/s", speed,
}
logpairs = append(logpairs, "alloc", libcommon.ByteCount(m.Alloc), "sys", libcommon.ByteCount(m.Sys))
log.Info(fmt.Sprintf("[%s] Translated contracts", logPrefix), logpairs...)
return currentContract, currentTime
}
func UnwindTranspileStage(u *UnwindState, s *StageState, tx kv.RwTx, cfg TranspileCfg, ctx context.Context) (err error) {
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
keyStart := dbutils.EncodeBlockNumber(u.UnwindPoint + 1)
c, err := tx.CursorDupSort(kv.CallTraceSet)
if err != nil {
return err
}
defer c.Close()
var (
codeHash common.Hash
codeHashBytes []byte
addr common.Address
addrBytes []byte
acc *accounts.Account
ok bool
)
stateReader := state.NewPlainStateReader(tx)
for k, addrStatus, err := c.Seek(keyStart); k != nil; k, addrStatus, err = c.Next() {
if err != nil {
return err
}
if addrStatus[len(addrStatus)-1]&4 == 0 {
continue
}
addrBytes = addrStatus[:len(addrStatus)-1]
addr = common.BytesToAddress(addrBytes)
acc, err = stateReader.ReadAccountData(addr)
if err != nil {
if errors.Is(err, ethdb.ErrKeyNotFound) {
continue
}
return fmt.Errorf("can't read account by address %q: %w", addr, err)
}
if acc == nil {
continue
}
codeHash = acc.CodeHash
if ok = accounts.IsEmptyCodeHash(codeHash); ok {
continue
}
codeHashBytes = codeHash.Bytes()
// check if we already have TEVM code
ok, err = tx.Has(kv.ContractTEVMCode, codeHashBytes)
if err != nil && !errors.Is(err, ethdb.ErrKeyNotFound) {
return fmt.Errorf("can't read code TEVM bucket by contract hash %q: %w", codeHash, err)
}
if err != nil || !ok {
// doesn't have TEVM code
continue
}
err = tx.Delete(kv.ContractTEVMCode, codeHashBytes, nil)
if err != nil {
return fmt.Errorf("can't delete TEVM code by hash %q: %w", codeHash, err)
}
}
if err = u.Done(tx); err != nil {
return err
}
if !useExternalTx {
if err = tx.Commit(); err != nil {
return err
}
}
return nil
}
// todo: TBD actual TEVM translator
func transpileCode(code []byte) ([]byte, error) {
return append(make([]byte, 0, len(code)), code...), nil
}
func PruneTranspileStage(p *PruneState, tx kv.RwTx, cfg TranspileCfg, initialCycle bool, 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
}