/
replay_fork.go
413 lines (363 loc) · 10.8 KB
/
replay_fork.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
package replay
import (
"bytes"
"errors"
"fmt"
"math/big"
"sort"
"strings"
"sync"
"github.com/Fantom-foundation/substate-cli/state"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/substate"
"github.com/ethereum/go-ethereum/tests"
"github.com/urfave/cli/v2"
)
// record-replay: replay-fork command
var ReplayForkCommand = cli.Command{
Action: replayForkAction,
Name: "replay-fork",
Usage: "executes and check output consistency of all transactions in the range with the given hard-fork",
ArgsUsage: "<blockNumFirst> <blockNumLast>",
Flags: []cli.Flag{
&substate.WorkersFlag,
&substate.SkipTransferTxsFlag,
&substate.SkipCallTxsFlag,
&substate.SkipCreateTxsFlag,
&HardForkFlag,
&substate.SubstateDirFlag,
},
Description: `
The replay-fork command requires two arguments:
<blockNumFirst> <blockNumLast>
<blockNumFirst> and <blockNumLast> are the first and
last block of the inclusive range of blocks to replay transactions.
--hard-fork parameter is recommended for this command.`,
}
var HardForkName = map[int64]string{
1: "Frontier",
1_150_000: "Homestead",
2_463_000: "Tangerine Whistle",
2_675_000: "Spurious Dragon",
4_370_000: "Byzantium",
7_280_000: "Constantinople + Petersburg",
9_069_000: "Istanbul",
12_244_000: "Berlin",
12_965_000: "London",
}
func hardForkFlagDefault() int64 {
var v int64 = 0
for num64 := range HardForkName {
if num64 > v {
v = num64
}
}
if v <= 0 {
panic(fmt.Errorf("substate-cli replay-fork: corrupted --hard-fork default value: %v", v))
}
return v
}
var HardForkFlag = cli.Int64Flag{
Name: "hard-fork",
Usage: func() string {
s := ""
s += "Hard-fork block number, won't change block number in Env for NUMBER instruction"
hardForkNums := make([]int64, 0, len(HardForkName))
for num64 := range HardForkName {
hardForkNums = append(hardForkNums, num64)
}
sort.Slice(hardForkNums, func(i, j int) bool { return hardForkNums[i] < hardForkNums[j] })
for _, num64 := range hardForkNums {
s += fmt.Sprintf("\n\t %v: %s", num64, HardForkName[num64])
}
return s
}(),
Value: hardForkFlagDefault(),
}
var ReplayForkChainConfig *params.ChainConfig = ¶ms.ChainConfig{}
type ReplayForkStat struct {
Count int64
ErrStr string
}
var ReplayForkStatChan chan *ReplayForkStat = make(chan *ReplayForkStat, 1_000_000)
var ReplayForkStatMap map[string]*ReplayForkStat = make(map[string]*ReplayForkStat)
var (
ErrReplayForkOutOfGas = errors.New("out of gas in replay-fork")
ErrReplayForkInvalidAlloc = errors.New("invalid alloc in replay-fork")
ErrReplayForkMoreGas = errors.New("more gas in replay-fork")
ErrReplayForkLessGas = errors.New("less gas in replay-fork")
ErrReplayForkMisc = errors.New("misc in replay-fork")
)
func replayForkTask(block uint64, tx int, recording *substate.Substate, taskPool *substate.SubstateTaskPool) error {
var stat *ReplayForkStat
defer func() {
if stat != nil {
ReplayForkStatChan <- stat
}
}()
inputAlloc := recording.InputAlloc
inputEnv := recording.Env
inputMessage := recording.Message
outputAlloc := recording.OutputAlloc
outputResult := recording.Result
var (
vmConfig vm.Config
getTracerFn func(txIndex int, txHash common.Hash) (tracer vm.Tracer, err error)
)
vmConfig = vm.Config{}
getTracerFn = func(txIndex int, txHash common.Hash) (tracer vm.Tracer, err error) {
return nil, nil
}
// getHash returns zero for block hash that does not exist
getHash := func(num uint64) common.Hash {
if inputEnv.BlockHashes == nil {
return common.Hash{}
}
h := inputEnv.BlockHashes[num]
return h
}
// Apply Message
var (
statedb = state.MakeOffTheChainStateDB(inputAlloc)
gaspool = new(core.GasPool)
txHash = common.Hash{0x01}
blockHash = common.Hash{0x02}
txIndex = tx
)
gaspool.AddGas(inputEnv.GasLimit)
blockCtx := vm.BlockContext{
CanTransfer: core.CanTransfer,
Transfer: core.Transfer,
Coinbase: inputEnv.Coinbase,
BlockNumber: new(big.Int).SetUint64(inputEnv.Number),
Time: new(big.Int).SetUint64(inputEnv.Timestamp),
Difficulty: inputEnv.Difficulty,
GasLimit: inputEnv.GasLimit,
GetHash: getHash,
}
// If currentBaseFee is defined, add it to the vmContext.
if inputEnv.BaseFee != nil {
blockCtx.BaseFee = new(big.Int).Set(inputEnv.BaseFee)
}
msg := inputMessage.AsMessage()
tracer, err := getTracerFn(txIndex, txHash)
if err != nil {
return err
}
vmConfig.Tracer = tracer
vmConfig.Debug = (tracer != nil)
statedb.Prepare(txHash, txIndex)
txCtx := vm.TxContext{
GasPrice: msg.GasPrice(),
Origin: msg.From(),
}
chainConfig := ReplayForkChainConfig
if chainConfig.IsLondon(blockCtx.BlockNumber) && blockCtx.BaseFee == nil {
// If blockCtx.BaseFee is nil, assume blockCtx.BaseFee is zero
blockCtx.BaseFee = new(big.Int)
}
evm := vm.NewEVM(blockCtx, txCtx, statedb, chainConfig, vmConfig)
snapshot := statedb.Snapshot()
msgResult, err := core.ApplyMessage(evm, msg, gaspool)
if err != nil {
statedb.RevertToSnapshot(snapshot)
stat = &ReplayForkStat{
Count: 1,
ErrStr: strings.Split(err.Error(), ":")[0],
}
return nil
}
if chainConfig.IsByzantium(blockCtx.BlockNumber) {
statedb.Finalise(true)
} else {
statedb.IntermediateRoot(chainConfig.IsEIP158(blockCtx.BlockNumber))
}
evmResult := &substate.SubstateResult{}
if msgResult.Failed() {
evmResult.Status = types.ReceiptStatusFailed
} else {
evmResult.Status = types.ReceiptStatusSuccessful
}
evmResult.Logs = statedb.GetLogs(txHash, blockHash)
evmResult.Bloom = types.BytesToBloom(types.LogsBloom(evmResult.Logs))
if to := msg.To(); to == nil {
evmResult.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, msg.Nonce())
}
evmResult.GasUsed = msgResult.UsedGas
evmAlloc := statedb.SubstatePostAlloc
if r, a := outputResult.Equal(evmResult), outputAlloc.Equal(evmAlloc); !(r && a) {
if outputResult.Status == types.ReceiptStatusSuccessful &&
evmResult.Status == types.ReceiptStatusSuccessful {
// when both output and evm were successful, check alloc and gas usage
// check account states
if len(outputAlloc) != len(evmAlloc) {
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkInvalidAlloc),
}
return nil
}
for addr := range outputAlloc {
account1 := outputAlloc[addr]
account2 := evmAlloc[addr]
if account2 == nil {
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkInvalidAlloc),
}
return nil
}
// check nonce
if account1.Nonce != account2.Nonce {
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkInvalidAlloc),
}
return nil
}
// check code
if !bytes.Equal(account1.Code, account2.Code) {
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkInvalidAlloc),
}
return nil
}
// check storage
storage1 := account1.Storage
storage2 := account2.Storage
if len(storage1) != len(storage2) {
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkInvalidAlloc),
}
return nil
}
for k, v1 := range storage1 {
if v2, exist := storage2[k]; !exist || v1 != v2 {
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkInvalidAlloc),
}
return nil
}
}
}
// more gas
if evmResult.GasUsed > outputResult.GasUsed {
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkMoreGas),
}
return nil
}
// less gas
if evmResult.GasUsed < outputResult.GasUsed {
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkLessGas),
}
return nil
}
// misc: logs, ...
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkMisc),
}
return nil
} else if outputResult.Status == types.ReceiptStatusSuccessful &&
evmResult.Status == types.ReceiptStatusFailed {
// if output was successful but evm failed, return runtime error
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", msgResult.Err),
}
return nil
} else {
// misc (logs, ...)
stat = &ReplayForkStat{
Count: 1,
ErrStr: fmt.Sprintf("%v", ErrReplayForkMisc),
}
return nil
}
}
return nil
}
// record-replay: func replayForkAction for replay-fork command
func replayForkAction(ctx *cli.Context) error {
var err error
if ctx.Args().Len() != 2 {
return fmt.Errorf("substate-cli replay-fork command requires exactly 2 arguments")
}
first, last, argErr := SetBlockRange(ctx.Args().Get(0), ctx.Args().Get(1))
if argErr != nil {
return argErr
}
hardFork := ctx.Int64(HardForkFlag.Name)
if hardForkName, exist := HardForkName[hardFork]; !exist {
return fmt.Errorf("substate-cli replay-fork: invalid hard-fork block number %v", hardFork)
} else {
fmt.Printf("substate-cli replay-fork: hard-fork: block %v (%s)\n", hardFork, hardForkName)
}
switch hardFork {
case 1:
*ReplayForkChainConfig = *tests.Forks["Frontier"]
case 1_150_000:
*ReplayForkChainConfig = *tests.Forks["Homestead"]
case 2_463_000:
*ReplayForkChainConfig = *tests.Forks["EIP150"] // Tangerine Whistle
case 2_675_000:
*ReplayForkChainConfig = *tests.Forks["EIP158"] // Spurious Dragon
case 4_370_000:
*ReplayForkChainConfig = *tests.Forks["Byzantium"]
case 7_280_000:
*ReplayForkChainConfig = *tests.Forks["ConstantinopleFix"]
case 9_069_000:
*ReplayForkChainConfig = *tests.Forks["Istanbul"]
case 12_244_000:
*ReplayForkChainConfig = *tests.Forks["Berlin"]
case 12_965_000:
*ReplayForkChainConfig = *tests.Forks["London"]
}
substate.SetSubstateFlags(ctx)
substate.OpenSubstateDBReadOnly()
defer substate.CloseSubstateDB()
statWg := &sync.WaitGroup{}
statWg.Add(1)
go func() {
for stat := range ReplayForkStatChan {
count := stat.Count
errstr := stat.ErrStr
if ReplayForkStatMap[errstr] == nil {
ReplayForkStatMap[errstr] = &ReplayForkStat{
Count: 0,
ErrStr: errstr,
}
}
ReplayForkStatMap[errstr].Count += count
}
statWg.Done()
}()
taskPool := substate.NewSubstateTaskPool("substate-cli replay-fork", replayForkTask, first, last, ctx)
err = taskPool.Execute()
if err == nil {
close(ReplayForkStatChan)
}
statWg.Wait()
errstrSlice := make([]string, 0, len(ReplayForkStatMap))
for errstr := range ReplayForkStatMap {
errstrSlice = append(errstrSlice, errstr)
}
for _, errstr := range errstrSlice {
stat := ReplayForkStatMap[errstr]
count := stat.Count
fmt.Printf("substate-cli replay-fork: %12v %s\n", count, errstr)
}
return err
}