flags.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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"
  23. "net/http"
  24. "os"
  25. "path/filepath"
  26. "runtime"
  27. "strconv"
  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/core/vm"
  34. "github.com/ethereum/go-ethereum/crypto"
  35. "github.com/ethereum/go-ethereum/eth"
  36. "github.com/ethereum/go-ethereum/ethdb"
  37. "github.com/ethereum/go-ethereum/event"
  38. "github.com/ethereum/go-ethereum/logger"
  39. "github.com/ethereum/go-ethereum/logger/glog"
  40. "github.com/ethereum/go-ethereum/metrics"
  41. "github.com/ethereum/go-ethereum/p2p/nat"
  42. "github.com/ethereum/go-ethereum/rpc/api"
  43. "github.com/ethereum/go-ethereum/rpc/codec"
  44. "github.com/ethereum/go-ethereum/rpc/comms"
  45. "github.com/ethereum/go-ethereum/rpc/shared"
  46. "github.com/ethereum/go-ethereum/rpc/useragent"
  47. "github.com/ethereum/go-ethereum/xeth"
  48. )
  49. func init() {
  50. cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
  51. VERSION:
  52. {{.Version}}
  53. COMMANDS:
  54. {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  55. {{end}}{{if .Flags}}
  56. GLOBAL OPTIONS:
  57. {{range .Flags}}{{.}}
  58. {{end}}{{end}}
  59. `
  60. cli.CommandHelpTemplate = `{{.Name}}{{if .Subcommands}} command{{end}}{{if .Flags}} [command options]{{end}} [arguments...]
  61. {{if .Description}}{{.Description}}
  62. {{end}}{{if .Subcommands}}
  63. SUBCOMMANDS:
  64. {{range .Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  65. {{end}}{{end}}{{if .Flags}}
  66. OPTIONS:
  67. {{range .Flags}}{{.}}
  68. {{end}}{{end}}
  69. `
  70. }
  71. // NewApp creates an app with sane defaults.
  72. func NewApp(version, usage string) *cli.App {
  73. app := cli.NewApp()
  74. app.Name = filepath.Base(os.Args[0])
  75. app.Author = ""
  76. //app.Authors = nil
  77. app.Email = ""
  78. app.Version = version
  79. app.Usage = usage
  80. return app
  81. }
  82. // These are all the command line flags we support.
  83. // If you add to this list, please remember to include the
  84. // flag in the appropriate command definition.
  85. //
  86. // The flags are defined here so their names and help texts
  87. // are the same for all commands.
  88. var (
  89. // General settings
  90. DataDirFlag = DirectoryFlag{
  91. Name: "datadir",
  92. Usage: "Data directory to be used",
  93. Value: DirectoryString{common.DefaultDataDir()},
  94. }
  95. NetworkIdFlag = cli.IntFlag{
  96. Name: "networkid",
  97. Usage: "Network Id (integer)",
  98. Value: eth.NetworkId,
  99. }
  100. BlockchainVersionFlag = cli.IntFlag{
  101. Name: "blockchainversion",
  102. Usage: "Blockchain version (integer)",
  103. Value: core.BlockChainVersion,
  104. }
  105. GenesisNonceFlag = cli.IntFlag{
  106. Name: "genesisnonce",
  107. Usage: "Sets the genesis nonce",
  108. Value: 42,
  109. }
  110. GenesisFileFlag = cli.StringFlag{
  111. Name: "genesis",
  112. Usage: "Inserts/Overwrites the genesis block (json format)",
  113. }
  114. DevModeFlag = cli.BoolFlag{
  115. Name: "dev",
  116. Usage: "Developer mode. This mode creates a private network and sets several debugging flags",
  117. }
  118. IdentityFlag = cli.StringFlag{
  119. Name: "identity",
  120. Usage: "Custom node name",
  121. }
  122. NatspecEnabledFlag = cli.BoolFlag{
  123. Name: "natspec",
  124. Usage: "Enable NatSpec confirmation notice",
  125. }
  126. CacheFlag = cli.IntFlag{
  127. Name: "cache",
  128. Usage: "Megabytes of memory allocated to internal caching",
  129. Value: 0,
  130. }
  131. OlympicFlag = cli.BoolFlag{
  132. Name: "olympic",
  133. Usage: "Use olympic style protocol",
  134. }
  135. EthVersionFlag = cli.IntFlag{
  136. Name: "eth",
  137. Value: 62,
  138. Usage: "Highest eth protocol to advertise (temporary, dev option)",
  139. }
  140. // miner settings
  141. // TODO: refactor CPU vs GPU mining flags
  142. MiningGPUFlag = cli.StringFlag{
  143. Name: "minegpu",
  144. Usage: "Mine with given GPUs. '--minegpu 0,1' will mine with the first two GPUs found.",
  145. }
  146. MinerThreadsFlag = cli.IntFlag{
  147. Name: "minerthreads",
  148. Usage: "Number of miner threads",
  149. Value: runtime.NumCPU(),
  150. }
  151. MiningEnabledFlag = cli.BoolFlag{
  152. Name: "mine",
  153. Usage: "Enable mining",
  154. }
  155. AutoDAGFlag = cli.BoolFlag{
  156. Name: "autodag",
  157. Usage: "Enable automatic DAG pregeneration",
  158. }
  159. EtherbaseFlag = cli.StringFlag{
  160. Name: "etherbase",
  161. Usage: "Public address for block mining rewards. By default the address first created is used",
  162. Value: "0",
  163. }
  164. GasPriceFlag = cli.StringFlag{
  165. Name: "gasprice",
  166. Usage: "Sets the minimal gasprice when mining transactions",
  167. Value: new(big.Int).Mul(big.NewInt(50), common.Shannon).String(),
  168. }
  169. UnlockedAccountFlag = cli.StringFlag{
  170. Name: "unlock",
  171. Usage: "Unlock the account given until this program exits (prompts for password). '--unlock n' unlocks the n-th account in order or creation.",
  172. Value: "",
  173. }
  174. PasswordFileFlag = cli.StringFlag{
  175. Name: "password",
  176. Usage: "Path to password file to use with options and subcommands needing a password",
  177. Value: "",
  178. }
  179. // vm flags
  180. VMDebugFlag = cli.BoolFlag{
  181. Name: "vmdebug",
  182. Usage: "Virtual Machine debug output",
  183. }
  184. VMForceJitFlag = cli.BoolFlag{
  185. Name: "forcejit",
  186. Usage: "Force the JIT VM to take precedence",
  187. }
  188. VMJitCacheFlag = cli.IntFlag{
  189. Name: "jitcache",
  190. Usage: "Amount of cached JIT VM programs",
  191. Value: 64,
  192. }
  193. VMEnableJitFlag = cli.BoolFlag{
  194. Name: "jitvm",
  195. Usage: "Enable the JIT VM",
  196. }
  197. // logging and debug settings
  198. LogFileFlag = cli.StringFlag{
  199. Name: "logfile",
  200. Usage: "Send log output to a file",
  201. }
  202. VerbosityFlag = cli.IntFlag{
  203. Name: "verbosity",
  204. Usage: "Logging verbosity: 0-6 (0=silent, 1=error, 2=warn, 3=info, 4=core, 5=debug, 6=debug detail)",
  205. Value: int(logger.InfoLevel),
  206. }
  207. LogJSONFlag = cli.StringFlag{
  208. Name: "logjson",
  209. Usage: "Send json structured log output to a file or '-' for standard output (default: no json output)",
  210. Value: "",
  211. }
  212. LogToStdErrFlag = cli.BoolFlag{
  213. Name: "logtostderr",
  214. Usage: "Logs are written to standard error instead of to files.",
  215. }
  216. LogVModuleFlag = cli.GenericFlag{
  217. Name: "vmodule",
  218. 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.",
  219. Value: glog.GetVModule(),
  220. }
  221. BacktraceAtFlag = cli.GenericFlag{
  222. Name: "backtrace_at",
  223. Usage: "If set to a file and line number (e.g., \"block.go:271\") holding a logging statement, a stack trace will be logged",
  224. Value: glog.GetTraceLocation(),
  225. }
  226. PProfEanbledFlag = cli.BoolFlag{
  227. Name: "pprof",
  228. Usage: "Enable the profiling server on localhost",
  229. }
  230. PProfPortFlag = cli.IntFlag{
  231. Name: "pprofport",
  232. Usage: "Port on which the profiler should listen",
  233. Value: 6060,
  234. }
  235. MetricsEnabledFlag = cli.BoolFlag{
  236. Name: metrics.MetricsEnabledFlag,
  237. Usage: "Enables metrics collection and reporting",
  238. }
  239. // RPC settings
  240. RPCEnabledFlag = cli.BoolFlag{
  241. Name: "rpc",
  242. Usage: "Enable the JSON-RPC server",
  243. }
  244. RPCListenAddrFlag = cli.StringFlag{
  245. Name: "rpcaddr",
  246. Usage: "Listening address for the JSON-RPC server",
  247. Value: "127.0.0.1",
  248. }
  249. RPCPortFlag = cli.IntFlag{
  250. Name: "rpcport",
  251. Usage: "Port on which the JSON-RPC server should listen",
  252. Value: 8545,
  253. }
  254. RPCCORSDomainFlag = cli.StringFlag{
  255. Name: "rpccorsdomain",
  256. Usage: "Domain on which to send Access-Control-Allow-Origin header",
  257. Value: "",
  258. }
  259. RpcApiFlag = cli.StringFlag{
  260. Name: "rpcapi",
  261. Usage: "Specify the API's which are offered over the HTTP RPC interface",
  262. Value: comms.DefaultHttpRpcApis,
  263. }
  264. IPCDisabledFlag = cli.BoolFlag{
  265. Name: "ipcdisable",
  266. Usage: "Disable the IPC-RPC server",
  267. }
  268. IPCApiFlag = cli.StringFlag{
  269. Name: "ipcapi",
  270. Usage: "Specify the API's which are offered over the IPC interface",
  271. Value: comms.DefaultIpcApis,
  272. }
  273. IPCPathFlag = DirectoryFlag{
  274. Name: "ipcpath",
  275. Usage: "Filename for IPC socket/pipe",
  276. Value: DirectoryString{common.DefaultIpcPath()},
  277. }
  278. ExecFlag = cli.StringFlag{
  279. Name: "exec",
  280. Usage: "Execute javascript statement (only in combination with console/attach)",
  281. }
  282. // Network Settings
  283. MaxPeersFlag = cli.IntFlag{
  284. Name: "maxpeers",
  285. Usage: "Maximum number of network peers (network disabled if set to 0)",
  286. Value: 25,
  287. }
  288. MaxPendingPeersFlag = cli.IntFlag{
  289. Name: "maxpendpeers",
  290. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  291. Value: 0,
  292. }
  293. ListenPortFlag = cli.IntFlag{
  294. Name: "port",
  295. Usage: "Network listening port",
  296. Value: 30303,
  297. }
  298. BootnodesFlag = cli.StringFlag{
  299. Name: "bootnodes",
  300. Usage: "Space-separated enode URLs for p2p discovery bootstrap",
  301. Value: "",
  302. }
  303. NodeKeyFileFlag = cli.StringFlag{
  304. Name: "nodekey",
  305. Usage: "P2P node key file",
  306. }
  307. NodeKeyHexFlag = cli.StringFlag{
  308. Name: "nodekeyhex",
  309. Usage: "P2P node key as hex (for testing)",
  310. }
  311. NATFlag = cli.StringFlag{
  312. Name: "nat",
  313. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  314. Value: "any",
  315. }
  316. NoDiscoverFlag = cli.BoolFlag{
  317. Name: "nodiscover",
  318. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  319. }
  320. WhisperEnabledFlag = cli.BoolFlag{
  321. Name: "shh",
  322. Usage: "Enable whisper",
  323. }
  324. // ATM the url is left to the user and deployment to
  325. JSpathFlag = cli.StringFlag{
  326. Name: "jspath",
  327. Usage: "JS library path to be used with console and js subcommands",
  328. Value: ".",
  329. }
  330. SolcPathFlag = cli.StringFlag{
  331. Name: "solc",
  332. Usage: "solidity compiler to be used",
  333. Value: "solc",
  334. }
  335. GpoMinGasPriceFlag = cli.StringFlag{
  336. Name: "gpomin",
  337. Usage: "Minimum suggested gas price",
  338. Value: new(big.Int).Mul(big.NewInt(50), common.Shannon).String(),
  339. }
  340. GpoMaxGasPriceFlag = cli.StringFlag{
  341. Name: "gpomax",
  342. Usage: "Maximum suggested gas price",
  343. Value: new(big.Int).Mul(big.NewInt(500), common.Shannon).String(),
  344. }
  345. GpoFullBlockRatioFlag = cli.IntFlag{
  346. Name: "gpofull",
  347. Usage: "Full block threshold for gas price calculation (%)",
  348. Value: 80,
  349. }
  350. GpobaseStepDownFlag = cli.IntFlag{
  351. Name: "gpobasedown",
  352. Usage: "Suggested gas price base step down ratio (1/1000)",
  353. Value: 10,
  354. }
  355. GpobaseStepUpFlag = cli.IntFlag{
  356. Name: "gpobaseup",
  357. Usage: "Suggested gas price base step up ratio (1/1000)",
  358. Value: 100,
  359. }
  360. GpobaseCorrectionFactorFlag = cli.IntFlag{
  361. Name: "gpobasecf",
  362. Usage: "Suggested gas price base correction factor (%)",
  363. Value: 110,
  364. }
  365. )
  366. // MakeNAT creates a port mapper from set command line flags.
  367. func MakeNAT(ctx *cli.Context) nat.Interface {
  368. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  369. if err != nil {
  370. Fatalf("Option %s: %v", NATFlag.Name, err)
  371. }
  372. return natif
  373. }
  374. // MakeNodeKey creates a node key from set command line flags.
  375. func MakeNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  376. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  377. var err error
  378. switch {
  379. case file != "" && hex != "":
  380. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  381. case file != "":
  382. if key, err = crypto.LoadECDSA(file); err != nil {
  383. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  384. }
  385. case hex != "":
  386. if key, err = crypto.HexToECDSA(hex); err != nil {
  387. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  388. }
  389. }
  390. return key
  391. }
  392. // MakeEthConfig creates ethereum options from set command line flags.
  393. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  394. customName := ctx.GlobalString(IdentityFlag.Name)
  395. if len(customName) > 0 {
  396. clientID += "/" + customName
  397. }
  398. am := MakeAccountManager(ctx)
  399. etherbase, err := ParamToAddress(ctx.GlobalString(EtherbaseFlag.Name), am)
  400. if err != nil {
  401. glog.V(logger.Error).Infoln("WARNING: No etherbase set and no accounts found as default")
  402. }
  403. cfg := &eth.Config{
  404. Name: common.MakeName(clientID, version),
  405. DataDir: MustDataDir(ctx),
  406. GenesisNonce: ctx.GlobalInt(GenesisNonceFlag.Name),
  407. GenesisFile: ctx.GlobalString(GenesisFileFlag.Name),
  408. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  409. DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
  410. SkipBcVersionCheck: false,
  411. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  412. LogFile: ctx.GlobalString(LogFileFlag.Name),
  413. Verbosity: ctx.GlobalInt(VerbosityFlag.Name),
  414. LogJSON: ctx.GlobalString(LogJSONFlag.Name),
  415. Etherbase: common.HexToAddress(etherbase),
  416. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  417. AccountManager: am,
  418. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  419. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  420. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  421. Port: ctx.GlobalString(ListenPortFlag.Name),
  422. Olympic: ctx.GlobalBool(OlympicFlag.Name),
  423. NAT: MakeNAT(ctx),
  424. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  425. Discovery: !ctx.GlobalBool(NoDiscoverFlag.Name),
  426. NodeKey: MakeNodeKey(ctx),
  427. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  428. Dial: true,
  429. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  430. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  431. GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
  432. GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
  433. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  434. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  435. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  436. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  437. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  438. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  439. }
  440. if ctx.GlobalBool(DevModeFlag.Name) {
  441. if !ctx.GlobalIsSet(VMDebugFlag.Name) {
  442. cfg.VmDebug = true
  443. }
  444. if !ctx.GlobalIsSet(MaxPeersFlag.Name) {
  445. cfg.MaxPeers = 0
  446. }
  447. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  448. cfg.GasPrice = new(big.Int)
  449. }
  450. if !ctx.GlobalIsSet(ListenPortFlag.Name) {
  451. cfg.Port = "0" // auto port
  452. }
  453. if !ctx.GlobalIsSet(WhisperEnabledFlag.Name) {
  454. cfg.Shh = true
  455. }
  456. if !ctx.GlobalIsSet(DataDirFlag.Name) {
  457. cfg.DataDir = os.TempDir() + "/ethereum_dev_mode"
  458. }
  459. cfg.PowTest = true
  460. cfg.DevMode = true
  461. glog.V(logger.Info).Infoln("dev mode enabled")
  462. }
  463. return cfg
  464. }
  465. // SetupLogger configures glog from the logging-related command line flags.
  466. func SetupLogger(ctx *cli.Context) {
  467. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  468. glog.CopyStandardLogTo("INFO")
  469. glog.SetToStderr(true)
  470. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  471. }
  472. // SetupVM configured the VM package's global settings
  473. func SetupVM(ctx *cli.Context) {
  474. vm.EnableJit = ctx.GlobalBool(VMEnableJitFlag.Name)
  475. vm.ForceJit = ctx.GlobalBool(VMForceJitFlag.Name)
  476. vm.SetJITCacheSize(ctx.GlobalInt(VMJitCacheFlag.Name))
  477. }
  478. // SetupEth configures the eth packages global settings
  479. func SetupEth(ctx *cli.Context) {
  480. version := ctx.GlobalInt(EthVersionFlag.Name)
  481. for len(eth.ProtocolVersions) > 0 && eth.ProtocolVersions[0] > uint(version) {
  482. eth.ProtocolVersions = eth.ProtocolVersions[1:]
  483. eth.ProtocolLengths = eth.ProtocolLengths[1:]
  484. }
  485. if len(eth.ProtocolVersions) == 0 {
  486. Fatalf("No valid eth protocols remaining")
  487. }
  488. }
  489. // MakeChain creates a chain manager from set command line flags.
  490. func MakeChain(ctx *cli.Context) (chain *core.ChainManager, chainDb ethdb.Database) {
  491. datadir := MustDataDir(ctx)
  492. cache := ctx.GlobalInt(CacheFlag.Name)
  493. var err error
  494. if chainDb, err = ethdb.NewLDBDatabase(filepath.Join(datadir, "chaindata"), cache); err != nil {
  495. Fatalf("Could not open database: %v", err)
  496. }
  497. if ctx.GlobalBool(OlympicFlag.Name) {
  498. InitOlympic()
  499. _, err := core.WriteTestNetGenesisBlock(chainDb, 42)
  500. if err != nil {
  501. glog.Fatalln(err)
  502. }
  503. }
  504. eventMux := new(event.TypeMux)
  505. pow := ethash.New()
  506. //genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  507. chain, err = core.NewChainManager(chainDb, pow, eventMux)
  508. if err != nil {
  509. Fatalf("Could not start chainmanager: %v", err)
  510. }
  511. proc := core.NewBlockProcessor(chainDb, pow, chain, eventMux)
  512. chain.SetProcessor(proc)
  513. return chain, chainDb
  514. }
  515. // MakeChain creates an account manager from set command line flags.
  516. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  517. dataDir := MustDataDir(ctx)
  518. ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keystore"))
  519. return accounts.NewManager(ks)
  520. }
  521. // MustDataDir retrieves the currently requested data directory, terminating if
  522. // none (or the empty string) is specified.
  523. func MustDataDir(ctx *cli.Context) string {
  524. if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
  525. return path
  526. }
  527. Fatalf("Cannot determine default data directory, please set manually (--datadir)")
  528. return ""
  529. }
  530. func IpcSocketPath(ctx *cli.Context) (ipcpath string) {
  531. if runtime.GOOS == "windows" {
  532. ipcpath = common.DefaultIpcPath()
  533. if ctx.GlobalIsSet(IPCPathFlag.Name) {
  534. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  535. }
  536. } else {
  537. ipcpath = common.DefaultIpcPath()
  538. if ctx.GlobalIsSet(DataDirFlag.Name) {
  539. ipcpath = filepath.Join(ctx.GlobalString(DataDirFlag.Name), "geth.ipc")
  540. }
  541. if ctx.GlobalIsSet(IPCPathFlag.Name) {
  542. ipcpath = ctx.GlobalString(IPCPathFlag.Name)
  543. }
  544. }
  545. return
  546. }
  547. func StartIPC(eth *eth.Ethereum, ctx *cli.Context) error {
  548. config := comms.IpcConfig{
  549. Endpoint: IpcSocketPath(ctx),
  550. }
  551. initializer := func(conn net.Conn) (shared.EthereumApi, error) {
  552. fe := useragent.NewRemoteFrontend(conn, eth.AccountManager())
  553. xeth := xeth.New(eth, fe)
  554. codec := codec.JSON
  555. apis, err := api.ParseApiString(ctx.GlobalString(IPCApiFlag.Name), codec, xeth, eth)
  556. if err != nil {
  557. return nil, err
  558. }
  559. return api.Merge(apis...), nil
  560. }
  561. return comms.StartIpc(config, codec.JSON, initializer)
  562. }
  563. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  564. config := comms.HttpConfig{
  565. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  566. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  567. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  568. }
  569. xeth := xeth.New(eth, nil)
  570. codec := codec.JSON
  571. apis, err := api.ParseApiString(ctx.GlobalString(RpcApiFlag.Name), codec, xeth, eth)
  572. if err != nil {
  573. return err
  574. }
  575. return comms.StartHttp(config, codec, api.Merge(apis...))
  576. }
  577. func StartPProf(ctx *cli.Context) {
  578. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  579. go func() {
  580. log.Println(http.ListenAndServe(address, nil))
  581. }()
  582. }
  583. func ParamToAddress(addr string, am *accounts.Manager) (addrHex string, err error) {
  584. if !((len(addr) == 40) || (len(addr) == 42)) { // with or without 0x
  585. index, err := strconv.Atoi(addr)
  586. if err != nil {
  587. Fatalf("Invalid account address '%s'", addr)
  588. }
  589. addrHex, err = am.AddressByIndex(index)
  590. if err != nil {
  591. return "", err
  592. }
  593. } else {
  594. addrHex = addr
  595. }
  596. return
  597. }