flags.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. package utils
  2. import (
  3. "crypto/ecdsa"
  4. "fmt"
  5. "log"
  6. "math/big"
  7. "net/http"
  8. "os"
  9. "runtime"
  10. "path/filepath"
  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. )
  26. func init() {
  27. cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
  28. VERSION:
  29. {{.Version}}
  30. COMMANDS:
  31. {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  32. {{end}}{{if .Flags}}
  33. GLOBAL OPTIONS:
  34. {{range .Flags}}{{.}}
  35. {{end}}{{end}}
  36. `
  37. cli.CommandHelpTemplate = `{{.Name}}{{if .Subcommands}} command{{end}}{{if .Flags}} [command options]{{end}} [arguments...]
  38. {{if .Description}}{{.Description}}
  39. {{end}}{{if .Subcommands}}
  40. SUBCOMMANDS:
  41. {{range .Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  42. {{end}}{{end}}{{if .Flags}}
  43. OPTIONS:
  44. {{range .Flags}}{{.}}
  45. {{end}}{{end}}
  46. `
  47. }
  48. // NewApp creates an app with sane defaults.
  49. func NewApp(version, usage string) *cli.App {
  50. app := cli.NewApp()
  51. app.Name = filepath.Base(os.Args[0])
  52. app.Author = ""
  53. //app.Authors = nil
  54. app.Email = ""
  55. app.Version = version
  56. app.Usage = usage
  57. return app
  58. }
  59. // These are all the command line flags we support.
  60. // If you add to this list, please remember to include the
  61. // flag in the appropriate command definition.
  62. //
  63. // The flags are defined here so their names and help texts
  64. // are the same for all commands.
  65. var (
  66. // General settings
  67. DataDirFlag = DirectoryFlag{
  68. Name: "datadir",
  69. Usage: "Data directory to be used",
  70. Value: DirectoryString{common.DefaultDataDir()},
  71. }
  72. ProtocolVersionFlag = cli.IntFlag{
  73. Name: "protocolversion",
  74. Usage: "ETH protocol version (integer)",
  75. Value: eth.ProtocolVersion,
  76. }
  77. NetworkIdFlag = cli.IntFlag{
  78. Name: "networkid",
  79. Usage: "Network Id (integer)",
  80. Value: eth.NetworkId,
  81. }
  82. BlockchainVersionFlag = cli.IntFlag{
  83. Name: "blockchainversion",
  84. Usage: "Blockchain version (integer)",
  85. Value: core.BlockChainVersion,
  86. }
  87. IdentityFlag = cli.StringFlag{
  88. Name: "identity",
  89. Usage: "Custom node name",
  90. }
  91. NatspecEnabledFlag = cli.BoolFlag{
  92. Name: "natspec",
  93. Usage: "Enable NatSpec confirmation notice",
  94. }
  95. // miner settings
  96. MinerThreadsFlag = cli.IntFlag{
  97. Name: "minerthreads",
  98. Usage: "Number of miner threads",
  99. Value: runtime.NumCPU(),
  100. }
  101. MiningEnabledFlag = cli.BoolFlag{
  102. Name: "mine",
  103. Usage: "Enable mining",
  104. }
  105. EtherbaseFlag = cli.StringFlag{
  106. Name: "etherbase",
  107. Usage: "Public address for block mining rewards. By default the address of your primary account is used",
  108. Value: "primary",
  109. }
  110. GasPriceFlag = cli.StringFlag{
  111. Name: "gasprice",
  112. Usage: "Sets the minimal gasprice when mining transactions",
  113. Value: new(big.Int).Mul(big.NewInt(10), common.Szabo).String(),
  114. }
  115. UnlockedAccountFlag = cli.StringFlag{
  116. Name: "unlock",
  117. Usage: "Unlock the account given until this program exits (prompts for password). '--unlock primary' unlocks the primary account",
  118. Value: "",
  119. }
  120. PasswordFileFlag = cli.StringFlag{
  121. Name: "password",
  122. Usage: "Path to password file to use with options and subcommands needing a password",
  123. Value: "",
  124. }
  125. // logging and debug settings
  126. LogFileFlag = cli.StringFlag{
  127. Name: "logfile",
  128. Usage: "Send log output to a file",
  129. }
  130. VerbosityFlag = cli.IntFlag{
  131. Name: "verbosity",
  132. Usage: "Logging verbosity: 0-6 (0=silent, 1=error, 2=warn, 3=info, 4=core, 5=debug, 6=debug detail)",
  133. Value: int(logger.InfoLevel),
  134. }
  135. LogJSONFlag = cli.StringFlag{
  136. Name: "logjson",
  137. Usage: "Send json structured log output to a file or '-' for standard output (default: no json output)",
  138. Value: "",
  139. }
  140. LogToStdErrFlag = cli.BoolFlag{
  141. Name: "logtostderr",
  142. Usage: "Logs are written to standard error instead of to files.",
  143. }
  144. LogVModuleFlag = cli.GenericFlag{
  145. Name: "vmodule",
  146. 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.",
  147. Value: glog.GetVModule(),
  148. }
  149. VMDebugFlag = cli.BoolFlag{
  150. Name: "vmdebug",
  151. Usage: "Virtual Machine debug output",
  152. }
  153. BacktraceAtFlag = cli.GenericFlag{
  154. Name: "backtrace_at",
  155. Usage: "If set to a file and line number (e.g., \"block.go:271\") holding a logging statement, a stack trace will be logged",
  156. Value: glog.GetTraceLocation(),
  157. }
  158. PProfEanbledFlag = cli.BoolFlag{
  159. Name: "pprof",
  160. Usage: "Enable the profiling server on localhost",
  161. }
  162. PProfPortFlag = cli.IntFlag{
  163. Name: "pprofport",
  164. Usage: "Port on which the profiler should listen",
  165. Value: 6060,
  166. }
  167. // RPC settings
  168. RPCEnabledFlag = cli.BoolFlag{
  169. Name: "rpc",
  170. Usage: "Enable the JSON-RPC server",
  171. }
  172. RPCListenAddrFlag = cli.StringFlag{
  173. Name: "rpcaddr",
  174. Usage: "Listening address for the JSON-RPC server",
  175. Value: "127.0.0.1",
  176. }
  177. RPCPortFlag = cli.IntFlag{
  178. Name: "rpcport",
  179. Usage: "Port on which the JSON-RPC server should listen",
  180. Value: 8545,
  181. }
  182. RPCCORSDomainFlag = cli.StringFlag{
  183. Name: "rpccorsdomain",
  184. Usage: "Domain on which to send Access-Control-Allow-Origin header",
  185. Value: "",
  186. }
  187. // Network Settings
  188. MaxPeersFlag = cli.IntFlag{
  189. Name: "maxpeers",
  190. Usage: "Maximum number of network peers (network disabled if set to 0)",
  191. Value: 25,
  192. }
  193. MaxPendingPeersFlag = cli.IntFlag{
  194. Name: "maxpendpeers",
  195. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  196. Value: 0,
  197. }
  198. ListenPortFlag = cli.IntFlag{
  199. Name: "port",
  200. Usage: "Network listening port",
  201. Value: 30303,
  202. }
  203. BootnodesFlag = cli.StringFlag{
  204. Name: "bootnodes",
  205. Usage: "Space-separated enode URLs for p2p discovery bootstrap",
  206. Value: "",
  207. }
  208. NodeKeyFileFlag = cli.StringFlag{
  209. Name: "nodekey",
  210. Usage: "P2P node key file",
  211. }
  212. NodeKeyHexFlag = cli.StringFlag{
  213. Name: "nodekeyhex",
  214. Usage: "P2P node key as hex (for testing)",
  215. }
  216. NATFlag = cli.StringFlag{
  217. Name: "nat",
  218. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  219. Value: "any",
  220. }
  221. WhisperEnabledFlag = cli.BoolFlag{
  222. Name: "shh",
  223. Usage: "Enable whisper",
  224. }
  225. // ATM the url is left to the user and deployment to
  226. JSpathFlag = cli.StringFlag{
  227. Name: "jspath",
  228. Usage: "JS library path to be used with console and js subcommands",
  229. Value: ".",
  230. }
  231. SolcPathFlag = cli.StringFlag{
  232. Name: "solc",
  233. Usage: "solidity compiler to be used",
  234. Value: "solc",
  235. }
  236. )
  237. func GetNAT(ctx *cli.Context) nat.Interface {
  238. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  239. if err != nil {
  240. Fatalf("Option %s: %v", NATFlag.Name, err)
  241. }
  242. return natif
  243. }
  244. func GetNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  245. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  246. var err error
  247. switch {
  248. case file != "" && hex != "":
  249. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  250. case file != "":
  251. if key, err = crypto.LoadECDSA(file); err != nil {
  252. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  253. }
  254. case hex != "":
  255. if key, err = crypto.HexToECDSA(hex); err != nil {
  256. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  257. }
  258. }
  259. return key
  260. }
  261. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  262. // Set verbosity on glog
  263. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  264. // Set the log type
  265. //glog.SetToStderr(ctx.GlobalBool(LogToStdErrFlag.Name))
  266. glog.SetToStderr(true)
  267. // Set the log dir
  268. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  269. customName := ctx.GlobalString(IdentityFlag.Name)
  270. if len(customName) > 0 {
  271. clientID += "/" + customName
  272. }
  273. return &eth.Config{
  274. Name: common.MakeName(clientID, version),
  275. DataDir: ctx.GlobalString(DataDirFlag.Name),
  276. ProtocolVersion: ctx.GlobalInt(ProtocolVersionFlag.Name),
  277. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  278. SkipBcVersionCheck: false,
  279. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  280. LogFile: ctx.GlobalString(LogFileFlag.Name),
  281. Verbosity: ctx.GlobalInt(VerbosityFlag.Name),
  282. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  283. Etherbase: ctx.GlobalString(EtherbaseFlag.Name),
  284. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  285. AccountManager: GetAccountManager(ctx),
  286. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  287. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  288. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  289. Port: ctx.GlobalString(ListenPortFlag.Name),
  290. NAT: GetNAT(ctx),
  291. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  292. NodeKey: GetNodeKey(ctx),
  293. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  294. Dial: true,
  295. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  296. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  297. }
  298. }
  299. func GetChain(ctx *cli.Context) (*core.ChainManager, common.Database, common.Database) {
  300. dataDir := ctx.GlobalString(DataDirFlag.Name)
  301. blockDb, err := ethdb.NewLDBDatabase(filepath.Join(dataDir, "blockchain"))
  302. if err != nil {
  303. Fatalf("Could not open database: %v", err)
  304. }
  305. stateDb, err := ethdb.NewLDBDatabase(filepath.Join(dataDir, "state"))
  306. if err != nil {
  307. Fatalf("Could not open database: %v", err)
  308. }
  309. extraDb, err := ethdb.NewLDBDatabase(filepath.Join(dataDir, "extra"))
  310. if err != nil {
  311. Fatalf("Could not open database: %v", err)
  312. }
  313. eventMux := new(event.TypeMux)
  314. chainManager := core.NewChainManager(blockDb, stateDb, eventMux)
  315. pow := ethash.New()
  316. txPool := core.NewTxPool(eventMux, chainManager.State, chainManager.GasLimit)
  317. blockProcessor := core.NewBlockProcessor(stateDb, extraDb, pow, txPool, chainManager, eventMux)
  318. chainManager.SetProcessor(blockProcessor)
  319. return chainManager, blockDb, stateDb
  320. }
  321. func GetAccountManager(ctx *cli.Context) *accounts.Manager {
  322. dataDir := ctx.GlobalString(DataDirFlag.Name)
  323. ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keys"))
  324. return accounts.NewManager(ks)
  325. }
  326. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  327. config := rpc.RpcConfig{
  328. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  329. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  330. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  331. }
  332. xeth := xeth.New(eth, nil)
  333. return rpc.Start(xeth, config)
  334. }
  335. func StartPProf(ctx *cli.Context) {
  336. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  337. go func() {
  338. log.Println(http.ListenAndServe(address, nil))
  339. }()
  340. }