github.com/theQRL/go-zond@v0.1.1/cmd/gzond/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 "os" 23 "sort" 24 "strconv" 25 "strings" 26 "time" 27 28 "github.com/theQRL/go-zond/accounts" 29 "github.com/theQRL/go-zond/accounts/keystore" 30 "github.com/theQRL/go-zond/cmd/utils" 31 "github.com/theQRL/go-zond/common" 32 "github.com/theQRL/go-zond/console/prompt" 33 "github.com/theQRL/go-zond/internal/debug" 34 "github.com/theQRL/go-zond/internal/ethapi" 35 "github.com/theQRL/go-zond/internal/flags" 36 "github.com/theQRL/go-zond/log" 37 "github.com/theQRL/go-zond/metrics" 38 "github.com/theQRL/go-zond/node" 39 "github.com/theQRL/go-zond/zond" 40 "github.com/theQRL/go-zond/zond/downloader" 41 "github.com/theQRL/go-zond/zondclient" 42 43 // Force-load the tracer engines to trigger registration 44 _ "github.com/theQRL/go-zond/zond/tracers/js" 45 _ "github.com/theQRL/go-zond/zond/tracers/native" 46 "go.uber.org/automaxprocs/maxprocs" 47 48 "github.com/urfave/cli/v2" 49 ) 50 51 const ( 52 clientIdentifier = "gzond" // Client identifier to advertise over the network 53 ) 54 55 var ( 56 // flags that configure the node 57 nodeFlags = flags.Merge([]cli.Flag{ 58 utils.IdentityFlag, 59 utils.UnlockedAccountFlag, 60 utils.PasswordFileFlag, 61 utils.BootnodesFlag, 62 utils.MinFreeDiskSpaceFlag, 63 utils.KeyStoreDirFlag, 64 utils.ExternalSignerFlag, 65 utils.NoUSBFlag, 66 utils.USBFlag, 67 utils.SmartCardDaemonPathFlag, 68 utils.OverrideCancun, 69 utils.OverrideVerkle, 70 utils.EnablePersonal, 71 utils.TxPoolLocalsFlag, 72 utils.TxPoolNoLocalsFlag, 73 utils.TxPoolJournalFlag, 74 utils.TxPoolRejournalFlag, 75 utils.TxPoolPriceLimitFlag, 76 utils.TxPoolPriceBumpFlag, 77 utils.TxPoolAccountSlotsFlag, 78 utils.TxPoolGlobalSlotsFlag, 79 utils.TxPoolAccountQueueFlag, 80 utils.TxPoolGlobalQueueFlag, 81 utils.TxPoolLifetimeFlag, 82 utils.BlobPoolDataDirFlag, 83 utils.BlobPoolDataCapFlag, 84 utils.BlobPoolPriceBumpFlag, 85 utils.SyncModeFlag, 86 utils.SyncTargetFlag, 87 utils.ExitWhenSyncedFlag, 88 utils.GCModeFlag, 89 utils.SnapshotFlag, 90 utils.TxLookupLimitFlag, 91 utils.TransactionHistoryFlag, 92 utils.StateSchemeFlag, 93 utils.StateHistoryFlag, 94 utils.LightServeFlag, 95 utils.LightIngressFlag, 96 utils.LightEgressFlag, 97 utils.LightMaxPeersFlag, 98 utils.LightNoPruneFlag, 99 utils.LightKDFFlag, 100 utils.LightNoSyncServeFlag, 101 utils.EthRequiredBlocksFlag, 102 utils.LegacyWhitelistFlag, 103 utils.BloomFilterSizeFlag, 104 utils.CacheFlag, 105 utils.CacheDatabaseFlag, 106 utils.CacheTrieFlag, 107 utils.CacheTrieJournalFlag, 108 utils.CacheTrieRejournalFlag, 109 utils.CacheGCFlag, 110 utils.CacheSnapshotFlag, 111 utils.CacheNoPrefetchFlag, 112 utils.CachePreimagesFlag, 113 utils.CacheLogSizeFlag, 114 utils.FDLimitFlag, 115 utils.CryptoKZGFlag, 116 utils.ListenPortFlag, 117 utils.DiscoveryPortFlag, 118 utils.MaxPeersFlag, 119 utils.MaxPendingPeersFlag, 120 utils.MiningEnabledFlag, 121 utils.MinerGasLimitFlag, 122 utils.MinerGasPriceFlag, 123 utils.MinerEtherbaseFlag, 124 utils.MinerExtraDataFlag, 125 utils.MinerRecommitIntervalFlag, 126 utils.MinerNewPayloadTimeout, 127 utils.NATFlag, 128 utils.NoDiscoverFlag, 129 utils.DiscoveryV4Flag, 130 utils.DiscoveryV5Flag, 131 utils.LegacyDiscoveryV5Flag, 132 utils.NetrestrictFlag, 133 utils.NodeKeyFileFlag, 134 utils.NodeKeyHexFlag, 135 utils.DNSDiscoveryFlag, 136 utils.DeveloperFlag, 137 utils.DeveloperGasLimitFlag, 138 utils.DeveloperPeriodFlag, 139 utils.VMEnableDebugFlag, 140 utils.NetworkIdFlag, 141 utils.EthStatsURLFlag, 142 utils.NoCompactionFlag, 143 utils.GpoBlocksFlag, 144 utils.GpoPercentileFlag, 145 utils.GpoMaxGasPriceFlag, 146 utils.GpoIgnoreGasPriceFlag, 147 configFileFlag, 148 }, utils.NetworkFlags, utils.DatabasePathFlags) 149 150 rpcFlags = []cli.Flag{ 151 utils.HTTPEnabledFlag, 152 utils.HTTPListenAddrFlag, 153 utils.HTTPPortFlag, 154 utils.HTTPCORSDomainFlag, 155 utils.AuthListenFlag, 156 utils.AuthPortFlag, 157 utils.AuthVirtualHostsFlag, 158 utils.JWTSecretFlag, 159 utils.HTTPVirtualHostsFlag, 160 utils.GraphQLEnabledFlag, 161 utils.GraphQLCORSDomainFlag, 162 utils.GraphQLVirtualHostsFlag, 163 utils.HTTPApiFlag, 164 utils.HTTPPathPrefixFlag, 165 utils.WSEnabledFlag, 166 utils.WSListenAddrFlag, 167 utils.WSPortFlag, 168 utils.WSApiFlag, 169 utils.WSAllowedOriginsFlag, 170 utils.WSPathPrefixFlag, 171 utils.IPCDisabledFlag, 172 utils.IPCPathFlag, 173 utils.InsecureUnlockAllowedFlag, 174 utils.RPCGlobalGasCapFlag, 175 utils.RPCGlobalEVMTimeoutFlag, 176 utils.RPCGlobalTxFeeCapFlag, 177 utils.AllowUnprotectedTxs, 178 utils.BatchRequestLimit, 179 utils.BatchResponseMaxSize, 180 } 181 182 metricsFlags = []cli.Flag{ 183 utils.MetricsEnabledFlag, 184 utils.MetricsEnabledExpensiveFlag, 185 utils.MetricsHTTPFlag, 186 utils.MetricsPortFlag, 187 utils.MetricsEnableInfluxDBFlag, 188 utils.MetricsInfluxDBEndpointFlag, 189 utils.MetricsInfluxDBDatabaseFlag, 190 utils.MetricsInfluxDBUsernameFlag, 191 utils.MetricsInfluxDBPasswordFlag, 192 utils.MetricsInfluxDBTagsFlag, 193 utils.MetricsEnableInfluxDBV2Flag, 194 utils.MetricsInfluxDBTokenFlag, 195 utils.MetricsInfluxDBBucketFlag, 196 utils.MetricsInfluxDBOrganizationFlag, 197 } 198 ) 199 200 var app = flags.NewApp("the go-ethereum command line interface") 201 202 func init() { 203 // Initialize the CLI app and start Geth 204 app.Action = geth 205 app.Copyright = "Copyright 2013-2023 The go-ethereum Authors" 206 app.Commands = []*cli.Command{ 207 // See chaincmd.go: 208 initCommand, 209 importCommand, 210 exportCommand, 211 importPreimagesCommand, 212 exportPreimagesCommand, 213 removedbCommand, 214 dumpCommand, 215 dumpGenesisCommand, 216 // See accountcmd.go: 217 accountCommand, 218 walletCommand, 219 // See consolecmd.go: 220 consoleCommand, 221 attachCommand, 222 javascriptCommand, 223 // See misccmd.go: 224 versionCommand, 225 versionCheckCommand, 226 licenseCommand, 227 // See config.go 228 dumpConfigCommand, 229 // see dbcmd.go 230 dbCommand, 231 // See cmd/utils/flags_legacy.go 232 utils.ShowDeprecated, 233 // See snapshot.go 234 snapshotCommand, 235 // See verkle.go 236 verkleCommand, 237 } 238 sort.Sort(cli.CommandsByName(app.Commands)) 239 240 app.Flags = flags.Merge( 241 nodeFlags, 242 rpcFlags, 243 consoleFlags, 244 debug.Flags, 245 metricsFlags, 246 ) 247 flags.AutoEnvVars(app.Flags, "GZOND") 248 249 app.Before = func(ctx *cli.Context) error { 250 maxprocs.Set() // Automatically set GOMAXPROCS to match Linux container CPU quota. 251 flags.MigrateGlobalFlags(ctx) 252 if err := debug.Setup(ctx); err != nil { 253 return err 254 } 255 flags.CheckEnvVars(ctx, app.Flags, "GZOND") 256 return nil 257 } 258 app.After = func(ctx *cli.Context) error { 259 debug.Exit() 260 prompt.Stdin.Close() // Resets terminal mode. 261 return nil 262 } 263 } 264 265 func main() { 266 if err := app.Run(os.Args); err != nil { 267 fmt.Fprintln(os.Stderr, err) 268 os.Exit(1) 269 } 270 } 271 272 // prepare manipulates memory cache allowance and setups metric system. 273 // This function should be called before launching devp2p stack. 274 func prepare(ctx *cli.Context) { 275 // If we're running a known preset, log it for convenience. 276 switch { 277 case ctx.IsSet(utils.GoerliFlag.Name): 278 log.Info("Starting Geth on Görli testnet...") 279 280 case ctx.IsSet(utils.SepoliaFlag.Name): 281 log.Info("Starting Geth on Sepolia testnet...") 282 283 case ctx.IsSet(utils.HoleskyFlag.Name): 284 log.Info("Starting Geth on Holesky testnet...") 285 286 case ctx.IsSet(utils.BetaNetFlag.Name): 287 log.Info("Starting Geth on BetaNet testnet...") 288 289 case ctx.IsSet(utils.DeveloperFlag.Name): 290 log.Info("Starting Geth in ephemeral dev mode...") 291 log.Warn(`You are running Geth in --dev mode. Please note the following: 292 293 1. This mode is only intended for fast, iterative development without assumptions on 294 security or persistence. 295 2. The database is created in memory unless specified otherwise. Therefore, shutting down 296 your computer or losing power will wipe your entire block data and chain state for 297 your dev environment. 298 3. A random, pre-allocated developer account will be available and unlocked as 299 zond.coinbase, which can be used for testing. The random dev account is temporary, 300 stored on a ramdisk, and will be lost if your machine is restarted. 301 4. Mining is enabled by default. However, the client will only seal blocks if transactions 302 are pending in the mempool. The miner's minimum accepted gas price is 1. 303 5. Networking is disabled; there is no listen-address, the maximum number of peers is set 304 to 0, and discovery is disabled. 305 `) 306 307 case !ctx.IsSet(utils.NetworkIdFlag.Name): 308 log.Info("Starting Geth on Ethereum mainnet...") 309 } 310 // If we're a full node on mainnet without --cache specified, bump default cache allowance 311 if ctx.String(utils.SyncModeFlag.Name) != "light" && !ctx.IsSet(utils.CacheFlag.Name) && !ctx.IsSet(utils.NetworkIdFlag.Name) { 312 // Make sure we're not on any supported preconfigured testnet either 313 if !ctx.IsSet(utils.HoleskyFlag.Name) && 314 !ctx.IsSet(utils.SepoliaFlag.Name) && 315 !ctx.IsSet(utils.GoerliFlag.Name) && 316 !ctx.IsSet(utils.DeveloperFlag.Name) { 317 // Nope, we're really on mainnet. Bump that cache up! 318 log.Info("Bumping default cache on mainnet", "provided", ctx.Int(utils.CacheFlag.Name), "updated", 4096) 319 ctx.Set(utils.CacheFlag.Name, strconv.Itoa(4096)) 320 } 321 } 322 // If we're running a light client on any network, drop the cache to some meaningfully low amount 323 if ctx.String(utils.SyncModeFlag.Name) == "light" && !ctx.IsSet(utils.CacheFlag.Name) { 324 log.Info("Dropping default light client cache", "provided", ctx.Int(utils.CacheFlag.Name), "updated", 128) 325 ctx.Set(utils.CacheFlag.Name, strconv.Itoa(128)) 326 } 327 328 // Start metrics export if enabled 329 utils.SetupMetrics(ctx) 330 331 // Start system runtime metrics collection 332 go metrics.CollectProcessMetrics(3 * time.Second) 333 } 334 335 // geth is the main entry point into the system if no special subcommand is run. 336 // It creates a default node based on the command line arguments and runs it in 337 // blocking mode, waiting for it to be shut down. 338 func geth(ctx *cli.Context) error { 339 if args := ctx.Args().Slice(); len(args) > 0 { 340 return fmt.Errorf("invalid command: %q", args[0]) 341 } 342 343 prepare(ctx) 344 stack, backend := makeFullNode(ctx) 345 defer stack.Close() 346 347 startNode(ctx, stack, backend, false) 348 stack.Wait() 349 return nil 350 } 351 352 // startNode boots up the system node and all registered protocols, after which 353 // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the 354 // miner. 355 func startNode(ctx *cli.Context, stack *node.Node, backend ethapi.Backend, isConsole bool) { 356 debug.Memsize.Add("node", stack) 357 358 // Start up the node itself 359 utils.StartNode(ctx, stack, isConsole) 360 361 // Unlock any account specifically requested 362 unlockAccounts(ctx, stack) 363 364 // Register wallet event handlers to open and auto-derive wallets 365 events := make(chan accounts.WalletEvent, 16) 366 stack.AccountManager().Subscribe(events) 367 368 // Create a client to interact with local geth node. 369 rpcClient := stack.Attach() 370 ethClient := zondclient.NewClient(rpcClient) 371 372 go func() { 373 // Open any wallets already attached 374 for _, wallet := range stack.AccountManager().Wallets() { 375 if err := wallet.Open(""); err != nil { 376 log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err) 377 } 378 } 379 // Listen for wallet event till termination 380 for event := range events { 381 switch event.Kind { 382 case accounts.WalletArrived: 383 if err := event.Wallet.Open(""); err != nil { 384 log.Warn("New wallet appeared, failed to open", "url", event.Wallet.URL(), "err", err) 385 } 386 case accounts.WalletOpened: 387 status, _ := event.Wallet.Status() 388 log.Info("New wallet appeared", "url", event.Wallet.URL(), "status", status) 389 390 var derivationPaths []accounts.DerivationPath 391 if event.Wallet.URL().Scheme == "ledger" { 392 derivationPaths = append(derivationPaths, accounts.LegacyLedgerBaseDerivationPath) 393 } 394 derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath) 395 396 event.Wallet.SelfDerive(derivationPaths, ethClient) 397 398 case accounts.WalletDropped: 399 log.Info("Old wallet dropped", "url", event.Wallet.URL()) 400 event.Wallet.Close() 401 } 402 } 403 }() 404 405 // Spawn a standalone goroutine for status synchronization monitoring, 406 // close the node when synchronization is complete if user required. 407 if ctx.Bool(utils.ExitWhenSyncedFlag.Name) { 408 go func() { 409 sub := stack.EventMux().Subscribe(downloader.DoneEvent{}) 410 defer sub.Unsubscribe() 411 for { 412 event := <-sub.Chan() 413 if event == nil { 414 continue 415 } 416 done, ok := event.Data.(downloader.DoneEvent) 417 if !ok { 418 continue 419 } 420 if timestamp := time.Unix(int64(done.Latest.Time), 0); time.Since(timestamp) < 10*time.Minute { 421 log.Info("Synchronisation completed", "latestnum", done.Latest.Number, "latesthash", done.Latest.Hash(), 422 "age", common.PrettyAge(timestamp)) 423 stack.Close() 424 } 425 } 426 }() 427 } 428 429 // Start auxiliary services if enabled 430 if ctx.Bool(utils.MiningEnabledFlag.Name) { 431 // Mining only makes sense if a full Ethereum node is running 432 if ctx.String(utils.SyncModeFlag.Name) == "light" { 433 utils.Fatalf("Light clients do not support mining") 434 } 435 ethBackend, ok := backend.(*zond.EthAPIBackend) 436 if !ok { 437 utils.Fatalf("Ethereum service not running") 438 } 439 // Set the gas price to the limits from the CLI and start mining 440 gasprice := flags.GlobalBig(ctx, utils.MinerGasPriceFlag.Name) 441 ethBackend.TxPool().SetGasTip(gasprice) 442 if err := ethBackend.StartMining(); err != nil { 443 utils.Fatalf("Failed to start mining: %v", err) 444 } 445 } 446 } 447 448 // unlockAccounts unlocks any account specifically requested. 449 func unlockAccounts(ctx *cli.Context, stack *node.Node) { 450 var unlocks []string 451 inputs := strings.Split(ctx.String(utils.UnlockedAccountFlag.Name), ",") 452 for _, input := range inputs { 453 if trimmed := strings.TrimSpace(input); trimmed != "" { 454 unlocks = append(unlocks, trimmed) 455 } 456 } 457 // Short circuit if there is no account to unlock. 458 if len(unlocks) == 0 { 459 return 460 } 461 // If insecure account unlocking is not allowed if node's APIs are exposed to external. 462 // Print warning log to user and skip unlocking. 463 if !stack.Config().InsecureUnlockAllowed && stack.Config().ExtRPCEnabled() { 464 utils.Fatalf("Account unlock with HTTP access is forbidden!") 465 } 466 backends := stack.AccountManager().Backends(keystore.KeyStoreType) 467 if len(backends) == 0 { 468 log.Warn("Failed to unlock accounts, keystore is not available") 469 return 470 } 471 ks := backends[0].(*keystore.KeyStore) 472 passwords := utils.MakePasswordList(ctx) 473 for i, account := range unlocks { 474 unlockAccount(ks, account, i, passwords) 475 } 476 }