flags.go 20 KB

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