main.go 11 KB

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