flags.go 20 KB

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