flags.go 19 KB

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