github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/cmd/geth/main.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of go-ethereum. 3 // 4 // go-ethereum is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // go-ethereum is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>. 16 17 // geth is the official command-line client for Ethereum. 18 package main 19 20 import ( 21 "fmt" 22 "math" 23 "os" 24 "runtime" 25 godebug "runtime/debug" 26 "sort" 27 "strconv" 28 "strings" 29 "time" 30 31 "github.com/elastic/gosigar" 32 "github.com/ethereum-optimism/optimism/l2geth/accounts" 33 "github.com/ethereum-optimism/optimism/l2geth/accounts/keystore" 34 "github.com/ethereum-optimism/optimism/l2geth/cmd/utils" 35 "github.com/ethereum-optimism/optimism/l2geth/common" 36 "github.com/ethereum-optimism/optimism/l2geth/console" 37 "github.com/ethereum-optimism/optimism/l2geth/eth" 38 "github.com/ethereum-optimism/optimism/l2geth/eth/downloader" 39 "github.com/ethereum-optimism/optimism/l2geth/ethclient" 40 "github.com/ethereum-optimism/optimism/l2geth/internal/debug" 41 "github.com/ethereum-optimism/optimism/l2geth/les" 42 "github.com/ethereum-optimism/optimism/l2geth/log" 43 "github.com/ethereum-optimism/optimism/l2geth/metrics" 44 "github.com/ethereum-optimism/optimism/l2geth/node" 45 cli "gopkg.in/urfave/cli.v1" 46 ) 47 48 const ( 49 clientIdentifier = "geth" // Client identifier to advertise over the network 50 ) 51 52 var ( 53 // Git SHA1 commit hash of the release (set via linker flags) 54 gitCommit = "" 55 gitDate = "" 56 // The app that holds all commands and flags. 57 app = utils.NewApp(gitCommit, gitDate, "the go-ethereum command line interface") 58 // flags that configure the node 59 nodeFlags = []cli.Flag{ 60 utils.IdentityFlag, 61 utils.UnlockedAccountFlag, 62 utils.PasswordFileFlag, 63 utils.BootnodesFlag, 64 utils.BootnodesV4Flag, 65 utils.BootnodesV5Flag, 66 utils.DataDirFlag, 67 utils.AncientFlag, 68 utils.KeyStoreDirFlag, 69 utils.ExternalSignerFlag, 70 utils.NoUSBFlag, 71 utils.SmartCardDaemonPathFlag, 72 utils.OverrideIstanbulFlag, 73 utils.OverrideMuirGlacierFlag, 74 utils.EthashCacheDirFlag, 75 utils.EthashCachesInMemoryFlag, 76 utils.EthashCachesOnDiskFlag, 77 utils.EthashDatasetDirFlag, 78 utils.EthashDatasetsInMemoryFlag, 79 utils.EthashDatasetsOnDiskFlag, 80 utils.TxPoolLocalsFlag, 81 utils.TxPoolNoLocalsFlag, 82 utils.TxPoolJournalFlag, 83 utils.TxPoolRejournalFlag, 84 utils.TxPoolPriceLimitFlag, 85 utils.TxPoolPriceBumpFlag, 86 utils.TxPoolAccountSlotsFlag, 87 utils.TxPoolGlobalSlotsFlag, 88 utils.TxPoolAccountQueueFlag, 89 utils.TxPoolGlobalQueueFlag, 90 utils.TxPoolLifetimeFlag, 91 utils.SyncModeFlag, 92 utils.ExitWhenSyncedFlag, 93 utils.GCModeFlag, 94 utils.LightServeFlag, 95 utils.LightLegacyServFlag, 96 utils.LightIngressFlag, 97 utils.LightEgressFlag, 98 utils.LightMaxPeersFlag, 99 utils.LightLegacyPeersFlag, 100 utils.LightKDFFlag, 101 utils.UltraLightServersFlag, 102 utils.UltraLightFractionFlag, 103 utils.UltraLightOnlyAnnounceFlag, 104 utils.WhitelistFlag, 105 utils.CacheFlag, 106 utils.CacheDatabaseFlag, 107 utils.CacheTrieFlag, 108 utils.CacheGCFlag, 109 utils.CacheNoPrefetchFlag, 110 utils.ListenPortFlag, 111 utils.MaxPeersFlag, 112 utils.MaxPendingPeersFlag, 113 utils.MiningEnabledFlag, 114 utils.MinerThreadsFlag, 115 utils.MinerLegacyThreadsFlag, 116 utils.MinerNotifyFlag, 117 utils.MinerGasTargetFlag, 118 utils.MinerLegacyGasTargetFlag, 119 utils.MinerGasLimitFlag, 120 utils.MinerGasPriceFlag, 121 utils.MinerLegacyGasPriceFlag, 122 utils.MinerEtherbaseFlag, 123 utils.MinerLegacyEtherbaseFlag, 124 utils.MinerExtraDataFlag, 125 utils.MinerLegacyExtraDataFlag, 126 utils.MinerRecommitIntervalFlag, 127 utils.MinerNoVerfiyFlag, 128 utils.NATFlag, 129 utils.NoDiscoverFlag, 130 utils.DiscoveryV5Flag, 131 utils.NetrestrictFlag, 132 utils.NodeKeyFileFlag, 133 utils.NodeKeyHexFlag, 134 utils.DeveloperFlag, 135 utils.DeveloperPeriodFlag, 136 utils.TestnetFlag, 137 utils.RinkebyFlag, 138 utils.GoerliFlag, 139 utils.VMEnableDebugFlag, 140 utils.NetworkIdFlag, 141 utils.EthStatsURLFlag, 142 utils.FakePoWFlag, 143 utils.NoCompactionFlag, 144 utils.GpoBlocksFlag, 145 utils.GpoPercentileFlag, 146 utils.EWASMInterpreterFlag, 147 utils.EVMInterpreterFlag, 148 configFileFlag, 149 } 150 151 // UsingOVM 152 // Optimism specific flags must be added to the application 153 // flag parsing logic 154 optimismFlags = []cli.Flag{ 155 utils.Eth1SyncServiceEnable, 156 utils.Eth1CanonicalTransactionChainDeployHeightFlag, 157 utils.RollupClientHttpFlag, 158 utils.RollupEnableVerifierFlag, 159 utils.RollupTimstampRefreshFlag, 160 utils.RollupPollIntervalFlag, 161 utils.RollupMaxCalldataSizeFlag, 162 utils.RollupBackendFlag, 163 utils.RollupEnforceFeesFlag, 164 utils.RollupFeeThresholdDownFlag, 165 utils.RollupFeeThresholdUpFlag, 166 utils.RollupGenesisTimeoutSecondsFlag, 167 utils.SequencerClientHttpFlag, 168 } 169 170 rpcFlags = []cli.Flag{ 171 utils.RPCEnabledFlag, 172 utils.RPCListenAddrFlag, 173 utils.RPCPortFlag, 174 utils.RPCCORSDomainFlag, 175 utils.RPCVirtualHostsFlag, 176 utils.GraphQLEnabledFlag, 177 utils.GraphQLListenAddrFlag, 178 utils.GraphQLPortFlag, 179 utils.GraphQLCORSDomainFlag, 180 utils.GraphQLVirtualHostsFlag, 181 utils.RPCApiFlag, 182 utils.WSEnabledFlag, 183 utils.WSListenAddrFlag, 184 utils.WSPortFlag, 185 utils.WSApiFlag, 186 utils.WSAllowedOriginsFlag, 187 utils.IPCDisabledFlag, 188 utils.IPCPathFlag, 189 utils.InsecureUnlockAllowedFlag, 190 utils.RPCGlobalGasCap, 191 utils.RPCGlobalEVMTimeoutFlag, 192 } 193 194 whisperFlags = []cli.Flag{ 195 utils.WhisperEnabledFlag, 196 utils.WhisperMaxMessageSizeFlag, 197 utils.WhisperMinPOWFlag, 198 utils.WhisperRestrictConnectionBetweenLightClientsFlag, 199 } 200 201 metricsFlags = []cli.Flag{ 202 utils.MetricsEnabledFlag, 203 utils.MetricsEnabledExpensiveFlag, 204 utils.MetricsEnableInfluxDBFlag, 205 utils.MetricsInfluxDBEndpointFlag, 206 utils.MetricsInfluxDBDatabaseFlag, 207 utils.MetricsInfluxDBUsernameFlag, 208 utils.MetricsInfluxDBPasswordFlag, 209 utils.MetricsInfluxDBTagsFlag, 210 } 211 ) 212 213 func init() { 214 // Initialize the CLI app and start Geth 215 app.Action = geth 216 app.HideVersion = true // we have a command to print the version 217 app.Copyright = "Copyright 2013-2020 The go-ethereum Authors" 218 app.Commands = []cli.Command{ 219 // See chaincmd.go: 220 initCommand, 221 dumpChainCfgCommand, 222 importCommand, 223 exportCommand, 224 importPreimagesCommand, 225 exportPreimagesCommand, 226 copydbCommand, 227 removedbCommand, 228 dumpCommand, 229 inspectCommand, 230 // See accountcmd.go: 231 accountCommand, 232 walletCommand, 233 // See consolecmd.go: 234 consoleCommand, 235 attachCommand, 236 javascriptCommand, 237 // See misccmd.go: 238 makecacheCommand, 239 makedagCommand, 240 versionCommand, 241 licenseCommand, 242 // See config.go 243 dumpConfigCommand, 244 // See retesteth.go 245 retestethCommand, 246 } 247 sort.Sort(cli.CommandsByName(app.Commands)) 248 249 app.Flags = append(app.Flags, nodeFlags...) 250 // UsingOVM 251 app.Flags = append(app.Flags, optimismFlags...) 252 app.Flags = append(app.Flags, rpcFlags...) 253 app.Flags = append(app.Flags, consoleFlags...) 254 app.Flags = append(app.Flags, debug.Flags...) 255 app.Flags = append(app.Flags, whisperFlags...) 256 app.Flags = append(app.Flags, metricsFlags...) 257 258 app.Before = func(ctx *cli.Context) error { 259 return debug.Setup(ctx, "") 260 } 261 app.After = func(ctx *cli.Context) error { 262 debug.Exit() 263 console.Stdin.Close() // Resets terminal mode. 264 return nil 265 } 266 } 267 268 func main() { 269 if err := app.Run(os.Args); err != nil { 270 fmt.Fprintln(os.Stderr, err) 271 os.Exit(1) 272 } 273 } 274 275 // prepare manipulates memory cache allowance and setups metric system. 276 // This function should be called before launching devp2p stack. 277 func prepare(ctx *cli.Context) { 278 // If we're a full node on mainnet without --cache specified, bump default cache allowance 279 if ctx.GlobalString(utils.SyncModeFlag.Name) != "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) && !ctx.GlobalIsSet(utils.NetworkIdFlag.Name) { 280 // Make sure we're not on any supported preconfigured testnet either 281 if !ctx.GlobalIsSet(utils.TestnetFlag.Name) && !ctx.GlobalIsSet(utils.RinkebyFlag.Name) && !ctx.GlobalIsSet(utils.GoerliFlag.Name) && !ctx.GlobalIsSet(utils.DeveloperFlag.Name) { 282 // Nope, we're really on mainnet. Bump that cache up! 283 log.Info("Bumping default cache on mainnet", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 4096) 284 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(4096)) 285 } 286 } 287 // If we're running a light client on any network, drop the cache to some meaningfully low amount 288 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" && !ctx.GlobalIsSet(utils.CacheFlag.Name) { 289 log.Info("Dropping default light client cache", "provided", ctx.GlobalInt(utils.CacheFlag.Name), "updated", 128) 290 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(128)) 291 } 292 // Cap the cache allowance and tune the garbage collector 293 var mem gosigar.Mem 294 // Workaround until OpenBSD support lands into gosigar 295 // Check https://github.com/elastic/gosigar#supported-platforms 296 if runtime.GOOS != "openbsd" { 297 if err := mem.Get(); err == nil { 298 allowance := int(mem.Total / 1024 / 1024 / 3) 299 if cache := ctx.GlobalInt(utils.CacheFlag.Name); cache > allowance { 300 log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) 301 ctx.GlobalSet(utils.CacheFlag.Name, strconv.Itoa(allowance)) 302 } 303 } 304 } 305 // Ensure Go's GC ignores the database cache for trigger percentage 306 cache := ctx.GlobalInt(utils.CacheFlag.Name) 307 gogc := math.Max(20, math.Min(100, 100/(float64(cache)/1024))) 308 309 log.Debug("Sanitizing Go's GC trigger", "percent", int(gogc)) 310 godebug.SetGCPercent(int(gogc)) 311 312 // Start metrics export if enabled 313 utils.SetupMetrics(ctx) 314 315 // Start system runtime metrics collection 316 go metrics.CollectProcessMetrics(3 * time.Second) 317 } 318 319 // geth is the main entry point into the system if no special subcommand is ran. 320 // It creates a default node based on the command line arguments and runs it in 321 // blocking mode, waiting for it to be shut down. 322 func geth(ctx *cli.Context) error { 323 if args := ctx.Args(); len(args) > 0 { 324 return fmt.Errorf("invalid command: %q", args[0]) 325 } 326 prepare(ctx) 327 node := makeFullNode(ctx) 328 defer node.Close() 329 startNode(ctx, node) 330 node.Wait() 331 return nil 332 } 333 334 // startNode boots up the system node and all registered protocols, after which 335 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 336 // miner. 337 func startNode(ctx *cli.Context, stack *node.Node) { 338 debug.Memsize.Add("node", stack) 339 340 // Start up the node itself 341 utils.StartNode(stack) 342 343 // Unlock any account specifically requested 344 unlockAccounts(ctx, stack) 345 346 // Register wallet event handlers to open and auto-derive wallets 347 events := make(chan accounts.WalletEvent, 16) 348 stack.AccountManager().Subscribe(events) 349 350 // Create a client to interact with local geth node. 351 rpcClient, err := stack.Attach() 352 if err != nil { 353 utils.Fatalf("Failed to attach to self: %v", err) 354 } 355 ethClient := ethclient.NewClient(rpcClient) 356 357 // Set contract backend for ethereum service if local node 358 // is serving LES requests. 359 if ctx.GlobalInt(utils.LightLegacyServFlag.Name) > 0 || ctx.GlobalInt(utils.LightServeFlag.Name) > 0 { 360 var ethService *eth.Ethereum 361 if err := stack.Service(ðService); err != nil { 362 utils.Fatalf("Failed to retrieve ethereum service: %v", err) 363 } 364 ethService.SetContractBackend(ethClient) 365 } 366 // Set contract backend for les service if local node is 367 // running as a light client. 368 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 369 var lesService *les.LightEthereum 370 if err := stack.Service(&lesService); err != nil { 371 utils.Fatalf("Failed to retrieve light ethereum service: %v", err) 372 } 373 lesService.SetContractBackend(ethClient) 374 } 375 376 go func() { 377 // Open any wallets already attached 378 for _, wallet := range stack.AccountManager().Wallets() { 379 if err := wallet.Open(""); err != nil { 380 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 381 } 382 } 383 // Listen for wallet event till termination 384 for event := range events { 385 switch event.Kind { 386 case accounts.WalletArrived: 387 if err := event.Wallet.Open(""); err != nil { 388 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 389 } 390 case accounts.WalletOpened: 391 status, _ := event.Wallet.Status() 392 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 393 394 var derivationPaths []accounts.DerivationPath 395 if event.Wallet.URL().Scheme == "ledger" { 396 derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath) 397 } 398 derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath) 399 400 event.Wallet.SelfDerive(derivationPaths, ethClient) 401 402 case accounts.WalletDropped: 403 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 404 event.Wallet.Close() 405 } 406 } 407 }() 408 409 // Spawn a standalone goroutine for status synchronization monitoring, 410 // close the node when synchronization is complete if user required. 411 if ctx.GlobalBool(utils.ExitWhenSyncedFlag.Name) { 412 go func() { 413 sub := stack.EventMux().Subscribe(downloader.DoneEvent{}) 414 defer sub.Unsubscribe() 415 for { 416 event := <-sub.Chan() 417 if event == nil { 418 continue 419 } 420 done, ok := event.Data.(downloader.DoneEvent) 421 if !ok { 422 continue 423 } 424 if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute { 425 log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(), 426 "age", common.PrettyAge(timestamp)) 427 stack.Stop() 428 } 429 } 430 }() 431 } 432 433 // Start auxiliary services if enabled 434 if ctx.GlobalBool(utils.MiningEnabledFlag.Name) || ctx.GlobalBool(utils.DeveloperFlag.Name) { 435 // Mining only makes sense if a full Ethereum node is running 436 if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { 437 utils.Fatalf("Light clients do not support mining") 438 } 439 var ethereum *eth.Ethereum 440 if err := stack.Service(ðereum); err != nil { 441 utils.Fatalf("Ethereum service not running: %v", err) 442 } 443 // Set the gas price to the limits from the CLI and start mining 444 gasprice := utils.GlobalBig(ctx, utils.MinerLegacyGasPriceFlag.Name) 445 if ctx.IsSet(utils.MinerGasPriceFlag.Name) { 446 gasprice = utils.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 447 } 448 ethereum.TxPool().SetGasPrice(gasprice) 449 450 threads := ctx.GlobalInt(utils.MinerLegacyThreadsFlag.Name) 451 if ctx.GlobalIsSet(utils.MinerThreadsFlag.Name) { 452 threads = ctx.GlobalInt(utils.MinerThreadsFlag.Name) 453 } 454 if err := ethereum.StartMining(threads); err != nil { 455 utils.Fatalf("Failed to start mining: %v", err) 456 } 457 // UsingOVM 458 // Can optionally configure the sync service. Turning it off allows 459 // for statically serving historical data and is also useful for 460 // local development. When it is turned on, it will attempt to sync 461 // using the `RollupClient` 462 if ctx.GlobalBool(utils.Eth1SyncServiceEnable.Name) { 463 if err := ethereum.SyncService().Start(); err != nil { 464 utils.Fatalf("Failed to start syncservice: %v", err) 465 } 466 } 467 } 468 } 469 470 // unlockAccounts unlocks any account specifically requested. 471 func unlockAccounts(ctx *cli.Context, stack *node.Node) { 472 var unlocks []string 473 inputs := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",") 474 for _, input := range inputs { 475 if trimmed := strings.TrimSpace(input); trimmed != "" { 476 unlocks = append(unlocks, trimmed) 477 } 478 } 479 // Short circuit if there is no account to unlock. 480 if len(unlocks) == 0 { 481 return 482 } 483 // If insecure account unlocking is not allowed if node's APIs are exposed to external. 484 // Print warning log to user and skip unlocking. 485 if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() { 486 utils.Fatalf("Account unlock with HTTP access is forbidden!") 487 } 488 ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 489 passwords := utils.MakePasswordList(ctx) 490 for i, account := range unlocks { 491 unlockAccount(ks, account, i, passwords) 492 } 493 }