backend.go 20 KB

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