main.go 8.9 KB

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