chain_manager.go 21 KB

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