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/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: 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. ProtocolVersion: ctx.GlobalInt(ProtocolVersionFlag.Name),
  341. GenesisNonce: ctx.GlobalInt(GenesisNonceFlag.Name),
  342. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  343. SkipBcVersionCheck: false,
  344. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  345. LogFile: ctx.GlobalString(LogFileFlag.Name),
  346. Verbosity: ctx.GlobalInt(VerbosityFlag.Name),
  347. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  348. Etherbase: ctx.GlobalString(EtherbaseFlag.Name),
  349. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  350. AccountManager: MakeAccountManager(ctx),
  351. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  352. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  353. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  354. Port: ctx.GlobalString(ListenPortFlag.Name),
  355. NAT: MakeNAT(ctx),
  356. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  357. Discovery: !ctx.GlobalBool(NoDiscoverFlag.Name),
  358. NodeKey: MakeNodeKey(ctx),
  359. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  360. Dial: true,
  361. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  362. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  363. GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
  364. GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
  365. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  366. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  367. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  368. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  369. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  370. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  371. }
  372. }
  373. // SetupLogger configures glog from the logging-related command line flags.
  374. func SetupLogger(ctx *cli.Context) {
  375. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  376. glog.CopyStandardLogTo("INFO")
  377. glog.SetToStderr(true)
  378. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  379. }
  380. // MakeChain creates a chain manager from set command line flags.
  381. func MakeChain(ctx *cli.Context) (chain *core.ChainManager, blockDB, stateDB, extraDB common.Database) {
  382. dd := ctx.GlobalString(DataDirFlag.Name)
  383. var err error
  384. if blockDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "blockchain")); err != nil {
  385. Fatalf("Could not open database: %v", err)
  386. }
  387. if stateDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "state")); err != nil {
  388. Fatalf("Could not open database: %v", err)
  389. }
  390. if extraDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "extra")); err != nil {
  391. Fatalf("Could not open database: %v", err)
  392. }
  393. eventMux := new(event.TypeMux)
  394. pow := ethash.New()
  395. genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  396. chain, err = core.NewChainManager(genesis, blockDB, stateDB, pow, eventMux)
  397. if err != nil {
  398. Fatalf("Could not start chainmanager: %v", err)
  399. }
  400. proc := core.NewBlockProcessor(stateDB, extraDB, pow, chain, eventMux)
  401. chain.SetProcessor(proc)
  402. return chain, blockDB, stateDB, extraDB
  403. }
  404. // MakeChain creates an account manager from set command line flags.
  405. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  406. dataDir := ctx.GlobalString(DataDirFlag.Name)
  407. ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keystore"))
  408. return accounts.NewManager(ks)
  409. }
  410. func IpcSocketPath(ctx *cli.Context) (ipcpath string) {
  411. if common.IsWindows() {
  412. ipcpath = common.DefaultIpcPath()
  413. if ipcpath != ctx.GlobalString(IPCPathFlag.Name) {
  414. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  415. }
  416. } else {
  417. ipcpath = common.DefaultIpcPath()
  418. if ctx.GlobalString(IPCPathFlag.Name) != common.DefaultIpcPath() {
  419. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  420. } else if ctx.GlobalString(DataDirFlag.Name) != "" &&
  421. ctx.GlobalString(DataDirFlag.Name) != common.DefaultDataDir() {
  422. ipcpath = filepath.Join(ctx.GlobalString(DataDirFlag.Name), "geth.ipc")
  423. }
  424. }
  425. return
  426. }
  427. func StartIPC(eth *eth.Ethereum, ctx *cli.Context) error {
  428. config := comms.IpcConfig{
  429. Endpoint: IpcSocketPath(ctx),
  430. }
  431. xeth := xeth.New(eth, nil)
  432. codec := codec.JSON
  433. apis, err := api.ParseApiString(ctx.GlobalString(IPCApiFlag.Name), codec, xeth, eth)
  434. if err != nil {
  435. return err
  436. }
  437. return comms.StartIpc(config, codec, apis...)
  438. }
  439. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  440. config := comms.HttpConfig{
  441. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  442. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  443. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  444. }
  445. xeth := xeth.New(eth, nil)
  446. codec := codec.JSON
  447. apis, err := api.ParseApiString(ctx.GlobalString(RpcApiFlag.Name), codec, xeth, eth)
  448. if err != nil {
  449. return err
  450. }
  451. return comms.StartHttp(config, codec, apis...)
  452. }
  453. func StartPProf(ctx *cli.Context) {
  454. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  455. go func() {
  456. log.Println(http.ListenAndServe(address, nil))
  457. }()
  458. }