flags.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 for the databases and keystore",
  95. Value: DirectoryString{common.DefaultDataDir()},
  96. }
  97. NetworkIdFlag = cli.IntFlag{
  98. Name: "networkid",
  99. Usage: "Network identifier (integer, 0=Olympic, 1=Frontier, 2=Morden)",
  100. Value: eth.NetworkId,
  101. }
  102. OlympicFlag = cli.BoolFlag{
  103. Name: "olympic",
  104. Usage: "Olympic network: pre-configured pre-release test network",
  105. }
  106. TestNetFlag = cli.BoolFlag{
  107. Name: "testnet",
  108. Usage: "Morden network: pre-configured test network with modified starting nonces (replay protection)",
  109. }
  110. DevModeFlag = cli.BoolFlag{
  111. Name: "dev",
  112. Usage: "Developer mode: pre-configured private network with several debugging flags",
  113. }
  114. GenesisFileFlag = cli.StringFlag{
  115. Name: "genesis",
  116. Usage: "Insert/overwrite the genesis block (JSON format)",
  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. DocRootFlag = DirectoryFlag{
  127. Name: "docroot",
  128. Usage: "Document Root for HTTPClient file scheme",
  129. Value: DirectoryString{common.HomeDir()},
  130. }
  131. CacheFlag = cli.IntFlag{
  132. Name: "cache",
  133. Usage: "Megabytes of memory allocated to internal caching (min 16MB / database forced)",
  134. Value: 0,
  135. }
  136. BlockchainVersionFlag = cli.IntFlag{
  137. Name: "blockchainversion",
  138. Usage: "Blockchain version (integer)",
  139. Value: core.BlockChainVersion,
  140. }
  141. FastSyncFlag = cli.BoolFlag{
  142. Name: "fast",
  143. Usage: "Enable fast syncing through state downloads",
  144. }
  145. LightKDFFlag = cli.BoolFlag{
  146. Name: "lightkdf",
  147. Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
  148. }
  149. // Miner settings
  150. // TODO: refactor CPU vs GPU mining flags
  151. MiningEnabledFlag = cli.BoolFlag{
  152. Name: "mine",
  153. Usage: "Enable mining",
  154. }
  155. MinerThreadsFlag = cli.IntFlag{
  156. Name: "minerthreads",
  157. Usage: "Number of CPU threads to use for mining",
  158. Value: runtime.NumCPU(),
  159. }
  160. MiningGPUFlag = cli.StringFlag{
  161. Name: "minergpus",
  162. Usage: "List of GPUs to use for mining (e.g. '0,1' will use the first two GPUs found)",
  163. }
  164. AutoDAGFlag = cli.BoolFlag{
  165. Name: "autodag",
  166. Usage: "Enable automatic DAG pregeneration",
  167. }
  168. EtherbaseFlag = cli.StringFlag{
  169. Name: "etherbase",
  170. Usage: "Public address for block mining rewards (default = first account created)",
  171. Value: "0",
  172. }
  173. GasPriceFlag = cli.StringFlag{
  174. Name: "gasprice",
  175. Usage: "Minimal gas price to accept for mining a transactions",
  176. Value: new(big.Int).Mul(big.NewInt(50), common.Shannon).String(),
  177. }
  178. ExtraDataFlag = cli.StringFlag{
  179. Name: "extradata",
  180. Usage: "Block extra data set by the miner (default = client version)",
  181. }
  182. // Account settings
  183. UnlockedAccountFlag = cli.StringFlag{
  184. Name: "unlock",
  185. Usage: "Unlock an account (may be creation index) until this program exits (prompts for password)",
  186. Value: "",
  187. }
  188. PasswordFileFlag = cli.StringFlag{
  189. Name: "password",
  190. Usage: "Password file to use with options/subcommands needing a pass phrase",
  191. Value: "",
  192. }
  193. // vm flags
  194. VMDebugFlag = cli.BoolFlag{
  195. Name: "vmdebug",
  196. Usage: "Virtual Machine debug output",
  197. }
  198. VMForceJitFlag = cli.BoolFlag{
  199. Name: "forcejit",
  200. Usage: "Force the JIT VM to take precedence",
  201. }
  202. VMJitCacheFlag = cli.IntFlag{
  203. Name: "jitcache",
  204. Usage: "Amount of cached JIT VM programs",
  205. Value: 64,
  206. }
  207. VMEnableJitFlag = cli.BoolFlag{
  208. Name: "jitvm",
  209. Usage: "Enable the JIT VM",
  210. }
  211. // logging and debug settings
  212. VerbosityFlag = cli.IntFlag{
  213. Name: "verbosity",
  214. Usage: "Logging verbosity: 0-6 (0=silent, 1=error, 2=warn, 3=info, 4=core, 5=debug, 6=debug detail)",
  215. Value: int(logger.InfoLevel),
  216. }
  217. LogFileFlag = cli.StringFlag{
  218. Name: "logfile",
  219. Usage: "Log output file within the data dir (default = no log file generated)",
  220. Value: "",
  221. }
  222. LogVModuleFlag = cli.GenericFlag{
  223. Name: "vmodule",
  224. Usage: "Per-module verbosity: comma-separated list of <module>=<level>, where <module> is file literal or a glog pattern",
  225. Value: glog.GetVModule(),
  226. }
  227. BacktraceAtFlag = cli.GenericFlag{
  228. Name: "backtrace",
  229. Usage: "Request a stack trace at a specific logging statement (e.g. \"block.go:271\")",
  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: "Profile server listening port",
  239. Value: 6060,
  240. }
  241. MetricsEnabledFlag = cli.BoolFlag{
  242. Name: metrics.MetricsEnabledFlag,
  243. Usage: "Enable metrics collection and reporting",
  244. }
  245. // RPC settings
  246. RPCEnabledFlag = cli.BoolFlag{
  247. Name: "rpc",
  248. Usage: "Enable the HTTP-RPC server",
  249. }
  250. RPCListenAddrFlag = cli.StringFlag{
  251. Name: "rpcaddr",
  252. Usage: "HTTP-RPC server listening interface",
  253. Value: "127.0.0.1",
  254. }
  255. RPCPortFlag = cli.IntFlag{
  256. Name: "rpcport",
  257. Usage: "HTTP-RPC server listening port",
  258. Value: 8545,
  259. }
  260. RPCCORSDomainFlag = cli.StringFlag{
  261. Name: "rpccorsdomain",
  262. Usage: "Domains from which to accept cross origin requests (browser enforced)",
  263. Value: "",
  264. }
  265. RpcApiFlag = cli.StringFlag{
  266. Name: "rpcapi",
  267. Usage: "API's 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: "API's offered over the IPC-RPC 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: "JavaSript root path for `loadScript` and document root for `admin.httpGet`",
  334. Value: ".",
  335. }
  336. SolcPathFlag = cli.StringFlag{
  337. Name: "solc",
  338. Usage: "Solidity compiler command to be used",
  339. Value: "solc",
  340. }
  341. // Gas price oracle settings
  342. GpoMinGasPriceFlag = cli.StringFlag{
  343. Name: "gpomin",
  344. Usage: "Minimum suggested gas price",
  345. Value: new(big.Int).Mul(big.NewInt(50), common.Shannon).String(),
  346. }
  347. GpoMaxGasPriceFlag = cli.StringFlag{
  348. Name: "gpomax",
  349. Usage: "Maximum suggested gas price",
  350. Value: new(big.Int).Mul(big.NewInt(500), common.Shannon).String(),
  351. }
  352. GpoFullBlockRatioFlag = cli.IntFlag{
  353. Name: "gpofull",
  354. Usage: "Full block threshold for gas price calculation (%)",
  355. Value: 80,
  356. }
  357. GpobaseStepDownFlag = cli.IntFlag{
  358. Name: "gpobasedown",
  359. Usage: "Suggested gas price base step down ratio (1/1000)",
  360. Value: 10,
  361. }
  362. GpobaseStepUpFlag = cli.IntFlag{
  363. Name: "gpobaseup",
  364. Usage: "Suggested gas price base step up ratio (1/1000)",
  365. Value: 100,
  366. }
  367. GpobaseCorrectionFactorFlag = cli.IntFlag{
  368. Name: "gpobasecf",
  369. Usage: "Suggested gas price base correction factor (%)",
  370. Value: 110,
  371. }
  372. )
  373. // MakeNAT creates a port mapper from set command line flags.
  374. func MakeNAT(ctx *cli.Context) nat.Interface {
  375. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  376. if err != nil {
  377. Fatalf("Option %s: %v", NATFlag.Name, err)
  378. }
  379. return natif
  380. }
  381. // MakeNodeKey creates a node key from set command line flags.
  382. func MakeNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) {
  383. hex, file := ctx.GlobalString(NodeKeyHexFlag.Name), ctx.GlobalString(NodeKeyFileFlag.Name)
  384. var err error
  385. switch {
  386. case file != "" && hex != "":
  387. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  388. case file != "":
  389. if key, err = crypto.LoadECDSA(file); err != nil {
  390. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  391. }
  392. case hex != "":
  393. if key, err = crypto.HexToECDSA(hex); err != nil {
  394. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  395. }
  396. }
  397. return key
  398. }
  399. // MakeEthConfig creates ethereum options from set command line flags.
  400. func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
  401. customName := ctx.GlobalString(IdentityFlag.Name)
  402. if len(customName) > 0 {
  403. clientID += "/" + customName
  404. }
  405. am := MakeAccountManager(ctx)
  406. etherbase, err := ParamToAddress(ctx.GlobalString(EtherbaseFlag.Name), am)
  407. if err != nil {
  408. glog.V(logger.Error).Infoln("WARNING: No etherbase set and no accounts found as default")
  409. }
  410. // Assemble the entire eth configuration and return
  411. cfg := &eth.Config{
  412. Name: common.MakeName(clientID, version),
  413. DataDir: MustDataDir(ctx),
  414. GenesisFile: ctx.GlobalString(GenesisFileFlag.Name),
  415. FastSync: ctx.GlobalBool(FastSyncFlag.Name),
  416. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  417. DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
  418. SkipBcVersionCheck: false,
  419. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  420. LogFile: ctx.GlobalString(LogFileFlag.Name),
  421. Verbosity: ctx.GlobalInt(VerbosityFlag.Name),
  422. Etherbase: common.HexToAddress(etherbase),
  423. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  424. AccountManager: am,
  425. VmDebug: ctx.GlobalBool(VMDebugFlag.Name),
  426. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  427. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  428. Port: ctx.GlobalString(ListenPortFlag.Name),
  429. Olympic: ctx.GlobalBool(OlympicFlag.Name),
  430. NAT: MakeNAT(ctx),
  431. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  432. DocRoot: ctx.GlobalString(DocRootFlag.Name),
  433. Discovery: !ctx.GlobalBool(NoDiscoverFlag.Name),
  434. NodeKey: MakeNodeKey(ctx),
  435. Shh: ctx.GlobalBool(WhisperEnabledFlag.Name),
  436. Dial: true,
  437. BootNodes: ctx.GlobalString(BootnodesFlag.Name),
  438. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  439. GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
  440. GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
  441. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  442. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  443. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  444. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  445. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  446. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  447. }
  448. if ctx.GlobalBool(DevModeFlag.Name) && ctx.GlobalBool(TestNetFlag.Name) {
  449. glog.Fatalf("%s and %s are mutually exclusive\n", DevModeFlag.Name, TestNetFlag.Name)
  450. }
  451. if ctx.GlobalBool(TestNetFlag.Name) {
  452. // testnet is always stored in the testnet folder
  453. cfg.DataDir += "/testnet"
  454. cfg.NetworkId = 2
  455. cfg.TestNet = true
  456. }
  457. if ctx.GlobalBool(VMEnableJitFlag.Name) {
  458. cfg.Name += "/JIT"
  459. }
  460. if ctx.GlobalBool(DevModeFlag.Name) {
  461. if !ctx.GlobalIsSet(VMDebugFlag.Name) {
  462. cfg.VmDebug = true
  463. }
  464. if !ctx.GlobalIsSet(MaxPeersFlag.Name) {
  465. cfg.MaxPeers = 0
  466. }
  467. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  468. cfg.GasPrice = new(big.Int)
  469. }
  470. if !ctx.GlobalIsSet(ListenPortFlag.Name) {
  471. cfg.Port = "0" // auto port
  472. }
  473. if !ctx.GlobalIsSet(WhisperEnabledFlag.Name) {
  474. cfg.Shh = true
  475. }
  476. if !ctx.GlobalIsSet(DataDirFlag.Name) {
  477. cfg.DataDir = os.TempDir() + "/ethereum_dev_mode"
  478. }
  479. cfg.PowTest = true
  480. cfg.DevMode = true
  481. glog.V(logger.Info).Infoln("dev mode enabled")
  482. }
  483. return cfg
  484. }
  485. // SetupLogger configures glog from the logging-related command line flags.
  486. func SetupLogger(ctx *cli.Context) {
  487. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  488. glog.CopyStandardLogTo("INFO")
  489. glog.SetToStderr(true)
  490. glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
  491. }
  492. // SetupNetwork configures the system for either the main net or some test network.
  493. func SetupNetwork(ctx *cli.Context) {
  494. switch {
  495. case ctx.GlobalBool(OlympicFlag.Name):
  496. params.DurationLimit = big.NewInt(8)
  497. params.GenesisGasLimit = big.NewInt(3141592)
  498. params.MinGasLimit = big.NewInt(125000)
  499. params.MaximumExtraDataSize = big.NewInt(1024)
  500. NetworkIdFlag.Value = 0
  501. core.BlockReward = big.NewInt(1.5e+18)
  502. core.ExpDiffPeriod = big.NewInt(math.MaxInt64)
  503. }
  504. }
  505. // SetupVM configured the VM package's global settings
  506. func SetupVM(ctx *cli.Context) {
  507. vm.EnableJit = ctx.GlobalBool(VMEnableJitFlag.Name)
  508. vm.ForceJit = ctx.GlobalBool(VMForceJitFlag.Name)
  509. vm.SetJITCacheSize(ctx.GlobalInt(VMJitCacheFlag.Name))
  510. }
  511. // MakeChain creates a chain manager from set command line flags.
  512. func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database) {
  513. datadir := MustDataDir(ctx)
  514. cache := ctx.GlobalInt(CacheFlag.Name)
  515. var err error
  516. if chainDb, err = ethdb.NewLDBDatabase(filepath.Join(datadir, "chaindata"), cache); err != nil {
  517. Fatalf("Could not open database: %v", err)
  518. }
  519. if ctx.GlobalBool(OlympicFlag.Name) {
  520. _, err := core.WriteTestNetGenesisBlock(chainDb, 42)
  521. if err != nil {
  522. glog.Fatalln(err)
  523. }
  524. }
  525. eventMux := new(event.TypeMux)
  526. pow := ethash.New()
  527. //genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  528. chain, err = core.NewBlockChain(chainDb, pow, eventMux)
  529. if err != nil {
  530. Fatalf("Could not start chainmanager: %v", err)
  531. }
  532. proc := core.NewBlockProcessor(chainDb, pow, chain, eventMux)
  533. chain.SetProcessor(proc)
  534. return chain, chainDb
  535. }
  536. // MakeChain creates an account manager from set command line flags.
  537. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  538. dataDir := MustDataDir(ctx)
  539. if ctx.GlobalBool(TestNetFlag.Name) {
  540. dataDir += "/testnet"
  541. }
  542. scryptN := crypto.StandardScryptN
  543. scryptP := crypto.StandardScryptP
  544. if ctx.GlobalBool(LightKDFFlag.Name) {
  545. scryptN = crypto.LightScryptN
  546. scryptP = crypto.LightScryptP
  547. }
  548. ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keystore"), scryptN, scryptP)
  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) (comms.Stopper, shared.EthereumApi, error) {
  582. fe := useragent.NewRemoteFrontend(conn, eth.AccountManager())
  583. xeth := xeth.New(eth, fe)
  584. apis, err := api.ParseApiString(ctx.GlobalString(IPCApiFlag.Name), codec.JSON, xeth, eth)
  585. if err != nil {
  586. return nil, nil, err
  587. }
  588. return xeth, api.Merge(apis...), nil
  589. }
  590. return comms.StartIpc(config, codec.JSON, initializer)
  591. }
  592. func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
  593. config := comms.HttpConfig{
  594. ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
  595. ListenPort: uint(ctx.GlobalInt(RPCPortFlag.Name)),
  596. CorsDomain: ctx.GlobalString(RPCCORSDomainFlag.Name),
  597. }
  598. xeth := xeth.New(eth, nil)
  599. codec := codec.JSON
  600. apis, err := api.ParseApiString(ctx.GlobalString(RpcApiFlag.Name), codec, xeth, eth)
  601. if err != nil {
  602. return err
  603. }
  604. return comms.StartHttp(config, codec, api.Merge(apis...))
  605. }
  606. func StartPProf(ctx *cli.Context) {
  607. address := fmt.Sprintf("localhost:%d", ctx.GlobalInt(PProfPortFlag.Name))
  608. go func() {
  609. log.Println(http.ListenAndServe(address, nil))
  610. }()
  611. }
  612. func ParamToAddress(addr string, am *accounts.Manager) (addrHex string, err error) {
  613. if !((len(addr) == 40) || (len(addr) == 42)) { // with or without 0x
  614. index, err := strconv.Atoi(addr)
  615. if err != nil {
  616. Fatalf("Invalid account address '%s'", addr)
  617. }
  618. addrHex, err = am.AddressByIndex(index)
  619. if err != nil {
  620. return "", err
  621. }
  622. } else {
  623. addrHex = addr
  624. }
  625. return
  626. }