main.go 13 KB

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