chain_manager.go 24 KB

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