flags.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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. "io/ioutil"
  21. "math"
  22. "math/big"
  23. "os"
  24. "path/filepath"
  25. "runtime"
  26. "strconv"
  27. "strings"
  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/state"
  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/node"
  43. "github.com/ethereum/go-ethereum/p2p/discover"
  44. "github.com/ethereum/go-ethereum/p2p/nat"
  45. "github.com/ethereum/go-ethereum/params"
  46. "github.com/ethereum/go-ethereum/rpc"
  47. "github.com/ethereum/go-ethereum/whisper"
  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 for the databases and keystore",
  93. Value: DirectoryString{common.DefaultDataDir()},
  94. }
  95. KeyStoreDirFlag = DirectoryFlag{
  96. Name: "keystore",
  97. Usage: "Directory for the keystore (default = inside the datadir)",
  98. }
  99. NetworkIdFlag = cli.IntFlag{
  100. Name: "networkid",
  101. Usage: "Network identifier (integer, 0=Olympic, 1=Frontier, 2=Morden)",
  102. Value: eth.NetworkId,
  103. }
  104. OlympicFlag = cli.BoolFlag{
  105. Name: "olympic",
  106. Usage: "Olympic network: pre-configured pre-release test network",
  107. }
  108. TestNetFlag = cli.BoolFlag{
  109. Name: "testnet",
  110. Usage: "Morden network: pre-configured test network with modified starting nonces (replay protection)",
  111. }
  112. DevModeFlag = cli.BoolFlag{
  113. Name: "dev",
  114. Usage: "Developer mode: pre-configured private network with several debugging flags",
  115. }
  116. GenesisFileFlag = cli.StringFlag{
  117. Name: "genesis",
  118. Usage: "Insert/overwrite the genesis block (JSON format)",
  119. }
  120. IdentityFlag = cli.StringFlag{
  121. Name: "identity",
  122. Usage: "Custom node name",
  123. }
  124. NatspecEnabledFlag = cli.BoolFlag{
  125. Name: "natspec",
  126. Usage: "Enable NatSpec confirmation notice",
  127. }
  128. DocRootFlag = DirectoryFlag{
  129. Name: "docroot",
  130. Usage: "Document Root for HTTPClient file scheme",
  131. Value: DirectoryString{common.HomeDir()},
  132. }
  133. CacheFlag = cli.IntFlag{
  134. Name: "cache",
  135. Usage: "Megabytes of memory allocated to internal caching (min 16MB / database forced)",
  136. Value: 128,
  137. }
  138. BlockchainVersionFlag = cli.IntFlag{
  139. Name: "blockchainversion",
  140. Usage: "Blockchain version (integer)",
  141. Value: core.BlockChainVersion,
  142. }
  143. FastSyncFlag = cli.BoolFlag{
  144. Name: "fast",
  145. Usage: "Enable fast syncing through state downloads",
  146. }
  147. LightKDFFlag = cli.BoolFlag{
  148. Name: "lightkdf",
  149. Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
  150. }
  151. // Miner settings
  152. // TODO: refactor CPU vs GPU mining flags
  153. MiningEnabledFlag = cli.BoolFlag{
  154. Name: "mine",
  155. Usage: "Enable mining",
  156. }
  157. MinerThreadsFlag = cli.IntFlag{
  158. Name: "minerthreads",
  159. Usage: "Number of CPU threads to use for mining",
  160. Value: runtime.NumCPU(),
  161. }
  162. MiningGPUFlag = cli.StringFlag{
  163. Name: "minergpus",
  164. Usage: "List of GPUs to use for mining (e.g. '0,1' will use the first two GPUs found)",
  165. }
  166. AutoDAGFlag = cli.BoolFlag{
  167. Name: "autodag",
  168. Usage: "Enable automatic DAG pregeneration",
  169. }
  170. EtherbaseFlag = cli.StringFlag{
  171. Name: "etherbase",
  172. Usage: "Public address for block mining rewards (default = first account created)",
  173. Value: "0",
  174. }
  175. GasPriceFlag = cli.StringFlag{
  176. Name: "gasprice",
  177. Usage: "Minimal gas price to accept for mining a transactions",
  178. Value: new(big.Int).Mul(big.NewInt(20), common.Shannon).String(),
  179. }
  180. ExtraDataFlag = cli.StringFlag{
  181. Name: "extradata",
  182. Usage: "Block extra data set by the miner (default = client version)",
  183. }
  184. // Account settings
  185. UnlockedAccountFlag = cli.StringFlag{
  186. Name: "unlock",
  187. Usage: "Comma separated list of accounts to unlock",
  188. Value: "",
  189. }
  190. PasswordFileFlag = cli.StringFlag{
  191. Name: "password",
  192. Usage: "Password file to use for non-inteactive password input",
  193. Value: "",
  194. }
  195. // vm flags
  196. VMDebugFlag = cli.BoolFlag{
  197. Name: "vmdebug",
  198. Usage: "Virtual Machine debug output",
  199. }
  200. VMForceJitFlag = cli.BoolFlag{
  201. Name: "forcejit",
  202. Usage: "Force the JIT VM to take precedence",
  203. }
  204. VMJitCacheFlag = cli.IntFlag{
  205. Name: "jitcache",
  206. Usage: "Amount of cached JIT VM programs",
  207. Value: 64,
  208. }
  209. VMEnableJitFlag = cli.BoolFlag{
  210. Name: "jitvm",
  211. Usage: "Enable the JIT VM",
  212. }
  213. // logging and debug settings
  214. MetricsEnabledFlag = cli.BoolFlag{
  215. Name: metrics.MetricsEnabledFlag,
  216. Usage: "Enable metrics collection and reporting",
  217. }
  218. // RPC settings
  219. RPCEnabledFlag = cli.BoolFlag{
  220. Name: "rpc",
  221. Usage: "Enable the HTTP-RPC server",
  222. }
  223. RPCListenAddrFlag = cli.StringFlag{
  224. Name: "rpcaddr",
  225. Usage: "HTTP-RPC server listening interface",
  226. Value: common.DefaultHTTPHost,
  227. }
  228. RPCPortFlag = cli.IntFlag{
  229. Name: "rpcport",
  230. Usage: "HTTP-RPC server listening port",
  231. Value: common.DefaultHTTPPort,
  232. }
  233. RPCCORSDomainFlag = cli.StringFlag{
  234. Name: "rpccorsdomain",
  235. Usage: "Domains from which to accept cross origin requests (browser enforced)",
  236. Value: "",
  237. }
  238. RPCApiFlag = cli.StringFlag{
  239. Name: "rpcapi",
  240. Usage: "API's offered over the HTTP-RPC interface",
  241. Value: rpc.DefaultHTTPApis,
  242. }
  243. IPCDisabledFlag = cli.BoolFlag{
  244. Name: "ipcdisable",
  245. Usage: "Disable the IPC-RPC server",
  246. }
  247. IPCApiFlag = cli.StringFlag{
  248. Name: "ipcapi",
  249. Usage: "API's offered over the IPC-RPC interface",
  250. Value: rpc.DefaultIPCApis,
  251. }
  252. IPCPathFlag = DirectoryFlag{
  253. Name: "ipcpath",
  254. Usage: "Filename for IPC socket/pipe within the datadir (explicit paths escape it)",
  255. Value: DirectoryString{common.DefaultIPCSocket},
  256. }
  257. WSEnabledFlag = cli.BoolFlag{
  258. Name: "ws",
  259. Usage: "Enable the WS-RPC server",
  260. }
  261. WSListenAddrFlag = cli.StringFlag{
  262. Name: "wsaddr",
  263. Usage: "WS-RPC server listening interface",
  264. Value: common.DefaultWSHost,
  265. }
  266. WSPortFlag = cli.IntFlag{
  267. Name: "wsport",
  268. Usage: "WS-RPC server listening port",
  269. Value: common.DefaultWSPort,
  270. }
  271. WSApiFlag = cli.StringFlag{
  272. Name: "wsapi",
  273. Usage: "API's offered over the WS-RPC interface",
  274. Value: rpc.DefaultHTTPApis,
  275. }
  276. WSAllowedDomainsFlag = cli.StringFlag{
  277. Name: "wsdomains",
  278. Usage: "Domains from which to accept websockets requests (can be spoofed)",
  279. Value: "",
  280. }
  281. ExecFlag = cli.StringFlag{
  282. Name: "exec",
  283. Usage: "Execute JavaScript statement (only in combination with console/attach)",
  284. }
  285. // Network Settings
  286. MaxPeersFlag = cli.IntFlag{
  287. Name: "maxpeers",
  288. Usage: "Maximum number of network peers (network disabled if set to 0)",
  289. Value: 25,
  290. }
  291. MaxPendingPeersFlag = cli.IntFlag{
  292. Name: "maxpendpeers",
  293. Usage: "Maximum number of pending connection attempts (defaults used if set to 0)",
  294. Value: 0,
  295. }
  296. ListenPortFlag = cli.IntFlag{
  297. Name: "port",
  298. Usage: "Network listening port",
  299. Value: 30303,
  300. }
  301. BootnodesFlag = cli.StringFlag{
  302. Name: "bootnodes",
  303. Usage: "Comma separated enode URLs for P2P discovery bootstrap",
  304. Value: "",
  305. }
  306. NodeKeyFileFlag = cli.StringFlag{
  307. Name: "nodekey",
  308. Usage: "P2P node key file",
  309. }
  310. NodeKeyHexFlag = cli.StringFlag{
  311. Name: "nodekeyhex",
  312. Usage: "P2P node key as hex (for testing)",
  313. }
  314. NATFlag = cli.StringFlag{
  315. Name: "nat",
  316. Usage: "NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
  317. Value: "any",
  318. }
  319. NoDiscoverFlag = cli.BoolFlag{
  320. Name: "nodiscover",
  321. Usage: "Disables the peer discovery mechanism (manual peer addition)",
  322. }
  323. WhisperEnabledFlag = cli.BoolFlag{
  324. Name: "shh",
  325. Usage: "Enable Whisper",
  326. }
  327. // ATM the url is left to the user and deployment to
  328. JSpathFlag = cli.StringFlag{
  329. Name: "jspath",
  330. Usage: "JavaScript root path for `loadScript` and document root for `admin.httpGet`",
  331. Value: ".",
  332. }
  333. SolcPathFlag = cli.StringFlag{
  334. Name: "solc",
  335. Usage: "Solidity compiler command to be used",
  336. Value: "solc",
  337. }
  338. // Gas price oracle settings
  339. GpoMinGasPriceFlag = cli.StringFlag{
  340. Name: "gpomin",
  341. Usage: "Minimum suggested gas price",
  342. Value: new(big.Int).Mul(big.NewInt(20), common.Shannon).String(),
  343. }
  344. GpoMaxGasPriceFlag = cli.StringFlag{
  345. Name: "gpomax",
  346. Usage: "Maximum suggested gas price",
  347. Value: new(big.Int).Mul(big.NewInt(500), common.Shannon).String(),
  348. }
  349. GpoFullBlockRatioFlag = cli.IntFlag{
  350. Name: "gpofull",
  351. Usage: "Full block threshold for gas price calculation (%)",
  352. Value: 80,
  353. }
  354. GpobaseStepDownFlag = cli.IntFlag{
  355. Name: "gpobasedown",
  356. Usage: "Suggested gas price base step down ratio (1/1000)",
  357. Value: 10,
  358. }
  359. GpobaseStepUpFlag = cli.IntFlag{
  360. Name: "gpobaseup",
  361. Usage: "Suggested gas price base step up ratio (1/1000)",
  362. Value: 100,
  363. }
  364. GpobaseCorrectionFactorFlag = cli.IntFlag{
  365. Name: "gpobasecf",
  366. Usage: "Suggested gas price base correction factor (%)",
  367. Value: 110,
  368. }
  369. )
  370. // MustMakeDataDir retrieves the currently requested data directory, terminating
  371. // if none (or the empty string) is specified. If the node is starting a testnet,
  372. // the a subdirectory of the specified datadir will be used.
  373. func MustMakeDataDir(ctx *cli.Context) string {
  374. if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
  375. if ctx.GlobalBool(TestNetFlag.Name) {
  376. return filepath.Join(path, "/testnet")
  377. }
  378. return path
  379. }
  380. Fatalf("Cannot determine default data directory, please set manually (--datadir)")
  381. return ""
  382. }
  383. // MakeKeyStoreDir resolves the folder to use for storing the account keys from the
  384. // set command line flags, returning the explicitly requested path, or one inside
  385. // the data directory otherwise.
  386. func MakeKeyStoreDir(datadir string, ctx *cli.Context) string {
  387. if path := ctx.GlobalString(KeyStoreDirFlag.Name); path != "" {
  388. return path
  389. }
  390. return filepath.Join(datadir, "keystore")
  391. }
  392. // MakeIPCPath creates an IPC path configuration from the set command line flags,
  393. // returning an empty string if IPC was explicitly disabled, or the set path.
  394. func MakeIPCPath(ctx *cli.Context) string {
  395. if ctx.GlobalBool(IPCDisabledFlag.Name) {
  396. return ""
  397. }
  398. return ctx.GlobalString(IPCPathFlag.Name)
  399. }
  400. // MakeNodeKey creates a node key from set command line flags, either loading it
  401. // from a file or as a specified hex value. If neither flags were provided, this
  402. // method returns nil and an emphemeral key is to be generated.
  403. func MakeNodeKey(ctx *cli.Context) *ecdsa.PrivateKey {
  404. var (
  405. hex = ctx.GlobalString(NodeKeyHexFlag.Name)
  406. file = ctx.GlobalString(NodeKeyFileFlag.Name)
  407. key *ecdsa.PrivateKey
  408. err error
  409. )
  410. switch {
  411. case file != "" && hex != "":
  412. Fatalf("Options %q and %q are mutually exclusive", NodeKeyFileFlag.Name, NodeKeyHexFlag.Name)
  413. case file != "":
  414. if key, err = crypto.LoadECDSA(file); err != nil {
  415. Fatalf("Option %q: %v", NodeKeyFileFlag.Name, err)
  416. }
  417. case hex != "":
  418. if key, err = crypto.HexToECDSA(hex); err != nil {
  419. Fatalf("Option %q: %v", NodeKeyHexFlag.Name, err)
  420. }
  421. }
  422. return key
  423. }
  424. // MakeNodeName creates a node name from a base set and the command line flags.
  425. func MakeNodeName(client, version string, ctx *cli.Context) string {
  426. name := common.MakeName(client, version)
  427. if identity := ctx.GlobalString(IdentityFlag.Name); len(identity) > 0 {
  428. name += "/" + identity
  429. }
  430. if ctx.GlobalBool(VMEnableJitFlag.Name) {
  431. name += "/JIT"
  432. }
  433. return name
  434. }
  435. // MakeBootstrapNodes creates a list of bootstrap nodes from the command line
  436. // flags, reverting to pre-configured ones if none have been specified.
  437. func MakeBootstrapNodes(ctx *cli.Context) []*discover.Node {
  438. // Return pre-configured nodes if none were manually requested
  439. if !ctx.GlobalIsSet(BootnodesFlag.Name) {
  440. if ctx.GlobalBool(TestNetFlag.Name) {
  441. return TestNetBootNodes
  442. }
  443. return FrontierBootNodes
  444. }
  445. // Otherwise parse and use the CLI bootstrap nodes
  446. bootnodes := []*discover.Node{}
  447. for _, url := range strings.Split(ctx.GlobalString(BootnodesFlag.Name), ",") {
  448. node, err := discover.ParseNode(url)
  449. if err != nil {
  450. glog.V(logger.Error).Infof("Bootstrap URL %s: %v\n", url, err)
  451. continue
  452. }
  453. bootnodes = append(bootnodes, node)
  454. }
  455. return bootnodes
  456. }
  457. // MakeListenAddress creates a TCP listening address string from set command
  458. // line flags.
  459. func MakeListenAddress(ctx *cli.Context) string {
  460. return fmt.Sprintf(":%d", ctx.GlobalInt(ListenPortFlag.Name))
  461. }
  462. // MakeNAT creates a port mapper from set command line flags.
  463. func MakeNAT(ctx *cli.Context) nat.Interface {
  464. natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
  465. if err != nil {
  466. Fatalf("Option %s: %v", NATFlag.Name, err)
  467. }
  468. return natif
  469. }
  470. // MakeHTTPRpcHost creates the HTTP RPC listener interface string from the set
  471. // command line flags, returning empty if the HTTP endpoint is disabled.
  472. func MakeHTTPRpcHost(ctx *cli.Context) string {
  473. if !ctx.GlobalBool(RPCEnabledFlag.Name) {
  474. return ""
  475. }
  476. return ctx.GlobalString(RPCListenAddrFlag.Name)
  477. }
  478. // MakeWSRpcHost creates the WebSocket RPC listener interface string from the set
  479. // command line flags, returning empty if the HTTP endpoint is disabled.
  480. func MakeWSRpcHost(ctx *cli.Context) string {
  481. if !ctx.GlobalBool(WSEnabledFlag.Name) {
  482. return ""
  483. }
  484. return ctx.GlobalString(WSListenAddrFlag.Name)
  485. }
  486. // MakeGenesisBlock loads up a genesis block from an input file specified in the
  487. // command line, or returns the empty string if none set.
  488. func MakeGenesisBlock(ctx *cli.Context) string {
  489. genesis := ctx.GlobalString(GenesisFileFlag.Name)
  490. if genesis == "" {
  491. return ""
  492. }
  493. data, err := ioutil.ReadFile(genesis)
  494. if err != nil {
  495. Fatalf("Failed to load custom genesis file: %v", err)
  496. }
  497. return string(data)
  498. }
  499. // MakeDatabaseHandles raises out the number of allowed file handles per process
  500. // for Geth and returns half of the allowance to assign to the database.
  501. func MakeDatabaseHandles() int {
  502. if err := raiseFdLimit(2048); err != nil {
  503. Fatalf("Failed to raise file descriptor allowance: %v", err)
  504. }
  505. limit, err := getFdLimit()
  506. if err != nil {
  507. Fatalf("Failed to retrieve file descriptor allowance: %v", err)
  508. }
  509. if limit > 2048 { // cap database file descriptors even if more is available
  510. limit = 2048
  511. }
  512. return limit / 2 // Leave half for networking and other stuff
  513. }
  514. // MakeAccountManager creates an account manager from set command line flags.
  515. func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
  516. // Create the keystore crypto primitive, light if requested
  517. scryptN := crypto.StandardScryptN
  518. scryptP := crypto.StandardScryptP
  519. if ctx.GlobalBool(LightKDFFlag.Name) {
  520. scryptN = crypto.LightScryptN
  521. scryptP = crypto.LightScryptP
  522. }
  523. // Assemble an account manager using the configured datadir
  524. var (
  525. datadir = MustMakeDataDir(ctx)
  526. keystoredir = MakeKeyStoreDir(datadir, ctx)
  527. keystore = crypto.NewKeyStorePassphrase(keystoredir, scryptN, scryptP)
  528. )
  529. return accounts.NewManager(keystore)
  530. }
  531. // MakeAddress converts an account specified directly as a hex encoded string or
  532. // a key index in the key store to an internal account representation.
  533. func MakeAddress(accman *accounts.Manager, account string) (a common.Address, err error) {
  534. // If the specified account is a valid address, return it
  535. if common.IsHexAddress(account) {
  536. return common.HexToAddress(account), nil
  537. }
  538. // Otherwise try to interpret the account as a keystore index
  539. index, err := strconv.Atoi(account)
  540. if err != nil {
  541. return a, fmt.Errorf("invalid account address or index %q", account)
  542. }
  543. hex, err := accman.AddressByIndex(index)
  544. if err != nil {
  545. return a, fmt.Errorf("can't get account #%d (%v)", index, err)
  546. }
  547. return common.HexToAddress(hex), nil
  548. }
  549. // MakeEtherbase retrieves the etherbase either from the directly specified
  550. // command line flags or from the keystore if CLI indexed.
  551. func MakeEtherbase(accman *accounts.Manager, ctx *cli.Context) common.Address {
  552. accounts, _ := accman.Accounts()
  553. if !ctx.GlobalIsSet(EtherbaseFlag.Name) && len(accounts) == 0 {
  554. glog.V(logger.Error).Infoln("WARNING: No etherbase set and no accounts found as default")
  555. return common.Address{}
  556. }
  557. etherbase := ctx.GlobalString(EtherbaseFlag.Name)
  558. if etherbase == "" {
  559. return common.Address{}
  560. }
  561. // If the specified etherbase is a valid address, return it
  562. addr, err := MakeAddress(accman, etherbase)
  563. if err != nil {
  564. Fatalf("Option %q: %v", EtherbaseFlag.Name, err)
  565. }
  566. return addr
  567. }
  568. // MakeMinerExtra resolves extradata for the miner from the set command line flags
  569. // or returns a default one composed on the client, runtime and OS metadata.
  570. func MakeMinerExtra(extra []byte, ctx *cli.Context) []byte {
  571. if ctx.GlobalIsSet(ExtraDataFlag.Name) {
  572. return []byte(ctx.GlobalString(ExtraDataFlag.Name))
  573. }
  574. return extra
  575. }
  576. // MakePasswordList loads up a list of password from a file specified by the
  577. // command line flags.
  578. func MakePasswordList(ctx *cli.Context) []string {
  579. if path := ctx.GlobalString(PasswordFileFlag.Name); path != "" {
  580. blob, err := ioutil.ReadFile(path)
  581. if err != nil {
  582. Fatalf("Failed to read password file: %v", err)
  583. }
  584. return strings.Split(string(blob), "\n")
  585. }
  586. return nil
  587. }
  588. // MakeSystemNode sets up a local node, configures the services to launch and
  589. // assembles the P2P protocol stack.
  590. func MakeSystemNode(name, version string, extra []byte, ctx *cli.Context) *node.Node {
  591. // Avoid conflicting network flags
  592. networks, netFlags := 0, []cli.BoolFlag{DevModeFlag, TestNetFlag, OlympicFlag}
  593. for _, flag := range netFlags {
  594. if ctx.GlobalBool(flag.Name) {
  595. networks++
  596. }
  597. }
  598. if networks > 1 {
  599. Fatalf("The %v flags are mutually exclusive", netFlags)
  600. }
  601. // Configure the node's service container
  602. stackConf := &node.Config{
  603. DataDir: MustMakeDataDir(ctx),
  604. PrivateKey: MakeNodeKey(ctx),
  605. Name: MakeNodeName(name, version, ctx),
  606. NoDiscovery: ctx.GlobalBool(NoDiscoverFlag.Name),
  607. BootstrapNodes: MakeBootstrapNodes(ctx),
  608. ListenAddr: MakeListenAddress(ctx),
  609. NAT: MakeNAT(ctx),
  610. MaxPeers: ctx.GlobalInt(MaxPeersFlag.Name),
  611. MaxPendingPeers: ctx.GlobalInt(MaxPendingPeersFlag.Name),
  612. IPCPath: MakeIPCPath(ctx),
  613. HTTPHost: MakeHTTPRpcHost(ctx),
  614. HTTPPort: ctx.GlobalInt(RPCPortFlag.Name),
  615. HTTPCors: ctx.GlobalString(RPCCORSDomainFlag.Name),
  616. HTTPModules: strings.Split(ctx.GlobalString(RPCApiFlag.Name), ","),
  617. WSHost: MakeWSRpcHost(ctx),
  618. WSPort: ctx.GlobalInt(WSPortFlag.Name),
  619. WSDomains: ctx.GlobalString(WSAllowedDomainsFlag.Name),
  620. WSModules: strings.Split(ctx.GlobalString(WSApiFlag.Name), ","),
  621. }
  622. // Configure the Ethereum service
  623. accman := MakeAccountManager(ctx)
  624. ethConf := &eth.Config{
  625. Genesis: MakeGenesisBlock(ctx),
  626. FastSync: ctx.GlobalBool(FastSyncFlag.Name),
  627. BlockChainVersion: ctx.GlobalInt(BlockchainVersionFlag.Name),
  628. DatabaseCache: ctx.GlobalInt(CacheFlag.Name),
  629. DatabaseHandles: MakeDatabaseHandles(),
  630. NetworkId: ctx.GlobalInt(NetworkIdFlag.Name),
  631. AccountManager: accman,
  632. Etherbase: MakeEtherbase(accman, ctx),
  633. MinerThreads: ctx.GlobalInt(MinerThreadsFlag.Name),
  634. ExtraData: MakeMinerExtra(extra, ctx),
  635. NatSpec: ctx.GlobalBool(NatspecEnabledFlag.Name),
  636. DocRoot: ctx.GlobalString(DocRootFlag.Name),
  637. GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
  638. GpoMinGasPrice: common.String2Big(ctx.GlobalString(GpoMinGasPriceFlag.Name)),
  639. GpoMaxGasPrice: common.String2Big(ctx.GlobalString(GpoMaxGasPriceFlag.Name)),
  640. GpoFullBlockRatio: ctx.GlobalInt(GpoFullBlockRatioFlag.Name),
  641. GpobaseStepDown: ctx.GlobalInt(GpobaseStepDownFlag.Name),
  642. GpobaseStepUp: ctx.GlobalInt(GpobaseStepUpFlag.Name),
  643. GpobaseCorrectionFactor: ctx.GlobalInt(GpobaseCorrectionFactorFlag.Name),
  644. SolcPath: ctx.GlobalString(SolcPathFlag.Name),
  645. AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
  646. }
  647. // Configure the Whisper service
  648. shhEnable := ctx.GlobalBool(WhisperEnabledFlag.Name)
  649. // Override any default configs in dev mode or the test net
  650. switch {
  651. case ctx.GlobalBool(OlympicFlag.Name):
  652. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  653. ethConf.NetworkId = 1
  654. }
  655. if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
  656. ethConf.Genesis = core.OlympicGenesisBlock()
  657. }
  658. case ctx.GlobalBool(TestNetFlag.Name):
  659. if !ctx.GlobalIsSet(NetworkIdFlag.Name) {
  660. ethConf.NetworkId = 2
  661. }
  662. if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
  663. ethConf.Genesis = core.TestNetGenesisBlock()
  664. }
  665. state.StartingNonce = 1048576 // (2**20)
  666. // overwrite homestead block
  667. params.HomesteadBlock = params.TestNetHomesteadBlock
  668. case ctx.GlobalBool(DevModeFlag.Name):
  669. // Override the base network stack configs
  670. if !ctx.GlobalIsSet(DataDirFlag.Name) {
  671. stackConf.DataDir = filepath.Join(os.TempDir(), "/ethereum_dev_mode")
  672. }
  673. if !ctx.GlobalIsSet(MaxPeersFlag.Name) {
  674. stackConf.MaxPeers = 0
  675. }
  676. if !ctx.GlobalIsSet(ListenPortFlag.Name) {
  677. stackConf.ListenAddr = ":0"
  678. }
  679. // Override the Ethereum protocol configs
  680. if !ctx.GlobalIsSet(GenesisFileFlag.Name) {
  681. ethConf.Genesis = core.OlympicGenesisBlock()
  682. }
  683. if !ctx.GlobalIsSet(GasPriceFlag.Name) {
  684. ethConf.GasPrice = new(big.Int)
  685. }
  686. if !ctx.GlobalIsSet(WhisperEnabledFlag.Name) {
  687. shhEnable = true
  688. }
  689. if !ctx.GlobalIsSet(VMDebugFlag.Name) {
  690. vm.Debug = true
  691. }
  692. ethConf.PowTest = true
  693. }
  694. // Assemble and return the protocol stack
  695. stack, err := node.New(stackConf)
  696. if err != nil {
  697. Fatalf("Failed to create the protocol stack: %v", err)
  698. }
  699. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  700. return eth.New(ctx, ethConf)
  701. }); err != nil {
  702. Fatalf("Failed to register the Ethereum service: %v", err)
  703. }
  704. if shhEnable {
  705. if err := stack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
  706. Fatalf("Failed to register the Whisper service: %v", err)
  707. }
  708. }
  709. return stack
  710. }
  711. // SetupNetwork configures the system for either the main net or some test network.
  712. func SetupNetwork(ctx *cli.Context) {
  713. switch {
  714. case ctx.GlobalBool(OlympicFlag.Name):
  715. params.DurationLimit = big.NewInt(8)
  716. params.GenesisGasLimit = big.NewInt(3141592)
  717. params.MinGasLimit = big.NewInt(125000)
  718. params.MaximumExtraDataSize = big.NewInt(1024)
  719. NetworkIdFlag.Value = 0
  720. core.BlockReward = big.NewInt(1.5e+18)
  721. core.ExpDiffPeriod = big.NewInt(math.MaxInt64)
  722. }
  723. }
  724. // SetupVM configured the VM package's global settings
  725. func SetupVM(ctx *cli.Context) {
  726. vm.EnableJit = ctx.GlobalBool(VMEnableJitFlag.Name)
  727. vm.ForceJit = ctx.GlobalBool(VMForceJitFlag.Name)
  728. vm.SetJITCacheSize(ctx.GlobalInt(VMJitCacheFlag.Name))
  729. if ctx.GlobalIsSet(VMDebugFlag.Name) {
  730. vm.Debug = ctx.GlobalBool(VMDebugFlag.Name)
  731. }
  732. }
  733. // MakeChain creates a chain manager from set command line flags.
  734. func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database) {
  735. datadir := MustMakeDataDir(ctx)
  736. cache := ctx.GlobalInt(CacheFlag.Name)
  737. handles := MakeDatabaseHandles()
  738. var err error
  739. if chainDb, err = ethdb.NewLDBDatabase(filepath.Join(datadir, "chaindata"), cache, handles); err != nil {
  740. Fatalf("Could not open database: %v", err)
  741. }
  742. if ctx.GlobalBool(OlympicFlag.Name) {
  743. _, err := core.WriteTestNetGenesisBlock(chainDb)
  744. if err != nil {
  745. glog.Fatalln(err)
  746. }
  747. }
  748. eventMux := new(event.TypeMux)
  749. pow := ethash.New()
  750. //genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
  751. chain, err = core.NewBlockChain(chainDb, pow, eventMux)
  752. if err != nil {
  753. Fatalf("Could not start chainmanager: %v", err)
  754. }
  755. return chain, chainDb
  756. }