flags.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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"
  24. "github.com/ethereum/go-ethereum/xeth"
  25. "github.com/ethereum/go-ethereum/rpc/api"
  26. "github.com/ethereum/go-ethereum/rpc/comms"
  27. "github.com/ethereum/go-ethereum/rpc/codec"
  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. ProtocolVersionFlag = cli.IntFlag{
  76. Name: "protocolversion",
  77. Usage: "ETH protocol version (integer)",
  78. Value: eth.ProtocolVersion,
  79. }
  80. NetworkIdFlag = cli.IntFlag{
  81. Name: "networkid",
  82. Usage: "Network Id (integer)",
  83. Value: eth.NetworkId,
  84. }
  85. BlockchainVersionFlag = cli.IntFlag{
  86. Name: "blockchainversion",
  87. Usage: "Blockchain version (integer)",
  88. Value: core.BlockChainVersion,
  89. }
  90. GenesisNonceFlag = cli.IntFlag{
  91. Name: "genesisnonce",
  92. Usage: "Sets the genesis nonce",
  93. Value: 42,
  94. }
  95. IdentityFlag = cli.StringFlag{
  96. Name: "identity",
  97. Usage: "Custom node name",
  98. }
  99. NatspecEnabledFlag = cli.BoolFlag{
  100. Name: "natspec",
  101. Usage: "Enable NatSpec confirmation notice",
  102. }
  103. // miner settings
  104. MinerThreadsFlag = cli.IntFlag{
  105. Name: "minerthreads",
  106. Usage: "Number of miner threads",
  107. Value: runtime.NumCPU(),
  108. }
  109. MiningEnabledFlag = cli.BoolFlag{
  110. Name: "mine",
  111. Usage: "Enable mining",
  112. }
  113. AutoDAGFlag = cli.BoolFlag{
  114. Name: "autodag",
  115. Usage: "Enable automatic DAG pregeneration",
  116. }
  117. EtherbaseFlag = cli.StringFlag{
  118. Name: "etherbase",
  119. Usage: "Public address for block mining rewards. By default the address of your primary account is used",
  120. Value: "primary",
  121. }
  122. GasPriceFlag = cli.StringFlag{
  123. Name: "gasprice",
  124. Usage: "Sets the minimal gasprice when mining transactions",
  125. Value: new(big.Int).Mul(big.NewInt(10), common.Szabo).String(),
  126. }
  127. UnlockedAccountFlag = cli.StringFlag{
  128. Name: "unlock",
  129. Usage: "Unlock the account given until this program exits (prompts for password). '--unlock primary' unlocks the primary account",
  130. Value: "",
  131. }
  132. PasswordFileFlag = cli.StringFlag{
  133. Name: "password",
  134. Usage: "Path to password file to use with options and subcommands needing a password",
  135. Value: "",
  136. }
  137. // logging and debug settings
  138. LogFileFlag = cli.StringFlag{
  139. Name: "logfile",
  140. Usage: "Send log output to a file",
  141. }
  142. VerbosityFlag = cli.IntFlag{
  143. Name: "verbosity",
  144. Usage: "Logging verbosity: 0-6 (0=silent, 1=error, 2=warn, 3=info, 4=core, 5=debug, 6=debug detail)",
  145. Value: int(logger.InfoLevel),
  146. }
  147. LogJSONFlag = cli.StringFlag{
  148. Name: "logjson",
  149. Usage: "Send json structured log output to a file or '-' for standard output (default: no json output)",
  150. Value: "",
  151. }
  152. LogToStdErrFlag = cli.BoolFlag{
  153. Name: "logtostderr",
  154. Usage: "Logs are written to standard error instead of to files.",
  155. }
  156. LogVModuleFlag = cli.GenericFlag{
  157. Name: "vmodule",
  158. 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.",
  159. Value: glog.GetVModule(),
  160. }
  161. VMDebugFlag = cli.BoolFlag{
  162. Name: "vmdebug",
  163. Usage: "Virtual Machine debug output",
  164. }
  165. BacktraceAtFlag = cli.GenericFlag{
  166. Name: "backtrace_at",
  167. Usage: "If set to a file and line number (e.g., \"block.go:271\") holding a logging statement, a stack trace will be logged",
  168. Value: glog.GetTraceLocation(),
  169. }
  170. PProfEanbledFlag = cli.BoolFlag{
  171. Name: "pprof",
  172. Usage: "Enable the profiling server on localhost",
  173. }
  174. PProfPortFlag = cli.IntFlag{
  175. Name: "pprofport",
  176. Usage: "Port on which the profiler should listen",
  177. Value: 6060,
  178. }
  179. // RPC settings
  180. RPCEnabledFlag = cli.BoolFlag{
  181. Name: "rpc",
  182. Usage: "Enable the JSON-RPC server",
  183. }
  184. RPCListenAddrFlag = cli.StringFlag{
  185. Name: "rpcaddr",
  186. Usage: "Listening address for the JSON-RPC server",
  187. Value: "127.0.0.1",
  188. }
  189. RPCPortFlag = cli.IntFlag{
  190. Name: "rpcport",
  191. Usage: "Port on which the JSON-RPC server should listen",
  192. Value: 8545,
  193. }
  194. RPCCORSDomainFlag = cli.StringFlag{
  195. Name: "rpccorsdomain",
  196. Usage: "Domain on which to send Access-Control-Allow-Origin header",
  197. Value: "",
  198. }
  199. IPCDisabledFlag = cli.BoolFlag{
  200. Name: "ipcdisable",
  201. Usage: "Disable the IPC-RPC server",
  202. }
  203. IPCApiFlag = cli.StringFlag{
  204. Name: "ipcapi",
  205. Usage: "Specify the API's which are offered over this interface",
  206. Value: api.DefaultIpcApis,
  207. }
  208. IPCPathFlag = DirectoryFlag{
  209. Name: "ipcpath",
  210. Usage: "Filename for IPC socket/pipe",
  211. Value: DirectoryString{common.DefaultIpcPath()},
  212. }
  213. // Network Settings
  214. MaxPeersFlag = cli.IntFlag{
  215. Name: "maxpeers",
  216. Usage: "Maximum number of network peers (network disabled if set to 0)",
  217. Value: 25,
  218. }
  219. MaxPendingPeersFlag = cli.IntFlag{
  220. Name: "maxpendpeers",
  221. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  222. Value: 0,
  223. }
  224. ListenPortFlag = cli.IntFlag{
  225. Name: "port",
  226. Usage: "Network listening port",
  227. Value: 30303,
  228. }
  229. BootnodesFlag = cli.StringFlag{
  230. Name: "bootnodes",
  231. Usage: "Space-separated enode URLs for p2p discovery bootstrap",
  232. Value: "",
  233. }
  234. NodeKeyFileFlag = cli.StringFlag{
  235. Name: "nodekey",
  236. Usage: "P2P node key file",
  237. }
  238. NodeKeyHexFlag = cli.StringFlag{
  239. Name: "nodekeyhex",
  240. Usage: "P2P node key as hex (for testing)",
  241. }
  242. NATFlag = cli.StringFlag{
  243. Name: "nat",
  244. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  245. Value: "any",
  246. }
  247. NoDiscoverFlag = cli.BoolFlag{
  248. Name: "nodiscover",
  249. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  250. }
  251. WhisperEnabledFlag = cli.BoolFlag{
  252. Name: "shh",
  253. Usage: "Enable whisper",
  254. }
  255. // ATM the url is left to the user and deployment to
  256. JSpathFlag = cli.StringFlag{
  257. Name: "jspath",
  258. Usage: "JS library path to be used with console and js subcommands",
  259. Value: ".",
  260. }
  261. SolcPathFlag = cli.StringFlag{
  262. Name: "solc",
  263. Usage: "solidity compiler to be used",
  264. Value: "solc",
  265. }
  266. )
  267. // MakeNAT creates a port mapper from set command line flags.
  268. func MakeNAT(ctx *cli.Context) nat.Interface {
  269. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  270. if err != nil {
  271. Fatalf("Option %s: %v", NATFlag.Name, err)
  272. }
  273. return natif
  274. }
  275. // MakeNodeKey creates a node key from set command line flags.
  276. func MakeNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  277. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  278. var err error
  279. switch {
  280. case file != "" && hex != "":
  281. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  282. case file != "":
  283. if key, err = crypto.LoadECDSA(file); err != nil {
  284. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  285. }
  286. case hex != "":
  287. if key, err = crypto.HexToECDSA(hex); err != nil {
  288. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  289. }
  290. }
  291. return key
  292. }
  293. // MakeEthConfig creates ethereum options from set command line flags.
  294. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  295. customName := ctx.GlobalString(IdentityFlag.Name)
  296. if len(customName) > 0 {
  297. clientID += "/" + customName
  298. }
  299. return &eth.Config{
  300. Name: common.MakeName(clientID, version),
  301. DataDir: ctx.GlobalString(DataDirFlag.Name),
  302. ProtocolVersion: ctx.GlobalInt(ProtocolVersionFlag.Name),
  303. GenesisNonce: ctx.GlobalInt(GenesisNonceFlag.Name),
  304. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  305. SkipBcVersionCheck: false,
  306. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  307. LogFile: ctx.GlobalString(LogFileFlag.Name),
  308. Verbosity: ctx.GlobalInt(VerbosityFlag.Name),
  309. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  310. Etherbase: ctx.GlobalString(EtherbaseFlag.Name),
  311. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  312. AccountManager: MakeAccountManager(ctx),
  313. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  314. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  315. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  316. Port: ctx.GlobalString(ListenPortFlag.Name),
  317. NAT: MakeNAT(ctx),
  318. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  319. Discovery: !ctx.GlobalBool(NoDiscoverFlag.Name),
  320. NodeKey: MakeNodeKey(ctx),
  321. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  322. Dial: true,
  323. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  324. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  325. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  326. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  327. }
  328. }
  329. // SetupLogger configures glog from the logging-related command line flags.
  330. func SetupLogger(ctx *cli.Context) {
  331. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  332. glog.CopyStandardLogTo("INFO")
  333. glog.SetToStderr(true)
  334. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  335. }
  336. // MakeChain creates a chain manager from set command line flags.
  337. func MakeChain(ctx *cli.Context) (chain *core.ChainManager, blockDB, stateDB, extraDB common.Database) {
  338. dd := ctx.GlobalString(DataDirFlag.Name)
  339. var err error
  340. if blockDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "blockchain")); err != nil {
  341. Fatalf("Could not open database: %v", err)
  342. }
  343. if stateDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "state")); err != nil {
  344. Fatalf("Could not open database: %v", err)
  345. }
  346. if extraDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "extra")); err != nil {
  347. Fatalf("Could not open database: %v", err)
  348. }
  349. eventMux := new(event.TypeMux)
  350. pow := ethash.New()
  351. genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  352. chain, err = core.NewChainManager(genesis, blockDB, stateDB, pow, eventMux)
  353. if err != nil {
  354. Fatalf("Could not start chainmanager: %v", err)
  355. }
  356. proc := core.NewBlockProcessor(stateDB, extraDB, pow, chain, eventMux)
  357. chain.SetProcessor(proc)
  358. return chain, blockDB, stateDB, extraDB
  359. }
  360. // MakeChain creates an account manager from set command line flags.
  361. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  362. dataDir := ctx.GlobalString(DataDirFlag.Name)
  363. ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keystore"))
  364. return accounts.NewManager(ks)
  365. }
  366. func IpcSocketPath(ctx *cli.Context) (ipcpath string) {
  367. if common.IsWindows() {
  368. ipcpath = common.DefaultIpcPath()
  369. if ipcpath != ctx.GlobalString(IPCPathFlag.Name) {
  370. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  371. }
  372. } else {
  373. ipcpath = common.DefaultIpcPath()
  374. if ctx.GlobalString(IPCPathFlag.Name) != common.DefaultIpcPath() {
  375. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  376. } else if ctx.GlobalString(DataDirFlag.Name) != "" &&
  377. ctx.GlobalString(DataDirFlag.Name) != common.DefaultDataDir() {
  378. ipcpath = filepath.Join(ctx.GlobalString(DataDirFlag.Name), "geth.ipc")
  379. }
  380. }
  381. return
  382. }
  383. func StartIPC(eth *eth.Ethereum, ctx *cli.Context) error {
  384. config := comms.IpcConfig{
  385. Endpoint: IpcSocketPath(ctx),
  386. }
  387. xeth := xeth.New(eth, nil)
  388. codec := codec.JSON
  389. apis, err := api.ParseApiString(ctx.GlobalString(IPCApiFlag.Name), codec, xeth, eth)
  390. if err != nil {
  391. return err
  392. }
  393. return comms.StartIpc(config, codec, apis...)
  394. }
  395. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  396. config := rpc.RpcConfig{
  397. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  398. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  399. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  400. }
  401. xeth := xeth.New(eth, nil)
  402. return rpc.Start(xeth, config)
  403. }
  404. func StartPProf(ctx *cli.Context) {
  405. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  406. go func() {
  407. log.Println(http.ListenAndServe(address, nil))
  408. }()
  409. }