flags.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. package utils
  2. import (
  3. "crypto/ecdsa"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "path"
  9. "runtime"
  10. "github.com/codegangsta/cli"
  11. "github.com/ethereum/ethash"
  12. "github.com/ethereum/go-ethereum/accounts"
  13. "github.com/ethereum/go-ethereum/common"
  14. "github.com/ethereum/go-ethereum/core"
  15. "github.com/ethereum/go-ethereum/crypto"
  16. "github.com/ethereum/go-ethereum/eth"
  17. "github.com/ethereum/go-ethereum/ethdb"
  18. "github.com/ethereum/go-ethereum/event"
  19. "github.com/ethereum/go-ethereum/logger"
  20. "github.com/ethereum/go-ethereum/logger/glog"
  21. "github.com/ethereum/go-ethereum/p2p/nat"
  22. "github.com/ethereum/go-ethereum/rpc"
  23. "github.com/ethereum/go-ethereum/xeth"
  24. )
  25. func init() {
  26. cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
  27. VERSION:
  28. {{.Version}}
  29. COMMANDS:
  30. {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  31. {{end}}{{if .Flags}}
  32. GLOBAL OPTIONS:
  33. {{range .Flags}}{{.}}
  34. {{end}}{{end}}
  35. `
  36. cli.CommandHelpTemplate = `{{.Name}}{{if .Subcommands}} command{{end}}{{if .Flags}} [command options]{{end}} [arguments...]
  37. {{if .Description}}{{.Description}}
  38. {{end}}{{if .Subcommands}}
  39. SUBCOMMANDS:
  40. {{range .Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  41. {{end}}{{end}}{{if .Flags}}
  42. OPTIONS:
  43. {{range .Flags}}{{.}}
  44. {{end}}{{end}}
  45. `
  46. }
  47. // NewApp creates an app with sane defaults.
  48. func NewApp(version, usage string) *cli.App {
  49. app := cli.NewApp()
  50. app.Name = path.Base(os.Args[0])
  51. app.Author = ""
  52. //app.Authors = nil
  53. app.Email = ""
  54. app.Version = version
  55. app.Usage = usage
  56. return app
  57. }
  58. // These are all the command line flags we support.
  59. // If you add to this list, please remember to include the
  60. // flag in the appropriate command definition.
  61. //
  62. // The flags are defined here so their names and help texts
  63. // are the same for all commands.
  64. var (
  65. // General settings
  66. DataDirFlag = DirectoryFlag{
  67. Name: "datadir",
  68. Usage: "Data directory to be used",
  69. Value: DirectoryString{common.DefaultDataDir()},
  70. }
  71. ProtocolVersionFlag = cli.IntFlag{
  72. Name: "protocolversion",
  73. Usage: "ETH protocol version",
  74. Value: eth.ProtocolVersion,
  75. }
  76. NetworkIdFlag = cli.IntFlag{
  77. Name: "networkid",
  78. Usage: "Network Id",
  79. Value: eth.NetworkId,
  80. }
  81. BlockchainVersionFlag = cli.IntFlag{
  82. Name: "blockchainversion",
  83. Usage: "Blockchain version",
  84. Value: core.BlockChainVersion,
  85. }
  86. IdentityFlag = cli.StringFlag{
  87. Name: "identity",
  88. Usage: "node name",
  89. }
  90. NatspecEnabledFlag = cli.BoolFlag{
  91. Name: "natspec",
  92. Usage: "Enable NatSpec confirmation notice",
  93. }
  94. // miner settings
  95. MinerThreadsFlag = cli.IntFlag{
  96. Name: "minerthreads",
  97. Usage: "Number of miner threads",
  98. Value: runtime.NumCPU(),
  99. }
  100. MiningEnabledFlag = cli.BoolFlag{
  101. Name: "mine",
  102. Usage: "Enable mining",
  103. }
  104. EtherbaseFlag = cli.StringFlag{
  105. Name: "etherbase",
  106. Usage: "public address for block mining rewards. By default the address of your primary account is used",
  107. Value: "primary",
  108. }
  109. UnlockedAccountFlag = cli.StringFlag{
  110. Name: "unlock",
  111. Usage: "unlock the account given until this program exits (prompts for password). '--unlock primary' unlocks the primary account",
  112. Value: "",
  113. }
  114. PasswordFileFlag = cli.StringFlag{
  115. Name: "password",
  116. Usage: "Path to password file for (un)locking an existing account.",
  117. Value: "",
  118. }
  119. // logging and debug settings
  120. LogFileFlag = cli.StringFlag{
  121. Name: "logfile",
  122. Usage: "Send log output to a file",
  123. }
  124. LogLevelFlag = cli.IntFlag{
  125. Name: "loglevel",
  126. Usage: "0-5 (silent, error, warn, info, debug, debug detail)",
  127. Value: int(logger.InfoLevel),
  128. }
  129. LogJSONFlag = cli.StringFlag{
  130. Name: "logjson",
  131. Usage: "Send json structured log output to a file or '-' for standard output (default: no json output)",
  132. Value: "",
  133. }
  134. LogToStdErrFlag = cli.BoolFlag{
  135. Name: "logtostderr",
  136. Usage: "Logs are written to standard error instead of to files.",
  137. }
  138. LogVModuleFlag = cli.GenericFlag{
  139. Name: "vmodule",
  140. Usage: "The syntax of the argument is a comma-separated list of pattern=N, where pattern is a literal file name (minus the \".go\" suffix) or \"glob\" pattern and N is a V level.",
  141. Value: glog.GetVModule(),
  142. }
  143. VMDebugFlag = cli.BoolFlag{
  144. Name: "vmdebug",
  145. Usage: "Virtual Machine debug output",
  146. }
  147. BacktraceAtFlag = cli.GenericFlag{
  148. Name: "backtrace_at",
  149. Usage: "When set to a file and line number holding a logging statement a stack trace will be written to the Info log",
  150. Value: glog.GetTraceLocation(),
  151. }
  152. PProfEanbledFlag = cli.BoolFlag{
  153. Name: "pprof",
  154. Usage: "Whether the profiling server should be enabled",
  155. }
  156. PProfPortFlag = cli.IntFlag{
  157. Name: "pprofport",
  158. Usage: "Port on which the profiler should listen",
  159. Value: 6060,
  160. }
  161. // RPC settings
  162. RPCEnabledFlag = cli.BoolFlag{
  163. Name: "rpc",
  164. Usage: "Whether RPC server is enabled",
  165. }
  166. RPCListenAddrFlag = cli.StringFlag{
  167. Name: "rpcaddr",
  168. Usage: "Listening address for the JSON-RPC server",
  169. Value: "127.0.0.1",
  170. }
  171. RPCPortFlag = cli.IntFlag{
  172. Name: "rpcport",
  173. Usage: "Port on which the JSON-RPC server should listen",
  174. Value: 8545,
  175. }
  176. RPCCORSDomainFlag = cli.StringFlag{
  177. Name: "rpccorsdomain",
  178. Usage: "Domain on which to send Access-Control-Allow-Origin header",
  179. Value: "",
  180. }
  181. // Network Settings
  182. MaxPeersFlag = cli.IntFlag{
  183. Name: "maxpeers",
  184. Usage: "Maximum number of network peers",
  185. Value: 16,
  186. }
  187. ListenPortFlag = cli.IntFlag{
  188. Name: "port",
  189. Usage: "Network listening port",
  190. Value: 30303,
  191. }
  192. BootnodesFlag = cli.StringFlag{
  193. Name: "bootnodes",
  194. Usage: "Space-separated enode URLs for discovery bootstrap",
  195. Value: "",
  196. }
  197. NodeKeyFileFlag = cli.StringFlag{
  198. Name: "nodekey",
  199. Usage: "P2P node key file",
  200. }
  201. NodeKeyHexFlag = cli.StringFlag{
  202. Name: "nodekeyhex",
  203. Usage: "P2P node key as hex (for testing)",
  204. }
  205. NATFlag = cli.StringFlag{
  206. Name: "nat",
  207. Usage: "Port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  208. Value: "any",
  209. }
  210. WhisperEnabledFlag = cli.BoolFlag{
  211. Name: "shh",
  212. Usage: "Whether the whisper sub-protocol is enabled",
  213. }
  214. JSpathFlag = cli.StringFlag{
  215. Name: "jspath",
  216. Usage: "JS library path to be used with console and js subcommands",
  217. Value: ".",
  218. }
  219. )
  220. func GetNAT(ctx *cli.Context) nat.Interface {
  221. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  222. if err != nil {
  223. Fatalf("Option %s: %v", NATFlag.Name, err)
  224. }
  225. return natif
  226. }
  227. func GetNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  228. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  229. var err error
  230. switch {
  231. case file != "" && hex != "":
  232. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  233. case file != "":
  234. if key, err = crypto.LoadECDSA(file); err != nil {
  235. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  236. }
  237. case hex != "":
  238. if key, err = crypto.HexToECDSA(hex); err != nil {
  239. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  240. }
  241. }
  242. return key
  243. }
  244. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  245. // Set verbosity on glog
  246. glog.SetV(ctx.GlobalInt(LogLevelFlag.Name))
  247. // Set the log type
  248. //glog.SetToStderr(ctx.GlobalBool(LogToStdErrFlag.Name))
  249. glog.SetToStderr(true)
  250. // Set the log dir
  251. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  252. customName := ctx.GlobalString(IdentityFlag.Name)
  253. if len(customName) > 0 {
  254. clientID += "/" + customName
  255. }
  256. return &eth.Config{
  257. Name: common.MakeName(clientID, version),
  258. DataDir: ctx.GlobalString(DataDirFlag.Name),
  259. ProtocolVersion: ctx.GlobalInt(ProtocolVersionFlag.Name),
  260. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  261. SkipBcVersionCheck: false,
  262. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  263. LogFile: ctx.GlobalString(LogFileFlag.Name),
  264. LogLevel: ctx.GlobalInt(LogLevelFlag.Name),
  265. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  266. Etherbase: ctx.GlobalString(EtherbaseFlag.Name),
  267. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  268. AccountManager: GetAccountManager(ctx),
  269. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  270. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  271. Port: ctx.GlobalString(ListenPortFlag.Name),
  272. NAT: GetNAT(ctx),
  273. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  274. NodeKey: GetNodeKey(ctx),
  275. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  276. Dial: true,
  277. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  278. }
  279. }
  280. func GetChain(ctx *cli.Context) (*core.ChainManager, common.Database, common.Database) {
  281. dataDir := ctx.GlobalString(DataDirFlag.Name)
  282. blockDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "blockchain"))
  283. if err != nil {
  284. Fatalf("Could not open database: %v", err)
  285. }
  286. stateDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "state"))
  287. if err != nil {
  288. Fatalf("Could not open database: %v", err)
  289. }
  290. extraDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "extra"))
  291. if err != nil {
  292. Fatalf("Could not open database: %v", err)
  293. }
  294. eventMux := new(event.TypeMux)
  295. chainManager := core.NewChainManager(blockDb, stateDb, eventMux)
  296. pow := ethash.New(chainManager)
  297. txPool := core.NewTxPool(eventMux, chainManager.State, chainManager.GasLimit)
  298. blockProcessor := core.NewBlockProcessor(stateDb, extraDb, pow, txPool, chainManager, eventMux)
  299. chainManager.SetProcessor(blockProcessor)
  300. return chainManager, blockDb, stateDb
  301. }
  302. func GetAccountManager(ctx *cli.Context) *accounts.Manager {
  303. dataDir := ctx.GlobalString(DataDirFlag.Name)
  304. ks := crypto.NewKeyStorePassphrase(path.Join(dataDir, "keys"))
  305. return accounts.NewManager(ks)
  306. }
  307. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) {
  308. config := rpc.RpcConfig{
  309. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  310. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  311. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  312. }
  313. xeth := xeth.New(eth, nil)
  314. _ = rpc.Start(xeth, config)
  315. }
  316. func StartPProf(ctx *cli.Context) {
  317. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  318. go func() {
  319. log.Println(http.ListenAndServe(address, nil))
  320. }()
  321. }