main.go 6.9 KB

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