backend.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser 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. // The go-ethereum library 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 Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package eth implements the Ethereum protocol.
  17. package eth
  18. import (
  19. "bytes"
  20. "fmt"
  21. "math/big"
  22. "os"
  23. "path/filepath"
  24. "regexp"
  25. "strings"
  26. "time"
  27. "github.com/ethereum/ethash"
  28. "github.com/ethereum/go-ethereum/accounts"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/common/compiler"
  31. "github.com/ethereum/go-ethereum/common/httpclient"
  32. "github.com/ethereum/go-ethereum/core"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/eth/downloader"
  35. "github.com/ethereum/go-ethereum/ethdb"
  36. "github.com/ethereum/go-ethereum/event"
  37. "github.com/ethereum/go-ethereum/logger"
  38. "github.com/ethereum/go-ethereum/logger/glog"
  39. "github.com/ethereum/go-ethereum/miner"
  40. "github.com/ethereum/go-ethereum/node"
  41. "github.com/ethereum/go-ethereum/p2p"
  42. "github.com/ethereum/go-ethereum/rlp"
  43. )
  44. const (
  45. epochLength = 30000
  46. ethashRevision = 23
  47. autoDAGcheckInterval = 10 * time.Hour
  48. autoDAGepochHeight = epochLength / 2
  49. )
  50. var (
  51. datadirInUseErrnos = map[uint]bool{11: true, 32: true, 35: true}
  52. portInUseErrRE = regexp.MustCompile("address already in use")
  53. )
  54. type Config struct {
  55. NetworkId int // Network ID to use for selecting peers to connect to
  56. Genesis string // Genesis JSON to seed the chain database with
  57. FastSync bool // Enables the state download based fast synchronisation algorithm
  58. BlockChainVersion int
  59. SkipBcVersionCheck bool // e.g. blockchain export
  60. DatabaseCache int
  61. NatSpec bool
  62. DocRoot string
  63. AutoDAG bool
  64. PowTest bool
  65. ExtraData []byte
  66. AccountManager *accounts.Manager
  67. Etherbase common.Address
  68. GasPrice *big.Int
  69. MinerThreads int
  70. SolcPath string
  71. GpoMinGasPrice *big.Int
  72. GpoMaxGasPrice *big.Int
  73. GpoFullBlockRatio int
  74. GpobaseStepDown int
  75. GpobaseStepUp int
  76. GpobaseCorrectionFactor int
  77. TestGenesisBlock *types.Block // Genesis block to seed the chain database with (testing only!)
  78. TestGenesisState ethdb.Database // Genesis state to seed the database with (testing only!)
  79. }
  80. type Ethereum struct {
  81. // Channel for shutting down the ethereum
  82. shutdownChan chan bool
  83. // DB interfaces
  84. chainDb ethdb.Database // Block chain database
  85. dappDb ethdb.Database // Dapp database
  86. // Handlers
  87. txPool *core.TxPool
  88. blockchain *core.BlockChain
  89. accountManager *accounts.Manager
  90. pow *ethash.Ethash
  91. protocolManager *ProtocolManager
  92. SolcPath string
  93. solc *compiler.Solidity
  94. GpoMinGasPrice *big.Int
  95. GpoMaxGasPrice *big.Int
  96. GpoFullBlockRatio int
  97. GpobaseStepDown int
  98. GpobaseStepUp int
  99. GpobaseCorrectionFactor int
  100. httpclient *httpclient.HTTPClient
  101. eventMux *event.TypeMux
  102. miner *miner.Miner
  103. Mining bool
  104. MinerThreads int
  105. NatSpec bool
  106. AutoDAG bool
  107. PowTest bool
  108. autodagquit chan bool
  109. etherbase common.Address
  110. netVersionId int
  111. }
  112. func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
  113. // 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)
  114. const dbCount = 3
  115. ethdb.OpenFileLimit = 128 / (dbCount + 1)
  116. // Open the chain database and perform any upgrades needed
  117. chainDb, err := ctx.OpenDatabase("chaindata", config.DatabaseCache)
  118. if err != nil {
  119. return nil, err
  120. }
  121. if db, ok := chainDb.(*ethdb.LDBDatabase); ok {
  122. db.Meter("eth/db/chaindata/")
  123. }
  124. if err := upgradeChainDatabase(chainDb); err != nil {
  125. return nil, err
  126. }
  127. if err := addMipmapBloomBins(chainDb); err != nil {
  128. return nil, err
  129. }
  130. dappDb, err := ctx.OpenDatabase("dapp", config.DatabaseCache)
  131. if err != nil {
  132. return nil, err
  133. }
  134. if db, ok := dappDb.(*ethdb.LDBDatabase); ok {
  135. db.Meter("eth/db/dapp/")
  136. }
  137. glog.V(logger.Info).Infof("Protocol Versions: %v, Network Id: %v", ProtocolVersions, config.NetworkId)
  138. // Load up any custom genesis block if requested
  139. if len(config.Genesis) > 0 {
  140. block, err := core.WriteGenesisBlock(chainDb, strings.NewReader(config.Genesis))
  141. if err != nil {
  142. return nil, err
  143. }
  144. glog.V(logger.Info).Infof("Successfully wrote custom genesis block: %x", block.Hash())
  145. }
  146. // Load up a test setup if directly injected
  147. if config.TestGenesisState != nil {
  148. chainDb = config.TestGenesisState
  149. }
  150. if config.TestGenesisBlock != nil {
  151. core.WriteTd(chainDb, config.TestGenesisBlock.Hash(), config.TestGenesisBlock.Difficulty())
  152. core.WriteBlock(chainDb, config.TestGenesisBlock)
  153. core.WriteCanonicalHash(chainDb, config.TestGenesisBlock.Hash(), config.TestGenesisBlock.NumberU64())
  154. core.WriteHeadBlockHash(chainDb, config.TestGenesisBlock.Hash())
  155. }
  156. if !config.SkipBcVersionCheck {
  157. b, _ := chainDb.Get([]byte("BlockchainVersion"))
  158. bcVersion := int(common.NewValue(b).Uint())
  159. if bcVersion != config.BlockChainVersion && bcVersion != 0 {
  160. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, config.BlockChainVersion)
  161. }
  162. saveBlockchainVersion(chainDb, config.BlockChainVersion)
  163. }
  164. glog.V(logger.Info).Infof("Blockchain DB Version: %d", config.BlockChainVersion)
  165. eth := &Ethereum{
  166. shutdownChan: make(chan bool),
  167. chainDb: chainDb,
  168. dappDb: dappDb,
  169. eventMux: &event.TypeMux{},
  170. accountManager: config.AccountManager,
  171. etherbase: config.Etherbase,
  172. netVersionId: config.NetworkId,
  173. NatSpec: config.NatSpec,
  174. MinerThreads: config.MinerThreads,
  175. SolcPath: config.SolcPath,
  176. AutoDAG: config.AutoDAG,
  177. PowTest: config.PowTest,
  178. GpoMinGasPrice: config.GpoMinGasPrice,
  179. GpoMaxGasPrice: config.GpoMaxGasPrice,
  180. GpoFullBlockRatio: config.GpoFullBlockRatio,
  181. GpobaseStepDown: config.GpobaseStepDown,
  182. GpobaseStepUp: config.GpobaseStepUp,
  183. GpobaseCorrectionFactor: config.GpobaseCorrectionFactor,
  184. httpclient: httpclient.New(config.DocRoot),
  185. }
  186. if config.PowTest {
  187. glog.V(logger.Info).Infof("ethash used in test mode")
  188. eth.pow, err = ethash.NewForTesting()
  189. if err != nil {
  190. return nil, err
  191. }
  192. } else {
  193. eth.pow = ethash.New()
  194. }
  195. //genesis := core.GenesisBlock(uint64(config.GenesisNonce), stateDb)
  196. eth.blockchain, err = core.NewBlockChain(chainDb, eth.pow, eth.EventMux())
  197. if err != nil {
  198. if err == core.ErrNoGenesis {
  199. return nil, fmt.Errorf(`Genesis block not found. Please supply a genesis block with the "--genesis /path/to/file" argument`)
  200. }
  201. return nil, err
  202. }
  203. newPool := core.NewTxPool(eth.EventMux(), eth.blockchain.State, eth.blockchain.GasLimit)
  204. eth.txPool = newPool
  205. if eth.protocolManager, err = NewProtocolManager(config.FastSync, config.NetworkId, eth.eventMux, eth.txPool, eth.pow, eth.blockchain, chainDb); err != nil {
  206. return nil, err
  207. }
  208. eth.miner = miner.New(eth, eth.EventMux(), eth.pow)
  209. eth.miner.SetGasPrice(config.GasPrice)
  210. eth.miner.SetExtra(config.ExtraData)
  211. return eth, nil
  212. }
  213. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  214. s.blockchain.ResetWithGenesisBlock(gb)
  215. }
  216. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  217. eb = s.etherbase
  218. if (eb == common.Address{}) {
  219. addr, e := s.AccountManager().AddressByIndex(0)
  220. if e != nil {
  221. err = fmt.Errorf("etherbase address must be explicitly specified")
  222. }
  223. eb = common.HexToAddress(addr)
  224. }
  225. return
  226. }
  227. // set in js console via admin interface or wrapper from cli flags
  228. func (self *Ethereum) SetEtherbase(etherbase common.Address) {
  229. self.etherbase = etherbase
  230. self.miner.SetEtherbase(etherbase)
  231. }
  232. func (s *Ethereum) StopMining() { s.miner.Stop() }
  233. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  234. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  235. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  236. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  237. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  238. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  239. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  240. func (s *Ethereum) DappDb() ethdb.Database { return s.dappDb }
  241. func (s *Ethereum) IsListening() bool { return true } // Always listening
  242. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  243. func (s *Ethereum) NetVersion() int { return s.netVersionId }
  244. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  245. // Protocols implements node.Service, returning all the currently configured
  246. // network protocols to start.
  247. func (s *Ethereum) Protocols() []p2p.Protocol {
  248. return s.protocolManager.SubProtocols
  249. }
  250. // Start implements node.Service, starting all internal goroutines needed by the
  251. // Ethereum protocol implementation.
  252. func (s *Ethereum) Start(*p2p.Server) error {
  253. if s.AutoDAG {
  254. s.StartAutoDAG()
  255. }
  256. s.protocolManager.Start()
  257. return nil
  258. }
  259. // Stop implements node.Service, terminating all internal goroutines used by the
  260. // Ethereum protocol.
  261. func (s *Ethereum) Stop() error {
  262. s.blockchain.Stop()
  263. s.protocolManager.Stop()
  264. s.txPool.Stop()
  265. s.eventMux.Stop()
  266. s.StopAutoDAG()
  267. s.chainDb.Close()
  268. s.dappDb.Close()
  269. close(s.shutdownChan)
  270. return nil
  271. }
  272. // This function will wait for a shutdown and resumes main thread execution
  273. func (s *Ethereum) WaitForShutdown() {
  274. <-s.shutdownChan
  275. }
  276. // StartAutoDAG() spawns a go routine that checks the DAG every autoDAGcheckInterval
  277. // by default that is 10 times per epoch
  278. // in epoch n, if we past autoDAGepochHeight within-epoch blocks,
  279. // it calls ethash.MakeDAG to pregenerate the DAG for the next epoch n+1
  280. // if it does not exist yet as well as remove the DAG for epoch n-1
  281. // the loop quits if autodagquit channel is closed, it can safely restart and
  282. // stop any number of times.
  283. // For any more sophisticated pattern of DAG generation, use CLI subcommand
  284. // makedag
  285. func (self *Ethereum) StartAutoDAG() {
  286. if self.autodagquit != nil {
  287. return // already started
  288. }
  289. go func() {
  290. glog.V(logger.Info).Infof("Automatic pregeneration of ethash DAG ON (ethash dir: %s)", ethash.DefaultDir)
  291. var nextEpoch uint64
  292. timer := time.After(0)
  293. self.autodagquit = make(chan bool)
  294. for {
  295. select {
  296. case <-timer:
  297. glog.V(logger.Info).Infof("checking DAG (ethash dir: %s)", ethash.DefaultDir)
  298. currentBlock := self.BlockChain().CurrentBlock().NumberU64()
  299. thisEpoch := currentBlock / epochLength
  300. if nextEpoch <= thisEpoch {
  301. if currentBlock%epochLength > autoDAGepochHeight {
  302. if thisEpoch > 0 {
  303. previousDag, previousDagFull := dagFiles(thisEpoch - 1)
  304. os.Remove(filepath.Join(ethash.DefaultDir, previousDag))
  305. os.Remove(filepath.Join(ethash.DefaultDir, previousDagFull))
  306. glog.V(logger.Info).Infof("removed DAG for epoch %d (%s)", thisEpoch-1, previousDag)
  307. }
  308. nextEpoch = thisEpoch + 1
  309. dag, _ := dagFiles(nextEpoch)
  310. if _, err := os.Stat(dag); os.IsNotExist(err) {
  311. glog.V(logger.Info).Infof("Pregenerating DAG for epoch %d (%s)", nextEpoch, dag)
  312. err := ethash.MakeDAG(nextEpoch*epochLength, "") // "" -> ethash.DefaultDir
  313. if err != nil {
  314. glog.V(logger.Error).Infof("Error generating DAG for epoch %d (%s)", nextEpoch, dag)
  315. return
  316. }
  317. } else {
  318. glog.V(logger.Error).Infof("DAG for epoch %d (%s)", nextEpoch, dag)
  319. }
  320. }
  321. }
  322. timer = time.After(autoDAGcheckInterval)
  323. case <-self.autodagquit:
  324. return
  325. }
  326. }
  327. }()
  328. }
  329. // stopAutoDAG stops automatic DAG pregeneration by quitting the loop
  330. func (self *Ethereum) StopAutoDAG() {
  331. if self.autodagquit != nil {
  332. close(self.autodagquit)
  333. self.autodagquit = nil
  334. }
  335. glog.V(logger.Info).Infof("Automatic pregeneration of ethash DAG OFF (ethash dir: %s)", ethash.DefaultDir)
  336. }
  337. // HTTPClient returns the light http client used for fetching offchain docs
  338. // (natspec, source for verification)
  339. func (self *Ethereum) HTTPClient() *httpclient.HTTPClient {
  340. return self.httpclient
  341. }
  342. func (self *Ethereum) Solc() (*compiler.Solidity, error) {
  343. var err error
  344. if self.solc == nil {
  345. self.solc, err = compiler.New(self.SolcPath)
  346. }
  347. return self.solc, err
  348. }
  349. // set in js console via admin interface or wrapper from cli flags
  350. func (self *Ethereum) SetSolc(solcPath string) (*compiler.Solidity, error) {
  351. self.SolcPath = solcPath
  352. self.solc = nil
  353. return self.Solc()
  354. }
  355. // dagFiles(epoch) returns the two alternative DAG filenames (not a path)
  356. // 1) <revision>-<hex(seedhash[8])> 2) full-R<revision>-<hex(seedhash[8])>
  357. func dagFiles(epoch uint64) (string, string) {
  358. seedHash, _ := ethash.GetSeedHash(epoch * epochLength)
  359. dag := fmt.Sprintf("full-R%d-%x", ethashRevision, seedHash[:8])
  360. return dag, "full-R" + dag
  361. }
  362. func saveBlockchainVersion(db ethdb.Database, bcVersion int) {
  363. d, _ := db.Get([]byte("BlockchainVersion"))
  364. blockchainVersion := common.NewValue(d).Uint()
  365. if blockchainVersion == 0 {
  366. db.Put([]byte("BlockchainVersion"), common.NewValue(bcVersion).Bytes())
  367. }
  368. }
  369. // upgradeChainDatabase ensures that the chain database stores block split into
  370. // separate header and body entries.
  371. func upgradeChainDatabase(db ethdb.Database) error {
  372. // Short circuit if the head block is stored already as separate header and body
  373. data, err := db.Get([]byte("LastBlock"))
  374. if err != nil {
  375. return nil
  376. }
  377. head := common.BytesToHash(data)
  378. if block := core.GetBlockByHashOld(db, head); block == nil {
  379. return nil
  380. }
  381. // At least some of the database is still the old format, upgrade (skip the head block!)
  382. glog.V(logger.Info).Info("Old database detected, upgrading...")
  383. if db, ok := db.(*ethdb.LDBDatabase); ok {
  384. blockPrefix := []byte("block-hash-")
  385. for it := db.NewIterator(); it.Next(); {
  386. // Skip anything other than a combined block
  387. if !bytes.HasPrefix(it.Key(), blockPrefix) {
  388. continue
  389. }
  390. // Skip the head block (merge last to signal upgrade completion)
  391. if bytes.HasSuffix(it.Key(), head.Bytes()) {
  392. continue
  393. }
  394. // Load the block, split and serialize (order!)
  395. block := core.GetBlockByHashOld(db, common.BytesToHash(bytes.TrimPrefix(it.Key(), blockPrefix)))
  396. if err := core.WriteTd(db, block.Hash(), block.DeprecatedTd()); err != nil {
  397. return err
  398. }
  399. if err := core.WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
  400. return err
  401. }
  402. if err := core.WriteHeader(db, block.Header()); err != nil {
  403. return err
  404. }
  405. if err := db.Delete(it.Key()); err != nil {
  406. return err
  407. }
  408. }
  409. // Lastly, upgrade the head block, disabling the upgrade mechanism
  410. current := core.GetBlockByHashOld(db, head)
  411. if err := core.WriteTd(db, current.Hash(), current.DeprecatedTd()); err != nil {
  412. return err
  413. }
  414. if err := core.WriteBody(db, current.Hash(), &types.Body{current.Transactions(), current.Uncles()}); err != nil {
  415. return err
  416. }
  417. if err := core.WriteHeader(db, current.Header()); err != nil {
  418. return err
  419. }
  420. }
  421. return nil
  422. }
  423. func addMipmapBloomBins(db ethdb.Database) (err error) {
  424. const mipmapVersion uint = 2
  425. // check if the version is set. We ignore data for now since there's
  426. // only one version so we can easily ignore it for now
  427. var data []byte
  428. data, _ = db.Get([]byte("setting-mipmap-version"))
  429. if len(data) > 0 {
  430. var version uint
  431. if err := rlp.DecodeBytes(data, &version); err == nil && version == mipmapVersion {
  432. return nil
  433. }
  434. }
  435. defer func() {
  436. if err == nil {
  437. var val []byte
  438. val, err = rlp.EncodeToBytes(mipmapVersion)
  439. if err == nil {
  440. err = db.Put([]byte("setting-mipmap-version"), val)
  441. }
  442. return
  443. }
  444. }()
  445. latestBlock := core.GetBlock(db, core.GetHeadBlockHash(db))
  446. if latestBlock == nil { // clean database
  447. return
  448. }
  449. tstart := time.Now()
  450. glog.V(logger.Info).Infoln("upgrading db log bloom bins")
  451. for i := uint64(0); i <= latestBlock.NumberU64(); i++ {
  452. hash := core.GetCanonicalHash(db, i)
  453. if (hash == common.Hash{}) {
  454. return fmt.Errorf("chain db corrupted. Could not find block %d.", i)
  455. }
  456. core.WriteMipmapBloom(db, i, core.GetBlockReceipts(db, hash))
  457. }
  458. glog.V(logger.Info).Infoln("upgrade completed in", time.Since(tstart))
  459. return nil
  460. }