commands.go 17.3 KB
Newer Older
1 2 3
package wheel

import (
4 5 6 7 8 9 10 11 12 13
	"context"
	"encoding"
	"encoding/json"
	"fmt"
	"io"
	"math/big"
	"os"
	"strings"
	"time"

14 15
	"github.com/urfave/cli/v2"

16
	"github.com/ethereum/go-ethereum/common"
17
	"github.com/ethereum/go-ethereum/common/hexutil"
18 19
	"github.com/ethereum/go-ethereum/core/rawdb"
	"github.com/ethereum/go-ethereum/ethdb"
20
	"github.com/ethereum/go-ethereum/log"
21
	"github.com/ethereum/go-ethereum/rpc"
22 23

	opservice "github.com/ethereum-optimism/optimism/op-service"
Sabnock01's avatar
Sabnock01 committed
24
	"github.com/ethereum-optimism/optimism/op-service/client"
25 26 27 28
	oplog "github.com/ethereum-optimism/optimism/op-service/log"
	opmetrics "github.com/ethereum-optimism/optimism/op-service/metrics"
	"github.com/ethereum-optimism/optimism/op-wheel/cheat"
	"github.com/ethereum-optimism/optimism/op-wheel/engine"
29 30
)

31 32
const envVarPrefix = "OP_WHEEL"

33 34 35 36
func prefixEnvVars(name string) []string {
	return []string{envVarPrefix + "_" + name}
}

37
var (
38
	GlobalGethLogLvlFlag = &cli.GenericFlag{
39 40 41
		Name:    "geth-log-level",
		Usage:   "Set the global geth logging level",
		EnvVars: prefixEnvVars("GETH_LOG_LEVEL"),
42
		Value:   oplog.NewLvlFlagValue(log.LvlError),
43
	}
44
	DataDirFlag = &cli.StringFlag{
45 46 47 48
		Name:      "data-dir",
		Usage:     "Geth data dir location.",
		Required:  true,
		TakesFile: true,
49
		EnvVars:   prefixEnvVars("DATA_DIR"),
50
	}
51
	EngineEndpoint = &cli.StringFlag{
52 53 54
		Name:     "engine",
		Usage:    "Engine API RPC endpoint, can be HTTP/WS/IPC",
		Required: true,
55
		EnvVars:  prefixEnvVars("ENGINE"),
56
	}
57
	EngineJWTPath = &cli.StringFlag{
58 59 60 61
		Name:      "engine.jwt-secret",
		Usage:     "Path to JWT secret file used to authenticate Engine API communication with.",
		Required:  true,
		TakesFile: true,
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
		EnvVars:   prefixEnvVars("ENGINE_JWT_SECRET"),
	}
	FeeRecipientFlag = &cli.GenericFlag{
		Name:    "fee-recipient",
		Usage:   "fee-recipient of the block building",
		EnvVars: prefixEnvVars("FEE_RECIPIENT"),
		Value:   &TextFlag[*common.Address]{Value: &common.Address{1: 0x13, 2: 0x37}},
	}
	RandaoFlag = &cli.GenericFlag{
		Name:    "randao",
		Usage:   "randao value of the block building",
		EnvVars: prefixEnvVars("RANDAO"),
		Value:   &TextFlag[*common.Hash]{Value: &common.Hash{1: 0x13, 2: 0x37}},
	}
	BlockTimeFlag = &cli.Uint64Flag{
		Name:    "block-time",
		Usage:   "block time, interval of timestamps between blocks to build, in seconds",
		EnvVars: prefixEnvVars("BLOCK_TIME"),
		Value:   12,
	}
	BuildingTime = &cli.DurationFlag{
		Name:    "building-time",
		Usage:   "duration of of block building, this should be set to something lower than the block time.",
		EnvVars: prefixEnvVars("BUILDING_TIME"),
		Value:   time.Second * 6,
	}
	AllowGaps = &cli.BoolFlag{
		Name:    "allow-gaps",
		Usage:   "allow gaps in block building, like missed slots on the beacon chain.",
		EnvVars: prefixEnvVars("ALLOW_GAPS"),
92
	}
93
)
94 95 96 97

