backend.go 19 KB

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