backend.go 20 KB

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