chain_manager.go 21 KB

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