backend.go 19 KB

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