main.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. // geth is the official command-line client for Ethereum.
  17. package main
  18. import (
  19. "encoding/hex"
  20. "fmt"
  21. "io/ioutil"
  22. "os"
  23. "path/filepath"
  24. "runtime"
  25. "strconv"
  26. "strings"
  27. "time"
  28. "github.com/ethereum/ethash"
  29. "github.com/ethereum/go-ethereum/cmd/utils"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/console"
  32. "github.com/ethereum/go-ethereum/contracts/release"
  33. "github.com/ethereum/go-ethereum/core"
  34. "github.com/ethereum/go-ethereum/core/state"
  35. "github.com/ethereum/go-ethereum/eth"
  36. "github.com/ethereum/go-ethereum/internal/debug"
  37. "github.com/ethereum/go-ethereum/logger"
  38. "github.com/ethereum/go-ethereum/logger/glog"
  39. "github.com/ethereum/go-ethereum/metrics"
  40. "github.com/ethereum/go-ethereum/node"
  41. "gopkg.in/urfave/cli.v1"
  42. )
  43. const (
  44. clientIdentifier = "geth" // Client identifier to advertise over the network
  45. )
  46. var (
  47. // Git SHA1 commit hash of the release (set via linker flags)
  48. gitCommit = ""
  49. // Ethereum address of the Geth release oracle.
  50. relOracle = common.HexToAddress("0xfa7b9770ca4cb04296cac84f37736d4041251cdf")
  51. // The app that holds all commands and flags.
  52. app = utils.NewApp(gitCommit, "the go-ethereum command line interface")
  53. )
  54. func init() {
  55. // Initialize the CLI app and start Geth
  56. app.Action = geth
  57. app.HideVersion = true // we have a command to print the version
  58. app.Commands = []cli.Command{
  59. importCommand,
  60. exportCommand,
  61. upgradedbCommand,
  62. removedbCommand,
  63. dumpCommand,
  64. monitorCommand,
  65. accountCommand,
  66. walletCommand,
  67. consoleCommand,
  68. attachCommand,
  69. javascriptCommand,
  70. {
  71. Action: makedag,
  72. Name: "makedag",
  73. Usage: "generate ethash dag (for testing)",
  74. Description: `
  75. The makedag command generates an ethash DAG in /tmp/dag.
  76. This command exists to support the system testing project.
  77. Regular users do not need to execute it.
  78. `,
  79. },
  80. {
  81. Action: version,
  82. Name: "version",
  83. Usage: "print ethereum version numbers",
  84. Description: `
  85. The output of this command is supposed to be machine-readable.
  86. `,
  87. },
  88. {
  89. Action: initGenesis,
  90. Name: "init",
  91. Usage: "bootstraps and initialises a new genesis block (JSON)",
  92. Description: `
  93. The init command initialises a new genesis block and definition for the network.
  94. This is a destructive action and changes the network in which you will be
  95. participating.
  96. `,
  97. },
  98. {
  99. Action: license,
  100. Name: "license",
  101. Usage: "displays geth's license information",
  102. },
  103. }
  104. app.Flags = []cli.Flag{
  105. utils.IdentityFlag,
  106. utils.UnlockedAccountFlag,
  107. utils.PasswordFileFlag,
  108. utils.BootnodesFlag,
  109. utils.DataDirFlag,
  110. utils.KeyStoreDirFlag,
  111. utils.OlympicFlag,
  112. utils.FastSyncFlag,
  113. utils.LightKDFFlag,
  114. utils.CacheFlag,
  115. utils.TrieCacheGenFlag,
  116. utils.JSpathFlag,
  117. utils.ListenPortFlag,
  118. utils.MaxPeersFlag,
  119. utils.MaxPendingPeersFlag,
  120. utils.EtherbaseFlag,
  121. utils.GasPriceFlag,
  122. utils.SupportDAOFork,
  123. utils.OpposeDAOFork,
  124. utils.MinerThreadsFlag,
  125. utils.MiningEnabledFlag,
  126. utils.AutoDAGFlag,
  127. utils.TargetGasLimitFlag,
  128. utils.NATFlag,
  129. utils.NatspecEnabledFlag,
  130. utils.NoDiscoverFlag,
  131. utils.NodeKeyFileFlag,
  132. utils.NodeKeyHexFlag,
  133. utils.RPCEnabledFlag,
  134. utils.RPCListenAddrFlag,
  135. utils.RPCPortFlag,
  136. utils.RPCApiFlag,
  137. utils.WSEnabledFlag,
  138. utils.WSListenAddrFlag,
  139. utils.WSPortFlag,
  140. utils.WSApiFlag,
  141. utils.WSAllowedOriginsFlag,
  142. utils.IPCDisabledFlag,
  143. utils.IPCApiFlag,
  144. utils.IPCPathFlag,
  145. utils.ExecFlag,
  146. utils.PreloadJSFlag,
  147. utils.WhisperEnabledFlag,
  148. utils.DevModeFlag,
  149. utils.TestNetFlag,
  150. utils.VMForceJitFlag,
  151. utils.VMJitCacheFlag,
  152. utils.VMEnableJitFlag,
  153. utils.NetworkIdFlag,
  154. utils.RPCCORSDomainFlag,
  155. utils.MetricsEnabledFlag,
  156. utils.FakePoWFlag,
  157. utils.SolcPathFlag,
  158. utils.GpoMinGasPriceFlag,
  159. utils.GpoMaxGasPriceFlag,
  160. utils.GpoFullBlockRatioFlag,
  161. utils.GpobaseStepDownFlag,
  162. utils.GpobaseStepUpFlag,
  163. utils.GpobaseCorrectionFactorFlag,
  164. utils.ExtraDataFlag,
  165. }
  166. app.Flags = append(app.Flags, debug.Flags...)
  167. app.Before = func(ctx *cli.Context) error {
  168. runtime.GOMAXPROCS(runtime.NumCPU())
  169. if err := debug.Setup(ctx); err != nil {
  170. return err
  171. }
  172. // Start system runtime metrics collection
  173. go metrics.CollectProcessMetrics(3 * time.Second)
  174. // This should be the only place where reporting is enabled
  175. // because it is not intended to run while testing.
  176. // In addition to this check, bad block reports are sent only
  177. // for chains with the main network genesis block and network id 1.
  178. eth.EnableBadBlockReporting = true
  179. utils.SetupNetwork(ctx)
  180. return nil
  181. }
  182. app.After = func(ctx *cli.Context) error {
  183. logger.Flush()
  184. debug.Exit()
  185. console.Stdin.Close() // Resets terminal mode.
  186. return nil
  187. }
  188. }
  189. func main() {
  190. if err := app.Run(os.Args); err != nil {
  191. fmt.Fprintln(os.Stderr, err)
  192. os.Exit(1)
  193. }
  194. }
  195. // geth is the main entry point into the system if no special subcommand is ran.
  196. // It creates a default node based on the command line arguments and runs it in
  197. // blocking mode, waiting for it to be shut down.
  198. func geth(ctx *cli.Context) error {
  199. node := makeFullNode(ctx)
  200. startNode(ctx, node)
  201. node.Wait()
  202. return nil
  203. }
  204. // initGenesis will initialise the given JSON format genesis file and writes it as
  205. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  206. func initGenesis(ctx *cli.Context) error {
  207. genesisPath := ctx.Args().First()
  208. if len(genesisPath) == 0 {
  209. utils.Fatalf("must supply path to genesis JSON file")
  210. }
  211. if ctx.GlobalBool(utils.TestNetFlag.Name) {
  212. state.StartingNonce = 1048576 // (2**20)
  213. }
  214. stack := makeFullNode(ctx)
  215. chaindb := utils.MakeChainDatabase(ctx, stack)
  216. genesisFile, err := os.Open(genesisPath)
  217. if err != nil {
  218. utils.Fatalf("failed to read genesis file: %v", err)
  219. }
  220. block, err := core.WriteGenesisBlock(chaindb, genesisFile)
  221. if err != nil {
  222. utils.Fatalf("failed to write genesis block: %v", err)
  223. }
  224. glog.V(logger.Info).Infof("successfully wrote genesis block and/or chain rule set: %x", block.Hash())
  225. return nil
  226. }
  227. func makeFullNode(ctx *cli.Context) *node.Node {
  228. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  229. utils.RegisterEthService(ctx, stack, utils.MakeDefaultExtraData(clientIdentifier))
  230. // Whisper must be explicitly enabled, but is auto-enabled in --dev mode.
  231. shhEnabled := ctx.GlobalBool(utils.WhisperEnabledFlag.Name)
  232. shhAutoEnabled := !ctx.GlobalIsSet(utils.WhisperEnabledFlag.Name) && ctx.GlobalIsSet(utils.DevModeFlag.Name)
  233. if shhEnabled || shhAutoEnabled {
  234. utils.RegisterShhService(stack)
  235. }
  236. // Add the release oracle service so it boots along with node.
  237. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  238. config := release.Config{
  239. Oracle: relOracle,
  240. Major: uint32(utils.VersionMajor),
  241. Minor: uint32(utils.VersionMinor),
  242. Patch: uint32(utils.VersionPatch),
  243. }
  244. commit, _ := hex.DecodeString(gitCommit)
  245. copy(config.Commit[:], commit)
  246. return release.NewReleaseService(ctx, config)
  247. }); err != nil {
  248. utils.Fatalf("Failed to register the Geth release oracle service: %v", err)
  249. }
  250. return stack
  251. }
  252. // startNode boots up the system node and all registered protocols, after which
  253. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  254. // miner.
  255. func startNode(ctx *cli.Context, stack *node.Node) {
  256. // Start up the node itself
  257. utils.StartNode(stack)
  258. // Unlock any account specifically requested
  259. accman := stack.AccountManager()
  260. passwords := utils.MakePasswordList(ctx)
  261. accounts := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  262. for i, account := range accounts {
  263. if trimmed := strings.TrimSpace(account); trimmed != "" {
  264. unlockAccount(ctx, accman, trimmed, i, passwords)
  265. }
  266. }
  267. // Start auxiliary services if enabled
  268. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
  269. var ethereum *eth.Ethereum
  270. if err := stack.Service(&ethereum); err != nil {
  271. utils.Fatalf("ethereum service not running: %v", err)
  272. }
  273. if err := ethereum.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name)); err != nil {
  274. utils.Fatalf("Failed to start mining: %v", err)
  275. }
  276. }
  277. }
  278. func makedag(ctx *cli.Context) error {
  279. args := ctx.Args()
  280. wrongArgs := func() {
  281. utils.Fatalf(`Usage: geth makedag <block number> <outputdir>`)
  282. }
  283. switch {
  284. case len(args) == 2:
  285. blockNum, err := strconv.ParseUint(args[0], 0, 64)
  286. dir := args[1]
  287. if err != nil {
  288. wrongArgs()
  289. } else {
  290. dir = filepath.Clean(dir)
  291. // seems to require a trailing slash
  292. if !strings.HasSuffix(dir, "/") {
  293. dir = dir + "/"
  294. }
  295. _, err = ioutil.ReadDir(dir)
  296. if err != nil {
  297. utils.Fatalf("Can't find dir")
  298. }
  299. fmt.Println("making DAG, this could take awhile...")
  300. ethash.MakeDAG(blockNum, dir)
  301. }
  302. default:
  303. wrongArgs()
  304. }
  305. return nil
  306. }
  307. func version(c *cli.Context) error {
  308. fmt.Println(strings.Title(clientIdentifier))
  309. fmt.Println("Version:", utils.Version)
  310. if gitCommit != "" {
  311. fmt.Println("Git Commit:", gitCommit)
  312. }
  313. fmt.Println("Protocol Versions:", eth.ProtocolVersions)
  314. fmt.Println("Network Id:", c.GlobalInt(utils.NetworkIdFlag.Name))
  315. fmt.Println("Go Version:", runtime.Version())
  316. fmt.Println("OS:", runtime.GOOS)
  317. fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
  318. fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
  319. return nil
  320. }
  321. func license(c *cli.Context) error {
  322. fmt.Println(`Geth is free software: you can redistribute it and/or modify
  323. it under the terms of the GNU General Public License as published by
  324. the Free Software Foundation, either version 3 of the License, or
  325. (at your option) any later version.
  326. Geth is distributed in the hope that it will be useful,
  327. but WITHOUT ANY WARRANTY; without even the implied warranty of
  328. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  329. GNU General Public License for more details.
  330. You should have received a copy of the GNU General Public License
  331. along with geth. If not, see <http://www.gnu.org/licenses/>.
  332. `)
  333. return nil
  334. }