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

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

	"github.com/ethereum/go-ethereum/common"
15
	"github.com/ethereum/go-ethereum/common/hexutil"
16 17 18
	"github.com/ethereum/go-ethereum/core/rawdb"
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/rpc"
19
	"github.com/urfave/cli/v2"
20

21
	"github.com/ethereum-optimism/optimism/op-node/client"
22
	opservice "github.com/ethereum-optimism/optimism/op-service"
23 24 25 26
	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"
27 28
)

29 30
const envVarPrefix = "OP_WHEEL"

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

35
var (
36 37 38 39 40
	GlobalGethLogLvlFlag = &cli.StringFlag{
		Name:    "geth-log-level",
		Usage:   "Set the global geth logging level",
		EnvVars: prefixEnvVars("GETH_LOG_LEVEL"),
		Value:   "error",
41
	}
42
	DataDirFlag = &cli.StringFlag{
43 44 45 46
		Name:      "data-dir",
		Usage:     "Geth data dir location.",
		Required:  true,
		TakesFile: true,
47
		EnvVars:   prefixEnvVars("DATA_DIR"),
48
	}
49
	EngineEndpoint = &cli.StringFlag{
50 51 52
		Name:     "engine",
		Usage:    "Engine API RPC endpoint, can be HTTP/WS/IPC",
		Required: true,
53
		EnvVars:  prefixEnvVars("ENGINE"),
54
	}
55
	EngineJWTPath = &cli.StringFlag{
56 57 58 59
		Name:      "engine.jwt-secret",
		Usage:     "Path to JWT secret file used to authenticate Engine API communication with.",
		Required:  true,
		TakesFile: true,
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
		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"),
90
	}
91
)
92 93 94 95

func ParseBuildingArgs(ctx *cli.Context) *engine.BlockBuildingSettings {
	return &engine.BlockBuildingSettings{
		BlockTime:    ctx.Uint64(BlockTimeFlag.Name),
96
		AllowGaps:    ctx.Bool(AllowGaps.Name),
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
		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
}

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

173 174
func textFlag[T Text](name string, usage string, value T) *cli.GenericFlag {
	return &cli.GenericFlag{
175 176
		Name:     name,
		Usage:    usage,
177
		EnvVars:  prefixEnvVars(strings.ToUpper(name)),
178 179 180 181 182
		Required: true,
		Value:    &TextFlag[T]{Value: value},
	}
}

183
func addrFlag(name string, usage string) *cli.GenericFlag {
184 185 186
	return textFlag[*common.Address](name, usage, new(common.Address))
}

187
func bytesFlag(name string, usage string) *cli.GenericFlag {
188 189 190
	return textFlag[*hexutil.Bytes](name, usage, new(hexutil.Bytes))
}

191
func hashFlag(name string, usage string) *cli.GenericFlag {
192 193 194
	return textFlag[*common.Hash](name, usage, new(common.Hash))
}

195
func bigFlag(name string, usage string) *cli.GenericFlag {
196 197 198 199 200 201 202
	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
}

203 204 205 206
func bytesFlagValue(name string, ctx *cli.Context) hexutil.Bytes {
	return *ctx.Generic(name).(*TextFlag[*hexutil.Bytes]).Value
}

207 208 209 210 211 212 213 214 215
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 (
216
	CheatStorageGetCmd = &cli.Command{
217 218 219 220 221 222 223 224 225 226 227
		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))
		}),
	}
228
	CheatStorageSetCmd = &cli.Command{
229 230 231 232 233 234 235 236 237 238 239 240
		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)))
		}),
	}
241
	CheatStorageReadAll = &cli.Command{
242 243 244 245 246 247 248 249
		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))
		}),
	}
250
	CheatStorageDiffCmd = &cli.Command{
251 252 253 254 255 256 257
		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)))
		}),
	}
258
	CheatStoragePatchCmd = &cli.Command{
259 260 261 262 263 264 265
		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)))
		}),
	}
266
	CheatStorageCmd = &cli.Command{
267
		Name: "storage",
268
		Subcommands: []*cli.Command{
269 270 271 272 273 274 275
			CheatStorageGetCmd,
			CheatStorageSetCmd,
			CheatStorageReadAll,
			CheatStorageDiffCmd,
			CheatStoragePatchCmd,
		},
	}
276
	CheatSetBalanceCmd = &cli.Command{
277 278 279 280 281 282 283 284 285 286
		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)))
		}),
	}
