main.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. "strings"
  26. "time"
  27. "github.com/codegangsta/cli"
  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.UnlockedAccountFlag,
  107. utils.BootnodesFlag,
  108. utils.DataDirFlag,
  109. utils.ListenPortFlag,
  110. utils.LogFileFlag,
  111. utils.LogFormatFlag,
  112. utils.LogLevelFlag,
  113. utils.MaxPeersFlag,
  114. utils.MinerThreadsFlag,
  115. utils.MiningEnabledFlag,
  116. utils.NATFlag,
  117. utils.NodeKeyFileFlag,
  118. utils.NodeKeyHexFlag,
  119. utils.RPCEnabledFlag,
  120. utils.RPCListenAddrFlag,
  121. utils.RPCPortFlag,
  122. utils.UnencryptedKeysFlag,
  123. utils.VMDebugFlag,
  124. //utils.VMTypeFlag,
  125. }
  126. // missing:
  127. // flag.StringVar(&ConfigFile, "conf", defaultConfigFile, "config file")
  128. // flag.BoolVar(&DiffTool, "difftool", false, "creates output for diff'ing. Sets LogLevel=0")
  129. // flag.StringVar(&DiffType, "diff", "all", "sets the level of diff output [vm, all]. Has no effect if difftool=false")
  130. // potential subcommands:
  131. // flag.StringVar(&SecretFile, "import", "", "imports the file given (hex or mnemonic formats)")
  132. // flag.StringVar(&ExportDir, "export", "", "exports the session keyring to files in the directory given")
  133. // flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key")
  134. }
  135. func main() {
  136. runtime.GOMAXPROCS(runtime.NumCPU())
  137. defer logger.Flush()
  138. if err := app.Run(os.Args); err != nil {
  139. fmt.Fprintln(os.Stderr, err)
  140. os.Exit(1)
  141. }
  142. }
  143. func run(ctx *cli.Context) {
  144. fmt.Printf("Welcome to the FRONTIER\n")
  145. utils.HandleInterrupt()
  146. cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
  147. ethereum, err := eth.New(cfg)
  148. if err != nil {
  149. utils.Fatalf("%v", err)
  150. }
  151. startEth(ctx, ethereum)
  152. // this blocks the thread
  153. ethereum.WaitForShutdown()
  154. }
  155. func runjs(ctx *cli.Context) {
  156. cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
  157. ethereum, err := eth.New(cfg)
  158. if err != nil {
  159. utils.Fatalf("%v", err)
  160. }
  161. startEth(ctx, ethereum)
  162. repl := newJSRE(ethereum)
  163. if len(ctx.Args()) == 0 {
  164. repl.interactive()
  165. } else {
  166. for _, file := range ctx.Args() {
  167. repl.exec(file)
  168. }
  169. }
  170. ethereum.Stop()
  171. ethereum.WaitForShutdown()
  172. }
  173. func startEth(ctx *cli.Context, eth *eth.Ethereum) {
  174. utils.StartEthereum(eth)
  175. // Load startup keys. XXX we are going to need a different format
  176. account := ctx.GlobalString(utils.UnlockedAccountFlag.Name)
  177. if len(account) > 0 {
  178. split := strings.Split(account, ":")
  179. if len(split) != 2 {
  180. utils.Fatalf("Illegal 'unlock' format (address:password)")
  181. }
  182. am := eth.AccountManager()
  183. // Attempt to unlock the account
  184. err := am.Unlock(ethutil.Hex2Bytes(split[0]), split[1])
  185. if err != nil {
  186. utils.Fatalf("Unlock account failed '%v'", err)
  187. }
  188. }
  189. // Start auxiliary services if enabled.
  190. if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
  191. utils.StartRPC(eth, ctx)
  192. }
  193. if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
  194. eth.StartMining()
  195. }
  196. }
  197. func accountList(ctx *cli.Context) {
  198. am := utils.GetAccountManager(ctx)
  199. accts, err := am.Accounts()
  200. if err != nil {
  201. utils.Fatalf("Could not list accounts: %v", err)
  202. }
  203. for _, acct := range accts {
  204. fmt.Printf("Address: %#x\n", acct)
  205. }
  206. }
  207. func accountCreate(ctx *cli.Context) {
  208. am := utils.GetAccountManager(ctx)
  209. passphrase := ""
  210. if !ctx.GlobalBool(utils.UnencryptedKeysFlag.Name) {
  211. fmt.Println("The new account will be encrypted with a passphrase.")
  212. fmt.Println("Please enter a passphrase now.")
  213. auth, err := readPassword("Passphrase: ", true)
  214. if err != nil {
  215. utils.Fatalf("%v", err)
  216. }
  217. confirm, err := readPassword("Repeat Passphrase: ", false)
  218. if err != nil {
  219. utils.Fatalf("%v", err)
  220. }
  221. if auth != confirm {
  222. utils.Fatalf("Passphrases did not match.")
  223. }
  224. passphrase = auth
  225. }
  226. acct, err := am.NewAccount(passphrase)
  227. if err != nil {
  228. utils.Fatalf("Could not create the account: %v", err)
  229. }
  230. fmt.Printf("Address: %#x\n", acct.Address)
  231. }
  232. func importchain(ctx *cli.Context) {
  233. if len(ctx.Args()) != 1 {
  234. utils.Fatalf("This command requires an argument.")
  235. }
  236. chainmgr, _, _ := utils.GetChain(ctx)
  237. start := time.Now()
  238. err := utils.ImportChain(chainmgr, ctx.Args().First())
  239. if err != nil {
  240. utils.Fatalf("Import error: %v\n", err)
  241. }
  242. fmt.Printf("Import done in %v", time.Since(start))
  243. return
  244. }
  245. func exportchain(ctx *cli.Context) {
  246. if len(ctx.Args()) != 1 {
  247. utils.Fatalf("This command requires an argument.")
  248. }
  249. chainmgr, _, _ := utils.GetChain(ctx)
  250. start := time.Now()
  251. err := utils.ExportChain(chainmgr, ctx.Args().First())
  252. if err != nil {
  253. utils.Fatalf("Export error: %v\n", err)
  254. }
  255. fmt.Printf("Export done in %v", time.Since(start))
  256. return
  257. }
  258. func dump(ctx *cli.Context) {
  259. chainmgr, _, stateDb := utils.GetChain(ctx)
  260. for _, arg := range ctx.Args() {
  261. var block *types.Block
  262. if hashish(arg) {
  263. block = chainmgr.GetBlock(ethutil.Hex2Bytes(arg))
  264. } else {
  265. num, _ := strconv.Atoi(arg)
  266. block = chainmgr.GetBlockByNumber(uint64(num))
  267. }
  268. if block == nil {
  269. fmt.Println("{}")
  270. utils.Fatalf("block not found")
  271. } else {
  272. statedb := state.New(block.Root(), stateDb)
  273. fmt.Printf("%s\n", statedb.Dump())
  274. // fmt.Println(block)
  275. }
  276. }
  277. }
  278. func version(c *cli.Context) {
  279. fmt.Printf(`%v
  280. Version: %v
  281. Protocol Version: %d
  282. Network Id: %d
  283. GO: %s
  284. OS: %s
  285. GOPATH=%s
  286. GOROOT=%s
  287. `, ClientIdentifier, Version, eth.ProtocolVersion, eth.NetworkId, runtime.Version(), runtime.GOOS, os.Getenv("GOPATH"), runtime.GOROOT())
  288. }
  289. // hashish returns true for strings that look like hashes.
  290. func hashish(x string) bool {
  291. _, err := strconv.Atoi(x)
  292. return err != nil
  293. }
  294. func readPassword(prompt string, warnTerm bool) (string, error) {
  295. if liner.TerminalSupported() {
  296. lr := liner.NewLiner()
  297. defer lr.Close()
  298. return lr.PasswordPrompt(prompt)
  299. }
  300. if warnTerm {
  301. fmt.Println("!! Unsupported terminal, password will be echoed.")
  302. }
  303. fmt.Print(prompt)
  304. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  305. fmt.Println()
  306. return input, err
  307. }