flags.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 (integer)",
  74. Value: eth.ProtocolVersion,
  75. }
  76. NetworkIdFlag = cli.IntFlag{
  77. Name: "networkid",
  78. Usage: "Network Id (integer)",
  79. Value: eth.NetworkId,
  80. }
  81. BlockchainVersionFlag = cli.IntFlag{
  82. Name: "blockchainversion",
  83. Usage: "Blockchain version (integer)",
  84. Value: core.BlockChainVersion,
  85. }
  86. IdentityFlag = cli.StringFlag{
  87. Name: "identity",
  88. Usage: "Custom 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 to use with options and subcommands needing a password",
  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: "Logging verbosity: 0-6 (0=silent, 1=error, 2=warn, 3=info, 4=core, 5=debug, 6=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 log verbosity 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: "If set to a file and line number (e.g., \"block.go:271\") holding a logging statement, a stack trace will be logged",
  150. Value: glog.GetTraceLocation(),
  151. }
  152. PProfEanbledFlag = cli.BoolFlag{
  153. Name: "pprof",
  154. Usage: "Enable the profiling server on localhost",
  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: "Enable the JSON-RPC server",
  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 (network disabled if set to 0)",
  185. Value: 25,
  186. }
  187. MaxPendingPeersFlag = cli.IntFlag{
  188. Name: "maxpendpeers",
  189. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  190. Value: 0,
  191. }
  192. ListenPortFlag = cli.IntFlag{
  193. Name: "port",
  194. Usage: "Network listening port",
  195. Value: 30303,
  196. }
  197. BootnodesFlag = cli.StringFlag{
  198. Name: "bootnodes",
  199. Usage: "Space-separated enode URLs for p2p discovery bootstrap",
  200. Value: "",
  201. }
  202. NodeKeyFileFlag = cli.StringFlag{
  203. Name: "nodekey",
  204. Usage: "P2P node key file",
  205. }
  206. NodeKeyHexFlag = cli.StringFlag{
  207. Name: "nodekeyhex",
  208. Usage: "P2P node key as hex (for testing)",
  209. }
  210. NATFlag = cli.StringFlag{
  211. Name: "nat",
  212. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  213. Value: "any",
  214. }
  215. WhisperEnabledFlag = cli.BoolFlag{
  216. Name: "shh",
  217. Usage: "Enable whisper",
  218. }
  219. // ATM the url is left to the user and deployment to
  220. JSpathFlag = cli.StringFlag{
  221. Name: "jspath",
  222. Usage: "JS library path to be used with console and js subcommands",
  223. Value: ".",
  224. }
  225. SolcPathFlag = cli.StringFlag{
  226. Name: "solc",
  227. Usage: "solidity compiler to be used",
  228. Value: "solc",
  229. }
  230. )
  231. func GetNAT(ctx *cli.Context) nat.Interface {
  232. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  233. if err != nil {
  234. Fatalf("Option %s: %v", NATFlag.Name, err)
  235. }
  236. return natif
  237. }
  238. func GetNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  239. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  240. var err error
  241. switch {
  242. case file != "" && hex != "":
  243. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  244. case file != "":
  245. if key, err = crypto.LoadECDSA(file); err != nil {
  246. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  247. }
  248. case hex != "":
  249. if key, err = crypto.HexToECDSA(hex); err != nil {
  250. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  251. }
  252. }
  253. return key
  254. }
  255. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  256. // Set verbosity on glog
  257. glog.SetV(ctx.GlobalInt(LogLevelFlag.Name))
  258. // Set the log type
  259. //glog.SetToStderr(ctx.GlobalBool(LogToStdErrFlag.Name))
  260. glog.SetToStderr(true)
  261. // Set the log dir
  262. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  263. customName := ctx.GlobalString(IdentityFlag.Name)
  264. if len(customName) > 0 {
  265. clientID += "/" + customName
  266. }
  267. return &eth.Config{
  268. Name: common.MakeName(clientID, version),
  269. DataDir: ctx.GlobalString(DataDirFlag.Name),
  270. ProtocolVersion: ctx.GlobalInt(ProtocolVersionFlag.Name),
  271. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  272. SkipBcVersionCheck: false,
  273. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  274. LogFile: ctx.GlobalString(LogFileFlag.Name),
  275. LogLevel: ctx.GlobalInt(LogLevelFlag.Name),
  276. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  277. Etherbase: ctx.GlobalString(EtherbaseFlag.Name),
  278. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  279. AccountManager: GetAccountManager(ctx),
  280. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  281. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  282. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  283. Port: ctx.GlobalString(ListenPortFlag.Name),
  284. NAT: GetNAT(ctx),
  285. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  286. NodeKey: GetNodeKey(ctx),
  287. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  288. Dial: true,
  289. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  290. }
  291. }
  292. func GetChain(ctx *cli.Context) (*core.ChainManager, common.Database, common.Database) {
  293. dataDir := ctx.GlobalString(DataDirFlag.Name)
  294. blockDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "blockchain"))
  295. if err != nil {
  296. Fatalf("Could not open database: %v", err)
  297. }
  298. stateDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "state"))
  299. if err != nil {
  300. Fatalf("Could not open database: %v", err)
  301. }
  302. extraDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "extra"))
  303. if err != nil {
  304. Fatalf("Could not open database: %v", err)
  305. }
  306. eventMux := new(event.TypeMux)
  307. chainManager := core.NewChainManager(blockDb, stateDb, eventMux)
  308. pow := ethash.New()
  309. txPool := core.NewTxPool(eventMux, chainManager.State, chainManager.GasLimit)
  310. blockProcessor := core.NewBlockProcessor(stateDb, extraDb, pow, txPool, chainManager, eventMux)
  311. chainManager.SetProcessor(blockProcessor)
  312. return chainManager, blockDb, stateDb
  313. }
  314. func GetAccountManager(ctx *cli.Context) *accounts.Manager {
  315. dataDir := ctx.GlobalString(DataDirFlag.Name)
  316. ks := crypto.NewKeyStorePassphrase(path.Join(dataDir, "keys"))
  317. return accounts.NewManager(ks)
  318. }
  319. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  320. config := rpc.RpcConfig{
  321. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  322. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  323. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  324. }
  325. xeth := xeth.New(eth, nil)
  326. return rpc.Start(xeth, config)
  327. }
  328. func StartPProf(ctx *cli.Context) {
  329. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  330. go func() {
  331. log.Println(http.ListenAndServe(address, nil))
  332. }()
  333. }