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