flags.go 11 KB

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