flags.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. GenesisNonceFlag = cli.IntFlag{
  88. Name: "genesisnonce",
  89. Usage: "Sets the genesis nonce",
  90. Value: 42,
  91. }
  92. IdentityFlag = cli.StringFlag{
  93. Name: "identity",
  94. Usage: "Custom node name",
  95. }
  96. NatspecEnabledFlag = cli.BoolFlag{
  97. Name: "natspec",
  98. Usage: "Enable NatSpec confirmation notice",
  99. }
  100. // miner settings
  101. MinerThreadsFlag = cli.IntFlag{
  102. Name: "minerthreads",
  103. Usage: "Number of miner threads",
  104. Value: runtime.NumCPU(),
  105. }
  106. MiningEnabledFlag = cli.BoolFlag{
  107. Name: "mine",
  108. Usage: "Enable mining",
  109. }
  110. AutoDAGFlag = cli.BoolFlag{
  111. Name: "autodag",
  112. Usage: "Enable automatic DAG pregeneration",
  113. }
  114. EtherbaseFlag = cli.StringFlag{
  115. Name: "etherbase",
  116. Usage: "Public address for block mining rewards. By default the address of your primary account is used",
  117. Value: "primary",
  118. }
  119. GasPriceFlag = cli.StringFlag{
  120. Name: "gasprice",
  121. Usage: "Sets the minimal gasprice when mining transactions",
  122. Value: new(big.Int).Mul(big.NewInt(10), common.Szabo).String(),
  123. }
  124. UnlockedAccountFlag = cli.StringFlag{
  125. Name: "unlock",
  126. Usage: "Unlock the account given until this program exits (prompts for password). '--unlock primary' unlocks the primary account",
  127. Value: "",
  128. }
  129. PasswordFileFlag = cli.StringFlag{
  130. Name: "password",
  131. Usage: "Path to password file to use with options and subcommands needing a password",
  132. Value: "",
  133. }
  134. // logging and debug settings
  135. LogFileFlag = cli.StringFlag{
  136. Name: "logfile",
  137. Usage: "Send log output to a file",
  138. }
  139. VerbosityFlag = cli.IntFlag{
  140. Name: "verbosity",
  141. Usage: "Logging verbosity: 0-6 (0=silent, 1=error, 2=warn, 3=info, 4=core, 5=debug, 6=debug detail)",
  142. Value: int(logger.InfoLevel),
  143. }
  144. LogJSONFlag = cli.StringFlag{
  145. Name: "logjson",
  146. Usage: "Send json structured log output to a file or '-' for standard output (default: no json output)",
  147. Value: "",
  148. }
  149. LogToStdErrFlag = cli.BoolFlag{
  150. Name: "logtostderr",
  151. Usage: "Logs are written to standard error instead of to files.",
  152. }
  153. LogVModuleFlag = cli.GenericFlag{
  154. Name: "vmodule",
  155. 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.",
  156. Value: glog.GetVModule(),
  157. }
  158. VMDebugFlag = cli.BoolFlag{
  159. Name: "vmdebug",
  160. Usage: "Virtual Machine debug output",
  161. }
  162. BacktraceAtFlag = cli.GenericFlag{
  163. Name: "backtrace_at",
  164. Usage: "If set to a file and line number (e.g., \"block.go:271\") holding a logging statement, a stack trace will be logged",
  165. Value: glog.GetTraceLocation(),
  166. }
  167. PProfEanbledFlag = cli.BoolFlag{
  168. Name: "pprof",
  169. Usage: "Enable the profiling server on localhost",
  170. }
  171. PProfPortFlag = cli.IntFlag{
  172. Name: "pprofport",
  173. Usage: "Port on which the profiler should listen",
  174. Value: 6060,
  175. }
  176. // RPC settings
  177. RPCEnabledFlag = cli.BoolFlag{
  178. Name: "rpc",
  179. Usage: "Enable the JSON-RPC server",
  180. }
  181. RPCListenAddrFlag = cli.StringFlag{
  182. Name: "rpcaddr",
  183. Usage: "Listening address for the JSON-RPC server",
  184. Value: "127.0.0.1",
  185. }
  186. RPCPortFlag = cli.IntFlag{
  187. Name: "rpcport",
  188. Usage: "Port on which the JSON-RPC server should listen",
  189. Value: 8545,
  190. }
  191. RPCCORSDomainFlag = cli.StringFlag{
  192. Name: "rpccorsdomain",
  193. Usage: "Domain on which to send Access-Control-Allow-Origin header",
  194. Value: "",
  195. }
  196. // Network Settings
  197. MaxPeersFlag = cli.IntFlag{
  198. Name: "maxpeers",
  199. Usage: "Maximum number of network peers (network disabled if set to 0)",
  200. Value: 25,
  201. }
  202. MaxPendingPeersFlag = cli.IntFlag{
  203. Name: "maxpendpeers",
  204. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  205. Value: 0,
  206. }
  207. ListenPortFlag = cli.IntFlag{
  208. Name: "port",
  209. Usage: "Network listening port",
  210. Value: 30303,
  211. }
  212. BootnodesFlag = cli.StringFlag{
  213. Name: "bootnodes",
  214. Usage: "Space-separated enode URLs for p2p discovery bootstrap",
  215. Value: "",
  216. }
  217. NodeKeyFileFlag = cli.StringFlag{
  218. Name: "nodekey",
  219. Usage: "P2P node key file",
  220. }
  221. NodeKeyHexFlag = cli.StringFlag{
  222. Name: "nodekeyhex",
  223. Usage: "P2P node key as hex (for testing)",
  224. }
  225. NATFlag = cli.StringFlag{
  226. Name: "nat",
  227. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  228. Value: "any",
  229. }
  230. NoDiscoverFlag = cli.BoolFlag{
  231. Name: "nodiscover",
  232. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  233. }
  234. WhisperEnabledFlag = cli.BoolFlag{
  235. Name: "shh",
  236. Usage: "Enable whisper",
  237. }
  238. // ATM the url is left to the user and deployment to
  239. JSpathFlag = cli.StringFlag{
  240. Name: "jspath",
  241. Usage: "JS library path to be used with console and js subcommands",
  242. Value: ".",
  243. }
  244. SolcPathFlag = cli.StringFlag{
  245. Name: "solc",
  246. Usage: "solidity compiler to be used",
  247. Value: "solc",
  248. }
  249. )
  250. // MakeNAT creates a port mapper from set command line flags.
  251. func MakeNAT(ctx *cli.Context) nat.Interface {
  252. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  253. if err != nil {
  254. Fatalf("Option %s: %v", NATFlag.Name, err)
  255. }
  256. return natif
  257. }
  258. // MakeNodeKey creates a node key from set command line flags.
  259. func MakeNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  260. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  261. var err error
  262. switch {
  263. case file != "" && hex != "":
  264. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  265. case file != "":
  266. if key, err = crypto.LoadECDSA(file); err != nil {
  267. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  268. }
  269. case hex != "":
  270. if key, err = crypto.HexToECDSA(hex); err != nil {
  271. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  272. }
  273. }
  274. return key
  275. }
  276. // MakeEthConfig creates ethereum options from set command line flags.
  277. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  278. customName := ctx.GlobalString(IdentityFlag.Name)
  279. if len(customName) > 0 {
  280. clientID += "/" + customName
  281. }
  282. return &eth.Config{
  283. Name: common.MakeName(clientID, version),
  284. DataDir: ctx.GlobalString(DataDirFlag.Name),
  285. ProtocolVersion: ctx.GlobalInt(ProtocolVersionFlag.Name),
  286. GenesisNonce: ctx.GlobalInt(GenesisNonceFlag.Name),
  287. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  288. SkipBcVersionCheck: false,
  289. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  290. LogFile: ctx.GlobalString(LogFileFlag.Name),
  291. Verbosity: ctx.GlobalInt(VerbosityFlag.Name),
  292. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  293. Etherbase: ctx.GlobalString(EtherbaseFlag.Name),
  294. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  295. AccountManager: MakeAccountManager(ctx),
  296. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  297. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  298. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  299. Port: ctx.GlobalString(ListenPortFlag.Name),
  300. NAT: MakeNAT(ctx),
  301. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  302. Discovery: !ctx.GlobalBool(NoDiscoverFlag.Name),
  303. NodeKey: MakeNodeKey(ctx),
  304. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  305. Dial: true,
  306. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  307. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  308. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  309. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  310. }
  311. }
  312. // SetupLogger configures glog from the logging-related command line flags.
  313. func SetupLogger(ctx *cli.Context) {
  314. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  315. glog.CopyStandardLogTo("INFO")
  316. glog.SetToStderr(true)
  317. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  318. }
  319. // MakeChain creates a chain manager from set command line flags.
  320. func MakeChain(ctx *cli.Context) (chain *core.ChainManager, blockDB, stateDB, extraDB common.Database) {
  321. dd := ctx.GlobalString(DataDirFlag.Name)
  322. var err error
  323. if blockDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "blockchain")); err != nil {
  324. Fatalf("Could not open database: %v", err)
  325. }
  326. if stateDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "state")); err != nil {
  327. Fatalf("Could not open database: %v", err)
  328. }
  329. if extraDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "extra")); err != nil {
  330. Fatalf("Could not open database: %v", err)
  331. }
  332. eventMux := new(event.TypeMux)
  333. pow := ethash.New()
  334. genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  335. chain, err = core.NewChainManager(genesis, blockDB, stateDB, pow, eventMux)
  336. if err != nil {
  337. Fatalf("Could not start chainmanager: %v", err)
  338. }
  339. proc := core.NewBlockProcessor(stateDB, extraDB, pow, chain, eventMux)
  340. chain.SetProcessor(proc)
  341. return chain, blockDB, stateDB, extraDB
  342. }
  343. // MakeChain creates an account manager from set command line flags.
  344. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  345. dataDir := ctx.GlobalString(DataDirFlag.Name)
  346. ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keystore"))
  347. return accounts.NewManager(ks)
  348. }
  349. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  350. config := rpc.RpcConfig{
  351. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  352. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  353. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  354. }
  355. xeth := xeth.New(eth, nil)
  356. return rpc.Start(xeth, config)
  357. }
  358. func StartPProf(ctx *cli.Context) {
  359. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  360. go func() {
  361. log.Println(http.ListenAndServe(address, nil))
  362. }()
  363. }