287
	CheatSetCodeCmd = &cli.Command{
288 289 290 291
		Name: "code",
		Flags: []cli.Flag{
			DataDirFlag,
			addrFlag("address", "Address to change code of"),
292
			bytesFlag("code", "New code of the account"),
293 294
		},
		Action: CheatAction(false, func(ctx *cli.Context, ch *cheat.Cheater) error {
295
			return ch.RunAndClose(cheat.SetCode(addrFlagValue("address", ctx), bytesFlagValue("code", ctx)))
296 297
		}),
	}
298
	CheatSetNonceCmd = &cli.Command{
299 300 301 302 303 304 305 306 307 308
		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()))
		}),
	}
309
	CheatOvmOwnersCmd = &cli.Command{
310 311 312
		Name: "ovm-owners",
		Flags: []cli.Flag{
			DataDirFlag,
313
			&cli.StringFlag{
314 315 316
				Name:     "config",
				Usage:    "Path to JSON config of OVM address replacements to apply.",
				Required: true,
317
				EnvVars:  prefixEnvVars("OVM_OWNERS"),
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
				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))
		}),
	}
333
	CheatPrintHeadBlock = &cli.Command{
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
		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(),
			})
		}),
	}
352
	CheatPrintHeadHeader = &cli.Command{
353 354 355 356 357 358 359 360 361 362 363
		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))
		}),
	}
364
	EngineBlockCmd = &cli.Command{
365 366 367 368
		Name:  "block",
		Usage: "build the next block using the Engine API",
		Flags: []cli.Flag{
			EngineEndpoint, EngineJWTPath,
369
			FeeRecipientFlag, RandaoFlag, BlockTimeFlag, BuildingTime, AllowGaps,
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
		},
		// 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
		}),
	}
389
	EngineAutoCmd = &cli.Command{
390 391 392 393 394
		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,
395
			FeeRecipientFlag, RandaoFlag, BlockTimeFlag, BuildingTime, AllowGaps,
396 397
		}, oplog.CLIFlags(envVarPrefix)...), opmetrics.CLIFlags(envVarPrefix)...),
		Action: EngineAction(func(ctx *cli.Context, client client.RPC) error {
398
			logCfg := oplog.ReadCLIConfig(ctx)
399 400 401 402 403 404 405 406
			if err := logCfg.Check(); err != nil {
				return fmt.Errorf("failed to parse log configuration: %w", err)
			}
			l := oplog.NewLogger(logCfg)

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

407
			metricsCfg := opmetrics.ReadCLIConfig(ctx)
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

			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)
					go func() {
						if err := opmetrics.ListenAndServe(ctx, registry, metricsCfg.ListenAddr, metricsCfg.ListenPort); err != nil {
							l.Error("error starting metrics server", err)
						}
					}()
				}
				return engine.Auto(ctx, metrics, client, l, shutdown, settings)
			})
		}),
	}
424
	EngineStatusCmd = &cli.Command{
425 426 427 428 429 430 431 432 433 434 435 436
		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)
		}),
	}
437
	EngineCopyCmd = &cli.Command{
438 439 440
		Name: "copy",
		Flags: []cli.Flag{
			EngineEndpoint, EngineJWTPath,
441
			&cli.StringFlag{
442 443 444
				Name:     "source",
				Usage:    "Unauthenticated regular eth JSON RPC to pull block data from, can be HTTP/WS/IPC.",
				Required: true,
445
				EnvVars:  prefixEnvVars("ENGINE"),
446 447 448 449 450 451 452 453 454 455 456 457 458
			},
		},
		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)
		}),
	}
)

459
var CheatCmd = &cli.Command{
460 461 462 463
	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.",
464
	Subcommands: []*cli.Command{
465 466
		CheatStorageCmd,
		CheatSetBalanceCmd,
467
		CheatSetCodeCmd,
468 469 470 471 472 473 474
		CheatSetNonceCmd,
		CheatOvmOwnersCmd,
		CheatPrintHeadBlock,
		CheatPrintHeadHeader,
	},
}

475
var EngineCmd = &cli.Command{
476 477 478
	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",
479
	Subcommands: []*cli.Command{
480 481 482 483 484 485
		EngineBlockCmd,
		EngineAutoCmd,
		EngineStatusCmd,
		EngineCopyCmd,
	},
}