main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. "bufio"
  21. "fmt"
  22. "io/ioutil"
  23. "os"
  24. "runtime"
  25. "strconv"
  26. "time"
  27. "github.com/codegangsta/cli"
  28. "github.com/ethereum/ethash"
  29. "github.com/ethereum/go-ethereum/accounts"
  30. "github.com/ethereum/go-ethereum/cmd/utils"
  31. "github.com/ethereum/go-ethereum/common"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/eth"
  35. "github.com/ethereum/go-ethereum/logger"
  36. "github.com/peterh/liner"
  37. )
  38. const (
  39. ClientIdentifier = "Geth"
  40. Version = "0.9.6"
  41. )
  42. var (
  43. clilogger = logger.NewLogger("CLI")
  44. app = utils.NewApp(Version, "the go-ethereum command line interface")
  45. )
  46. func init() {
  47. app.Action = run
  48. app.HideVersion = true // we have a command to print the version
  49. app.Commands = []cli.Command{
  50. blocktestCmd,
  51. {
  52. Action: makedag,
  53. Name: "makedag",
  54. Usage: "generate ethash dag (for testing)",
  55. Description: `
  56. The makedag command generates an ethash DAG in /tmp/dag.
  57. This command exists to support the system testing project.
  58. Regular users do not need to execute it.
  59. `,
  60. },
  61. {
  62. Action: version,
  63. Name: "version",
  64. Usage: "print ethereum version numbers",
  65. Description: `
  66. The output of this command is supposed to be machine-readable.
  67. `,
  68. },
  69. {
  70. Name: "wallet",
  71. Usage: "ethereum presale wallet",
  72. Subcommands: []cli.Command{
  73. {
  74. Action: importWallet,
  75. Name: "import",
  76. Usage: "import ethereum presale wallet",
  77. },
  78. },
  79. },
  80. {
  81. Action: accountList,
  82. Name: "account",
  83. Usage: "manage accounts",
  84. Description: `
  85. Manage accounts lets you create new accounts, list all existing accounts,
  86. import a private key into a new account.
  87. It supports interactive mode, when you are prompted for password as well as
  88. non-interactive mode where passwords are supplied via a given password file.
  89. Non-interactive mode is only meant for scripted use on test networks or known
  90. safe environments.
  91. Make sure you remember the password you gave when creating a new account (with
  92. either new or import). Without it you are not able to unlock your account.
  93. Note that exporting your key in unencrypted format is NOT supported.
  94. Keys are stored under <DATADIR>/keys.
  95. It is safe to transfer the entire directory or the individual keys therein
  96. between ethereum nodes.
  97. Make sure you backup your keys regularly.
  98. And finally. DO NOT FORGET YOUR PASSWORD.
  99. `,
  100. Subcommands: []cli.Command{
  101. {
  102. Action: accountList,
  103. Name: "list",
  104. Usage: "print account addresses",
  105. },
  106. {
  107. Action: accountCreate,
  108. Name: "new",
  109. Usage: "create a new account",
  110. Description: `
  111. ethereum account new
  112. Creates a new account. Prints the address.
  113. The account is saved in encrypted format, you are prompted for a passphrase.
  114. You must remember this passphrase to unlock your account in the future.
  115. For non-interactive use the passphrase can be specified with the --password flag:
  116. ethereum --password <passwordfile> account new
  117. Note, this is meant to be used for testing only, it is a bad idea to save your
  118. password to file or expose in any other way.
  119. `,
  120. },
  121. {
  122. Action: accountImport,
  123. Name: "import",
  124. Usage: "import a private key into a new account",
  125. Description: `
  126. ethereum account import <keyfile>
  127. Imports an unencrypted private key from <keyfile> and creates a new account.
  128. Prints the address.
  129. The keyfile is assumed to contain an unencrypted private key in canonical EC
  130. raw bytes format.
  131. The account is saved in encrypted format, you are prompted for a passphrase.
  132. You must remember this passphrase to unlock your account in the future.
  133. For non-interactive use the passphrase can be specified with the -password flag:
  134. ethereum --password <passwordfile> account import <keyfile>
  135. Note:
  136. As you can directly copy your encrypted accounts to another ethereum instance,
  137. this import mechanism is not needed when you transfer an account between
  138. nodes.
  139. `,
  140. },
  141. },
  142. },
  143. {
  144. Action: dump,
  145. Name: "dump",
  146. Usage: `dump a specific block from storage`,
  147. Description: `
  148. The arguments are interpreted as block numbers or hashes.
  149. Use "ethereum dump 0" to dump the genesis block.
  150. `,
  151. },
  152. {
  153. Action: console,
  154. Name: "console",
  155. Usage: `Geth Console: interactive JavaScript environment`,
  156. Description: `
  157. The Geth console is an interactive shell for the JavaScript runtime environment
  158. which exposes a node admin interface as well as the DAPP JavaScript API.
  159. See https://github.com/ethereum/go-ethereum/wiki/Frontier-Console
  160. `,
  161. },
  162. {
  163. Action: execJSFiles,
  164. Name: "js",
  165. Usage: `executes the given JavaScript files in the Geth JavaScript VM`,
  166. Description: `
  167. The JavaScript VM exposes a node admin interface as well as the DAPP
  168. JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
  169. `,
  170. },
  171. {
  172. Action: importchain,
  173. Name: "import",
  174. Usage: `import a blockchain file`,
  175. },
  176. {
  177. Action: exportchain,
  178. Name: "export",
  179. Usage: `export blockchain into file`,
  180. },
  181. }
  182. app.Flags = []cli.Flag{
  183. utils.UnlockedAccountFlag,
  184. utils.PasswordFileFlag,
  185. utils.BootnodesFlag,
  186. utils.DataDirFlag,
  187. utils.JSpathFlag,
  188. utils.ListenPortFlag,
  189. utils.LogFileFlag,
  190. utils.LogJSONFlag,
  191. utils.LogLevelFlag,
  192. utils.MaxPeersFlag,
  193. utils.EtherbaseFlag,
  194. utils.MinerThreadsFlag,
  195. utils.MiningEnabledFlag,
  196. utils.NATFlag,
  197. utils.NodeKeyFileFlag,
  198. utils.NodeKeyHexFlag,
  199. utils.RPCEnabledFlag,
  200. utils.RPCListenAddrFlag,
  201. utils.RPCPortFlag,
  202. utils.VMDebugFlag,
  203. utils.ProtocolVersionFlag,
  204. utils.NetworkIdFlag,
  205. utils.RPCCORSDomainFlag,
  206. utils.BacktraceAtFlag,
  207. utils.LogToStdErrFlag,
  208. }
  209. // missing:
  210. // flag.StringVar(&ConfigFile, "conf", defaultConfigFile, "config file")
  211. // flag.BoolVar(&DiffTool, "difftool", false, "creates output for diff'ing. Sets LogLevel=0")
  212. // flag.StringVar(&DiffType, "diff", "all", "sets the level of diff output [vm, all]. Has no effect if difftool=false")
  213. // potential subcommands:
  214. // flag.StringVar(&SecretFile, "import", "", "imports the file given (hex or mnemonic formats)")
  215. // flag.StringVar(&ExportDir, "export", "", "exports the session keyring to files in the directory given")
  216. // flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key")
  217. }
  218. func main() {
  219. runtime.GOMAXPROCS(runtime.NumCPU())
  220. defer logger.Flush()
  221. if err := app.Run(os.Args); err != nil {
  222. fmt.Fprintln(os.Stderr, err)
  223. os.Exit(1)
  224. }
  225. }
  226. func run(ctx *cli.Context) {
  227. fmt.Printf("Welcome to the FRONTIER\n")
  228. utils.HandleInterrupt()
  229. cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
  230. ethereum, err := eth.New(cfg)
  231. if err != nil {
  232. utils.Fatalf("%v", err)
  233. }
  234. startEth(ctx, ethereum)
  235. // this blocks the thread
  236. ethereum.WaitForShutdown()
  237. }
  238. func console(ctx *cli.Context) {
  239. cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
  240. ethereum, err := eth.New(cfg)
  241. if err != nil {
  242. utils.Fatalf("%v", err)
  243. }
  244. startEth(ctx, ethereum)
  245. repl := newJSRE(ethereum, ctx.String(utils.JSpathFlag.Name), true)
  246. repl.interactive()
  247. ethereum.Stop()
  248. ethereum.WaitForShutdown()
  249. }
  250. func execJSFiles(ctx *cli.Context) {
  251. cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
  252. ethereum, err := eth.New(cfg)
  253. if err != nil {
  254. utils.Fatalf("%v", err)
  255. }
  256. startEth(ctx, ethereum)
  257. repl := newJSRE(ethereum, ctx.String(utils.JSpathFlag.Name), false)
  258. for _, file := range ctx.Args() {
  259. repl.exec(file)
  260. }
  261. ethereum.Stop()
  262. ethereum.WaitForShutdown()
  263. }
  264. func unlockAccount(ctx *cli.Context, am *accounts.Manager, account string) (passphrase string) {
  265. var err error
  266. // Load startup keys. XXX we are going to need a different format
  267. // Attempt to unlock the account
  268. passphrase = getPassPhrase(ctx, "", false)
  269. accbytes := common.FromHex(account)
  270. if len(accbytes) == 0 {
  271. utils.Fatalf("Invalid account address '%s'", account)
  272. }
  273. err = am.Unlock(accbytes, passphrase)
  274. if err != nil {
  275. utils.Fatalf("Unlock account failed '%v'", err)
  276. }
  277. return
  278. }
  279. func startEth(ctx *cli.Context, eth *eth.Ethereum) {
  280. utils.StartEthereum(eth)
  281. am := eth.AccountManager()
  282. account := ctx.GlobalString(utils.UnlockedAccountFlag.Name)
  283. if len(account) > 0 {
  284. if account == "primary" {
  285. accbytes, err := am.Primary()
  286. if err != nil {
  287. utils.Fatalf("no primary account: %v", err)
  288. }
  289. account = common.ToHex(accbytes)
  290. }
  291. unlockAccount(ctx, am, account)
  292. }
  293. // Start auxiliary services if enabled.
  294. if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
  295. utils.StartRPC(eth, ctx)
  296. }
  297. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
  298. eth.StartMining()
  299. }
  300. }
  301. func accountList(ctx *cli.Context) {
  302. am := utils.GetAccountManager(ctx)
  303. accts, err := am.Accounts()
  304. if err != nil {
  305. utils.Fatalf("Could not list accounts: %v", err)
  306. }
  307. for _, acct := range accts {
  308. fmt.Printf("Address: %x\n", acct)
  309. }
  310. }
  311. func getPassPhrase(ctx *cli.Context, desc string, confirmation bool) (passphrase string) {
  312. passfile := ctx.GlobalString(utils.PasswordFileFlag.Name)
  313. if len(passfile) == 0 {
  314. fmt.Println(desc)
  315. auth, err := readPassword("Passphrase: ", true)
  316. if err != nil {
  317. utils.Fatalf("%v", err)
  318. }
  319. if confirmation {
  320. confirm, err := readPassword("Repeat Passphrase: ", false)
  321. if err != nil {
  322. utils.Fatalf("%v", err)
  323. }
  324. if auth != confirm {
  325. utils.Fatalf("Passphrases did not match.")
  326. }
  327. }
  328. passphrase = auth
  329. } else {
  330. passbytes, err := ioutil.ReadFile(passfile)
  331. if err != nil {
  332. utils.Fatalf("Unable to read password file '%s': %v", passfile, err)
  333. }
  334. passphrase = string(passbytes)
  335. }
  336. return
  337. }
  338. func accountCreate(ctx *cli.Context) {
  339. am := utils.GetAccountManager(ctx)
  340. passphrase := getPassPhrase(ctx, "Your new account is locked with a password. Please give a password. Do not forget this password.", true)
  341. acct, err := am.NewAccount(passphrase)
  342. if err != nil {
  343. utils.Fatalf("Could not create the account: %v", err)
  344. }
  345. fmt.Printf("Address: %x\n", acct)
  346. }
  347. func importWallet(ctx *cli.Context) {
  348. keyfile := ctx.Args().First()
  349. if len(keyfile) == 0 {
  350. utils.Fatalf("keyfile must be given as argument")
  351. }
  352. keyJson, err := ioutil.ReadFile(keyfile)
  353. if err != nil {
  354. utils.Fatalf("Could not read wallet file: %v", err)
  355. }
  356. am := utils.GetAccountManager(ctx)
  357. passphrase := getPassPhrase(ctx, "", false)
  358. acct, err := am.ImportPreSaleKey(keyJson, passphrase)
  359. if err != nil {
  360. utils.Fatalf("Could not create the account: %v", err)
  361. }
  362. fmt.Printf("Address: %x\n", acct)
  363. }
  364. func accountImport(ctx *cli.Context) {
  365. keyfile := ctx.Args().First()
  366. if len(keyfile) == 0 {
  367. utils.Fatalf("keyfile must be given as argument")
  368. }
  369. am := utils.GetAccountManager(ctx)
  370. passphrase := getPassPhrase(ctx, "Your new account is locked with a password. Please give a password. Do not forget this password.", true)
  371. acct, err := am.Import(keyfile, passphrase)
  372. if err != nil {
  373. utils.Fatalf("Could not create the account: %v", err)
  374. }
  375. fmt.Printf("Address: %x\n", acct)
  376. }
  377. func importchain(ctx *cli.Context) {
  378. if len(ctx.Args()) != 1 {
  379. utils.Fatalf("This command requires an argument.")
  380. }
  381. chainmgr, _, _ := utils.GetChain(ctx)
  382. start := time.Now()
  383. err := utils.ImportChain(chainmgr, ctx.Args().First())
  384. if err != nil {
  385. utils.Fatalf("Import error: %v\n", err)
  386. }
  387. fmt.Printf("Import done in %v", time.Since(start))
  388. return
  389. }
  390. func exportchain(ctx *cli.Context) {
  391. if len(ctx.Args()) != 1 {
  392. utils.Fatalf("This command requires an argument.")
  393. }
  394. chainmgr, _, _ := utils.GetChain(ctx)
  395. start := time.Now()
  396. err := utils.ExportChain(chainmgr, ctx.Args().First())
  397. if err != nil {
  398. utils.Fatalf("Export error: %v\n", err)
  399. }
  400. fmt.Printf("Export done in %v", time.Since(start))
  401. return
  402. }
  403. func dump(ctx *cli.Context) {
  404. chainmgr, _, stateDb := utils.GetChain(ctx)
  405. for _, arg := range ctx.Args() {
  406. var block *types.Block
  407. if hashish(arg) {
  408. block = chainmgr.GetBlock(common.HexToHash(arg))
  409. } else {
  410. num, _ := strconv.Atoi(arg)
  411. block = chainmgr.GetBlockByNumber(uint64(num))
  412. }
  413. if block == nil {
  414. fmt.Println("{}")
  415. utils.Fatalf("block not found")
  416. } else {
  417. statedb := state.New(block.Root(), stateDb)
  418. fmt.Printf("%s\n", statedb.Dump())
  419. }
  420. }
  421. }
  422. func makedag(ctx *cli.Context) {
  423. chain, _, _ := utils.GetChain(ctx)
  424. pow := ethash.New(chain)
  425. fmt.Println("making cache")
  426. pow.UpdateCache(0, true)
  427. fmt.Println("making DAG")
  428. pow.UpdateDAG()
  429. }
  430. func version(c *cli.Context) {
  431. fmt.Printf(`%v
  432. Version: %v
  433. Protocol Version: %d
  434. Network Id: %d
  435. GO: %s
  436. OS: %s
  437. GOPATH=%s
  438. GOROOT=%s
  439. `, ClientIdentifier, Version, c.GlobalInt(utils.ProtocolVersionFlag.Name), c.GlobalInt(utils.NetworkIdFlag.Name), runtime.Version(), runtime.GOOS, os.Getenv("GOPATH"), runtime.GOROOT())
  440. }
  441. // hashish returns true for strings that look like hashes.
  442. func hashish(x string) bool {
  443. _, err := strconv.Atoi(x)
  444. return err != nil
  445. }
  446. func readPassword(prompt string, warnTerm bool) (string, error) {
  447. if liner.TerminalSupported() {
  448. lr := liner.NewLiner()
  449. defer lr.Close()
  450. return lr.PasswordPrompt(prompt)
  451. }
  452. if warnTerm {
  453. fmt.Println("!! Unsupported terminal, password will be echoed.")
  454. }
  455. fmt.Print(prompt)
  456. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  457. fmt.Println()
  458. return input, err
  459. }