main.go 11 KB

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