chain_manager.go 22 KB

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