backend.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. package eth
  2. import (
  3. "crypto/ecdsa"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "math/big"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/ethereum/ethash"
  13. "github.com/ethereum/go-ethereum/accounts"
  14. "github.com/ethereum/go-ethereum/common"
  15. "github.com/ethereum/go-ethereum/common/compiler"
  16. "github.com/ethereum/go-ethereum/core"
  17. "github.com/ethereum/go-ethereum/core/types"
  18. "github.com/ethereum/go-ethereum/core/vm"
  19. "github.com/ethereum/go-ethereum/crypto"
  20. "github.com/ethereum/go-ethereum/eth/downloader"
  21. "github.com/ethereum/go-ethereum/ethdb"
  22. "github.com/ethereum/go-ethereum/event"
  23. "github.com/ethereum/go-ethereum/logger"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. "github.com/ethereum/go-ethereum/metrics"
  26. "github.com/ethereum/go-ethereum/miner"
  27. "github.com/ethereum/go-ethereum/p2p"
  28. "github.com/ethereum/go-ethereum/p2p/discover"
  29. "github.com/ethereum/go-ethereum/p2p/nat"
  30. "github.com/ethereum/go-ethereum/whisper"
  31. )
  32. const (
  33. epochLength = 30000
  34. ethashRevision = 23
  35. autoDAGcheckInterval = 10 * time.Hour
  36. autoDAGepochHeight = epochLength / 2
  37. )
  38. var (
  39. jsonlogger = logger.NewJsonLogger()
  40. defaultBootNodes = []*discover.Node{
  41. // ETH/DEV Go Bootnodes
  42. discover.MustParseNode("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:30303"),
  43. discover.MustParseNode("enode://de471bccee3d042261d52e9bff31458daecc406142b401d4cd848f677479f73104b9fdeb090af9583d3391b7f10cb2ba9e26865dd5fca4fcdc0fb1e3b723c786@54.94.239.50:30303"),
  44. // ETH/DEV cpp-ethereum (poc-9.ethdev.com)
  45. discover.MustParseNode("enode://487611428e6c99a11a9795a6abe7b529e81315ca6aad66e2a2fc76e3adf263faba0d35466c2f8f68d561dbefa8878d4df5f1f2ddb1fbeab7f42ffb8cd328bd4a@5.1.83.226:30303"),
  46. }
  47. staticNodes = "static-nodes.json" // Path within <datadir> to search for the static node list
  48. trustedNodes = "trusted-nodes.json" // Path within <datadir> to search for the trusted node list
  49. )
  50. type Config struct {
  51. Name string
  52. NetworkId int
  53. GenesisNonce int
  54. BlockChainVersion int
  55. SkipBcVersionCheck bool // e.g. blockchain export
  56. DataDir string
  57. LogFile string
  58. Verbosity int
  59. LogJSON string
  60. VmDebug bool
  61. NatSpec bool
  62. AutoDAG bool
  63. PowTest bool
  64. MaxPeers int
  65. MaxPendingPeers int
  66. Discovery bool
  67. Port string
  68. // Space-separated list of discovery node URLs
  69. BootNodes string
  70. // This key is used to identify the node on the network.
  71. // If nil, an ephemeral key is used.
  72. NodeKey *ecdsa.PrivateKey
  73. NAT nat.Interface
  74. Shh bool
  75. Dial bool
  76. Etherbase string
  77. GasPrice *big.Int
  78. MinerThreads int
  79. AccountManager *accounts.Manager
  80. SolcPath string
  81. GpoMinGasPrice *big.Int
  82. GpoMaxGasPrice *big.Int
  83. GpoFullBlockRatio int
  84. GpobaseStepDown int
  85. GpobaseStepUp int
  86. GpobaseCorrectionFactor int
  87. // NewDB is used to create databases.
  88. // If nil, the default is to create leveldb databases on disk.
  89. NewDB func(path string) (common.Database, error)
  90. }
  91. func (cfg *Config) parseBootNodes() []*discover.Node {
  92. if cfg.BootNodes == "" {
  93. return defaultBootNodes
  94. }
  95. var ns []*discover.Node
  96. for _, url := range strings.Split(cfg.BootNodes, " ") {
  97. if url == "" {
  98. continue
  99. }
  100. n, err := discover.ParseNode(url)
  101. if err != nil {
  102. glog.V(logger.Error).Infof("Bootstrap URL %s: %v\n", url, err)
  103. continue
  104. }
  105. ns = append(ns, n)
  106. }
  107. return ns
  108. }
  109. // parseNodes parses a list of discovery node URLs loaded from a .json file.
  110. func (cfg *Config) parseNodes(file string) []*discover.Node {
  111. // Short circuit if no node config is present
  112. path := filepath.Join(cfg.DataDir, file)
  113. if _, err := os.Stat(path); err != nil {
  114. return nil
  115. }
  116. // Load the nodes from the config file
  117. blob, err := ioutil.ReadFile(path)
  118. if err != nil {
  119. glog.V(logger.Error).Infof("Failed to access nodes: %v", err)
  120. return nil
  121. }
  122. nodelist := []string{}
  123. if err := json.Unmarshal(blob, &nodelist); err != nil {
  124. glog.V(logger.Error).Infof("Failed to load nodes: %v", err)
  125. return nil
  126. }
  127. // Interpret the list as a discovery node array
  128. var nodes []*discover.Node
  129. for _, url := range nodelist {
  130. if url == "" {
  131. continue
  132. }
  133. node, err := discover.ParseNode(url)
  134. if err != nil {
  135. glog.V(logger.Error).Infof("Node URL %s: %v\n", url, err)
  136. continue
  137. }
  138. nodes = append(nodes, node)
  139. }
  140. return nodes
  141. }
  142. func (cfg *Config) nodeKey() (*ecdsa.PrivateKey, error) {
  143. // use explicit key from command line args if set
  144. if cfg.NodeKey != nil {
  145. return cfg.NodeKey, nil
  146. }
  147. // use persistent key if present
  148. keyfile := filepath.Join(cfg.DataDir, "nodekey")
  149. key, err := crypto.LoadECDSA(keyfile)
  150. if err == nil {
  151. return key, nil
  152. }
  153. // no persistent key, generate and store a new one
  154. if key, err = crypto.GenerateKey(); err != nil {
  155. return nil, fmt.Errorf("could not generate server key: %v", err)
  156. }
  157. if err := crypto.SaveECDSA(keyfile, key); err != nil {
  158. glog.V(logger.Error).Infoln("could not persist nodekey: ", err)
  159. }
  160. return key, nil
  161. }
  162. type Ethereum struct {
  163. // Channel for shutting down the ethereum
  164. shutdownChan chan bool
  165. // DB interfaces
  166. blockDb common.Database // Block chain database
  167. stateDb common.Database // State changes database
  168. extraDb common.Database // Extra database (txs, etc)
  169. // Closed when databases are flushed and closed
  170. databasesClosed chan bool
  171. //*** SERVICES ***
  172. // State manager for processing new blocks and managing the over all states
  173. blockProcessor *core.BlockProcessor
  174. txPool *core.TxPool
  175. chainManager *core.ChainManager
  176. accountManager *accounts.Manager
  177. whisper *whisper.Whisper
  178. pow *ethash.Ethash
  179. protocolManager *ProtocolManager
  180. SolcPath string
  181. solc *compiler.Solidity
  182. GpoMinGasPrice *big.Int
  183. GpoMaxGasPrice *big.Int
  184. GpoFullBlockRatio int
  185. GpobaseStepDown int
  186. GpobaseStepUp int
  187. GpobaseCorrectionFactor int
  188. net *p2p.Server
  189. eventMux *event.TypeMux
  190. miner *miner.Miner
  191. // logger logger.LogSystem
  192. Mining bool
  193. MinerThreads int
  194. NatSpec bool
  195. DataDir string
  196. AutoDAG bool
  197. PowTest bool
  198. autodagquit chan bool
  199. etherbase common.Address
  200. clientVersion string
  201. netVersionId int
  202. shhVersionId int
  203. }
  204. func New(config *Config) (*Ethereum, error) {
  205. // Bootstrap database
  206. logger.New(config.DataDir, config.LogFile, config.Verbosity)
  207. if len(config.LogJSON) > 0 {
  208. logger.NewJSONsystem(config.DataDir, config.LogJSON)
  209. }
  210. // Let the database take 3/4 of the max open files (TODO figure out a way to get the actual limit of the open files)
  211. const dbCount = 3
  212. ethdb.OpenFileLimit = 128 / (dbCount + 1)
  213. newdb := config.NewDB
  214. if newdb == nil {
  215. newdb = func(path string) (common.Database, error) { return ethdb.NewLDBDatabase(path) }
  216. }
  217. blockDb, err := newdb(filepath.Join(config.DataDir, "blockchain"))
  218. if err != nil {
  219. return nil, fmt.Errorf("blockchain db err: %v", err)
  220. }
  221. if db, ok := blockDb.(*ethdb.LDBDatabase); ok {
  222. db.GetTimer = metrics.NewTimer("eth/db/block/user/gets")
  223. db.PutTimer = metrics.NewTimer("eth/db/block/user/puts")
  224. db.MissMeter = metrics.NewMeter("eth/db/block/user/misses")
  225. db.ReadMeter = metrics.NewMeter("eth/db/block/user/reads")
  226. db.WriteMeter = metrics.NewMeter("eth/db/block/user/writes")
  227. db.CompTimeMeter = metrics.NewMeter("eth/db/block/compact/time")
  228. db.CompReadMeter = metrics.NewMeter("eth/db/block/compact/input")
  229. db.CompWriteMeter = metrics.NewMeter("eth/db/block/compact/output")
  230. }
  231. stateDb, err := newdb(filepath.Join(config.DataDir, "state"))
  232. if err != nil {
  233. return nil, fmt.Errorf("state db err: %v", err)
  234. }
  235. if db, ok := stateDb.(*ethdb.LDBDatabase); ok {
  236. db.GetTimer = metrics.NewTimer("eth/db/state/user/gets")
  237. db.PutTimer = metrics.NewTimer("eth/db/state/user/puts")
  238. db.MissMeter = metrics.NewMeter("eth/db/state/user/misses")
  239. db.ReadMeter = metrics.NewMeter("eth/db/state/user/reads")
  240. db.WriteMeter = metrics.NewMeter("eth/db/state/user/writes")
  241. db.CompTimeMeter = metrics.NewMeter("eth/db/state/compact/time")
  242. db.CompReadMeter = metrics.NewMeter("eth/db/state/compact/input")
  243. db.CompWriteMeter = metrics.NewMeter("eth/db/state/compact/output")
  244. }
  245. extraDb, err := newdb(filepath.Join(config.DataDir, "extra"))
  246. if err != nil {
  247. return nil, fmt.Errorf("extra db err: %v", err)
  248. }
  249. if db, ok := extraDb.(*ethdb.LDBDatabase); ok {
  250. db.GetTimer = metrics.NewTimer("eth/db/extra/user/gets")
  251. db.PutTimer = metrics.NewTimer("eth/db/extra/user/puts")
  252. db.MissMeter = metrics.NewMeter("eth/db/extra/user/misses")
  253. db.ReadMeter = metrics.NewMeter("eth/db/extra/user/reads")
  254. db.WriteMeter = metrics.NewMeter("eth/db/extra/user/writes")
  255. db.CompTimeMeter = metrics.NewMeter("eth/db/extra/compact/time")
  256. db.CompReadMeter = metrics.NewMeter("eth/db/extra/compact/input")
  257. db.CompWriteMeter = metrics.NewMeter("eth/db/extra/compact/output")
  258. }
  259. nodeDb := filepath.Join(config.DataDir, "nodes")
  260. // Perform database sanity checks
  261. /*
  262. // The databases were previously tied to protocol versions. Currently we
  263. // are moving away from this decision as approaching Frontier. The below
  264. // check was left in for now but should eventually be just dropped.
  265. d, _ := blockDb.Get([]byte("ProtocolVersion"))
  266. protov := int(common.NewValue(d).Uint())
  267. if protov != config.ProtocolVersion && protov != 0 {
  268. path := filepath.Join(config.DataDir, "blockchain")
  269. return nil, fmt.Errorf("Database version mismatch. Protocol(%d / %d). `rm -rf %s`", protov, config.ProtocolVersion, path)
  270. }
  271. saveProtocolVersion(blockDb, config.ProtocolVersion)
  272. */
  273. glog.V(logger.Info).Infof("Protocol Versions: %v, Network Id: %v", ProtocolVersions, config.NetworkId)
  274. if !config.SkipBcVersionCheck {
  275. b, _ := blockDb.Get([]byte("BlockchainVersion"))
  276. bcVersion := int(common.NewValue(b).Uint())
  277. if bcVersion != config.BlockChainVersion && bcVersion != 0 {
  278. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, config.BlockChainVersion)
  279. }
  280. saveBlockchainVersion(blockDb, config.BlockChainVersion)
  281. }
  282. glog.V(logger.Info).Infof("Blockchain DB Version: %d", config.BlockChainVersion)
  283. eth := &Ethereum{
  284. shutdownChan: make(chan bool),
  285. databasesClosed: make(chan bool),
  286. blockDb: blockDb,
  287. stateDb: stateDb,
  288. extraDb: extraDb,
  289. eventMux: &event.TypeMux{},
  290. accountManager: config.AccountManager,
  291. DataDir: config.DataDir,
  292. etherbase: common.HexToAddress(config.Etherbase),
  293. clientVersion: config.Name, // TODO should separate from Name
  294. netVersionId: config.NetworkId,
  295. NatSpec: config.NatSpec,
  296. MinerThreads: config.MinerThreads,
  297. SolcPath: config.SolcPath,
  298. AutoDAG: config.AutoDAG,
  299. PowTest: config.PowTest,
  300. GpoMinGasPrice: config.GpoMinGasPrice,
  301. GpoMaxGasPrice: config.GpoMaxGasPrice,
  302. GpoFullBlockRatio: config.GpoFullBlockRatio,
  303. GpobaseStepDown: config.GpobaseStepDown,
  304. GpobaseStepUp: config.GpobaseStepUp,
  305. GpobaseCorrectionFactor: config.GpobaseCorrectionFactor,
  306. }
  307. if config.PowTest {
  308. glog.V(logger.Info).Infof("ethash used in test mode")
  309. eth.pow, err = ethash.NewForTesting()
  310. if err != nil {
  311. return nil, err
  312. }
  313. } else {
  314. eth.pow = ethash.New()
  315. }
  316. genesis := core.GenesisBlock(uint64(config.GenesisNonce), stateDb)
  317. eth.chainManager, err = core.NewChainManager(genesis, blockDb, stateDb, extraDb, eth.pow, eth.EventMux())
  318. if err != nil {
  319. return nil, err
  320. }
  321. eth.txPool = core.NewTxPool(eth.EventMux(), eth.chainManager.State, eth.chainManager.GasLimit)
  322. eth.blockProcessor = core.NewBlockProcessor(stateDb, extraDb, eth.pow, eth.chainManager, eth.EventMux())
  323. eth.chainManager.SetProcessor(eth.blockProcessor)
  324. eth.protocolManager = NewProtocolManager(config.NetworkId, eth.eventMux, eth.txPool, eth.pow, eth.chainManager)
  325. eth.miner = miner.New(eth, eth.EventMux(), eth.pow)
  326. eth.miner.SetGasPrice(config.GasPrice)
  327. if config.Shh {
  328. eth.whisper = whisper.New()
  329. eth.shhVersionId = int(eth.whisper.Version())
  330. }
  331. netprv, err := config.nodeKey()
  332. if err != nil {
  333. return nil, err
  334. }
  335. protocols := append([]p2p.Protocol{}, eth.protocolManager.SubProtocols...)
  336. if config.Shh {
  337. protocols = append(protocols, eth.whisper.Protocol())
  338. }
  339. eth.net = &p2p.Server{
  340. PrivateKey: netprv,
  341. Name: config.Name,
  342. MaxPeers: config.MaxPeers,
  343. MaxPendingPeers: config.MaxPendingPeers,
  344. Discovery: config.Discovery,
  345. Protocols: protocols,
  346. NAT: config.NAT,
  347. NoDial: !config.Dial,
  348. BootstrapNodes: config.parseBootNodes(),
  349. StaticNodes: config.parseNodes(staticNodes),
  350. TrustedNodes: config.parseNodes(trustedNodes),
  351. NodeDatabase: nodeDb,
  352. }
  353. if len(config.Port) > 0 {
  354. eth.net.ListenAddr = ":" + config.Port
  355. }
  356. vm.Debug = config.VmDebug
  357. return eth, nil
  358. }
  359. type NodeInfo struct {
  360. Name string
  361. NodeUrl string
  362. NodeID string
  363. IP string
  364. DiscPort int // UDP listening port for discovery protocol
  365. TCPPort int // TCP listening port for RLPx
  366. Td string
  367. ListenAddr string
  368. }
  369. func (s *Ethereum) NodeInfo() *NodeInfo {
  370. node := s.net.Self()
  371. return &NodeInfo{
  372. Name: s.Name(),
  373. NodeUrl: node.String(),
  374. NodeID: node.ID.String(),
  375. IP: node.IP.String(),
  376. DiscPort: int(node.UDP),
  377. TCPPort: int(node.TCP),
  378. ListenAddr: s.net.ListenAddr,
  379. Td: s.ChainManager().Td().String(),
  380. }
  381. }
  382. type PeerInfo struct {
  383. ID string
  384. Name string
  385. Caps string
  386. RemoteAddress string
  387. LocalAddress string
  388. }
  389. func newPeerInfo(peer *p2p.Peer) *PeerInfo {
  390. var caps []string
  391. for _, cap := range peer.Caps() {
  392. caps = append(caps, cap.String())
  393. }
  394. return &PeerInfo{
  395. ID: peer.ID().String(),
  396. Name: peer.Name(),
  397. Caps: strings.Join(caps, ", "),
  398. RemoteAddress: peer.RemoteAddr().String(),
  399. LocalAddress: peer.LocalAddr().String(),
  400. }
  401. }
  402. // PeersInfo returns an array of PeerInfo objects describing connected peers
  403. func (s *Ethereum) PeersInfo() (peersinfo []*PeerInfo) {
  404. for _, peer := range s.net.Peers() {
  405. if peer != nil {
  406. peersinfo = append(peersinfo, newPeerInfo(peer))
  407. }
  408. }
  409. return
  410. }
  411. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  412. s.chainManager.ResetWithGenesisBlock(gb)
  413. }
  414. func (s *Ethereum) StartMining(threads int) error {
  415. eb, err := s.Etherbase()
  416. if err != nil {
  417. err = fmt.Errorf("Cannot start mining without etherbase address: %v", err)
  418. glog.V(logger.Error).Infoln(err)
  419. return err
  420. }
  421. go s.miner.Start(eb, threads)
  422. return nil
  423. }
  424. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  425. eb = s.etherbase
  426. if (eb == common.Address{}) {
  427. err = fmt.Errorf("etherbase address must be explicitly specified")
  428. }
  429. return
  430. }
  431. func (s *Ethereum) StopMining() { s.miner.Stop() }
  432. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  433. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  434. // func (s *Ethereum) Logger() logger.LogSystem { return s.logger }
  435. func (s *Ethereum) Name() string { return s.net.Name }
  436. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  437. func (s *Ethereum) ChainManager() *core.ChainManager { return s.chainManager }
  438. func (s *Ethereum) BlockProcessor() *core.BlockProcessor { return s.blockProcessor }
  439. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  440. func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper }
  441. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  442. func (s *Ethereum) BlockDb() common.Database { return s.blockDb }
  443. func (s *Ethereum) StateDb() common.Database { return s.stateDb }
  444. func (s *Ethereum) ExtraDb() common.Database { return s.extraDb }
  445. func (s *Ethereum) IsListening() bool { return true } // Always listening
  446. func (s *Ethereum) PeerCount() int { return s.net.PeerCount() }
  447. func (s *Ethereum) Peers() []*p2p.Peer { return s.net.Peers() }
  448. func (s *Ethereum) MaxPeers() int { return s.net.MaxPeers }
  449. func (s *Ethereum) ClientVersion() string { return s.clientVersion }
  450. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  451. func (s *Ethereum) NetVersion() int { return s.netVersionId }
  452. func (s *Ethereum) ShhVersion() int { return s.shhVersionId }
  453. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  454. // Start the ethereum
  455. func (s *Ethereum) Start() error {
  456. jsonlogger.LogJson(&logger.LogStarting{
  457. ClientString: s.net.Name,
  458. ProtocolVersion: s.EthVersion(),
  459. })
  460. err := s.net.Start()
  461. if err != nil {
  462. return err
  463. }
  464. // periodically flush databases
  465. go s.syncDatabases()
  466. if s.AutoDAG {
  467. s.StartAutoDAG()
  468. }
  469. s.protocolManager.Start()
  470. if s.whisper != nil {
  471. s.whisper.Start()
  472. }
  473. glog.V(logger.Info).Infoln("Server started")
  474. return nil
  475. }
  476. // sync databases every minute. If flushing fails we exit immediatly. The system
  477. // may not continue under any circumstances.
  478. func (s *Ethereum) syncDatabases() {
  479. ticker := time.NewTicker(1 * time.Minute)
  480. done:
  481. for {
  482. select {
  483. case <-ticker.C:
  484. // don't change the order of database flushes
  485. if err := s.extraDb.Flush(); err != nil {
  486. glog.Fatalf("fatal error: flush extraDb: %v (Restart your node. We are aware of this issue)\n", err)
  487. }
  488. if err := s.stateDb.Flush(); err != nil {
  489. glog.Fatalf("fatal error: flush stateDb: %v (Restart your node. We are aware of this issue)\n", err)
  490. }
  491. if err := s.blockDb.Flush(); err != nil {
  492. glog.Fatalf("fatal error: flush blockDb: %v (Restart your node. We are aware of this issue)\n", err)
  493. }
  494. case <-s.shutdownChan:
  495. break done
  496. }
  497. }
  498. s.blockDb.Close()
  499. s.stateDb.Close()
  500. s.extraDb.Close()
  501. close(s.databasesClosed)
  502. }
  503. func (s *Ethereum) StartForTest() {
  504. jsonlogger.LogJson(&logger.LogStarting{
  505. ClientString: s.net.Name,
  506. ProtocolVersion: s.EthVersion(),
  507. })
  508. }
  509. // AddPeer connects to the given node and maintains the connection until the
  510. // server is shut down. If the connection fails for any reason, the server will
  511. // attempt to reconnect the peer.
  512. func (self *Ethereum) AddPeer(nodeURL string) error {
  513. n, err := discover.ParseNode(nodeURL)
  514. if err != nil {
  515. return fmt.Errorf("invalid node URL: %v", err)
  516. }
  517. self.net.AddPeer(n)
  518. return nil
  519. }
  520. func (s *Ethereum) Stop() {
  521. s.net.Stop()
  522. s.chainManager.Stop()
  523. s.protocolManager.Stop()
  524. s.txPool.Stop()
  525. s.eventMux.Stop()
  526. if s.whisper != nil {
  527. s.whisper.Stop()
  528. }
  529. s.StopAutoDAG()
  530. close(s.shutdownChan)
  531. }
  532. // This function will wait for a shutdown and resumes main thread execution
  533. func (s *Ethereum) WaitForShutdown() {
  534. <-s.databasesClosed
  535. <-s.shutdownChan
  536. }
  537. // StartAutoDAG() spawns a go routine that checks the DAG every autoDAGcheckInterval
  538. // by default that is 10 times per epoch
  539. // in epoch n, if we past autoDAGepochHeight within-epoch blocks,
  540. // it calls ethash.MakeDAG to pregenerate the DAG for the next epoch n+1
  541. // if it does not exist yet as well as remove the DAG for epoch n-1
  542. // the loop quits if autodagquit channel is closed, it can safely restart and
  543. // stop any number of times.
  544. // For any more sophisticated pattern of DAG generation, use CLI subcommand
  545. // makedag
  546. func (self *Ethereum) StartAutoDAG() {
  547. if self.autodagquit != nil {
  548. return // already started
  549. }
  550. go func() {
  551. glog.V(logger.Info).Infof("Automatic pregeneration of ethash DAG ON (ethash dir: %s)", ethash.DefaultDir)
  552. var nextEpoch uint64
  553. timer := time.After(0)
  554. self.autodagquit = make(chan bool)
  555. for {
  556. select {
  557. case <-timer:
  558. glog.V(logger.Info).Infof("checking DAG (ethash dir: %s)", ethash.DefaultDir)
  559. currentBlock := self.ChainManager().CurrentBlock().NumberU64()
  560. thisEpoch := currentBlock / epochLength
  561. if nextEpoch <= thisEpoch {
  562. if currentBlock%epochLength > autoDAGepochHeight {
  563. if thisEpoch > 0 {
  564. previousDag, previousDagFull := dagFiles(thisEpoch - 1)
  565. os.Remove(filepath.Join(ethash.DefaultDir, previousDag))
  566. os.Remove(filepath.Join(ethash.DefaultDir, previousDagFull))
  567. glog.V(logger.Info).Infof("removed DAG for epoch %d (%s)", thisEpoch-1, previousDag)
  568. }
  569. nextEpoch = thisEpoch + 1
  570. dag, _ := dagFiles(nextEpoch)
  571. if _, err := os.Stat(dag); os.IsNotExist(err) {
  572. glog.V(logger.Info).Infof("Pregenerating DAG for epoch %d (%s)", nextEpoch, dag)
  573. err := ethash.MakeDAG(nextEpoch*epochLength, "") // "" -> ethash.DefaultDir
  574. if err != nil {
  575. glog.V(logger.Error).Infof("Error generating DAG for epoch %d (%s)", nextEpoch, dag)
  576. return
  577. }
  578. } else {
  579. glog.V(logger.Error).Infof("DAG for epoch %d (%s)", nextEpoch, dag)
  580. }
  581. }
  582. }
  583. timer = time.After(autoDAGcheckInterval)
  584. case <-self.autodagquit:
  585. return
  586. }
  587. }
  588. }()
  589. }
  590. // dagFiles(epoch) returns the two alternative DAG filenames (not a path)
  591. // 1) <revision>-<hex(seedhash[8])> 2) full-R<revision>-<hex(seedhash[8])>
  592. func dagFiles(epoch uint64) (string, string) {
  593. seedHash, _ := ethash.GetSeedHash(epoch * epochLength)
  594. dag := fmt.Sprintf("full-R%d-%x", ethashRevision, seedHash[:8])
  595. return dag, "full-R" + dag
  596. }
  597. // stopAutoDAG stops automatic DAG pregeneration by quitting the loop
  598. func (self *Ethereum) StopAutoDAG() {
  599. if self.autodagquit != nil {
  600. close(self.autodagquit)
  601. self.autodagquit = nil
  602. }
  603. glog.V(logger.Info).Infof("Automatic pregeneration of ethash DAG OFF (ethash dir: %s)", ethash.DefaultDir)
  604. }
  605. /*
  606. // The databases were previously tied to protocol versions. Currently we
  607. // are moving away from this decision as approaching Frontier. The below
  608. // code was left in for now but should eventually be just dropped.
  609. func saveProtocolVersion(db common.Database, protov int) {
  610. d, _ := db.Get([]byte("ProtocolVersion"))
  611. protocolVersion := common.NewValue(d).Uint()
  612. if protocolVersion == 0 {
  613. db.Put([]byte("ProtocolVersion"), common.NewValue(protov).Bytes())
  614. }
  615. }
  616. */
  617. func saveBlockchainVersion(db common.Database, bcVersion int) {
  618. d, _ := db.Get([]byte("BlockchainVersion"))
  619. blockchainVersion := common.NewValue(d).Uint()
  620. if blockchainVersion == 0 {
  621. db.Put([]byte("BlockchainVersion"), common.NewValue(bcVersion).Bytes())
  622. }
  623. }
  624. func (self *Ethereum) Solc() (*compiler.Solidity, error) {
  625. var err error
  626. if self.solc == nil {
  627. self.solc, err = compiler.New(self.SolcPath)
  628. }
  629. return self.solc, err
  630. }
  631. // set in js console via admin interface or wrapper from cli flags
  632. func (self *Ethereum) SetSolc(solcPath string) (*compiler.Solidity, error) {
  633. self.SolcPath = solcPath
  634. self.solc = nil
  635. return self.Solc()
  636. }