main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. "fmt"
  20. "io/ioutil"
  21. "os"
  22. "path/filepath"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/codegangsta/cli"
  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/core"
  32. "github.com/ethereum/go-ethereum/eth"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/internal/debug"
  35. "github.com/ethereum/go-ethereum/logger"
  36. "github.com/ethereum/go-ethereum/logger/glog"
  37. "github.com/ethereum/go-ethereum/metrics"
  38. "github.com/ethereum/go-ethereum/node"
  39. "github.com/ethereum/go-ethereum/params"
  40. "github.com/ethereum/go-ethereum/rlp"
  41. )
  42. const (
  43. ClientIdentifier = "Geth"
  44. Version = "1.5.0-unstable"
  45. VersionMajor = 1
  46. VersionMinor = 5
  47. VersionPatch = 0
  48. )
  49. var (
  50. gitCommit string // set via linker flagg
  51. nodeNameVersion string
  52. app *cli.App
  53. )
  54. func init() {
  55. if gitCommit == "" {
  56. nodeNameVersion = Version
  57. } else {
  58. nodeNameVersion = Version + "-" + gitCommit[:8]
  59. }
  60. app = utils.NewApp(Version, "the go-ethereum command line interface")
  61. app.Action = geth
  62. app.HideVersion = true // we have a command to print the version
  63. app.Commands = []cli.Command{
  64. importCommand,
  65. exportCommand,
  66. upgradedbCommand,
  67. removedbCommand,
  68. dumpCommand,
  69. monitorCommand,
  70. accountCommand,
  71. walletCommand,
  72. {
  73. Action: makedag,
  74. Name: "makedag",
  75. Usage: "generate ethash dag (for testing)",
  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: gpuinfo,
  84. Name: "gpuinfo",
  85. Usage: "gpuinfo",
  86. Description: `
  87. Prints OpenCL device info for all found GPUs.
  88. `,
  89. },
  90. {
  91. Action: gpubench,
  92. Name: "gpubench",
  93. Usage: "benchmark GPU",
  94. Description: `
  95. Runs quick benchmark on first GPU found.
  96. `,
  97. },
  98. {
  99. Action: version,
  100. Name: "version",
  101. Usage: "print ethereum version numbers",
  102. Description: `
  103. The output of this command is supposed to be machine-readable.
  104. `,
  105. },
  106. {
  107. Action: initGenesis,
  108. Name: "init",
  109. Usage: "bootstraps and initialises a new genesis block (JSON)",
  110. Description: `
  111. The init command initialises a new genesis block and definition for the network.
  112. This is a destructive action and changes the network in which you will be
  113. participating.
  114. `,
  115. },
  116. {
  117. Action: console,
  118. Name: "console",
  119. Usage: `Geth Console: interactive JavaScript environment`,
  120. Description: `
  121. The Geth console is an interactive shell for the JavaScript runtime environment
  122. which exposes a node admin interface as well as the Ðapp JavaScript API.
  123. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
  124. `,
  125. },
  126. {
  127. Action: attach,
  128. Name: "attach",
  129. Usage: `Geth Console: interactive JavaScript environment (connect to node)`,
  130. Description: `
  131. The Geth console is an interactive shell for the JavaScript runtime environment
  132. which exposes a node admin interface as well as the Ðapp JavaScript API.
  133. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console.
  134. This command allows to open a console on a running geth node.
  135. `,
  136. },
  137. {
  138. Action: execScripts,
  139. Name: "js",
  140. Usage: `executes the given JavaScript files in the Geth JavaScript VM`,
  141. Description: `
  142. The JavaScript VM exposes a node admin interface as well as the Ðapp
  143. JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
  144. `,
  145. },
  146. }
  147. app.Flags = []cli.Flag{
  148. utils.IdentityFlag,
  149. utils.UnlockedAccountFlag,
  150. utils.PasswordFileFlag,
  151. utils.GenesisFileFlag,
  152. utils.BootnodesFlag,
  153. utils.DataDirFlag,
  154. utils.KeyStoreDirFlag,
  155. utils.BlockchainVersionFlag,
  156. utils.OlympicFlag,
  157. utils.FastSyncFlag,
  158. utils.CacheFlag,
  159. utils.LightKDFFlag,
  160. utils.JSpathFlag,
  161. utils.ListenPortFlag,
  162. utils.MaxPeersFlag,
  163. utils.MaxPendingPeersFlag,
  164. utils.EtherbaseFlag,
  165. utils.GasPriceFlag,
  166. utils.MinerThreadsFlag,
  167. utils.MiningEnabledFlag,
  168. utils.MiningGPUFlag,
  169. utils.AutoDAGFlag,
  170. utils.TargetGasLimitFlag,
  171. utils.NATFlag,
  172. utils.NatspecEnabledFlag,
  173. utils.NoDiscoverFlag,
  174. utils.NodeKeyFileFlag,
  175. utils.NodeKeyHexFlag,
  176. utils.RPCEnabledFlag,
  177. utils.RPCListenAddrFlag,
  178. utils.RPCPortFlag,
  179. utils.RPCApiFlag,
  180. utils.WSEnabledFlag,
  181. utils.WSListenAddrFlag,
  182. utils.WSPortFlag,
  183. utils.WSApiFlag,
  184. utils.WSAllowedOriginsFlag,
  185. utils.IPCDisabledFlag,
  186. utils.IPCApiFlag,
  187. utils.IPCPathFlag,
  188. utils.ExecFlag,
  189. utils.PreLoadJSFlag,
  190. utils.WhisperEnabledFlag,
  191. utils.DevModeFlag,
  192. utils.TestNetFlag,
  193. utils.VMForceJitFlag,
  194. utils.VMJitCacheFlag,
  195. utils.VMEnableJitFlag,
  196. utils.NetworkIdFlag,
  197. utils.RPCCORSDomainFlag,
  198. utils.MetricsEnabledFlag,
  199. utils.SolcPathFlag,
  200. utils.GpoMinGasPriceFlag,
  201. utils.GpoMaxGasPriceFlag,
  202. utils.GpoFullBlockRatioFlag,
  203. utils.GpobaseStepDownFlag,
  204. utils.GpobaseStepUpFlag,
  205. utils.GpobaseCorrectionFactorFlag,
  206. utils.ExtraDataFlag,
  207. }
  208. app.Flags = append(app.Flags, debug.Flags...)
  209. app.Before = func(ctx *cli.Context) error {
  210. runtime.GOMAXPROCS(runtime.NumCPU())
  211. if err := debug.Setup(ctx); err != nil {
  212. return err
  213. }
  214. // Start system runtime metrics collection
  215. go metrics.CollectProcessMetrics(3 * time.Second)
  216. utils.SetupNetwork(ctx)
  217. // Deprecation warning.
  218. if ctx.GlobalIsSet(utils.GenesisFileFlag.Name) {
  219. common.PrintDepricationWarning("--genesis is deprecated. Switch to use 'geth init /path/to/file'")
  220. }
  221. return nil
  222. }
  223. app.After = func(ctx *cli.Context) error {
  224. logger.Flush()
  225. debug.Exit()
  226. utils.Stdin.Close() // Resets terminal mode.
  227. return nil
  228. }
  229. }
  230. func main() {
  231. if err := app.Run(os.Args); err != nil {
  232. fmt.Fprintln(os.Stderr, err)
  233. os.Exit(1)
  234. }
  235. }
  236. func makeDefaultExtra() []byte {
  237. var clientInfo = struct {
  238. Version uint
  239. Name string
  240. GoVersion string
  241. Os string
  242. }{uint(VersionMajor<<16 | VersionMinor<<8 | VersionPatch), ClientIdentifier, runtime.Version(), runtime.GOOS}
  243. extra, err := rlp.EncodeToBytes(clientInfo)
  244. if err != nil {
  245. glog.V(logger.Warn).Infoln("error setting canonical miner information:", err)
  246. }
  247. if uint64(len(extra)) > params.MaximumExtraDataSize.Uint64() {
  248. glog.V(logger.Warn).Infoln("error setting canonical miner information: extra exceeds", params.MaximumExtraDataSize)
  249. glog.V(logger.Debug).Infof("extra: %x\n", extra)
  250. return nil
  251. }
  252. return extra
  253. }
  254. // geth is the main entry point into the system if no special subcommand is ran.
  255. // It creates a default node based on the command line arguments and runs it in
  256. // blocking mode, waiting for it to be shut down.
  257. func geth(ctx *cli.Context) {
  258. node := utils.MakeSystemNode(ClientIdentifier, nodeNameVersion, makeDefaultExtra(), ctx)
  259. startNode(ctx, node)
  260. node.Wait()
  261. }
  262. // attach will connect to a running geth instance attaching a JavaScript console and to it.
  263. func attach(ctx *cli.Context) {
  264. // attach to a running geth instance
  265. client, err := utils.NewRemoteRPCClient(ctx)
  266. if err != nil {
  267. utils.Fatalf("Unable to attach to geth: %v", err)
  268. }
  269. repl := newLightweightJSRE(
  270. ctx.GlobalString(utils.JSpathFlag.Name),
  271. client,
  272. ctx.GlobalString(utils.DataDirFlag.Name),
  273. true,
  274. )
  275. // preload user defined JS files into the console
  276. err = repl.preloadJSFiles(ctx)
  277. if err != nil {
  278. utils.Fatalf("unable to preload JS file %v", err)
  279. }
  280. // in case the exec flag holds a JS statement execute it and return
  281. if ctx.GlobalString(utils.ExecFlag.Name) != "" {
  282. repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
  283. } else {
  284. repl.welcome()
  285. repl.interactive()
  286. }
  287. }
  288. // initGenesis will initialise the given JSON format genesis file and writes it as
  289. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  290. func initGenesis(ctx *cli.Context) {
  291. genesisPath := ctx.Args().First()
  292. if len(genesisPath) == 0 {
  293. utils.Fatalf("must supply path to genesis JSON file")
  294. }
  295. chainDb, err := ethdb.NewLDBDatabase(filepath.Join(utils.MustMakeDataDir(ctx), "chaindata"), 0, 0)
  296. if err != nil {
  297. utils.Fatalf("could not open database: %v", err)
  298. }
  299. genesisFile, err := os.Open(genesisPath)
  300. if err != nil {
  301. utils.Fatalf("failed to read genesis file: %v", err)
  302. }
  303. block, err := core.WriteGenesisBlock(chainDb, genesisFile)
  304. if err != nil {
  305. utils.Fatalf("failed to write genesis block: %v", err)
  306. }
  307. glog.V(logger.Info).Infof("successfully wrote genesis block and/or chain rule set: %x", block.Hash())
  308. }
  309. // console starts a new geth node, attaching a JavaScript console to it at the
  310. // same time.
  311. func console(ctx *cli.Context) {
  312. // Create and start the node based on the CLI flags
  313. node := utils.MakeSystemNode(ClientIdentifier, nodeNameVersion, makeDefaultExtra(), ctx)
  314. startNode(ctx, node)
  315. // Attach to the newly started node, and either execute script or become interactive
  316. client, err := node.Attach()
  317. if err != nil {
  318. utils.Fatalf("Failed to attach to the inproc geth: %v", err)
  319. }
  320. repl := newJSRE(node,
  321. ctx.GlobalString(utils.JSpathFlag.Name),
  322. ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
  323. client, true)
  324. // preload user defined JS files into the console
  325. err = repl.preloadJSFiles(ctx)
  326. if err != nil {
  327. utils.Fatalf("unable to preload JS file %v", err)
  328. }
  329. // in case the exec flag holds a JS statement execute it and return
  330. if script := ctx.GlobalString(utils.ExecFlag.Name); script != "" {
  331. repl.batch(script)
  332. } else {
  333. repl.welcome()
  334. repl.interactive()
  335. }
  336. node.Stop()
  337. }
  338. // execScripts starts a new geth node based on the CLI flags, and executes each
  339. // of the JavaScript files specified as command arguments.
  340. func execScripts(ctx *cli.Context) {
  341. // Create and start the node based on the CLI flags
  342. node := utils.MakeSystemNode(ClientIdentifier, nodeNameVersion, makeDefaultExtra(), ctx)
  343. startNode(ctx, node)
  344. // Attach to the newly started node and execute the given scripts
  345. client, err := node.Attach()
  346. if err != nil {
  347. utils.Fatalf("Failed to attach to the inproc geth: %v", err)
  348. }
  349. repl := newJSRE(node,
  350. ctx.GlobalString(utils.JSpathFlag.Name),
  351. ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
  352. client, false)
  353. for _, file := range ctx.Args() {
  354. repl.exec(file)
  355. }
  356. node.Stop()
  357. }
  358. // startNode boots up the system node and all registered protocols, after which
  359. // it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
  360. // miner.
  361. func startNode(ctx *cli.Context, stack *node.Node) {
  362. // Start up the node itself
  363. utils.StartNode(stack)
  364. // Unlock any account specifically requested
  365. var ethereum *eth.Ethereum
  366. if err := stack.Service(&ethereum); err != nil {
  367. utils.Fatalf("ethereum service not running: %v", err)
  368. }
  369. accman := ethereum.AccountManager()
  370. passwords := utils.MakePasswordList(ctx)
  371. accounts := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
  372. for i, account := range accounts {
  373. if trimmed := strings.TrimSpace(account); trimmed != "" {
  374. unlockAccount(ctx, accman, trimmed, i, passwords)
  375. }
  376. }
  377. // Start auxiliary services if enabled
  378. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
  379. if err := ethereum.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name), ctx.GlobalString(utils.MiningGPUFlag.Name)); err != nil {
  380. utils.Fatalf("Failed to start mining: %v", err)
  381. }
  382. }
  383. }
  384. func makedag(ctx *cli.Context) {
  385. args := ctx.Args()
  386. wrongArgs := func() {
  387. utils.Fatalf(`Usage: geth makedag <block number> <outputdir>`)
  388. }
  389. switch {
  390. case len(args) == 2:
  391. blockNum, err := strconv.ParseUint(args[0], 0, 64)
  392. dir := args[1]
  393. if err != nil {
  394. wrongArgs()
  395. } else {
  396. dir = filepath.Clean(dir)
  397. // seems to require a trailing slash
  398. if !strings.HasSuffix(dir, "/") {
  399. dir = dir + "/"
  400. }
  401. _, err = ioutil.ReadDir(dir)
  402. if err != nil {
  403. utils.Fatalf("Can't find dir")
  404. }
  405. fmt.Println("making DAG, this could take awhile...")
  406. ethash.MakeDAG(blockNum, dir)
  407. }
  408. default:
  409. wrongArgs()
  410. }
  411. }
  412. func gpuinfo(ctx *cli.Context) {
  413. eth.PrintOpenCLDevices()
  414. }
  415. func gpubench(ctx *cli.Context) {
  416. args := ctx.Args()
  417. wrongArgs := func() {
  418. utils.Fatalf(`Usage: geth gpubench <gpu number>`)
  419. }
  420. switch {
  421. case len(args) == 1:
  422. n, err := strconv.ParseUint(args[0], 0, 64)
  423. if err != nil {
  424. wrongArgs()
  425. }
  426. eth.GPUBench(n)
  427. case len(args) == 0:
  428. eth.GPUBench(0)
  429. default:
  430. wrongArgs()
  431. }
  432. }
  433. func version(c *cli.Context) {
  434. fmt.Println(ClientIdentifier)
  435. fmt.Println("Version:", Version)
  436. if gitCommit != "" {
  437. fmt.Println("Git Commit:", gitCommit)
  438. }
  439. fmt.Println("Protocol Versions:", eth.ProtocolVersions)
  440. fmt.Println("Network Id:", c.GlobalInt(utils.NetworkIdFlag.Name))
  441. fmt.Println("Go Version:", runtime.Version())
  442. fmt.Println("OS:", runtime.GOOS)
  443. fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
  444. fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
  445. }