chain_manager.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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 core implements the Ethereum consensus protocol.
  17. package core
  18. import (
  19. "errors"
  20. "fmt"
  21. "io"
  22. "math/big"
  23. "runtime"
  24. "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/event"
  31. "github.com/ethereum/go-ethereum/logger"
  32. "github.com/ethereum/go-ethereum/logger/glog"
  33. "github.com/ethereum/go-ethereum/metrics"
  34. "github.com/ethereum/go-ethereum/pow"
  35. "github.com/hashicorp/golang-lru"
  36. )
  37. var (
  38. chainlogger = logger.NewLogger("CHAIN")
  39. jsonlogger = logger.NewJsonLogger()
  40. blockInsertTimer = metrics.NewTimer("chain/inserts")
  41. ErrNoGenesis = errors.New("Genesis not found in chain")
  42. )
  43. const (
  44. blockCacheLimit = 256
  45. maxFutureBlocks = 256
  46. maxTimeFutureBlocks = 30
  47. checkpointLimit = 200
  48. )
  49. type ChainManager struct {
  50. //eth EthManager
  51. blockDb common.Database
  52. stateDb common.Database
  53. extraDb common.Database
  54. processor types.BlockProcessor
  55. eventMux *event.TypeMux
  56. genesisBlock *types.Block
  57. // Last known total difficulty
  58. mu sync.RWMutex
  59. chainmu sync.RWMutex
  60. tsmu sync.RWMutex
  61. checkpoint int // checkpoint counts towards the new checkpoint
  62. td *big.Int
  63. currentBlock *types.Block
  64. lastBlockHash common.Hash
  65. currentGasLimit *big.Int
  66. cache *lru.Cache // cache is the LRU caching
  67. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  68. quit chan struct{}
  69. running int32 // running must be called automically
  70. // procInterrupt must be atomically called
  71. procInterrupt int32 // interrupt signaler for block processing
  72. wg sync.WaitGroup
  73. pow pow.PoW
  74. }
  75. func NewChainManager(blockDb, stateDb, extraDb common.Database, pow pow.PoW, mux *event.TypeMux) (*ChainManager, error) {
  76. cache, _ := lru.New(blockCacheLimit)
  77. bc := &ChainManager{
  78. blockDb: blockDb,
  79. stateDb: stateDb,
  80. extraDb: extraDb,
  81. eventMux: mux,
  82. quit: make(chan struct{}),
  83. cache: cache,
  84. pow: pow,
  85. }
  86. bc.genesisBlock = bc.GetBlockByNumber(0)
  87. if bc.genesisBlock == nil {
  88. reader, err := NewDefaultGenesisReader()
  89. if err != nil {
  90. return nil, err
  91. }
  92. bc.genesisBlock, err = WriteGenesisBlock(stateDb, blockDb, reader)
  93. if err != nil {
  94. return nil, err
  95. }
  96. glog.V(logger.Info).Infoln("WARNING: Wrote default ethereum genesis block")
  97. }
  98. if err := bc.setLastState(); err != nil {
  99. return nil, err
  100. }
  101. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  102. for hash, _ := range BadHashes {
  103. if block := bc.GetBlock(hash); block != nil {
  104. glog.V(logger.Error).Infof("Found bad hash. Reorganising chain to state %x\n", block.ParentHash().Bytes()[:4])
  105. block = bc.GetBlock(block.ParentHash())
  106. if block == nil {
  107. glog.Fatal("Unable to complete. Parent block not found. Corrupted DB?")
  108. }
  109. bc.SetHead(block)
  110. glog.V(logger.Error).Infoln("Chain reorg was successfull. Resuming normal operation")
  111. }
  112. }
  113. // Take ownership of this particular state
  114. bc.futureBlocks, _ = lru.New(maxFutureBlocks)
  115. bc.makeCache()
  116. go bc.update()
  117. return bc, nil
  118. }
  119. func (bc *ChainManager) SetHead(head *types.Block) {
  120. bc.mu.Lock()
  121. defer bc.mu.Unlock()
  122. for block := bc.currentBlock; block != nil && block.Hash() != head.Hash(); block = bc.GetBlock(block.ParentHash()) {
  123. bc.removeBlock(block)
  124. }
  125. bc.cache, _ = lru.New(blockCacheLimit)
  126. bc.currentBlock = head
  127. bc.makeCache()
  128. bc.setTotalDifficulty(head.Td)
  129. bc.insert(head)
  130. bc.setLastState()
  131. }
  132. func (self *ChainManager) Td() *big.Int {
  133. self.mu.RLock()
  134. defer self.mu.RUnlock()
  135. return new(big.Int).Set(self.td)
  136. }
  137. func (self *ChainManager) GasLimit() *big.Int {
  138. self.mu.RLock()
  139. defer self.mu.RUnlock()
  140. return self.currentBlock.GasLimit()
  141. }
  142. func (self *ChainManager) LastBlockHash() common.Hash {
  143. self.mu.RLock()
  144. defer self.mu.RUnlock()
  145. return self.lastBlockHash
  146. }
  147. func (self *ChainManager) CurrentBlock() *types.Block {
  148. self.mu.RLock()
  149. defer self.mu.RUnlock()
  150. return self.currentBlock
  151. }
  152. func (self *ChainManager) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  153. self.mu.RLock()
  154. defer self.mu.RUnlock()
  155. return new(big.Int).Set(self.td), self.currentBlock.Hash(), self.genesisBlock.Hash()
  156. }
  157. func (self *ChainManager) SetProcessor(proc types.BlockProcessor) {
  158. self.processor = proc
  159. }
  160. func (self *ChainManager) State() *state.StateDB {
  161. return state.New(self.CurrentBlock().Root(), self.stateDb)
  162. }
  163. func (bc *ChainManager) recover() bool {
  164. data, _ := bc.blockDb.Get([]byte("checkpoint"))
  165. if len(data) != 0 {
  166. block := bc.GetBlock(common.BytesToHash(data))
  167. if block != nil {
  168. err := bc.blockDb.Put([]byte("LastBlock"), block.Hash().Bytes())
  169. if err != nil {
  170. glog.Fatalln("db write err:", err)
  171. }
  172. bc.currentBlock = block
  173. bc.lastBlockHash = block.Hash()
  174. return true
  175. }
  176. }
  177. return false
  178. }
  179. func (bc *ChainManager) setLastState() error {
  180. data, _ := bc.blockDb.Get([]byte("LastBlock"))
  181. if len(data) != 0 {
  182. block := bc.GetBlock(common.BytesToHash(data))
  183. if block != nil {
  184. bc.currentBlock = block
  185. bc.lastBlockHash = block.Hash()
  186. } else {
  187. glog.Infof("LastBlock (%x) not found. Recovering...\n", data)
  188. if bc.recover() {
  189. glog.Infof("Recover successful")
  190. } else {
  191. glog.Fatalf("Recover failed. Please report")
  192. }
  193. }
  194. } else {
  195. bc.Reset()
  196. }
  197. bc.td = bc.currentBlock.Td
  198. bc.currentGasLimit = CalcGasLimit(bc.currentBlock)
  199. if glog.V(logger.Info) {
  200. glog.Infof("Last block (#%v) %x TD=%v\n", bc.currentBlock.Number(), bc.currentBlock.Hash(), bc.td)
  201. }
  202. return nil
  203. }
  204. func (bc *ChainManager) makeCache() {
  205. bc.cache, _ = lru.New(blockCacheLimit)
  206. // load in last `blockCacheLimit` - 1 blocks. Last block is the current.
  207. bc.cache.Add(bc.genesisBlock.Hash(), bc.genesisBlock)
  208. for _, block := range bc.GetBlocksFromHash(bc.currentBlock.Hash(), blockCacheLimit) {
  209. bc.cache.Add(block.Hash(), block)
  210. }
  211. }
  212. func (bc *ChainManager) Reset() {
  213. bc.mu.Lock()
  214. defer bc.mu.Unlock()
  215. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.ParentHash()) {
  216. bc.removeBlock(block)
  217. }
  218. bc.cache, _ = lru.New(blockCacheLimit)
  219. // Prepare the genesis block
  220. err := WriteBlock(bc.blockDb, bc.genesisBlock)
  221. if err != nil {
  222. glog.Fatalln("db err:", err)
  223. }
  224. bc.insert(bc.genesisBlock)
  225. bc.currentBlock = bc.genesisBlock
  226. bc.makeCache()
  227. bc.setTotalDifficulty(common.Big("0"))
  228. }
  229. func (bc *ChainManager) removeBlock(block *types.Block) {
  230. bc.blockDb.Delete(append(blockHashPre, block.Hash().Bytes()...))
  231. }
  232. func (bc *ChainManager) ResetWithGenesisBlock(gb *types.Block) {
  233. bc.mu.Lock()
  234. defer bc.mu.Unlock()
  235. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.ParentHash()) {
  236. bc.removeBlock(block)
  237. }
  238. // Prepare the genesis block
  239. gb.Td = gb.Difficulty()
  240. bc.genesisBlock = gb
  241. err := WriteBlock(bc.blockDb, bc.genesisBlock)
  242. if err != nil {
  243. glog.Fatalln("db err:", err)
  244. }
  245. bc.insert(bc.genesisBlock)
  246. bc.currentBlock = bc.genesisBlock
  247. bc.makeCache()
  248. bc.td = gb.Difficulty()
  249. }
  250. // Export writes the active chain to the given writer.
  251. func (self *ChainManager) Export(w io.Writer) error {
  252. if err := self.ExportN(w, uint64(0), self.currentBlock.NumberU64()); err != nil {
  253. return err
  254. }
  255. return nil
  256. }
  257. // ExportN writes a subset of the active chain to the given writer.
  258. func (self *ChainManager) ExportN(w io.Writer, first uint64, last uint64) error {
  259. self.mu.RLock()
  260. defer self.mu.RUnlock()
  261. if first > last {
  262. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  263. }
  264. glog.V(logger.Info).Infof("exporting %d blocks...\n", last-first+1)
  265. for nr := first; nr <= last; nr++ {
  266. block := self.GetBlockByNumber(nr)
  267. if block == nil {
  268. return fmt.Errorf("export failed on #%d: not found", nr)
  269. }
  270. if err := block.EncodeRLP(w); err != nil {
  271. return err
  272. }
  273. }
  274. return nil
  275. }
  276. // insert injects a block into the current chain block chain. Note, this function
  277. // assumes that the `mu` mutex is held!
  278. func (bc *ChainManager) insert(block *types.Block) {
  279. err := WriteHead(bc.blockDb, block)
  280. if err != nil {
  281. glog.Fatal("db write fail:", err)
  282. }
  283. bc.checkpoint++
  284. if bc.checkpoint > checkpointLimit {
  285. err = bc.blockDb.Put([]byte("checkpoint"), block.Hash().Bytes())
  286. if err != nil {
  287. glog.Fatal("db write fail:", err)
  288. }
  289. bc.checkpoint = 0
  290. }
  291. bc.currentBlock = block
  292. bc.lastBlockHash = block.Hash()
  293. }
  294. // Accessors
  295. func (bc *ChainManager) Genesis() *types.Block {
  296. return bc.genesisBlock
  297. }
  298. // Block fetching methods
  299. func (bc *ChainManager) HasBlock(hash common.Hash) bool {
  300. if bc.cache.Contains(hash) {
  301. return true
  302. }
  303. data, _ := bc.blockDb.Get(append(blockHashPre, hash[:]...))
  304. return len(data) != 0
  305. }
  306. func (self *ChainManager) GetBlockHashesFromHash(hash common.Hash, max uint64) (chain []common.Hash) {
  307. block := self.GetBlock(hash)
  308. if block == nil {
  309. return
  310. }
  311. // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)
  312. for i := uint64(0); i < max; i++ {
  313. block = self.GetBlock(block.ParentHash())
  314. if block == nil {
  315. break
  316. }
  317. chain = append(chain, block.Hash())
  318. if block.Number().Cmp(common.Big0) <= 0 {
  319. break
  320. }
  321. }
  322. return
  323. }
  324. func (self *ChainManager) GetBlock(hash common.Hash) *types.Block {
  325. if block, ok := self.cache.Get(hash); ok {
  326. return block.(*types.Block)
  327. }
  328. block := GetBlockByHash(self.blockDb, hash)
  329. if block == nil {
  330. return nil
  331. }
  332. // Add the block to the cache
  333. self.cache.Add(hash, (*types.Block)(block))
  334. return (*types.Block)(block)
  335. }
  336. func (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {
  337. self.mu.RLock()
  338. defer self.mu.RUnlock()
  339. return self.getBlockByNumber(num)
  340. }
  341. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  342. func (self *ChainManager) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  343. for i := 0; i < n; i++ {
  344. block := self.GetBlock(hash)
  345. if block == nil {
  346. break
  347. }
  348. blocks = append(blocks, block)
  349. hash = block.ParentHash()
  350. }
  351. return
  352. }
  353. // non blocking version
  354. func (self *ChainManager) getBlockByNumber(num uint64) *types.Block {
  355. return GetBlockByNumber(self.blockDb, num)
  356. }
  357. func (self *ChainManager) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) {
  358. for i := 0; block != nil && i < length; i++ {
  359. uncles = append(uncles, block.Uncles()...)
  360. block = self.GetBlock(block.ParentHash())
  361. }
  362. return
  363. }
  364. // setTotalDifficulty updates the TD of the chain manager. Note, this function
  365. // assumes that the `mu` mutex is held!
  366. func (bc *ChainManager) setTotalDifficulty(td *big.Int) {
  367. bc.td = new(big.Int).Set(td)
  368. }
  369. func (bc *ChainManager) Stop() {
  370. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  371. return
  372. }
  373. close(bc.quit)
  374. atomic.StoreInt32(&bc.procInterrupt, 1)
  375. bc.wg.Wait()
  376. glog.V(logger.Info).Infoln("Chain manager stopped")
  377. }
  378. type queueEvent struct {
  379. queue []interface{}
  380. canonicalCount int
  381. sideCount int
  382. splitCount int
  383. }
  384. func (self *ChainManager) procFutureBlocks() {
  385. blocks := make([]*types.Block, self.futureBlocks.Len())
  386. for i, hash := range self.futureBlocks.Keys() {
  387. block, _ := self.futureBlocks.Get(hash)
  388. blocks[i] = block.(*types.Block)
  389. }
  390. if len(blocks) > 0 {
  391. types.BlockBy(types.Number).Sort(blocks)
  392. self.InsertChain(blocks)
  393. }
  394. }
  395. type writeStatus byte
  396. const (
  397. NonStatTy writeStatus = iota
  398. CanonStatTy
  399. SplitStatTy
  400. SideStatTy
  401. )
  402. // WriteBlock writes the block to the chain (or pending queue)
  403. func (self *ChainManager) WriteBlock(block *types.Block, queued bool) (status writeStatus, err error) {
  404. self.wg.Add(1)
  405. defer self.wg.Done()
  406. cblock := self.currentBlock
  407. // Compare the TD of the last known block in the canonical chain to make sure it's greater.
  408. // At this point it's possible that a different chain (fork) becomes the new canonical chain.
  409. if block.Td.Cmp(self.Td()) > 0 {
  410. // chain fork
  411. if block.ParentHash() != cblock.Hash() {
  412. // during split we merge two different chains and create the new canonical chain
  413. err := self.merge(cblock, block)
  414. if err != nil {
  415. return NonStatTy, err
  416. }
  417. status = SplitStatTy
  418. }
  419. self.mu.Lock()
  420. self.setTotalDifficulty(block.Td)
  421. self.insert(block)
  422. self.mu.Unlock()
  423. status = CanonStatTy
  424. } else {
  425. status = SideStatTy
  426. }
  427. err = WriteBlock(self.blockDb, block)
  428. if err != nil {
  429. glog.Fatalln("db err:", err)
  430. }
  431. // Delete from future blocks
  432. self.futureBlocks.Remove(block.Hash())
  433. return
  434. }
  435. // InsertChain will attempt to insert the given chain in to the canonical chain or, otherwise, create a fork. It an error is returned
  436. // it will return the index number of the failing block as well an error describing what went wrong (for possible errors see core/errors.go).
  437. func (self *ChainManager) InsertChain(chain types.Blocks) (int, error) {
  438. self.wg.Add(1)
  439. defer self.wg.Done()
  440. self.chainmu.Lock()
  441. defer self.chainmu.Unlock()
  442. // A queued approach to delivering events. This is generally
  443. // faster than direct delivery and requires much less mutex
  444. // acquiring.
  445. var (
  446. queue = make([]interface{}, len(chain))
  447. queueEvent = queueEvent{queue: queue}
  448. stats struct{ queued, processed, ignored int }
  449. tstart = time.Now()
  450. nonceDone = make(chan nonceResult, len(chain))
  451. nonceQuit = make(chan struct{})
  452. nonceChecked = make([]bool, len(chain))
  453. )
  454. // Start the parallel nonce verifier.
  455. go verifyNonces(self.pow, chain, nonceQuit, nonceDone)
  456. defer close(nonceQuit)
  457. txcount := 0
  458. for i, block := range chain {
  459. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  460. glog.V(logger.Debug).Infoln("Premature abort during chain processing")
  461. break
  462. }
  463. bstart := time.Now()
  464. // Wait for block i's nonce to be verified before processing
  465. // its state transition.
  466. for !nonceChecked[i] {
  467. r := <-nonceDone
  468. nonceChecked[r.i] = true
  469. if !r.valid {
  470. block := chain[r.i]
  471. return r.i, &BlockNonceErr{Hash: block.Hash(), Number: block.Number(), Nonce: block.Nonce()}
  472. }
  473. }
  474. if BadHashes[block.Hash()] {
  475. err := fmt.Errorf("Found known bad hash in chain %x", block.Hash())
  476. blockErr(block, err)
  477. return i, err
  478. }
  479. // Setting block.Td regardless of error (known for example) prevents errors down the line
  480. // in the protocol handler
  481. block.Td = new(big.Int).Set(CalcTD(block, self.GetBlock(block.ParentHash())))
  482. // Call in to the block processor and check for errors. It's likely that if one block fails
  483. // all others will fail too (unless a known block is returned).
  484. logs, receipts, err := self.processor.Process(block)
  485. if err != nil {
  486. if IsKnownBlockErr(err) {
  487. stats.ignored++
  488. continue
  489. }
  490. if err == BlockFutureErr {
  491. // Allow up to MaxFuture second in the future blocks. If this limit
  492. // is exceeded the chain is discarded and processed at a later time
  493. // if given.
  494. if max := uint64(time.Now().Unix()) + maxTimeFutureBlocks; block.Time() > max {
  495. return i, fmt.Errorf("%v: BlockFutureErr, %v > %v", BlockFutureErr, block.Time(), max)
  496. }
  497. self.futureBlocks.Add(block.Hash(), block)
  498. stats.queued++
  499. continue
  500. }
  501. if IsParentErr(err) && self.futureBlocks.Contains(block.ParentHash()) {
  502. self.futureBlocks.Add(block.Hash(), block)
  503. stats.queued++
  504. continue
  505. }
  506. blockErr(block, err)
  507. go ReportBlock(block, err)
  508. return i, err
  509. }
  510. txcount += len(block.Transactions())
  511. // write the block to the chain and get the status
  512. status, err := self.WriteBlock(block, true)
  513. if err != nil {
  514. return i, err
  515. }
  516. switch status {
  517. case CanonStatTy:
  518. if glog.V(logger.Debug) {
  519. glog.Infof("[%v] inserted block #%d (%d TXs %v G %d UNCs) (%x...). Took %v\n", time.Now().UnixNano(), block.Number(), len(block.Transactions()), block.GasUsed(), len(block.Uncles()), block.Hash().Bytes()[0:4], time.Since(bstart))
  520. }
  521. queue[i] = ChainEvent{block, block.Hash(), logs}
  522. queueEvent.canonicalCount++
  523. // This puts transactions in a extra db for rpc
  524. PutTransactions(self.extraDb, block, block.Transactions())
  525. // store the receipts
  526. PutReceipts(self.extraDb, receipts)
  527. case SideStatTy:
  528. if glog.V(logger.Detail) {
  529. glog.Infof("inserted forked block #%d (TD=%v) (%d TXs %d UNCs) (%x...). Took %v\n", block.Number(), block.Difficulty(), len(block.Transactions()), len(block.Uncles()), block.Hash().Bytes()[0:4], time.Since(bstart))
  530. }
  531. queue[i] = ChainSideEvent{block, logs}
  532. queueEvent.sideCount++
  533. case SplitStatTy:
  534. queue[i] = ChainSplitEvent{block, logs}
  535. queueEvent.splitCount++
  536. }
  537. PutBlockReceipts(self.extraDb, block, receipts)
  538. stats.processed++
  539. }
  540. if (stats.queued > 0 || stats.processed > 0 || stats.ignored > 0) && bool(glog.V(logger.Info)) {
  541. tend := time.Since(tstart)
  542. start, end := chain[0], chain[len(chain)-1]
  543. glog.Infof("imported %d block(s) (%d queued %d ignored) including %d txs in %v. #%v [%x / %x]\n", stats.processed, stats.queued, stats.ignored, txcount, tend, end.Number(), start.Hash().Bytes()[:4], end.Hash().Bytes()[:4])
  544. }
  545. go self.eventMux.Post(queueEvent)
  546. return 0, nil
  547. }
  548. // diff takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  549. // to be part of the new canonical chain.
  550. func (self *ChainManager) diff(oldBlock, newBlock *types.Block) (types.Blocks, error) {
  551. var (
  552. newChain types.Blocks
  553. commonBlock *types.Block
  554. oldStart = oldBlock
  555. newStart = newBlock
  556. )
  557. // first reduce whoever is higher bound
  558. if oldBlock.NumberU64() > newBlock.NumberU64() {
  559. // reduce old chain
  560. for oldBlock = oldBlock; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = self.GetBlock(oldBlock.ParentHash()) {
  561. }
  562. } else {
  563. // reduce new chain and append new chain blocks for inserting later on
  564. for newBlock = newBlock; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = self.GetBlock(newBlock.ParentHash()) {
  565. newChain = append(newChain, newBlock)
  566. }
  567. }
  568. if oldBlock == nil {
  569. return nil, fmt.Errorf("Invalid old chain")
  570. }
  571. if newBlock == nil {
  572. return nil, fmt.Errorf("Invalid new chain")
  573. }
  574. numSplit := newBlock.Number()
  575. for {
  576. if oldBlock.Hash() == newBlock.Hash() {
  577. commonBlock = oldBlock
  578. break
  579. }
  580. newChain = append(newChain, newBlock)
  581. oldBlock, newBlock = self.GetBlock(oldBlock.ParentHash()), self.GetBlock(newBlock.ParentHash())
  582. if oldBlock == nil {
  583. return nil, fmt.Errorf("Invalid old chain")
  584. }
  585. if newBlock == nil {
  586. return nil, fmt.Errorf("Invalid new chain")
  587. }
  588. }
  589. if glog.V(logger.Debug) {
  590. commonHash := commonBlock.Hash()
  591. glog.Infof("Chain split detected @ %x. Reorganising chain from #%v %x to %x", commonHash[:4], numSplit, oldStart.Hash().Bytes()[:4], newStart.Hash().Bytes()[:4])
  592. }
  593. return newChain, nil
  594. }
  595. // merge merges two different chain to the new canonical chain
  596. func (self *ChainManager) merge(oldBlock, newBlock *types.Block) error {
  597. newChain, err := self.diff(oldBlock, newBlock)
  598. if err != nil {
  599. return fmt.Errorf("chain reorg failed: %v", err)
  600. }
  601. // insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
  602. self.mu.Lock()
  603. for _, block := range newChain {
  604. // insert the block in the canonical way, re-writing history
  605. self.insert(block)
  606. // write canonical receipts and transactions
  607. PutTransactions(self.extraDb, block, block.Transactions())
  608. PutReceipts(self.extraDb, GetBlockReceipts(self.extraDb, block.Hash()))
  609. }
  610. self.mu.Unlock()
  611. return nil
  612. }
  613. func (self *ChainManager) update() {
  614. events := self.eventMux.Subscribe(queueEvent{})
  615. futureTimer := time.Tick(5 * time.Second)
  616. out:
  617. for {
  618. select {
  619. case ev := <-events.Chan():
  620. switch ev := ev.(type) {
  621. case queueEvent:
  622. for _, event := range ev.queue {
  623. switch event := event.(type) {
  624. case ChainEvent:
  625. // We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
  626. // and in most cases isn't even necessary.
  627. if self.lastBlockHash == event.Hash {
  628. self.currentGasLimit = CalcGasLimit(event.Block)
  629. self.eventMux.Post(ChainHeadEvent{event.Block})
  630. }
  631. }
  632. self.eventMux.Post(event)
  633. }
  634. }
  635. case <-futureTimer:
  636. self.procFutureBlocks()
  637. case <-self.quit:
  638. break out
  639. }
  640. }
  641. }
  642. func blockErr(block *types.Block, err error) {
  643. h := block.Header()
  644. glog.V(logger.Error).Infof("Bad block #%v (%x)\n", h.Number, h.Hash().Bytes())
  645. glog.V(logger.Error).Infoln(err)
  646. glog.V(logger.Debug).Infoln(verifyNonces)
  647. }
  648. type nonceResult struct {
  649. i int
  650. valid bool
  651. }
  652. // block verifies nonces of the given blocks in parallel and returns
  653. // an error if one of the blocks nonce verifications failed.
  654. func verifyNonces(pow pow.PoW, blocks []*types.Block, quit <-chan struct{}, done chan<- nonceResult) {
  655. // Spawn a few workers. They listen for blocks on the in channel
  656. // and send results on done. The workers will exit in the
  657. // background when in is closed.
  658. var (
  659. in = make(chan int)
  660. nworkers = runtime.GOMAXPROCS(0)
  661. )
  662. defer close(in)
  663. if len(blocks) < nworkers {
  664. nworkers = len(blocks)
  665. }
  666. for i := 0; i < nworkers; i++ {
  667. go func() {
  668. for i := range in {
  669. done <- nonceResult{i: i, valid: pow.Verify(blocks[i])}
  670. }
  671. }()
  672. }
  673. // Feed block indices to the workers.
  674. for i := range blocks {
  675. select {
  676. case in <- i:
  677. continue
  678. case <-quit:
  679. return
  680. }
  681. }
  682. }