func ParseBuildingArgs(ctx *cli.Context) *engine.BlockBuildingSettings {
	return &engine.BlockBuildingSettings{
		BlockTime:    ctx.Uint64(BlockTimeFlag.Name),
98
		AllowGaps:    ctx.Bool(AllowGaps.Name),
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
		Random:       hashFlagValue(RandaoFlag.Name, ctx),
		FeeRecipient: addrFlagValue(FeeRecipientFlag.Name, ctx),
		BuildTime:    ctx.Duration(BuildingTime.Name),
	}
}

func CheatAction(readOnly bool, fn func(ctx *cli.Context, ch *cheat.Cheater) error) cli.ActionFunc {
	return func(ctx *cli.Context) error {
		dataDir := ctx.String(DataDirFlag.Name)
		ch, err := cheat.OpenGethDB(dataDir, readOnly)
		if err != nil {
			return fmt.Errorf("failed to open geth db: %w", err)
		}
		return fn(ctx, ch)
	}
}

func CheatRawDBAction(readOnly bool, fn func(ctx *cli.Context, db ethdb.Database) error) cli.ActionFunc {
	return func(ctx *cli.Context) error {
		dataDir := ctx.String(DataDirFlag.Name)
		db, err := cheat.OpenGethRawDB(dataDir, readOnly)
		if err != nil {
			return fmt.Errorf("failed to open raw geth db: %w", err)
		}
		return fn(ctx, db)
	}
}

func EngineAction(fn func(ctx *cli.Context, client client.RPC) error) cli.ActionFunc {
	return func(ctx *cli.Context) error {
		jwtData, err := os.ReadFile(ctx.String(EngineJWTPath.Name))
		if err != nil {
			return fmt.Errorf("failed to read jwt: %w", err)
		}
		secret := common.HexToHash(strings.TrimSpace(string(jwtData)))
		endpoint := ctx.String(EngineEndpoint.Name)
		client, err := engine.DialClient(context.Background(), endpoint, secret)
		if err != nil {
			return fmt.Errorf("failed to dial Engine API endpoint %q: %w", endpoint, err)
		}
		return fn(ctx, client)
	}
}

type Text interface {
	encoding.TextUnmarshaler
	fmt.Stringer
	comparable
}

type TextFlag[T Text] struct {
	Value T
}

func (a *TextFlag[T]) Set(value string) error {
	var defaultValue T
	if a.Value == defaultValue {
		return fmt.Errorf("cannot unmarshal into nil value")
	}
	return a.Value.UnmarshalText([]byte(value))
}

func (a *TextFlag[T]) String() string {
	var defaultValue T
	if a.Value == defaultValue {
		return "<nil>"
	}
	return a.Value.String()
}

func (a *TextFlag[T]) Get() T {
	return a.Value
}

173 174 175 176 177 178 179 180
func (a *TextFlag[T]) Clone() any {
	var out TextFlag[T]
	if err := out.Set(a.String()); err != nil {
		panic(fmt.Errorf("cannot clone invalid text value: %w", err))
	}
	return &out
}

181 182
var _ cli.Generic = (*TextFlag[*common.Address])(nil)

183 184
func textFlag[T Text](name string, usage string, value T) *cli.GenericFlag {
	return &cli.GenericFlag{
185 186
		Name:     name,
		Usage:    usage,
187
		EnvVars:  prefixEnvVars(strings.ToUpper(name)),
188 189 190 191 192
		Required: true,
		Value:    &TextFlag[T]{Value: value},
	}
}

193
func addrFlag(name string, usage string) *cli.GenericFlag {
194 195 196
	return textFlag[*common.Address](name, usage, new(common.Address))
}

197
func bytesFlag(name string, usage string) *cli.GenericFlag {
198 199 200
	return textFlag[*hexutil.Bytes](name, usage, new(hexutil.Bytes))
}

