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