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