201
func hashFlag(name string, usage string) *cli.GenericFlag {
202 203 204
	return textFlag[*common.Hash](name, usage, new(common.Hash))
}

205
func bigFlag(name string, usage string) *cli.GenericFlag {
206 207 208 209 210 211 212
	return textFlag[*big.Int](name, usage, new(big.Int))
}

func addrFlagValue(name string, ctx *cli.Context) common.Address {
	return *ctx.Generic(name).(*TextFlag[*common.Address]).Value
}

213 214 215 216
func bytesFlagValue(name string, ctx *cli.Context) hexutil.Bytes {
	return *ctx.Generic(name).(*TextFlag[*hexutil.Bytes]).Value
}

217 218 219 220 221 222 223 224 225
func hashFlagValue(name string, ctx *cli.Context) common.Hash {
	return *ctx.Generic(name).(*TextFlag[*common.Hash]).Value
}

func bigFlagValue(name string, ctx *cli.Context) *big.Int {
	return ctx.Generic(name).(*TextFlag[*big.Int]).Value
}

var (
226
	CheatStorageGetCmd = &cli.Command{
227 228 229 230 231 232 233 234 235 236 237
		Name:    "get",
		Aliases: []string{"read"},
		Flags: []cli.Flag{
			DataDirFlag,
			addrFlag("address", "Address to read storage of"),
			hashFlag("key", "key in storage of address to read value"),
		},
		Action: CheatAction(true, func(ctx *cli.Context, ch *cheat.Cheater) error {
			return ch.RunAndClose(cheat.StorageGet(addrFlagValue("address", ctx), hashFlagValue("key", ctx), ctx.App.Writer))
		}),
	}
238
	CheatStorageSetCmd = &cli.Command{
239 240 241 242 243 244 245 246 247 248 249 250
		Name:    "set",
		Aliases: []string{"write"},
		Flags: []cli.Flag{
			DataDirFlag,
			addrFlag("address", "Address to write storage of"),
			hashFlag("key", "key in storage of address to set value of"),
			hashFlag("value", "the value to write"),
		},
		Action: CheatAction(false, func(ctx *cli.Context, ch *cheat.Cheater) error {
			return ch.RunAndClose(cheat.StorageSet(addrFlagValue("address", ctx), hashFlagValue("key", ctx), hashFlagValue("value", ctx)))
		}),
	}
251
	CheatStorageReadAll = &cli.Command{
252 253 254 255 256 257 258 259
		Name:    "read-all",
		Aliases: []string{"get-all"},
		Usage:   "Read all storage of the given account",
		Flags:   []cli.Flag{DataDirFlag, addrFlag("address", "Address to read all storage of")},
		Action: CheatAction(true, func(ctx *cli.Context, ch *cheat.Cheater) error {
			return ch.RunAndClose(cheat.StorageReadAll(addrFlagValue("address", ctx), ctx.App.Writer))
		}),
	}
260
	CheatStorageDiffCmd = &cli.Command{
261 262 263 264 265 266 267
		Name:  "diff",
		Usage: "Diff the storage of accounts A and B",
		Flags: []cli.Flag{DataDirFlag, hashFlag("a", "address of account A"), hashFlag("b", "address of account B")},
		Action: CheatAction(true, func(ctx *cli.Context, ch *cheat.Cheater) error {
			return ch.RunAndClose(cheat.StorageDiff(ctx.App.Writer, addrFlagValue("a", ctx), addrFlagValue("b", ctx)))
		}),
	}
268
	CheatStoragePatchCmd = &cli.Command{
269 270 271 272 273 274 275
		Name:  "patch",
		Usage: "Apply storage patch from STDIN to the given account address",
		Flags: []cli.Flag{DataDirFlag, addrFlag("address", "Address to patch storage of")},
		Action: CheatAction(false, func(ctx *cli.Context, ch *cheat.Cheater) error {
			return ch.RunAndClose(cheat.StoragePatch(os.Stdin, addrFlagValue("address", ctx)))
		}),
	}
276
	CheatStorageCmd = &cli.Command{
277
		Name: "storage",
278
		Subcommands: []*cli.Command{
279 280 281 282 283 284 285
			CheatStorageGetCmd,
			CheatStorageSetCmd,
			CheatStorageReadAll,
			CheatStorageDiffCmd,
			CheatStoragePatchCmd,
		},
	}
286
	CheatSetBalanceCmd = &cli.Command{
287 288 289 290 291 292 293 294 295 296
		Name: "balance",
		Flags: []cli.Flag{
			DataDirFlag,
			addrFlag("address", "Address to change balance of"),
			bigFlag("balance", "New balance of the account"),
		},
		Action: CheatAction(false, func(ctx *cli.Context, ch *cheat.Cheater) error {
			return ch.RunAndClose(cheat.SetBalance(addrFlagValue("address", ctx), bigFlagValue("balance", ctx)))
		}),
	}
297
	CheatSetCodeCmd = &cli.Command{
298 299 300 301
		Name: "code",
		Flags: []cli.Flag{
			DataDirFlag,
			addrFlag("address", "Address to change code of"),
302
			bytesFlag("code", "New code of the account"),
303 304
		},
		Action: CheatAction(false, func(ctx *cli.Context, ch *cheat.Cheater) error {
305
			return ch.RunAndClose(cheat.SetCode(addrFlagValue("address", ctx), bytesFlagValue("code", ctx)))
306 307
		}),
	}
308
	CheatSetNonceCmd = &cli.Command{
309 310 311 312 313 314 315 316 317 318
		Name: "nonce",
		Flags: []cli.Flag{
			DataDirFlag,
			addrFlag("address", "Address to change nonce of"),
			bigFlag("nonce", "New nonce of the account"),
		},
		Action: CheatAction(false, func(ctx *cli.Context, ch *cheat.Cheater) error {
			return ch.RunAndClose(cheat.SetNonce(addrFlagValue("address", ctx), bigFlagValue("balance", ctx).Uint64()))
		}),
	}
319
	CheatOvmOwnersCmd = &cli.Command{
320 321 322
		Name: "ovm-owners",
		Flags: []cli.Flag{
			DataDirFlag,
323
			&cli.StringFlag{
324 325 326
				Name:     "config",
				Usage:    "Path to JSON config of OVM address replacements to apply.",
				Required: true,
327
				EnvVars:  prefixEnvVars("OVM_OWNERS"),
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
				Value:    "ovm-owners.json",
			},
		},
		Action: CheatAction(false, func(ctx *cli.Context, ch *cheat.Cheater) error {
			confData, err := os.ReadFile(ctx.String("config"))
			if err != nil {
				return fmt.Errorf("failed to read OVM owners JSON config file: %w", err)
			}
			var conf cheat.OvmOwnersConfig
			if err := json.Unmarshal(confData, &conf); err != nil {
				return err
			}
			return ch.RunAndClose(cheat.OvmOwners(&conf))
		}),
	}
343
	CheatPrintHeadBlock = &cli.Command{
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
		Name:  "head-block",
		Usage: "dump head block as JSON",
		Flags: []cli.Flag{
			DataDirFlag,
		},
		Action: CheatRawDBAction(true, func(c *cli.Context, db ethdb.Database) error {
			enc := json.NewEncoder(c.App.Writer)
			enc.SetIndent("  ", "  ")
			block := rawdb.ReadHeadBlock(db)
			if block == nil {
				return enc.Encode(nil)
			}
			return enc.Encode(engine.RPCBlock{
				Header:       *block.Header(),
				Transactions: block.Transactions(),
			})
		}),
	}
362
	CheatPrintHeadHeader = &cli.Command{
363 364 365 366 367 368 369 370 371 372 373
		Name:  "head-header",
		Usage: "dump head header as JSON",
		Flags: []cli.Flag{
			DataDirFlag,
		},
		Action: CheatRawDBAction(true, func(c *cli.Context, db ethdb.Database) error {
			enc := json.NewEncoder(c.App.Writer)
			enc.SetIndent("  ", "  ")
			return enc.Encode(rawdb.ReadHeadHeader(db))
		}),
	}
374
	EngineBlockCmd = &cli.Command{
375 376 377 378
		Name:  "block",
		Usage: "build the next block using the Engine API",
		Flags: []cli.Flag{
			EngineEndpoint, EngineJWTPath,
379
			FeeRecipientFlag, RandaoFlag, BlockTimeFlag, BuildingTime, AllowGaps,
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
		},
		// TODO: maybe support transaction and tx pool engine flags, since we use op-geth?
		// TODO: reorg flag
		// TODO: finalize/safe flag

		Action: EngineAction(func(ctx *cli.Context, client client.RPC) error {
			settings := ParseBuildingArgs(ctx)
			status, err := engine.Status(context.Background(), client)
			if err != nil {
				return err
			}
			payload, err := engine.BuildBlock(context.Background(), client, status, settings)
			if err != nil {
				return err
			}
			_, err = io.WriteString(ctx.App.Writer, payload.BlockHash.String())
			return err
		}),
	}
399
	EngineAutoCmd = &cli.Command{
400 401 402 403 404
		Name:        "auto",
		Usage:       "Run a proof-of-nothing chain with fixed block time.",
		Description: "The block time can be changed. The execution engine must be synced to a post-Merge state first.",
		Flags: append(append([]cli.Flag{
			EngineEndpoint, EngineJWTPath,
405
			FeeRecipientFlag, RandaoFlag, BlockTimeFlag, BuildingTime, AllowGaps,
406 407
		}, oplog.CLIFlags(envVarPrefix)...), opmetrics.CLIFlags(envVarPrefix)...),
		Action: EngineAction(func(ctx *cli.Context, client client.RPC) error {
408
			logCfg := oplog.ReadCLIConfig(ctx)
409
			l := oplog.NewLogger(oplog.AppOut(ctx), logCfg)
410
			oplog.SetGlobalLogHandler(l.GetHandler())
411 412 413 414

			settings := ParseBuildingArgs(ctx)
			// TODO: finalize/safe flag

415
			metricsCfg := opmetrics.ReadCLIConfig(ctx)
416 417 418 419 420 421

			return opservice.CloseAction(func(ctx context.Context, shutdown <-chan struct{}) error {
				registry := opmetrics.NewRegistry()
				metrics := engine.NewMetrics("wheel", registry)
				if metricsCfg.Enabled {
					l.Info("starting metrics server", "addr", metricsCfg.ListenAddr, "port", metricsCfg.ListenPort)
422 423 424 425
					metricsSrv, err := opmetrics.StartServer(registry, metricsCfg.ListenAddr, metricsCfg.ListenPort)
					if err != nil {
						return fmt.Errorf("failed to start metrics server: %w", err)
					}
426 427 428 429 430
					defer func() {
						if err := metricsSrv.Stop(context.Background()); err != nil {
							l.Error("failed to stop metrics server: %w", err)
						}
					}()
431 432 433 434 435
				}
				return engine.Auto(ctx, metrics, client, l, shutdown, settings)
			})
		}),
	}
436
	EngineStatusCmd = &cli.Command{
437 438 439 440 441 442 443 444 445 446 447 448
		Name:  "status",
		Flags: []cli.Flag{EngineEndpoint, EngineJWTPath},
		Action: EngineAction(func(ctx *cli.Context, client client.RPC) error {
			stat, err := engine.Status(context.Background(), client)
			if err != nil {
				return err
			}
			enc := json.NewEncoder(ctx.App.Writer)
			enc.SetIndent("", "  ")
			return enc.Encode(stat)
		}),
	}
449
	EngineCopyCmd = &cli.Command{
450 451 452
		Name: "copy",
		Flags: []cli.Flag{
			EngineEndpoint, EngineJWTPath,
453
			&cli.StringFlag{
454 455 456
				Name:     "source",
				Usage:    "Unauthenticated regular eth JSON RPC to pull block data from, can be HTTP/WS/IPC.",
				Required: true,
457
				EnvVars:  prefixEnvVars("ENGINE"),
458 459 460 461 462 463 464 465 466 467 468
			},
		},
		Action: EngineAction(func(ctx *cli.Context, dest client.RPC) error {
			rpcClient, err := rpc.DialOptions(context.Background(), ctx.String("source"))
			if err != nil {
				return fmt.Errorf("failed to dial engine source endpoint: %w", err)
			}
			source := client.NewBaseRPCClient(rpcClient)
			return engine.Copy(context.Background(), source, dest)
		}),
	}
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 520 521 522 523 524 525

	EngineSetForkchoiceCmd = &cli.Command{
		Name:        "set-forkchoice",
		Description: "Set forkchoice, specify unsafe, safe and finalized blocks by number",
		Flags: []cli.Flag{
			EngineEndpoint, EngineJWTPath,
			&cli.Uint64Flag{
				Name:     "unsafe",
				Usage:    "Block number of block to set as latest block",
				Required: true,
				EnvVars:  prefixEnvVars("UNSAFE"),
			},
			&cli.Uint64Flag{
				Name:     "safe",
				Usage:    "Block number of block to set as safe block",
				Required: true,
				EnvVars:  prefixEnvVars("SAFE"),
			},
			&cli.Uint64Flag{
				Name:     "finalized",
				Usage:    "Block number of block to set as finalized block",
				Required: true,
				EnvVars:  prefixEnvVars("FINALIZED"),
			},
		},
		Action: EngineAction(func(ctx *cli.Context, client client.RPC) error {
			return engine.SetForkchoice(ctx.Context, client, ctx.Uint64("finalized"), ctx.Uint64("safe"), ctx.Uint64("unsafe"))
		}),
	}

	EngineJSONCmd = &cli.Command{
		Name:        "json",
		Description: "read json values from remaining args, or STDIN, and use them as RPC params to call the engine RPC method (first arg)",
		Flags: []cli.Flag{
			EngineEndpoint, EngineJWTPath,
			&cli.BoolFlag{
				Name:     "stdin",
				Usage:    "Read params from stdin instead",
				Required: false,
				EnvVars:  prefixEnvVars("STDIN"),
			},
		},
		ArgsUsage: "<rpc-method-name> [params...]",
		Action: EngineAction(func(ctx *cli.Context, client client.RPC) error {
			if ctx.NArg() == 0 {
				return fmt.Errorf("expected at least 1 argument: RPC method name")
			}
			var r io.Reader
			var args []string
			if ctx.Bool("stdin") {
				r = ctx.App.Reader
			} else {
				args = ctx.Args().Tail()
			}
			return engine.RawJSONInteraction(ctx.Context, client, ctx.Args().Get(0), args, r, ctx.App.Writer)
		}),
	}
526 527
)

528
var CheatCmd = &cli.Command{
529 530 531 532
	Name:  "cheat",
	Usage: "Cheating commands to modify a Geth database.",
	Description: "Each sub-command opens a Geth database, applies the cheat, and then saves and closes the database." +
		"The Geth node will live in its own false reality, other nodes cannot sync the cheated state if they process the blocks.",
533
	Subcommands: []*cli.Command{
534 535
		CheatStorageCmd,
		CheatSetBalanceCmd,
536
		CheatSetCodeCmd,
537 538 539 540 541 542 543
		CheatSetNonceCmd,
		CheatOvmOwnersCmd,
		CheatPrintHeadBlock,
		CheatPrintHeadHeader,
	},
}

544
var EngineCmd = &cli.Command{
545 546 547
	Name:        "engine",
	Usage:       "Engine API commands to build/reorg/finalize blocks.",
	Description: "Each sub-command dials the engine API endpoint (with provided JWT secret) and then runs the action",
548
	Subcommands: []*cli.Command{
549 550 551 552
		EngineBlockCmd,
		EngineAutoCmd,
		EngineStatusCmd,
		EngineCopyCmd,
553 554
		EngineSetForkchoiceCmd,
		EngineJSONCmd,
555 556
	},
}