main.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. "os"
  23. "runtime"
  24. "strconv"
  25. "time"
  26. "github.com/codegangsta/cli"
  27. "github.com/ethereum/go-ethereum/accounts"
  28. "github.com/ethereum/go-ethereum/cmd/utils"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/eth"
  31. "github.com/ethereum/go-ethereum/ethutil"
  32. "github.com/ethereum/go-ethereum/logger"
  33. "github.com/ethereum/go-ethereum/state"
  34. "github.com/peterh/liner"
  35. )
  36. const (
  37. ClientIdentifier = "Ethereum(G)"
  38. Version = "0.9.0"
  39. )
  40. var (
  41. clilogger = logger.NewLogger("CLI")
  42. app = utils.NewApp(Version, "the go-ethereum command line interface")
  43. )
  44. func init() {
  45. app.Action = run
  46. app.HideVersion = true // we have a command to print the version
  47. app.Commands = []cli.Command{
  48. {
  49. Action: version,
  50. Name: "version",
  51. Usage: "print ethereum version numbers",
  52. Description: `
  53. The output of this command is supposed to be machine-readable.
  54. `,
  55. },
  56. {
  57. Action: accountList,
  58. Name: "account",
  59. Usage: "manage accounts",
  60. Subcommands: []cli.Command{
  61. {
  62. Action: accountList,
  63. Name: "list",
  64. Usage: "print account addresses",
  65. },
  66. {
  67. Action: accountCreate,
  68. Name: "new",
  69. Usage: "create a new account",
  70. },
  71. },
  72. },
  73. {
  74. Action: dump,
  75. Name: "dump",
  76. Usage: `dump a specific block from storage`,
  77. Description: `
  78. The arguments are interpreted as block numbers or hashes.
  79. Use "ethereum dump 0" to dump the genesis block.
  80. `,
  81. },
  82. {
  83. Action: runjs,
  84. Name: "js",
  85. Usage: `interactive JavaScript console`,
  86. Description: `
  87. In the console, you can use the eth object to interact
  88. with the running ethereum stack. The API does not match
  89. ethereum.js.
  90. A JavaScript file can be provided as the argument. The
  91. runtime will execute the file and exit.
  92. `,
  93. },
  94. {
  95. Action: importchain,
  96. Name: "import",
  97. Usage: `import a blockchain file`,
  98. },
  99. {
  100. Action: exportchain,
  101. Name: "export",
  102. Usage: `export blockchain into file`,
  103. },
  104. }
  105. app.Flags = []cli.Flag{
  106. utils.BootnodesFlag,
  107. utils.DataDirFlag,
  108. utils.ListenPortFlag,
  109. utils.LogFileFlag,
  110. utils.LogFormatFlag,
  111. utils.LogLevelFlag,
  112. utils.MaxPeersFlag,
  113. utils.MinerThreadsFlag,
  114. utils.MiningEnabledFlag,
  115. utils.NATFlag,
  116. utils.NodeKeyFileFlag,
  117. utils.NodeKeyHexFlag,
  118. utils.RPCEnabledFlag,
  119. utils.RPCListenAddrFlag,
  120. utils.RPCPortFlag,
  121. utils.VMDebugFlag,
  122. //utils.VMTypeFlag,
  123. }
  124. // missing:
  125. // flag.StringVar(&ConfigFile, "conf", defaultConfigFile, "config file")
  126. // flag.BoolVar(&DiffTool, "difftool", false, "creates output for diff'ing. Sets LogLevel=0")
  127. // flag.StringVar(&DiffType, "diff", "all", "sets the level of diff output [vm, all]. Has no effect if difftool=false")
  128. // potential subcommands:
  129. // flag.StringVar(&SecretFile, "import", "", "imports the file given (hex or mnemonic formats)")
  130. // flag.StringVar(&ExportDir, "export", "", "exports the session keyring to files in the directory given")
  131. // flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key")
  132. }
  133. func main() {
  134. runtime.GOMAXPROCS(runtime.NumCPU())
  135. defer logger.Flush()
  136. if err := app.Run(os.Args); err != nil {
  137. fmt.Fprintln(os.Stderr, err)
  138. os.Exit(1)
  139. }
  140. }
  141. func run(ctx *cli.Context) {
  142. fmt.Printf("Welcome to the FRONTIER\n")
  143. utils.HandleInterrupt()
  144. eth, err := utils.GetEthereum(ClientIdentifier, Version, ctx)
  145. if err == accounts.ErrNoKeys {
  146. utils.Fatalf(`No accounts configured.
  147. Please run 'ethereum account new' to create a new account.`)
  148. } else if err != nil {
  149. utils.Fatalf("%v", err)
  150. }
  151. startEth(ctx, eth)
  152. // this blocks the thread
  153. eth.WaitForShutdown()
  154. }
  155. func runjs(ctx *cli.Context) {
  156. eth, err := utils.GetEthereum(ClientIdentifier, Version, ctx)
  157. if err == accounts.ErrNoKeys {
  158. utils.Fatalf(`No accounts configured.
  159. Please run 'ethereum account new' to create a new account.`)
  160. } else if err != nil {
  161. utils.Fatalf("%v", err)
  162. }
  163. startEth(ctx, eth)
  164. repl := newJSRE(eth)
  165. if len(ctx.Args()) == 0 {
  166. repl.interactive()
  167. } else {
  168. for _, file := range ctx.Args() {
  169. repl.exec(file)
  170. }
  171. }
  172. eth.Stop()
  173. eth.WaitForShutdown()
  174. }
  175. func startEth(ctx *cli.Context, eth *eth.Ethereum) {
  176. utils.StartEthereum(eth)
  177. // Start auxiliary services if enabled.
  178. if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
  179. utils.StartRPC(eth, ctx)
  180. }
  181. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
  182. eth.Miner().Start()
  183. }
  184. }
  185. func accountList(ctx *cli.Context) {
  186. am := utils.GetAccountManager(ctx)
  187. accts, err := am.Accounts()
  188. if err != nil {
  189. utils.Fatalf("Could not list accounts: %v", err)
  190. }
  191. for _, acct := range accts {
  192. fmt.Printf("Address: %#x\n", acct)
  193. }
  194. }
  195. func accountCreate(ctx *cli.Context) {
  196. am := utils.GetAccountManager(ctx)
  197. fmt.Println("The new account will be encrypted with a passphrase.")
  198. fmt.Println("Please enter a passphrase now.")
  199. auth, err := readPassword("Passphrase: ", true)
  200. if err != nil {
  201. utils.Fatalf("%v", err)
  202. }
  203. confirm, err := readPassword("Repeat Passphrase: ", false)
  204. if err != nil {
  205. utils.Fatalf("%v", err)
  206. }
  207. if auth != confirm {
  208. utils.Fatalf("Passphrases did not match.")
  209. }
  210. acct, err := am.NewAccount(auth)
  211. if err != nil {
  212. utils.Fatalf("Could not create the account: %v", err)
  213. }
  214. fmt.Printf("Address: %#x\n", acct.Address)
  215. }
  216. func importchain(ctx *cli.Context) {
  217. if len(ctx.Args()) != 1 {
  218. utils.Fatalf("This command requires an argument.")
  219. }
  220. chainmgr, _, _ := utils.GetChain(ctx)
  221. start := time.Now()
  222. err := utils.ImportChain(chainmgr, ctx.Args().First())
  223. if err != nil {
  224. utils.Fatalf("Import error: %v\n", err)
  225. }
  226. fmt.Printf("Import done in %v", time.Since(start))
  227. return
  228. }
  229. func exportchain(ctx *cli.Context) {
  230. if len(ctx.Args()) != 1 {
  231. utils.Fatalf("This command requires an argument.")
  232. }
  233. chainmgr, _, _ := utils.GetChain(ctx)
  234. start := time.Now()
  235. err := utils.ExportChain(chainmgr, ctx.Args().First())
  236. if err != nil {
  237. utils.Fatalf("Export error: %v\n", err)
  238. }
  239. fmt.Printf("Export done in %v", time.Since(start))
  240. return
  241. }
  242. func dump(ctx *cli.Context) {
  243. chainmgr, _, stateDb := utils.GetChain(ctx)
  244. for _, arg := range ctx.Args() {
  245. var block *types.Block
  246. if hashish(arg) {
  247. block = chainmgr.GetBlock(ethutil.Hex2Bytes(arg))
  248. } else {
  249. num, _ := strconv.Atoi(arg)
  250. block = chainmgr.GetBlockByNumber(uint64(num))
  251. }
  252. if block == nil {
  253. fmt.Println("{}")
  254. utils.Fatalf("block not found")
  255. } else {
  256. statedb := state.New(block.Root(), stateDb)
  257. fmt.Printf("%s\n", statedb.Dump())
  258. // fmt.Println(block)
  259. }
  260. }
  261. }
  262. func version(c *cli.Context) {
  263. fmt.Printf(`%v
  264. Version: %v
  265. Protocol Version: %d
  266. Network Id: %d
  267. GO: %s
  268. OS: %s
  269. GOPATH=%s
  270. GOROOT=%s
  271. `, ClientIdentifier, Version, eth.ProtocolVersion, eth.NetworkId, runtime.Version(), runtime.GOOS, os.Getenv("GOPATH"), runtime.GOROOT())
  272. }
  273. // hashish returns true for strings that look like hashes.
  274. func hashish(x string) bool {
  275. _, err := strconv.Atoi(x)
  276. return err != nil
  277. }
  278. func readPassword(prompt string, warnTerm bool) (string, error) {
  279. if liner.TerminalSupported() {
  280. lr := liner.NewLiner()
  281. defer lr.Close()
  282. return lr.PasswordPrompt(prompt)
  283. }
  284. if warnTerm {
  285. fmt.Println("!! Unsupported terminal, password will be echoed.")
  286. }
  287. fmt.Print(prompt)
  288. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  289. fmt.Println()
  290. return input, err
  291. }