flags.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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/ethereum/go-ethereum/metrics"
  12. "github.com/codegangsta/cli"
  13. "github.com/ethereum/ethash"
  14. "github.com/ethereum/go-ethereum/accounts"
  15. "github.com/ethereum/go-ethereum/common"
  16. "github.com/ethereum/go-ethereum/core"
  17. "github.com/ethereum/go-ethereum/crypto"
  18. "github.com/ethereum/go-ethereum/eth"
  19. "github.com/ethereum/go-ethereum/ethdb"
  20. "github.com/ethereum/go-ethereum/event"
  21. "github.com/ethereum/go-ethereum/logger"
  22. "github.com/ethereum/go-ethereum/logger/glog"
  23. "github.com/ethereum/go-ethereum/p2p/nat"
  24. "github.com/ethereum/go-ethereum/rpc/api"
  25. "github.com/ethereum/go-ethereum/rpc/codec"
  26. "github.com/ethereum/go-ethereum/rpc/comms"
  27. "github.com/ethereum/go-ethereum/xeth"
  28. )
  29. func init() {
  30. cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
  31. VERSION:
  32. {{.Version}}
  33. COMMANDS:
  34. {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  35. {{end}}{{if .Flags}}
  36. GLOBAL OPTIONS:
  37. {{range .Flags}}{{.}}
  38. {{end}}{{end}}
  39. `
  40. cli.CommandHelpTemplate = `{{.Name}}{{if .Subcommands}} command{{end}}{{if .Flags}} [command options]{{end}} [arguments...]
  41. {{if .Description}}{{.Description}}
  42. {{end}}{{if .Subcommands}}
  43. SUBCOMMANDS:
  44. {{range .Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  45. {{end}}{{end}}{{if .Flags}}
  46. OPTIONS:
  47. {{range .Flags}}{{.}}
  48. {{end}}{{end}}
  49. `
  50. }
  51. // NewApp creates an app with sane defaults.
  52. func NewApp(version, usage string) *cli.App {
  53. app := cli.NewApp()
  54. app.Name = filepath.Base(os.Args[0])
  55. app.Author = ""
  56. //app.Authors = nil
  57. app.Email = ""
  58. app.Version = version
  59. app.Usage = usage
  60. return app
  61. }
  62. // These are all the command line flags we support.
  63. // If you add to this list, please remember to include the
  64. // flag in the appropriate command definition.
  65. //
  66. // The flags are defined here so their names and help texts
  67. // are the same for all commands.
  68. var (
  69. // General settings
  70. DataDirFlag = DirectoryFlag{
  71. Name: "datadir",
  72. Usage: "Data directory to be used",
  73. Value: DirectoryString{common.DefaultDataDir()},
  74. }
  75. NetworkIdFlag = cli.IntFlag{
  76. Name: "networkid",
  77. Usage: "Network Id (integer)",
  78. Value: eth.NetworkId,
  79. }
  80. BlockchainVersionFlag = cli.IntFlag{
  81. Name: "blockchainversion",
  82. Usage: "Blockchain version (integer)",
  83. Value: core.BlockChainVersion,
  84. }
  85. GenesisNonceFlag = cli.IntFlag{
  86. Name: "genesisnonce",
  87. Usage: "Sets the genesis nonce",
  88. Value: 42,
  89. }
  90. IdentityFlag = cli.StringFlag{
  91. Name: "identity",
  92. Usage: "Custom node name",
  93. }
  94. NatspecEnabledFlag = cli.BoolFlag{
  95. Name: "natspec",
  96. Usage: "Enable NatSpec confirmation notice",
  97. }
  98. // miner settings
  99. MinerThreadsFlag = cli.IntFlag{
  100. Name: "minerthreads",
  101. Usage: "Number of miner threads",
  102. Value: runtime.NumCPU(),
  103. }
  104. MiningEnabledFlag = cli.BoolFlag{
  105. Name: "mine",
  106. Usage: "Enable mining",
  107. }
  108. AutoDAGFlag = cli.BoolFlag{
  109. Name: "autodag",
  110. Usage: "Enable automatic DAG pregeneration",
  111. }
  112. EtherbaseFlag = cli.StringFlag{
  113. Name: "etherbase",
  114. Usage: "Public address for block mining rewards. By default the address of your primary account is used",
  115. Value: "primary",
  116. }
  117. GasPriceFlag = cli.StringFlag{
  118. Name: "gasprice",
  119. Usage: "Sets the minimal gasprice when mining transactions",
  120. Value: new(big.Int).Mul(big.NewInt(1), common.Szabo).String(),
  121. }
  122. UnlockedAccountFlag = cli.StringFlag{
  123. Name: "unlock",
  124. Usage: "Unlock the account given until this program exits (prompts for password). '--unlock primary' unlocks the primary account",
  125. Value: "",
  126. }
  127. PasswordFileFlag = cli.StringFlag{
  128. Name: "password",
  129. Usage: "Path to password file to use with options and subcommands needing a password",
  130. Value: "",
  131. }
  132. // logging and debug settings
  133. LogFileFlag = cli.StringFlag{
  134. Name: "logfile",
  135. Usage: "Send log output to a file",
  136. }
  137. VerbosityFlag = cli.IntFlag{
  138. Name: "verbosity",
  139. Usage: "Logging verbosity: 0-6 (0=silent, 1=error, 2=warn, 3=info, 4=core, 5=debug, 6=debug detail)",
  140. Value: int(logger.InfoLevel),
  141. }
  142. LogJSONFlag = cli.StringFlag{
  143. Name: "logjson",
  144. Usage: "Send json structured log output to a file or '-' for standard output (default: no json output)",
  145. Value: "",
  146. }
  147. LogToStdErrFlag = cli.BoolFlag{
  148. Name: "logtostderr",
  149. Usage: "Logs are written to standard error instead of to files.",
  150. }
  151. LogVModuleFlag = cli.GenericFlag{
  152. Name: "vmodule",
  153. 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.",
  154. Value: glog.GetVModule(),
  155. }
  156. VMDebugFlag = cli.BoolFlag{
  157. Name: "vmdebug",
  158. Usage: "Virtual Machine debug output",
  159. }
  160. BacktraceAtFlag = cli.GenericFlag{
  161. Name: "backtrace_at",
  162. Usage: "If set to a file and line number (e.g., \"block.go:271\") holding a logging statement, a stack trace will be logged",
  163. Value: glog.GetTraceLocation(),
  164. }
  165. PProfEanbledFlag = cli.BoolFlag{
  166. Name: "pprof",
  167. Usage: "Enable the profiling server on localhost",
  168. }
  169. PProfPortFlag = cli.IntFlag{
  170. Name: "pprofport",
  171. Usage: "Port on which the profiler should listen",
  172. Value: 6060,
  173. }
  174. MetricsEnabledFlag = cli.BoolFlag{
  175. Name: metrics.MetricsEnabledFlag,
  176. Usage: "Enables metrics collection and reporting",
  177. }
  178. // RPC settings
  179. RPCEnabledFlag = cli.BoolFlag{
  180. Name: "rpc",
  181. Usage: "Enable the JSON-RPC server",
  182. }
  183. RPCListenAddrFlag = cli.StringFlag{
  184. Name: "rpcaddr",
  185. Usage: "Listening address for the JSON-RPC server",
  186. Value: "127.0.0.1",
  187. }
  188. RPCPortFlag = cli.IntFlag{
  189. Name: "rpcport",
  190. Usage: "Port on which the JSON-RPC server should listen",
  191. Value: 8545,
  192. }
  193. RPCCORSDomainFlag = cli.StringFlag{
  194. Name: "rpccorsdomain",
  195. Usage: "Domain on which to send Access-Control-Allow-Origin header",
  196. Value: "",
  197. }
  198. RpcApiFlag = cli.StringFlag{
  199. Name: "rpcapi",
  200. Usage: "Specify the API's which are offered over the HTTP RPC interface",
  201. Value: comms.DefaultHttpRpcApis,
  202. }
  203. IPCDisabledFlag = cli.BoolFlag{
  204. Name: "ipcdisable",
  205. Usage: "Disable the IPC-RPC server",
  206. }
  207. IPCApiFlag = cli.StringFlag{
  208. Name: "ipcapi",
  209. Usage: "Specify the API's which are offered over the IPC interface",
  210. Value: comms.DefaultIpcApis,
  211. }
  212. IPCPathFlag = DirectoryFlag{
  213. Name: "ipcpath",
  214. Usage: "Filename for IPC socket/pipe",
  215. Value: DirectoryString{common.DefaultIpcPath()},
  216. }
  217. ExecFlag = cli.StringFlag{
  218. Name: "exec",
  219. Usage: "Execute javascript statement (only in combination with console/attach)",
  220. }
  221. // Network Settings
  222. MaxPeersFlag = cli.IntFlag{
  223. Name: "maxpeers",
  224. Usage: "Maximum number of network peers (network disabled if set to 0)",
  225. Value: 25,
  226. }
  227. MaxPendingPeersFlag = cli.IntFlag{
  228. Name: "maxpendpeers",
  229. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  230. Value: 0,
  231. }
  232. ListenPortFlag = cli.IntFlag{
  233. Name: "port",
  234. Usage: "Network listening port",
  235. Value: 30303,
  236. }
  237. BootnodesFlag = cli.StringFlag{
  238. Name: "bootnodes",
  239. Usage: "Space-separated enode URLs for p2p discovery bootstrap",
  240. Value: "",
  241. }
  242. NodeKeyFileFlag = cli.StringFlag{
  243. Name: "nodekey",
  244. Usage: "P2P node key file",
  245. }
  246. NodeKeyHexFlag = cli.StringFlag{
  247. Name: "nodekeyhex",
  248. Usage: "P2P node key as hex (for testing)",
  249. }
  250. NATFlag = cli.StringFlag{
  251. Name: "nat",
  252. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  253. Value: "any",
  254. }
  255. NoDiscoverFlag = cli.BoolFlag{
  256. Name: "nodiscover",
  257. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  258. }
  259. WhisperEnabledFlag = cli.BoolFlag{
  260. Name: "shh",
  261. Usage: "Enable whisper",
  262. }
  263. // ATM the url is left to the user and deployment to
  264. JSpathFlag = cli.StringFlag{
  265. Name: "jspath",
  266. Usage: "JS library path to be used with console and js subcommands",
  267. Value: ".",
  268. }
  269. SolcPathFlag = cli.StringFlag{
  270. Name: "solc",
  271. Usage: "solidity compiler to be used",
  272. Value: "solc",
  273. }
  274. GpoMinGasPriceFlag = cli.StringFlag{
  275. Name: "gpomin",
  276. Usage: "Minimum suggested gas price",
  277. Value: new(big.Int).Mul(big.NewInt(1), common.Szabo).String(),
  278. }
  279. GpoMaxGasPriceFlag = cli.StringFlag{
  280. Name: "gpomax",
  281. Usage: "Maximum suggested gas price",
  282. Value: new(big.Int).Mul(big.NewInt(100), common.Szabo).String(),
  283. }
  284. GpoFullBlockRatioFlag = cli.IntFlag{
  285. Name: "gpofull",
  286. Usage: "Full block threshold for gas price calculation (%)",
  287. Value: 80,
  288. }
  289. GpobaseStepDownFlag = cli.IntFlag{
  290. Name: "gpobasedown",
  291. Usage: "Suggested gas price base step down ratio (1/1000)",
  292. Value: 10,
  293. }
  294. GpobaseStepUpFlag = cli.IntFlag{
  295. Name: "gpobaseup",
  296. Usage: "Suggested gas price base step up ratio (1/1000)",
  297. Value: 100,
  298. }
  299. GpobaseCorrectionFactorFlag = cli.IntFlag{
  300. Name: "gpobasecf",
  301. Usage: "Suggested gas price base correction factor (%)",
  302. Value: 110,
  303. }
  304. )
  305. // MakeNAT creates a port mapper from set command line flags.
  306. func MakeNAT(ctx *cli.Context) nat.Interface {
  307. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  308. if err != nil {
  309. Fatalf("Option %s: %v", NATFlag.Name, err)
  310. }
  311. return natif
  312. }
  313. // MakeNodeKey creates a node key from set command line flags.
  314. func MakeNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  315. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  316. var err error
  317. switch {
  318. case file != "" && hex != "":
  319. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  320. case file != "":
  321. if key, err = crypto.LoadECDSA(file); err != nil {
  322. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  323. }
  324. case hex != "":
  325. if key, err = crypto.HexToECDSA(hex); err != nil {
  326. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  327. }
  328. }
  329. return key
  330. }
  331. // MakeEthConfig creates ethereum options from set command line flags.
  332. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  333. customName := ctx.GlobalString(IdentityFlag.Name)
  334. if len(customName) > 0 {
  335. clientID += "/" + customName
  336. }
  337. return &eth.Config{
  338. Name: common.MakeName(clientID, version),
  339. DataDir: ctx.GlobalString(DataDirFlag.Name),
  340. GenesisNonce: ctx.GlobalInt(GenesisNonceFlag.Name),
  341. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  342. SkipBcVersionCheck: false,
  343. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  344. LogFile: ctx.GlobalString(LogFileFlag.Name),
  345. Verbosity: ctx.GlobalInt(VerbosityFlag.Name),
  346. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  347. Etherbase: ctx.GlobalString(EtherbaseFlag.Name),
  348. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  349. AccountManager: MakeAccountManager(ctx),
  350. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  351. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  352. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  353. Port: ctx.GlobalString(ListenPortFlag.Name),
  354. NAT: MakeNAT(ctx),
  355. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  356. Discovery: !ctx.GlobalBool(NoDiscoverFlag.Name),
  357. NodeKey: MakeNodeKey(ctx),
  358. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  359. Dial: true,
  360. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  361. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  362. GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
  363. GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
  364. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  365. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  366. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  367. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  368. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  369. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  370. }
  371. }
  372. // SetupLogger configures glog from the logging-related command line flags.
  373. func SetupLogger(ctx *cli.Context) {
  374. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  375. glog.CopyStandardLogTo("INFO")
  376. glog.SetToStderr(true)
  377. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  378. }
  379. // MakeChain creates a chain manager from set command line flags.
  380. func MakeChain(ctx *cli.Context) (chain *core.ChainManager, blockDB, stateDB, extraDB common.Database) {
  381. dd := ctx.GlobalString(DataDirFlag.Name)
  382. var err error
  383. if blockDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "blockchain")); err != nil {
  384. Fatalf("Could not open database: %v", err)
  385. }
  386. if stateDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "state")); err != nil {
  387. Fatalf("Could not open database: %v", err)
  388. }
  389. if extraDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "extra")); err != nil {
  390. Fatalf("Could not open database: %v", err)
  391. }
  392. eventMux := new(event.TypeMux)
  393. pow := ethash.New()
  394. genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  395. chain, err = core.NewChainManager(genesis, blockDB, stateDB, extraDB, pow, eventMux)
  396. if err != nil {
  397. Fatalf("Could not start chainmanager: %v", err)
  398. }
  399. proc := core.NewBlockProcessor(stateDB, extraDB, pow, chain, eventMux)
  400. chain.SetProcessor(proc)
  401. return chain, blockDB, stateDB, extraDB
  402. }
  403. // MakeChain creates an account manager from set command line flags.
  404. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  405. dataDir := ctx.GlobalString(DataDirFlag.Name)
  406. ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keystore"))
  407. return accounts.NewManager(ks)
  408. }
  409. func IpcSocketPath(ctx *cli.Context) (ipcpath string) {
  410. if common.IsWindows() {
  411. ipcpath = common.DefaultIpcPath()
  412. if ipcpath != ctx.GlobalString(IPCPathFlag.Name) {
  413. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  414. }
  415. } else {
  416. ipcpath = common.DefaultIpcPath()
  417. if ctx.GlobalString(IPCPathFlag.Name) != common.DefaultIpcPath() {
  418. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  419. } else if ctx.GlobalString(DataDirFlag.Name) != "" &&
  420. ctx.GlobalString(DataDirFlag.Name) != common.DefaultDataDir() {
  421. ipcpath = filepath.Join(ctx.GlobalString(DataDirFlag.Name), "geth.ipc")
  422. }
  423. }
  424. return
  425. }
  426. func StartIPC(eth *eth.Ethereum, ctx *cli.Context) error {
  427. config := comms.IpcConfig{
  428. Endpoint: IpcSocketPath(ctx),
  429. }
  430. xeth := xeth.New(eth, nil)
  431. codec := codec.JSON
  432. apis, err := api.ParseApiString(ctx.GlobalString(IPCApiFlag.Name), codec, xeth, eth)
  433. if err != nil {
  434. return err
  435. }
  436. return comms.StartIpc(config, codec, api.Merge(apis...))
  437. }
  438. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  439. config := comms.HttpConfig{
  440. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  441. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  442. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  443. }
  444. xeth := xeth.New(eth, nil)
  445. codec := codec.JSON
  446. apis, err := api.ParseApiString(ctx.GlobalString(RpcApiFlag.Name), codec, xeth, eth)
  447. if err != nil {
  448. return err
  449. }
  450. return comms.StartHttp(config, codec, api.Merge(apis...))
  451. }
  452. func StartPProf(ctx *cli.Context) {
  453. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  454. go func() {
  455. log.Println(http.ListenAndServe(address, nil))
  456. }()
  457. }