chain_manager.go 21 KB

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