flags.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. GenesisFileFlag = cli.StringFlag{
  107. Name: "genesis",
  108. Usage: "Inserts/Overwrites the genesis block (json format)",
  109. }
  110. IdentityFlag = cli.StringFlag{
  111. Name: "identity",
  112. Usage: "Custom node name",
  113. }
  114. NatspecEnabledFlag = cli.BoolFlag{
  115. Name: "natspec",
  116. Usage: "Enable NatSpec confirmation notice",
  117. }
  118. // miner settings
  119. MinerThreadsFlag = cli.IntFlag{
  120. Name: "minerthreads",
  121. Usage: "Number of miner threads",
  122. Value: runtime.NumCPU(),
  123. }
  124. MiningEnabledFlag = cli.BoolFlag{
  125. Name: "mine",
  126. Usage: "Enable mining",
  127. }
  128. AutoDAGFlag = cli.BoolFlag{
  129. Name: "autodag",
  130. Usage: "Enable automatic DAG pregeneration",
  131. }
  132. EtherbaseFlag = cli.StringFlag{
  133. Name: "etherbase",
  134. Usage: "Public address for block mining rewards. By default the address first created is used",
  135. Value: "0",
  136. }
  137. GasPriceFlag = cli.StringFlag{
  138. Name: "gasprice",
  139. Usage: "Sets the minimal gasprice when mining transactions",
  140. Value: new(big.Int).Mul(big.NewInt(1), common.Szabo).String(),
  141. }
  142. UnlockedAccountFlag = cli.StringFlag{
  143. Name: "unlock",
  144. Usage: "Unlock the account given until this program exits (prompts for password). '--unlock n' unlocks the n-th account in order or creation.",
  145. Value: "",
  146. }
  147. PasswordFileFlag = cli.StringFlag{
  148. Name: "password",
  149. Usage: "Path to password file to use with options and subcommands needing a password",
  150. Value: "",
  151. }
  152. // logging and debug settings
  153. LogFileFlag = cli.StringFlag{
  154. Name: "logfile",
  155. Usage: "Send log output to a file",
  156. }
  157. VerbosityFlag = cli.IntFlag{
  158. Name: "verbosity",
  159. Usage: "Logging verbosity: 0-6 (0=silent, 1=error, 2=warn, 3=info, 4=core, 5=debug, 6=debug detail)",
  160. Value: int(logger.InfoLevel),
  161. }
  162. LogJSONFlag = cli.StringFlag{
  163. Name: "logjson",
  164. Usage: "Send json structured log output to a file or '-' for standard output (default: no json output)",
  165. Value: "",
  166. }
  167. LogToStdErrFlag = cli.BoolFlag{
  168. Name: "logtostderr",
  169. Usage: "Logs are written to standard error instead of to files.",
  170. }
  171. LogVModuleFlag = cli.GenericFlag{
  172. Name: "vmodule",
  173. 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.",
  174. Value: glog.GetVModule(),
  175. }
  176. VMDebugFlag = cli.BoolFlag{
  177. Name: "vmdebug",
  178. Usage: "Virtual Machine debug output",
  179. }
  180. BacktraceAtFlag = cli.GenericFlag{
  181. Name: "backtrace_at",
  182. Usage: "If set to a file and line number (e.g., \"block.go:271\") holding a logging statement, a stack trace will be logged",
  183. Value: glog.GetTraceLocation(),
  184. }
  185. PProfEanbledFlag = cli.BoolFlag{
  186. Name: "pprof",
  187. Usage: "Enable the profiling server on localhost",
  188. }
  189. PProfPortFlag = cli.IntFlag{
  190. Name: "pprofport",
  191. Usage: "Port on which the profiler should listen",
  192. Value: 6060,
  193. }
  194. MetricsEnabledFlag = cli.BoolFlag{
  195. Name: metrics.MetricsEnabledFlag,
  196. Usage: "Enables metrics collection and reporting",
  197. }
  198. // RPC settings
  199. RPCEnabledFlag = cli.BoolFlag{
  200. Name: "rpc",
  201. Usage: "Enable the JSON-RPC server",
  202. }
  203. RPCListenAddrFlag = cli.StringFlag{
  204. Name: "rpcaddr",
  205. Usage: "Listening address for the JSON-RPC server",
  206. Value: "127.0.0.1",
  207. }
  208. RPCPortFlag = cli.IntFlag{
  209. Name: "rpcport",
  210. Usage: "Port on which the JSON-RPC server should listen",
  211. Value: 8545,
  212. }
  213. RPCCORSDomainFlag = cli.StringFlag{
  214. Name: "rpccorsdomain",
  215. Usage: "Domain on which to send Access-Control-Allow-Origin header",
  216. Value: "",
  217. }
  218. RpcApiFlag = cli.StringFlag{
  219. Name: "rpcapi",
  220. Usage: "Specify the API's which are offered over the HTTP RPC interface",
  221. Value: comms.DefaultHttpRpcApis,
  222. }
  223. IPCDisabledFlag = cli.BoolFlag{
  224. Name: "ipcdisable",
  225. Usage: "Disable the IPC-RPC server",
  226. }
  227. IPCApiFlag = cli.StringFlag{
  228. Name: "ipcapi",
  229. Usage: "Specify the API's which are offered over the IPC interface",
  230. Value: comms.DefaultIpcApis,
  231. }
  232. IPCPathFlag = DirectoryFlag{
  233. Name: "ipcpath",
  234. Usage: "Filename for IPC socket/pipe",
  235. Value: DirectoryString{common.DefaultIpcPath()},
  236. }
  237. ExecFlag = cli.StringFlag{
  238. Name: "exec",
  239. Usage: "Execute javascript statement (only in combination with console/attach)",
  240. }
  241. // Network Settings
  242. MaxPeersFlag = cli.IntFlag{
  243. Name: "maxpeers",
  244. Usage: "Maximum number of network peers (network disabled if set to 0)",
  245. Value: 25,
  246. }
  247. MaxPendingPeersFlag = cli.IntFlag{
  248. Name: "maxpendpeers",
  249. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  250. Value: 0,
  251. }
  252. ListenPortFlag = cli.IntFlag{
  253. Name: "port",
  254. Usage: "Network listening port",
  255. Value: 30303,
  256. }
  257. BootnodesFlag = cli.StringFlag{
  258. Name: "bootnodes",
  259. Usage: "Space-separated enode URLs for p2p discovery bootstrap",
  260. Value: "",
  261. }
  262. NodeKeyFileFlag = cli.StringFlag{
  263. Name: "nodekey",
  264. Usage: "P2P node key file",
  265. }
  266. NodeKeyHexFlag = cli.StringFlag{
  267. Name: "nodekeyhex",
  268. Usage: "P2P node key as hex (for testing)",
  269. }
  270. NATFlag = cli.StringFlag{
  271. Name: "nat",
  272. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  273. Value: "any",
  274. }
  275. NoDiscoverFlag = cli.BoolFlag{
  276. Name: "nodiscover",
  277. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  278. }
  279. WhisperEnabledFlag = cli.BoolFlag{
  280. Name: "shh",
  281. Usage: "Enable whisper",
  282. }
  283. // ATM the url is left to the user and deployment to
  284. JSpathFlag = cli.StringFlag{
  285. Name: "jspath",
  286. Usage: "JS library path to be used with console and js subcommands",
  287. Value: ".",
  288. }
  289. SolcPathFlag = cli.StringFlag{
  290. Name: "solc",
  291. Usage: "solidity compiler to be used",
  292. Value: "solc",
  293. }
  294. GpoMinGasPriceFlag = cli.StringFlag{
  295. Name: "gpomin",
  296. Usage: "Minimum suggested gas price",
  297. Value: new(big.Int).Mul(big.NewInt(1), common.Szabo).String(),
  298. }
  299. GpoMaxGasPriceFlag = cli.StringFlag{
  300. Name: "gpomax",
  301. Usage: "Maximum suggested gas price",
  302. Value: new(big.Int).Mul(big.NewInt(100), common.Szabo).String(),
  303. }
  304. GpoFullBlockRatioFlag = cli.IntFlag{
  305. Name: "gpofull",
  306. Usage: "Full block threshold for gas price calculation (%)",
  307. Value: 80,
  308. }
  309. GpobaseStepDownFlag = cli.IntFlag{
  310. Name: "gpobasedown",
  311. Usage: "Suggested gas price base step down ratio (1/1000)",
  312. Value: 10,
  313. }
  314. GpobaseStepUpFlag = cli.IntFlag{
  315. Name: "gpobaseup",
  316. Usage: "Suggested gas price base step up ratio (1/1000)",
  317. Value: 100,
  318. }
  319. GpobaseCorrectionFactorFlag = cli.IntFlag{
  320. Name: "gpobasecf",
  321. Usage: "Suggested gas price base correction factor (%)",
  322. Value: 110,
  323. }
  324. )
  325. // MakeNAT creates a port mapper from set command line flags.
  326. func MakeNAT(ctx *cli.Context) nat.Interface {
  327. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  328. if err != nil {
  329. Fatalf("Option %s: %v", NATFlag.Name, err)
  330. }
  331. return natif
  332. }
  333. // MakeNodeKey creates a node key from set command line flags.
  334. func MakeNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  335. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  336. var err error
  337. switch {
  338. case file != "" && hex != "":
  339. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  340. case file != "":
  341. if key, err = crypto.LoadECDSA(file); err != nil {
  342. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  343. }
  344. case hex != "":
  345. if key, err = crypto.HexToECDSA(hex); err != nil {
  346. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  347. }
  348. }
  349. return key
  350. }
  351. // MakeEthConfig creates ethereum options from set command line flags.
  352. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  353. customName := ctx.GlobalString(IdentityFlag.Name)
  354. if len(customName) > 0 {
  355. clientID += "/" + customName
  356. }
  357. am := MakeAccountManager(ctx)
  358. etherbase, err := ParamToAddress(ctx.GlobalString(EtherbaseFlag.Name), am)
  359. if err != nil {
  360. glog.V(logger.Error).Infoln("WARNING: No etherbase set and no accounts found as default")
  361. }
  362. return &eth.Config{
  363. Name: common.MakeName(clientID, version),
  364. DataDir: ctx.GlobalString(DataDirFlag.Name),
  365. GenesisNonce: ctx.GlobalInt(GenesisNonceFlag.Name),
  366. GenesisFile: ctx.GlobalString(GenesisFileFlag.Name),
  367. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  368. SkipBcVersionCheck: false,
  369. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  370. LogFile: ctx.GlobalString(LogFileFlag.Name),
  371. Verbosity: ctx.GlobalInt(VerbosityFlag.Name),
  372. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  373. Etherbase: common.HexToAddress(etherbase),
  374. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  375. AccountManager: am,
  376. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  377. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  378. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  379. Port: ctx.GlobalString(ListenPortFlag.Name),
  380. NAT: MakeNAT(ctx),
  381. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  382. Discovery: !ctx.GlobalBool(NoDiscoverFlag.Name),
  383. NodeKey: MakeNodeKey(ctx),
  384. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  385. Dial: true,
  386. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  387. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  388. GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
  389. GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
  390. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  391. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  392. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  393. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  394. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  395. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  396. }
  397. }
  398. // SetupLogger configures glog from the logging-related command line flags.
  399. func SetupLogger(ctx *cli.Context) {
  400. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  401. glog.CopyStandardLogTo("INFO")
  402. glog.SetToStderr(true)
  403. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  404. }
  405. // MakeChain creates a chain manager from set command line flags.
  406. func MakeChain(ctx *cli.Context) (chain *core.ChainManager, blockDB, stateDB, extraDB common.Database) {
  407. dd := ctx.GlobalString(DataDirFlag.Name)
  408. var err error
  409. if blockDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "blockchain")); err != nil {
  410. Fatalf("Could not open database: %v", err)
  411. }
  412. if stateDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "state")); err != nil {
  413. Fatalf("Could not open database: %v", err)
  414. }
  415. if extraDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "extra")); err != nil {
  416. Fatalf("Could not open database: %v", err)
  417. }
  418. eventMux := new(event.TypeMux)
  419. pow := ethash.New()
  420. //genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  421. chain, err = core.NewChainManager(blockDB, stateDB, extraDB, pow, eventMux)
  422. if err != nil {
  423. Fatalf("Could not start chainmanager: %v", err)
  424. }
  425. proc := core.NewBlockProcessor(stateDB, extraDB, pow, chain, eventMux)
  426. chain.SetProcessor(proc)
  427. return chain, blockDB, stateDB, extraDB
  428. }
  429. // MakeChain creates an account manager from set command line flags.
  430. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  431. dataDir := ctx.GlobalString(DataDirFlag.Name)
  432. ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keystore"))
  433. return accounts.NewManager(ks)
  434. }
  435. func IpcSocketPath(ctx *cli.Context) (ipcpath string) {
  436. if common.IsWindows() {
  437. ipcpath = common.DefaultIpcPath()
  438. if ctx.GlobalIsSet(IPCPathFlag.Name) {
  439. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  440. }
  441. } else {
  442. ipcpath = common.DefaultIpcPath()
  443. if ctx.GlobalIsSet(DataDirFlag.Name) {
  444. ipcpath = filepath.Join(ctx.GlobalString(DataDirFlag.Name), "geth.ipc")
  445. }
  446. if ctx.GlobalIsSet(IPCPathFlag.Name) {
  447. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  448. }
  449. }
  450. return
  451. }
  452. func StartIPC(eth *eth.Ethereum, ctx *cli.Context) error {
  453. config := comms.IpcConfig{
  454. Endpoint: IpcSocketPath(ctx),
  455. }
  456. xeth := xeth.New(eth, nil)
  457. codec := codec.JSON
  458. apis, err := api.ParseApiString(ctx.GlobalString(IPCApiFlag.Name), codec, xeth, eth)
  459. if err != nil {
  460. return err
  461. }
  462. return comms.StartIpc(config, codec, api.Merge(apis...))
  463. }
  464. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  465. config := comms.HttpConfig{
  466. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  467. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  468. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  469. }
  470. xeth := xeth.New(eth, nil)
  471. codec := codec.JSON
  472. apis, err := api.ParseApiString(ctx.GlobalString(RpcApiFlag.Name), codec, xeth, eth)
  473. if err != nil {
  474. return err
  475. }
  476. return comms.StartHttp(config, codec, api.Merge(apis...))
  477. }
  478. func StartPProf(ctx *cli.Context) {
  479. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  480. go func() {
  481. log.Println(http.ListenAndServe(address, nil))
  482. }()
  483. }
  484. func ParamToAddress(addr string, am *accounts.Manager) (addrHex string, err error) {
  485. if !((len(addr) == 40) || (len(addr) == 42)) { // with or without 0x
  486. index, err := strconv.Atoi(addr)
  487. if err != nil {
  488. Fatalf("Invalid account address '%s'", addr)
  489. }
  490. addrHex, err = am.AddressByIndex(index)
  491. if err != nil {
  492. return "", err
  493. }
  494. } else {
  495. addrHex = addr
  496. }
  497. return
  498. }