flags.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. // MakeNAT creates a port mapper from set command line flags.
  246. func MakeNAT(ctx *cli.Context) nat.Interface {
  247. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  248. if err != nil {
  249. Fatalf("Option %s: %v", NATFlag.Name, err)
  250. }
  251. return natif
  252. }
  253. // MakeNodeKey creates a node key from set command line flags.
  254. func MakeNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  255. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  256. var err error
  257. switch {
  258. case file != "" && hex != "":
  259. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  260. case file != "":
  261. if key, err = crypto.LoadECDSA(file); err != nil {
  262. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  263. }
  264. case hex != "":
  265. if key, err = crypto.HexToECDSA(hex); err != nil {
  266. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  267. }
  268. }
  269. return key
  270. }
  271. // MakeEthConfig creates ethereum options from set command line flags.
  272. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  273. customName := ctx.GlobalString(IdentityFlag.Name)
  274. if len(customName) > 0 {
  275. clientID += "/" + customName
  276. }
  277. return &eth.Config{
  278. Name: common.MakeName(clientID, version),
  279. DataDir: ctx.GlobalString(DataDirFlag.Name),
  280. ProtocolVersion: ctx.GlobalInt(ProtocolVersionFlag.Name),
  281. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  282. SkipBcVersionCheck: false,
  283. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  284. LogFile: ctx.GlobalString(LogFileFlag.Name),
  285. Verbosity: ctx.GlobalInt(VerbosityFlag.Name),
  286. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  287. Etherbase: ctx.GlobalString(EtherbaseFlag.Name),
  288. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  289. AccountManager: MakeAccountManager(ctx),
  290. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  291. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  292. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  293. Port: ctx.GlobalString(ListenPortFlag.Name),
  294. NAT: MakeNAT(ctx),
  295. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  296. Discovery: !ctx.GlobalBool(NoDiscoverFlag.Name),
  297. NodeKey: MakeNodeKey(ctx),
  298. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  299. Dial: true,
  300. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  301. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  302. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  303. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  304. }
  305. }
  306. // SetupLogger configures glog from the logging-related command line flags.
  307. func SetupLogger(ctx *cli.Context) {
  308. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  309. glog.CopyStandardLogTo("INFO")
  310. glog.SetToStderr(true)
  311. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  312. }
  313. // MakeChain creates a chain manager from set command line flags.
  314. func MakeChain(ctx *cli.Context) (chain *core.ChainManager, blockDB, stateDB, extraDB common.Database) {
  315. dd := ctx.GlobalString(DataDirFlag.Name)
  316. var err error
  317. if blockDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "blockchain")); err != nil {
  318. Fatalf("Could not open database: %v", err)
  319. }
  320. if stateDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "state")); err != nil {
  321. Fatalf("Could not open database: %v", err)
  322. }
  323. if extraDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "extra")); err != nil {
  324. Fatalf("Could not open database: %v", err)
  325. }
  326. eventMux := new(event.TypeMux)
  327. pow := ethash.New()
  328. chain = core.NewChainManager(blockDB, stateDB, pow, eventMux)
  329. proc := core.NewBlockProcessor(stateDB, extraDB, pow, chain, eventMux)
  330. chain.SetProcessor(proc)
  331. return chain, blockDB, stateDB, extraDB
  332. }
  333. // MakeChain creates an account manager from set command line flags.
  334. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  335. dataDir := ctx.GlobalString(DataDirFlag.Name)
  336. ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keystore"))
  337. return accounts.NewManager(ks)
  338. }
  339. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  340. config := rpc.RpcConfig{
  341. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  342. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  343. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  344. }
  345. xeth := xeth.New(eth, nil)
  346. return rpc.Start(xeth, config)
  347. }
  348. func StartPProf(ctx *cli.Context) {
  349. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  350. go func() {
  351. log.Println(http.ListenAndServe(address, nil))
  352. }()
  353. }