flags.go 16 KB

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