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