main.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /*
  2. This file is part of go-ethereum
  3. go-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. go-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /**
  15. * @authors
  16. * Jeffrey Wilcke <i@jev.io>
  17. */
  18. package main
  19. import (
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. _ "net/http/pprof"
  24. "os"
  25. "path/filepath"
  26. "runtime"
  27. "strconv"
  28. "strings"
  29. "time"
  30. "github.com/codegangsta/cli"
  31. "github.com/ethereum/ethash"
  32. "github.com/ethereum/go-ethereum/accounts"
  33. "github.com/ethereum/go-ethereum/cmd/utils"
  34. "github.com/ethereum/go-ethereum/common"
  35. "github.com/ethereum/go-ethereum/eth"
  36. "github.com/ethereum/go-ethereum/logger"
  37. "github.com/ethereum/go-ethereum/metrics"
  38. "github.com/ethereum/go-ethereum/rpc/codec"
  39. "github.com/ethereum/go-ethereum/rpc/comms"
  40. "github.com/mattn/go-colorable"
  41. "github.com/mattn/go-isatty"
  42. )
  43. const (
  44. ClientIdentifier = "Geth"
  45. Version = "0.9.34"
  46. )
  47. var (
  48. gitCommit string // set via linker flag
  49. nodeNameVersion string
  50. app *cli.App
  51. )
  52. func init() {
  53. if gitCommit == "" {
  54. nodeNameVersion = Version
  55. } else {
  56. nodeNameVersion = Version + "-" + gitCommit[:8]
  57. }
  58. app = utils.NewApp(Version, "the go-ethereum command line interface")
  59. app.Action = run
  60. app.HideVersion = true // we have a command to print the version
  61. app.Commands = []cli.Command{
  62. blocktestCommand,
  63. importCommand,
  64. exportCommand,
  65. upgradedbCommand,
  66. removedbCommand,
  67. dumpCommand,
  68. monitorCommand,
  69. {
  70. Action: makedag,
  71. Name: "makedag",
  72. Usage: "generate ethash dag (for testing)",
  73. Description: `
  74. The makedag command generates an ethash DAG in /tmp/dag.
  75. This command exists to support the system testing project.
  76. Regular users do not need to execute it.
  77. `,
  78. },
  79. {
  80. Action: version,
  81. Name: "version",
  82. Usage: "print ethereum version numbers",
  83. Description: `
  84. The output of this command is supposed to be machine-readable.
  85. `,
  86. },
  87. {
  88. Name: "wallet",
  89. Usage: "ethereum presale wallet",
  90. Subcommands: []cli.Command{
  91. {
  92. Action: importWallet,
  93. Name: "import",
  94. Usage: "import ethereum presale wallet",
  95. },
  96. },
  97. Description: `
  98. get wallet import /path/to/my/presale.wallet
  99. will prompt for your password and imports your ether presale account.
  100. It can be used non-interactively with the --password option taking a
  101. passwordfile as argument containing the wallet password in plaintext.
  102. `},
  103. {
  104. Action: accountList,
  105. Name: "account",
  106. Usage: "manage accounts",
  107. Description: `
  108. Manage accounts lets you create new accounts, list all existing accounts,
  109. import a private key into a new account.
  110. ' help' shows a list of subcommands or help for one subcommand.
  111. It supports interactive mode, when you are prompted for password as well as
  112. non-interactive mode where passwords are supplied via a given password file.
  113. Non-interactive mode is only meant for scripted use on test networks or known
  114. safe environments.
  115. Make sure you remember the password you gave when creating a new account (with
  116. either new or import). Without it you are not able to unlock your account.
  117. Note that exporting your key in unencrypted format is NOT supported.
  118. Keys are stored under <DATADIR>/keys.
  119. It is safe to transfer the entire directory or the individual keys therein
  120. between ethereum nodes.
  121. Make sure you backup your keys regularly.
  122. And finally. DO NOT FORGET YOUR PASSWORD.
  123. `,
  124. Subcommands: []cli.Command{
  125. {
  126. Action: accountList,
  127. Name: "list",
  128. Usage: "print account addresses",
  129. },
  130. {
  131. Action: accountCreate,
  132. Name: "new",
  133. Usage: "create a new account",
  134. Description: `
  135. ethereum account new
  136. Creates a new account. Prints the address.
  137. The account is saved in encrypted format, you are prompted for a passphrase.
  138. You must remember this passphrase to unlock your account in the future.
  139. For non-interactive use the passphrase can be specified with the --password flag:
  140. ethereum --password <passwordfile> account new
  141. Note, this is meant to be used for testing only, it is a bad idea to save your
  142. password to file or expose in any other way.
  143. `,
  144. },
  145. {
  146. Action: accountImport,
  147. Name: "import",
  148. Usage: "import a private key into a new account",
  149. Description: `
  150. ethereum account import <keyfile>
  151. Imports an unencrypted private key from <keyfile> and creates a new account.
  152. Prints the address.
  153. The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
  154. The account is saved in encrypted format, you are prompted for a passphrase.
  155. You must remember this passphrase to unlock your account in the future.
  156. For non-interactive use the passphrase can be specified with the -password flag:
  157. ethereum --password <passwordfile> account import <keyfile>
  158. Note:
  159. As you can directly copy your encrypted accounts to another ethereum instance,
  160. this import mechanism is not needed when you transfer an account between
  161. nodes.
  162. `,
  163. },
  164. },
  165. },
  166. {
  167. Action: console,
  168. Name: "console",
  169. Usage: `Geth Console: interactive JavaScript environment`,
  170. Description: `
  171. The Geth console is an interactive shell for the JavaScript runtime environment
  172. which exposes a node admin interface as well as the Ðapp JavaScript API.
  173. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
  174. `},
  175. {
  176. Action: attach,
  177. Name: "attach",
  178. Usage: `Geth Console: interactive JavaScript environment (connect to node)`,
  179. Description: `
  180. The Geth console is an interactive shell for the JavaScript runtime environment
  181. which exposes a node admin interface as well as the Ðapp JavaScript API.
  182. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console.
  183. This command allows to open a console on a running geth node.
  184. `,
  185. },
  186. {
  187. Action: execJSFiles,
  188. Name: "js",
  189. Usage: `executes the given JavaScript files in the Geth JavaScript VM`,
  190. Description: `
  191. The JavaScript VM exposes a node admin interface as well as the Ðapp
  192. JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
  193. `,
  194. },
  195. }
  196. app.Flags = []cli.Flag{
  197. utils.IdentityFlag,
  198. utils.UnlockedAccountFlag,
  199. utils.PasswordFileFlag,
  200. utils.GenesisNonceFlag,
  201. utils.BootnodesFlag,
  202. utils.DataDirFlag,
  203. utils.BlockchainVersionFlag,
  204. utils.JSpathFlag,
  205. utils.ListenPortFlag,
  206. utils.MaxPeersFlag,
  207. utils.MaxPendingPeersFlag,
  208. utils.EtherbaseFlag,
  209. utils.GasPriceFlag,
  210. utils.MinerThreadsFlag,
  211. utils.MiningEnabledFlag,
  212. utils.AutoDAGFlag,
  213. utils.NATFlag,
  214. utils.NatspecEnabledFlag,
  215. utils.NoDiscoverFlag,
  216. utils.NodeKeyFileFlag,
  217. utils.NodeKeyHexFlag,
  218. utils.RPCEnabledFlag,
  219. utils.RPCListenAddrFlag,
  220. utils.RPCPortFlag,
  221. utils.RpcApiFlag,
  222. utils.IPCDisabledFlag,
  223. utils.IPCApiFlag,
  224. utils.IPCPathFlag,
  225. utils.ExecFlag,
  226. utils.WhisperEnabledFlag,
  227. utils.VMDebugFlag,
  228. utils.ProtocolVersionFlag,
  229. utils.NetworkIdFlag,
  230. utils.RPCCORSDomainFlag,
  231. utils.VerbosityFlag,
  232. utils.BacktraceAtFlag,
  233. utils.LogToStdErrFlag,
  234. utils.LogVModuleFlag,
  235. utils.LogFileFlag,
  236. utils.LogJSONFlag,
  237. utils.PProfEanbledFlag,
  238. utils.PProfPortFlag,
  239. utils.MetricsEnabledFlag,
  240. utils.SolcPathFlag,
  241. utils.GpoMinGasPriceFlag,
  242. utils.GpoMaxGasPriceFlag,
  243. utils.GpoFullBlockRatioFlag,
  244. utils.GpobaseStepDownFlag,
  245. utils.GpobaseStepUpFlag,
  246. utils.GpobaseCorrectionFactorFlag,
  247. }
  248. app.Before = func(ctx *cli.Context) error {
  249. utils.SetupLogger(ctx)
  250. if ctx.GlobalBool(utils.PProfEanbledFlag.Name) {
  251. utils.StartPProf(ctx)
  252. }
  253. return nil
  254. }
  255. // Start system runtime metrics collection
  256. go metrics.CollectProcessMetrics(3 * time.Second)
  257. }
  258. func main() {
  259. runtime.GOMAXPROCS(runtime.NumCPU())
  260. defer logger.Flush()
  261. if err := app.Run(os.Args); err != nil {
  262. fmt.Fprintln(os.Stderr, err)
  263. os.Exit(1)
  264. }
  265. }
  266. func run(ctx *cli.Context) {
  267. utils.HandleInterrupt()
  268. cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
  269. ethereum, err := eth.New(cfg)
  270. if err != nil {
  271. utils.Fatalf("%v", err)
  272. }
  273. startEth(ctx, ethereum)
  274. // this blocks the thread
  275. ethereum.WaitForShutdown()
  276. }
  277. func attach(ctx *cli.Context) {
  278. // Wrap the standard output with a colorified stream (windows)
  279. if isatty.IsTerminal(os.Stdout.Fd()) {
  280. if pr, pw, err := os.Pipe(); err == nil {
  281. go io.Copy(colorable.NewColorableStdout(), pr)
  282. os.Stdout = pw
  283. }
  284. }
  285. var client comms.EthereumClient
  286. var err error
  287. if ctx.Args().Present() {
  288. client, err = comms.ClientFromEndpoint(ctx.Args().First(), codec.JSON)
  289. } else {
  290. cfg := comms.IpcConfig{
  291. Endpoint: ctx.GlobalString(utils.IPCPathFlag.Name),
  292. }
  293. client, err = comms.NewIpcClient(cfg, codec.JSON)
  294. }
  295. if err != nil {
  296. utils.Fatalf("Unable to attach to geth node - %v", err)
  297. }
  298. repl := newLightweightJSRE(
  299. ctx.GlobalString(utils.JSpathFlag.Name),
  300. client,
  301. true,
  302. nil)
  303. if ctx.GlobalString(utils.ExecFlag.Name) != "" {
  304. repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
  305. } else {
  306. repl.welcome()
  307. repl.interactive()
  308. }
  309. }
  310. func console(ctx *cli.Context) {
  311. // Wrap the standard output with a colorified stream (windows)
  312. if isatty.IsTerminal(os.Stdout.Fd()) {
  313. if pr, pw, err := os.Pipe(); err == nil {
  314. go io.Copy(colorable.NewColorableStdout(), pr)
  315. os.Stdout = pw
  316. }
  317. }
  318. cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
  319. ethereum, err := eth.New(cfg)
  320. if err != nil {
  321. utils.Fatalf("%v", err)
  322. }
  323. client := comms.NewInProcClient(codec.JSON)
  324. startEth(ctx, ethereum)
  325. repl := newJSRE(
  326. ethereum,
  327. ctx.GlobalString(utils.JSpathFlag.Name),
  328. ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
  329. client,
  330. true,
  331. nil,
  332. )
  333. if ctx.GlobalString(utils.ExecFlag.Name) != "" {
  334. repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
  335. } else {
  336. repl.welcome()
  337. repl.interactive()
  338. }
  339. ethereum.Stop()
  340. ethereum.WaitForShutdown()
  341. }
  342. func execJSFiles(ctx *cli.Context) {
  343. cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
  344. ethereum, err := eth.New(cfg)
  345. if err != nil {
  346. utils.Fatalf("%v", err)
  347. }
  348. client := comms.NewInProcClient(codec.JSON)
  349. startEth(ctx, ethereum)
  350. repl := newJSRE(
  351. ethereum,
  352. ctx.GlobalString(utils.JSpathFlag.Name),
  353. ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
  354. client,
  355. false,
  356. nil,
  357. )
  358. for _, file := range ctx.Args() {
  359. repl.exec(file)
  360. }
  361. ethereum.Stop()
  362. ethereum.WaitForShutdown()
  363. }
  364. func unlockAccount(ctx *cli.Context, am *accounts.Manager, account string) (passphrase string) {
  365. var err error
  366. // Load startup keys. XXX we are going to need a different format
  367. if !((len(account) == 40) || (len(account) == 42)) { // with or without 0x
  368. utils.Fatalf("Invalid account address '%s'", account)
  369. }
  370. // Attempt to unlock the account 3 times
  371. attempts := 3
  372. for tries := 0; tries < attempts; tries++ {
  373. msg := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", account, tries+1, attempts)
  374. passphrase = getPassPhrase(ctx, msg, false)
  375. err = am.Unlock(common.HexToAddress(account), passphrase)
  376. if err == nil {
  377. break
  378. }
  379. }
  380. if err != nil {
  381. utils.Fatalf("Unlock account failed '%v'", err)
  382. }
  383. fmt.Printf("Account '%s' unlocked.\n", account)
  384. return
  385. }
  386. func startEth(ctx *cli.Context, eth *eth.Ethereum) {
  387. // Start Ethereum itself
  388. utils.StartEthereum(eth)
  389. am := eth.AccountManager()
  390. account := ctx.GlobalString(utils.UnlockedAccountFlag.Name)
  391. accounts := strings.Split(account, " ")
  392. for _, account := range accounts {
  393. if len(account) > 0 {
  394. if account == "primary" {
  395. primaryAcc, err := am.Primary()
  396. if err != nil {
  397. utils.Fatalf("no primary account: %v", err)
  398. }
  399. account = primaryAcc.Hex()
  400. }
  401. unlockAccount(ctx, am, account)
  402. }
  403. }
  404. // Start auxiliary services if enabled.
  405. if !ctx.GlobalBool(utils.IPCDisabledFlag.Name) {
  406. if err := utils.StartIPC(eth, ctx); err != nil {
  407. utils.Fatalf("Error string IPC: %v", err)
  408. }
  409. }
  410. if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
  411. if err := utils.StartRPC(eth, ctx); err != nil {
  412. utils.Fatalf("Error starting RPC: %v", err)
  413. }
  414. }
  415. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
  416. if err := eth.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name)); err != nil {
  417. utils.Fatalf("%v", err)
  418. }
  419. }
  420. }
  421. func accountList(ctx *cli.Context) {
  422. am := utils.MakeAccountManager(ctx)
  423. accts, err := am.Accounts()
  424. if err != nil {
  425. utils.Fatalf("Could not list accounts: %v", err)
  426. }
  427. name := "Primary"
  428. for i, acct := range accts {
  429. fmt.Printf("%s #%d: %x\n", name, i, acct)
  430. name = "Account"
  431. }
  432. }
  433. func getPassPhrase(ctx *cli.Context, desc string, confirmation bool) (passphrase string) {
  434. passfile := ctx.GlobalString(utils.PasswordFileFlag.Name)
  435. if len(passfile) == 0 {
  436. fmt.Println(desc)
  437. auth, err := utils.PromptPassword("Passphrase: ", true)
  438. if err != nil {
  439. utils.Fatalf("%v", err)
  440. }
  441. if confirmation {
  442. confirm, err := utils.PromptPassword("Repeat Passphrase: ", false)
  443. if err != nil {
  444. utils.Fatalf("%v", err)
  445. }
  446. if auth != confirm {
  447. utils.Fatalf("Passphrases did not match.")
  448. }
  449. }
  450. passphrase = auth
  451. } else {
  452. passbytes, err := ioutil.ReadFile(passfile)
  453. if err != nil {
  454. utils.Fatalf("Unable to read password file '%s': %v", passfile, err)
  455. }
  456. passphrase = string(passbytes)
  457. }
  458. return
  459. }
  460. func accountCreate(ctx *cli.Context) {
  461. am := utils.MakeAccountManager(ctx)
  462. passphrase := getPassPhrase(ctx, "Your new account is locked with a password. Please give a password. Do not forget this password.", true)
  463. acct, err := am.NewAccount(passphrase)
  464. if err != nil {
  465. utils.Fatalf("Could not create the account: %v", err)
  466. }
  467. fmt.Printf("Address: %x\n", acct)
  468. }
  469. func importWallet(ctx *cli.Context) {
  470. keyfile := ctx.Args().First()
  471. if len(keyfile) == 0 {
  472. utils.Fatalf("keyfile must be given as argument")
  473. }
  474. keyJson, err := ioutil.ReadFile(keyfile)
  475. if err != nil {
  476. utils.Fatalf("Could not read wallet file: %v", err)
  477. }
  478. am := utils.MakeAccountManager(ctx)
  479. passphrase := getPassPhrase(ctx, "", false)
  480. acct, err := am.ImportPreSaleKey(keyJson, passphrase)
  481. if err != nil {
  482. utils.Fatalf("Could not create the account: %v", err)
  483. }
  484. fmt.Printf("Address: %x\n", acct)
  485. }
  486. func accountImport(ctx *cli.Context) {
  487. keyfile := ctx.Args().First()
  488. if len(keyfile) == 0 {
  489. utils.Fatalf("keyfile must be given as argument")
  490. }
  491. am := utils.MakeAccountManager(ctx)
  492. passphrase := getPassPhrase(ctx, "Your new account is locked with a password. Please give a password. Do not forget this password.", true)
  493. acct, err := am.Import(keyfile, passphrase)
  494. if err != nil {
  495. utils.Fatalf("Could not create the account: %v", err)
  496. }
  497. fmt.Printf("Address: %x\n", acct)
  498. }
  499. func makedag(ctx *cli.Context) {
  500. args := ctx.Args()
  501. wrongArgs := func() {
  502. utils.Fatalf(`Usage: geth makedag <block number> <outputdir>`)
  503. }
  504. switch {
  505. case len(args) == 2:
  506. blockNum, err := strconv.ParseUint(args[0], 0, 64)
  507. dir := args[1]
  508. if err != nil {
  509. wrongArgs()
  510. } else {
  511. dir = filepath.Clean(dir)
  512. // seems to require a trailing slash
  513. if !strings.HasSuffix(dir, "/") {
  514. dir = dir + "/"
  515. }
  516. _, err = ioutil.ReadDir(dir)
  517. if err != nil {
  518. utils.Fatalf("Can't find dir")
  519. }
  520. fmt.Println("making DAG, this could take awhile...")
  521. ethash.MakeDAG(blockNum, dir)
  522. }
  523. default:
  524. wrongArgs()
  525. }
  526. }
  527. func version(c *cli.Context) {
  528. fmt.Println(ClientIdentifier)
  529. fmt.Println("Version:", Version)
  530. if gitCommit != "" {
  531. fmt.Println("Git Commit:", gitCommit)
  532. }
  533. fmt.Println("Protocol Version:", c.GlobalInt(utils.ProtocolVersionFlag.Name))
  534. fmt.Println("Network Id:", c.GlobalInt(utils.NetworkIdFlag.Name))
  535. fmt.Println("Go Version:", runtime.Version())
  536. fmt.Println("OS:", runtime.GOOS)
  537. fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
  538. fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
  539. }