flags.go 15 KB

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