chain_manager.go 21 KB

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