-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathrun.go
519 lines (468 loc) · 15.1 KB
/
run.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package cmd
import (
"context"
"fmt"
"os"
"os/exec"
"slices"
"strconv"
"strings"
"time"
"github.com/ethereum-optimism/optimism/cannon/mipsevm/versions"
"github.com/ethereum-optimism/optimism/cannon/serialize"
"github.com/ethereum-optimism/optimism/op-service/ioutil"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/log"
"github.com/pkg/profile"
"github.com/urfave/cli/v2"
"github.com/ethereum-optimism/optimism/cannon/mipsevm"
"github.com/ethereum-optimism/optimism/cannon/mipsevm/program"
preimage "github.com/ethereum-optimism/optimism/op-preimage"
"github.com/ethereum-optimism/optimism/op-service/jsonutil"
)
var (
RunInputFlag = &cli.PathFlag{
Name: "input",
Usage: "path of input JSON state. Stdin if left empty.",
TakesFile: true,
Value: "state.json",
Required: true,
}
RunOutputFlag = &cli.PathFlag{
Name: "output",
Usage: "path of output JSON state. Not written if empty, use - to write to Stdout.",
TakesFile: true,
Value: "out.json",
Required: false,
}
patternHelp = "'never' (default), 'always', '=123' at exactly step 123, '%123' for every 123 steps"
RunProofAtFlag = &cli.GenericFlag{
Name: "proof-at",
Usage: "step pattern to output proof at: " + patternHelp,
Value: new(StepMatcherFlag),
Required: false,
}
RunProofFmtFlag = &cli.StringFlag{
Name: "proof-fmt",
Usage: "format for proof data output file names. Proof data is written to stdout if -.",
Value: "proof-%d.json",
Required: false,
}
RunSnapshotAtFlag = &cli.GenericFlag{
Name: "snapshot-at",
Usage: "step pattern to output snapshots at: " + patternHelp,
Value: new(StepMatcherFlag),
Required: false,
}
RunSnapshotFmtFlag = &cli.StringFlag{
Name: "snapshot-fmt",
Usage: "format for snapshot output file names.",
Value: "state-%d.json",
Required: false,
}
RunStopAtFlag = &cli.GenericFlag{
Name: "stop-at",
Usage: "step pattern to stop at: " + patternHelp,
Value: new(StepMatcherFlag),
Required: false,
}
RunStopAtPreimageFlag = &cli.StringFlag{
Name: "stop-at-preimage",
Usage: "stop at the first preimage request matching this key",
Required: false,
}
RunStopAtPreimageTypeFlag = &cli.StringFlag{
Name: "stop-at-preimage-type",
Usage: "stop at the first preimage request matching this type",
Required: false,
}
RunStopAtPreimageLargerThanFlag = &cli.StringFlag{
Name: "stop-at-preimage-larger-than",
Usage: "stop at the first step that requests a preimage larger than the specified size (in bytes)",
Required: false,
}
RunMetaFlag = &cli.PathFlag{
Name: "meta",
Usage: "path to metadata file for symbol lookup for enhanced debugging info during execution.",
Value: "meta.json",
Required: false,
}
RunInfoAtFlag = &cli.GenericFlag{
Name: "info-at",
Usage: "step pattern to print info at: " + patternHelp,
Value: MustStepMatcherFlag("%100000"),
Required: false,
}
RunPProfCPU = &cli.BoolFlag{
Name: "pprof.cpu",
Usage: "enable pprof cpu profiling",
}
RunDebugFlag = &cli.BoolFlag{
Name: "debug",
Usage: "enable debug mode, which includes stack traces and other debug info in the output. Requires --meta.",
}
RunDebugInfoFlag = &cli.PathFlag{
Name: "debug-info",
Usage: "path to write debug info to",
TakesFile: true,
Required: false,
}
OutFilePerm = os.FileMode(0o755)
)
type Proof struct {
Step uint64 `json:"step"`
Pre common.Hash `json:"pre"`
Post common.Hash `json:"post"`
StateData hexutil.Bytes `json:"state-data"`
ProofData hexutil.Bytes `json:"proof-data"`
OracleKey hexutil.Bytes `json:"oracle-key,omitempty"`
OracleValue hexutil.Bytes `json:"oracle-value,omitempty"`
OracleOffset uint32 `json:"oracle-offset,omitempty"`
}
type rawHint string
func (rh rawHint) Hint() string {
return string(rh)
}
type rawKey [32]byte
func (rk rawKey) PreimageKey() [32]byte {
return rk
}
type ProcessPreimageOracle struct {
pCl *preimage.OracleClient
hCl *preimage.HintWriter
cmd *exec.Cmd
waitErr chan error
cancelIO context.CancelCauseFunc
}
const clientPollTimeout = time.Second * 15
func NewProcessPreimageOracle(name string, args []string, stdout log.Logger, stderr log.Logger) (*ProcessPreimageOracle, error) {
if name == "" {
return &ProcessPreimageOracle{}, nil
}
pClientRW, pOracleRW, err := preimage.CreateBidirectionalChannel()
if err != nil {
return nil, err
}
hClientRW, hOracleRW, err := preimage.CreateBidirectionalChannel()
if err != nil {
return nil, err
}
cmd := exec.Command(name, args...) // nosemgrep
cmd.Stdout = &mipsevm.LoggingWriter{Log: stdout}
cmd.Stderr = &mipsevm.LoggingWriter{Log: stderr}
cmd.ExtraFiles = []*os.File{
hOracleRW.Reader(),
hOracleRW.Writer(),
pOracleRW.Reader(),
pOracleRW.Writer(),
}
// Note that the client file descriptors are not closed when the pre-image server exits.
// So we use the FilePoller to ensure that we don't get stuck in a blocking read/write.
ctx, cancelIO := context.WithCancelCause(context.Background())
preimageClientIO := preimage.NewFilePoller(ctx, pClientRW, clientPollTimeout)
hostClientIO := preimage.NewFilePoller(ctx, hClientRW, clientPollTimeout)
out := &ProcessPreimageOracle{
pCl: preimage.NewOracleClient(preimageClientIO),
hCl: preimage.NewHintWriter(hostClientIO),
cmd: cmd,
waitErr: make(chan error),
cancelIO: cancelIO,
}
return out, nil
}
func (p *ProcessPreimageOracle) Hint(v []byte) {
if p.hCl == nil { // no hint processor
return
}
p.hCl.Hint(rawHint(v))
}
func (p *ProcessPreimageOracle) GetPreimage(k [32]byte) []byte {
if p.pCl == nil {
panic("no pre-image retriever available")
}
return p.pCl.Get(rawKey(k))
}
func (p *ProcessPreimageOracle) Start() error {
if p.cmd == nil {
return nil
}
err := p.cmd.Start()
go p.wait()
return err
}
func (p *ProcessPreimageOracle) Close() error {
if p.cmd == nil {
return nil
}
tryWait := func(dur time.Duration) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), dur)
defer cancel()
select {
case <-ctx.Done():
return false, nil
case err := <-p.waitErr:
return true, err
}
}
// Give the pre-image server time to exit cleanly before killing it.
if exited, err := tryWait(1 * time.Second); exited {
return err
}
// Politely ask the process to exit and give it some more time
_ = p.cmd.Process.Signal(os.Interrupt)
if exited, err := tryWait(30 * time.Second); exited {
return err
}
// Force the process to exit
_ = p.cmd.Process.Signal(os.Kill)
return <-p.waitErr
}
func (p *ProcessPreimageOracle) wait() {
err := p.cmd.Wait()
var waitErr error
if err, ok := err.(*exec.ExitError); !ok || !err.Success() {
waitErr = err
}
p.cancelIO(fmt.Errorf("%w: pre-image server has exited", waitErr))
p.waitErr <- waitErr
close(p.waitErr)
}
type StepFn func(proof bool) (*mipsevm.StepWitness, error)
func Guard(proc *os.ProcessState, fn StepFn) StepFn {
return func(proof bool) (*mipsevm.StepWitness, error) {
wit, err := fn(proof)
if err != nil {
if proc.Exited() {
return nil, fmt.Errorf("pre-image server exited with code %d, resulting in err %w", proc.ExitCode(), err)
} else {
return nil, err
}
}
return wit, nil
}
}
var _ mipsevm.PreimageOracle = (*ProcessPreimageOracle)(nil)
func Run(ctx *cli.Context) error {
if ctx.Bool(RunPProfCPU.Name) {
defer profile.Start(profile.NoShutdownHook, profile.ProfilePath("."), profile.CPUProfile).Stop()
}
guestLogger := Logger(os.Stderr, log.LevelInfo)
outLog := &mipsevm.LoggingWriter{Log: guestLogger.With("module", "guest", "stream", "stdout")}
errLog := &mipsevm.LoggingWriter{Log: guestLogger.With("module", "guest", "stream", "stderr")}
l := Logger(os.Stderr, log.LevelInfo).With("module", "vm")
stopAtAnyPreimage := false
var stopAtPreimageKeyPrefix []byte
stopAtPreimageOffset := uint32(0)
if ctx.IsSet(RunStopAtPreimageFlag.Name) {
val := ctx.String(RunStopAtPreimageFlag.Name)
parts := strings.Split(val, "@")
if len(parts) > 2 {
return fmt.Errorf("invalid %v: %v", RunStopAtPreimageFlag.Name, val)
}
stopAtPreimageKeyPrefix = common.FromHex(parts[0])
if len(parts) == 2 {
x, err := strconv.ParseUint(parts[1], 10, 32)
if err != nil {
return fmt.Errorf("invalid preimage offset: %w", err)
}
stopAtPreimageOffset = uint32(x)
}
} else {
switch ctx.String(RunStopAtPreimageTypeFlag.Name) {
case "local":
stopAtPreimageKeyPrefix = []byte{byte(preimage.LocalKeyType)}
case "keccak":
stopAtPreimageKeyPrefix = []byte{byte(preimage.Keccak256KeyType)}
case "sha256":
stopAtPreimageKeyPrefix = []byte{byte(preimage.Sha256KeyType)}
case "blob":
stopAtPreimageKeyPrefix = []byte{byte(preimage.BlobKeyType)}
case "precompile":
stopAtPreimageKeyPrefix = []byte{byte(preimage.PrecompileKeyType)}
case "any":
stopAtAnyPreimage = true
case "":
// 0 preimage type is forbidden so will not stop at any preimage
default:
return fmt.Errorf("invalid preimage type %q", ctx.String(RunStopAtPreimageTypeFlag.Name))
}
}
stopAtPreimageLargerThan := ctx.Int(RunStopAtPreimageLargerThanFlag.Name)
// split CLI args after first '--'
args := ctx.Args().Slice()
for i, arg := range args {
if arg == "--" {
args = args[i+1:]
break
}
}
if len(args) == 0 {
args = []string{""}
}
poOut := Logger(os.Stdout, log.LevelInfo).With("module", "host")
poErr := Logger(os.Stderr, log.LevelInfo).With("module", "host")
po, err := NewProcessPreimageOracle(args[0], args[1:], poOut, poErr)
if err != nil {
return fmt.Errorf("failed to create pre-image oracle process: %w", err)
}
if err := po.Start(); err != nil {
return fmt.Errorf("failed to start pre-image oracle server: %w", err)
}
defer func() {
if err := po.Close(); err != nil {
l.Error("failed to close pre-image server", "err", err)
}
}()
stopAt := ctx.Generic(RunStopAtFlag.Name).(*StepMatcherFlag).Matcher()
proofAt := ctx.Generic(RunProofAtFlag.Name).(*StepMatcherFlag).Matcher()
snapshotAt := ctx.Generic(RunSnapshotAtFlag.Name).(*StepMatcherFlag).Matcher()
infoAt := ctx.Generic(RunInfoAtFlag.Name).(*StepMatcherFlag).Matcher()
var meta *program.Metadata
if metaPath := ctx.Path(RunMetaFlag.Name); metaPath == "" {
l.Info("no metadata file specified, defaulting to empty metadata")
meta = &program.Metadata{Symbols: nil} // provide empty metadata by default
} else {
if m, err := jsonutil.LoadJSON[program.Metadata](metaPath); err != nil {
return fmt.Errorf("failed to load metadata: %w", err)
} else {
meta = m
}
}
state, err := versions.LoadStateFromFile(ctx.Path(RunInputFlag.Name))
if err != nil {
return fmt.Errorf("failed to load state: %w", err)
}
vm := state.CreateVM(l, po, outLog, errLog, meta)
debugProgram := ctx.Bool(RunDebugFlag.Name)
if debugProgram {
if metaPath := ctx.Path(RunMetaFlag.Name); metaPath == "" {
return fmt.Errorf("cannot enable debug mode without a metadata file")
}
if err := vm.InitDebug(); err != nil {
return fmt.Errorf("failed to initialize debug mode: %w", err)
}
}
proofFmt := ctx.String(RunProofFmtFlag.Name)
snapshotFmt := ctx.String(RunSnapshotFmtFlag.Name)
stepFn := vm.Step
if po.cmd != nil {
stepFn = Guard(po.cmd.ProcessState, stepFn)
}
start := time.Now()
startStep := state.GetStep()
for !state.GetExited() {
step := state.GetStep()
if step%100 == 0 { // don't do the ctx err check (includes lock) too often
if err := ctx.Context.Err(); err != nil {
return err
}
}
if infoAt(state) {
delta := time.Since(start)
l.Info("processing",
"step", step,
"pc", mipsevm.HexU32(state.GetPC()),
"insn", mipsevm.HexU32(state.GetMemory().GetMemory(state.GetPC())),
"ips", float64(step-startStep)/(float64(delta)/float64(time.Second)),
"pages", state.GetMemory().PageCount(),
"mem", state.GetMemory().Usage(),
"name", meta.LookupSymbol(state.GetPC()),
)
}
if vm.CheckInfiniteLoop() {
// don't loop forever when we get stuck because of an unexpected bad program
return fmt.Errorf("detected an infinite loop at step %d", step)
}
if stopAt(state) {
l.Info("Reached stop at")
break
}
if snapshotAt(state) {
if err := serialize.Write(fmt.Sprintf(snapshotFmt, step), state, OutFilePerm); err != nil {
return fmt.Errorf("failed to write state snapshot: %w", err)
}
}
if proofAt(state) {
witness, err := stepFn(true)
if err != nil {
return fmt.Errorf("failed at proof-gen step %d (PC: %08x): %w", step, state.GetPC(), err)
}
_, postStateHash := state.EncodeWitness()
proof := &Proof{
Step: step,
Pre: witness.StateHash,
Post: postStateHash,
StateData: witness.State,
ProofData: witness.ProofData,
}
if witness.HasPreimage() {
proof.OracleKey = witness.PreimageKey[:]
proof.OracleValue = witness.PreimageValue
proof.OracleOffset = witness.PreimageOffset
}
if err := jsonutil.WriteJSON(proof, ioutil.ToStdOutOrFileOrNoop(fmt.Sprintf(proofFmt, step), OutFilePerm)); err != nil {
return fmt.Errorf("failed to write proof data: %w", err)
}
} else {
_, err = stepFn(false)
if err != nil {
return fmt.Errorf("failed at step %d (PC: %08x): %w", step, state.GetPC(), err)
}
}
lastPreimageKey, lastPreimageValue, lastPreimageOffset := vm.LastPreimage()
if lastPreimageOffset != ^uint32(0) {
if stopAtAnyPreimage {
l.Info("Stopping at preimage read")
break
}
if len(stopAtPreimageKeyPrefix) > 0 &&
slices.Equal(lastPreimageKey[:len(stopAtPreimageKeyPrefix)], stopAtPreimageKeyPrefix) {
if stopAtPreimageOffset == lastPreimageOffset {
l.Info("Stopping at preimage read", "keyPrefix", common.Bytes2Hex(stopAtPreimageKeyPrefix), "offset", lastPreimageOffset)
break
}
}
if stopAtPreimageLargerThan != 0 && len(lastPreimageValue) > stopAtPreimageLargerThan {
l.Info("Stopping at preimage read", "size", len(lastPreimageValue), "min", stopAtPreimageLargerThan)
break
}
}
}
l.Info("Execution stopped", "exited", state.GetExited(), "code", state.GetExitCode())
if debugProgram {
vm.Traceback()
}
if err := serialize.Write(ctx.Path(RunOutputFlag.Name), state, OutFilePerm); err != nil {
return fmt.Errorf("failed to write state output: %w", err)
}
if debugInfoFile := ctx.Path(RunDebugInfoFlag.Name); debugInfoFile != "" {
if err := jsonutil.WriteJSON(vm.GetDebugInfo(), ioutil.ToStdOutOrFileOrNoop(debugInfoFile, OutFilePerm)); err != nil {
return fmt.Errorf("failed to write benchmark data: %w", err)
}
}
return nil
}
var RunCommand = &cli.Command{
Name: "run",
Usage: "Run VM step(s) and generate proof data to replicate onchain.",
Description: "Run VM step(s) and generate proof data to replicate onchain. See flags to match when to output a proof, a snapshot, or to stop early.",
Action: Run,
Flags: []cli.Flag{
RunInputFlag,
RunOutputFlag,
RunProofAtFlag,
RunProofFmtFlag,
RunSnapshotAtFlag,
RunSnapshotFmtFlag,
RunStopAtFlag,
RunStopAtPreimageFlag,
RunStopAtPreimageTypeFlag,
RunStopAtPreimageLargerThanFlag,
RunMetaFlag,
RunInfoAtFlag,
RunPProfCPU,
RunDebugFlag,
RunDebugInfoFlag,
},
}