chain_manager.go 21 KB

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