blockchain.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package core implements the Ethereum consensus protocol.
  17. package core
  18. import (
  19. "errors"
  20. "fmt"
  21. "io"
  22. "math/big"
  23. "sync"
  24. "sync/atomic"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/ethdb"
  30. "github.com/ethereum/go-ethereum/event"
  31. "github.com/ethereum/go-ethereum/logger"
  32. "github.com/ethereum/go-ethereum/logger/glog"
  33. "github.com/ethereum/go-ethereum/metrics"
  34. "github.com/ethereum/go-ethereum/pow"
  35. "github.com/ethereum/go-ethereum/rlp"
  36. "github.com/hashicorp/golang-lru"
  37. )
  38. var (
  39. chainlogger = logger.NewLogger("CHAIN")
  40. jsonlogger = logger.NewJsonLogger()
  41. blockInsertTimer = metrics.NewTimer("chain/inserts")
  42. ErrNoGenesis = errors.New("Genesis not found in chain")
  43. )
  44. const (
  45. headerCacheLimit = 512
  46. bodyCacheLimit = 256
  47. tdCacheLimit = 1024
  48. blockCacheLimit = 256
  49. maxFutureBlocks = 256
  50. maxTimeFutureBlocks = 30
  51. )
  52. type BlockChain struct {
  53. chainDb ethdb.Database
  54. processor types.BlockProcessor
  55. eventMux *event.TypeMux
  56. genesisBlock *types.Block
  57. // Last known total difficulty
  58. mu sync.RWMutex
  59. chainmu sync.RWMutex
  60. tsmu sync.RWMutex
  61. td *big.Int
  62. currentBlock *types.Block
  63. currentGasLimit *big.Int
  64. headerCache *lru.Cache // Cache for the most recent block headers
  65. bodyCache *lru.Cache // Cache for the most recent block bodies
  66. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  67. tdCache *lru.Cache // Cache for the most recent block total difficulties
  68. blockCache *lru.Cache // Cache for the most recent entire blocks
  69. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  70. quit chan struct{}
  71. running int32 // running must be called automically
  72. // procInterrupt must be atomically called
  73. procInterrupt int32 // interrupt signaler for block processing
  74. wg sync.WaitGroup
  75. pow pow.PoW
  76. }
  77. func NewBlockChain(chainDb ethdb.Database, pow pow.PoW, mux *event.TypeMux) (*BlockChain, error) {
  78. headerCache, _ := lru.New(headerCacheLimit)
  79. bodyCache, _ := lru.New(bodyCacheLimit)
  80. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  81. tdCache, _ := lru.New(tdCacheLimit)
  82. blockCache, _ := lru.New(blockCacheLimit)
  83. futureBlocks, _ := lru.New(maxFutureBlocks)
  84. bc := &BlockChain{
  85. chainDb: chainDb,
  86. eventMux: mux,
  87. quit: make(chan struct{}),
  88. headerCache: headerCache,
  89. bodyCache: bodyCache,
  90. bodyRLPCache: bodyRLPCache,
  91. tdCache: tdCache,
  92. blockCache: blockCache,
  93. futureBlocks: futureBlocks,
  94. pow: pow,
  95. }
  96. bc.genesisBlock = bc.GetBlockByNumber(0)
  97. if bc.genesisBlock == nil {
  98. reader, err := NewDefaultGenesisReader()
  99. if err != nil {
  100. return nil, err
  101. }
  102. bc.genesisBlock, err = WriteGenesisBlock(chainDb, reader)
  103. if err != nil {
  104. return nil, err
  105. }
  106. glog.V(logger.Info).Infoln("WARNING: Wrote default ethereum genesis block")
  107. }
  108. if err := bc.setLastState(); err != nil {
  109. return nil, err
  110. }
  111. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  112. for hash, _ := range BadHashes {
  113. if block := bc.GetBlock(hash); block != nil {
  114. glog.V(logger.Error).Infof("Found bad hash. Reorganising chain to state %x\n", block.ParentHash().Bytes()[:4])
  115. block = bc.GetBlock(block.ParentHash())
  116. if block == nil {
  117. glog.Fatal("Unable to complete. Parent block not found. Corrupted DB?")
  118. }
  119. bc.SetHead(block)
  120. glog.V(logger.Error).Infoln("Chain reorg was successfull. Resuming normal operation")
  121. }
  122. }
  123. // Take ownership of this particular state
  124. go bc.update()
  125. return bc, nil
  126. }
  127. func (bc *BlockChain) SetHead(head *types.Block) {
  128. bc.mu.Lock()
  129. defer bc.mu.Unlock()
  130. for block := bc.currentBlock; block != nil && block.Hash() != head.Hash(); block = bc.GetBlock(block.ParentHash()) {
  131. DeleteBlock(bc.chainDb, block.Hash())
  132. }
  133. bc.headerCache.Purge()
  134. bc.bodyCache.Purge()
  135. bc.bodyRLPCache.Purge()
  136. bc.blockCache.Purge()
  137. bc.futureBlocks.Purge()
  138. bc.currentBlock = head
  139. bc.setTotalDifficulty(bc.GetTd(head.Hash()))
  140. bc.insert(head)
  141. bc.setLastState()
  142. }
  143. func (self *BlockChain) Td() *big.Int {
  144. self.mu.RLock()
  145. defer self.mu.RUnlock()
  146. return new(big.Int).Set(self.td)
  147. }
  148. func (self *BlockChain) GasLimit() *big.Int {
  149. self.mu.RLock()
  150. defer self.mu.RUnlock()
  151. return self.currentBlock.GasLimit()
  152. }
  153. func (self *BlockChain) LastBlockHash() common.Hash {
  154. self.mu.RLock()
  155. defer self.mu.RUnlock()
  156. return self.currentBlock.Hash()
  157. }
  158. func (self *BlockChain) CurrentBlock() *types.Block {
  159. self.mu.RLock()
  160. defer self.mu.RUnlock()
  161. return self.currentBlock
  162. }
  163. func (self *BlockChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  164. self.mu.RLock()
  165. defer self.mu.RUnlock()
  166. return new(big.Int).Set(self.td), self.currentBlock.Hash(), self.genesisBlock.Hash()
  167. }
  168. func (self *BlockChain) SetProcessor(proc types.BlockProcessor) {
  169. self.processor = proc
  170. }
  171. func (self *BlockChain) State() *state.StateDB {
  172. return state.New(self.CurrentBlock().Root(), self.chainDb)
  173. }
  174. func (bc *BlockChain) setLastState() error {
  175. head := GetHeadBlockHash(bc.chainDb)
  176. if head != (common.Hash{}) {
  177. block := bc.GetBlock(head)
  178. if block != nil {
  179. bc.currentBlock = block
  180. }
  181. } else {
  182. bc.Reset()
  183. }
  184. bc.td = bc.GetTd(bc.currentBlock.Hash())
  185. bc.currentGasLimit = CalcGasLimit(bc.currentBlock)
  186. if glog.V(logger.Info) {
  187. glog.Infof("Last block (#%v) %x TD=%v\n", bc.currentBlock.Number(), bc.currentBlock.Hash(), bc.td)
  188. }
  189. return nil
  190. }
  191. // Reset purges the entire blockchain, restoring it to its genesis state.
  192. func (bc *BlockChain) Reset() {
  193. bc.ResetWithGenesisBlock(bc.genesisBlock)
  194. }
  195. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  196. // specified genesis state.
  197. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) {
  198. bc.mu.Lock()
  199. defer bc.mu.Unlock()
  200. // Dump the entire block chain and purge the caches
  201. for block := bc.currentBlock; block != nil; block = bc.GetBlock(block.ParentHash()) {
  202. DeleteBlock(bc.chainDb, block.Hash())
  203. }
  204. bc.headerCache.Purge()
  205. bc.bodyCache.Purge()
  206. bc.bodyRLPCache.Purge()
  207. bc.blockCache.Purge()
  208. bc.futureBlocks.Purge()
  209. // Prepare the genesis block and reinitialize the chain
  210. if err := WriteTd(bc.chainDb, genesis.Hash(), genesis.Difficulty()); err != nil {
  211. glog.Fatalf("failed to write genesis block TD: %v", err)
  212. }
  213. if err := WriteBlock(bc.chainDb, genesis); err != nil {
  214. glog.Fatalf("failed to write genesis block: %v", err)
  215. }
  216. bc.genesisBlock = genesis
  217. bc.insert(bc.genesisBlock)
  218. bc.currentBlock = bc.genesisBlock
  219. bc.setTotalDifficulty(genesis.Difficulty())
  220. }
  221. // Export writes the active chain to the given writer.
  222. func (self *BlockChain) Export(w io.Writer) error {
  223. if err := self.ExportN(w, uint64(0), self.currentBlock.NumberU64()); err != nil {
  224. return err
  225. }
  226. return nil
  227. }
  228. // ExportN writes a subset of the active chain to the given writer.
  229. func (self *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  230. self.mu.RLock()
  231. defer self.mu.RUnlock()
  232. if first > last {
  233. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  234. }
  235. glog.V(logger.Info).Infof("exporting %d blocks...\n", last-first+1)
  236. for nr := first; nr <= last; nr++ {
  237. block := self.GetBlockByNumber(nr)
  238. if block == nil {
  239. return fmt.Errorf("export failed on #%d: not found", nr)
  240. }
  241. if err := block.EncodeRLP(w); err != nil {
  242. return err
  243. }
  244. }
  245. return nil
  246. }
  247. // insert injects a block into the current chain block chain. Note, this function
  248. // assumes that the `mu` mutex is held!
  249. func (bc *BlockChain) insert(block *types.Block) {
  250. // Add the block to the canonical chain number scheme and mark as the head
  251. if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
  252. glog.Fatalf("failed to insert block number: %v", err)
  253. }
  254. if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
  255. glog.Fatalf("failed to insert block number: %v", err)
  256. }
  257. bc.currentBlock = block
  258. }
  259. // Accessors
  260. func (bc *BlockChain) Genesis() *types.Block {
  261. return bc.genesisBlock
  262. }
  263. // HasHeader checks if a block header is present in the database or not, caching
  264. // it if present.
  265. func (bc *BlockChain) HasHeader(hash common.Hash) bool {
  266. return bc.GetHeader(hash) != nil
  267. }
  268. // GetHeader retrieves a block header from the database by hash, caching it if
  269. // found.
  270. func (self *BlockChain) GetHeader(hash common.Hash) *types.Header {
  271. // Short circuit if the header's already in the cache, retrieve otherwise
  272. if header, ok := self.headerCache.Get(hash); ok {
  273. return header.(*types.Header)
  274. }
  275. header := GetHeader(self.chainDb, hash)
  276. if header == nil {
  277. return nil
  278. }
  279. // Cache the found header for next time and return
  280. self.headerCache.Add(header.Hash(), header)
  281. return header
  282. }
  283. // GetHeaderByNumber retrieves a block header from the database by number,
  284. // caching it (associated with its hash) if found.
  285. func (self *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  286. hash := GetCanonicalHash(self.chainDb, number)
  287. if hash == (common.Hash{}) {
  288. return nil
  289. }
  290. return self.GetHeader(hash)
  291. }
  292. // GetBody retrieves a block body (transactions and uncles) from the database by
  293. // hash, caching it if found.
  294. func (self *BlockChain) GetBody(hash common.Hash) *types.Body {
  295. // Short circuit if the body's already in the cache, retrieve otherwise
  296. if cached, ok := self.bodyCache.Get(hash); ok {
  297. body := cached.(*types.Body)
  298. return body
  299. }
  300. body := GetBody(self.chainDb, hash)
  301. if body == nil {
  302. return nil
  303. }
  304. // Cache the found body for next time and return
  305. self.bodyCache.Add(hash, body)
  306. return body
  307. }
  308. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  309. // caching it if found.
  310. func (self *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  311. // Short circuit if the body's already in the cache, retrieve otherwise
  312. if cached, ok := self.bodyRLPCache.Get(hash); ok {
  313. return cached.(rlp.RawValue)
  314. }
  315. body := GetBodyRLP(self.chainDb, hash)
  316. if len(body) == 0 {
  317. return nil
  318. }
  319. // Cache the found body for next time and return
  320. self.bodyRLPCache.Add(hash, body)
  321. return body
  322. }
  323. // GetTd retrieves a block's total difficulty in the canonical chain from the
  324. // database by hash, caching it if found.
  325. func (self *BlockChain) GetTd(hash common.Hash) *big.Int {
  326. // Short circuit if the td's already in the cache, retrieve otherwise
  327. if cached, ok := self.tdCache.Get(hash); ok {
  328. return cached.(*big.Int)
  329. }
  330. td := GetTd(self.chainDb, hash)
  331. if td == nil {
  332. return nil
  333. }
  334. // Cache the found body for next time and return
  335. self.tdCache.Add(hash, td)
  336. return td
  337. }
  338. // HasBlock checks if a block is fully present in the database or not, caching
  339. // it if present.
  340. func (bc *BlockChain) HasBlock(hash common.Hash) bool {
  341. return bc.GetBlock(hash) != nil
  342. }
  343. // GetBlock retrieves a block from the database by hash, caching it if found.
  344. func (self *BlockChain) GetBlock(hash common.Hash) *types.Block {
  345. // Short circuit if the block's already in the cache, retrieve otherwise
  346. if block, ok := self.blockCache.Get(hash); ok {
  347. return block.(*types.Block)
  348. }
  349. block := GetBlock(self.chainDb, hash)
  350. if block == nil {
  351. return nil
  352. }
  353. // Cache the found block for next time and return
  354. self.blockCache.Add(block.Hash(), block)
  355. return block
  356. }
  357. // GetBlockByNumber retrieves a block from the database by number, caching it
  358. // (associated with its hash) if found.
  359. func (self *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  360. hash := GetCanonicalHash(self.chainDb, number)
  361. if hash == (common.Hash{}) {
  362. return nil
  363. }
  364. return self.GetBlock(hash)
  365. }
  366. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  367. // hash, fetching towards the genesis block.
  368. func (self *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  369. // Get the origin header from which to fetch
  370. header := self.GetHeader(hash)
  371. if header == nil {
  372. return nil
  373. }
  374. // Iterate the headers until enough is collected or the genesis reached
  375. chain := make([]common.Hash, 0, max)
  376. for i := uint64(0); i < max; i++ {
  377. if header = self.GetHeader(header.ParentHash); header == nil {
  378. break
  379. }
  380. chain = append(chain, header.Hash())
  381. if header.Number.Cmp(common.Big0) == 0 {
  382. break
  383. }
  384. }
  385. return chain
  386. }
  387. // [deprecated by eth/62]
  388. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  389. func (self *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  390. for i := 0; i < n; i++ {
  391. block := self.GetBlock(hash)
  392. if block == nil {
  393. break
  394. }
  395. blocks = append(blocks, block)
  396. hash = block.ParentHash()
  397. }
  398. return
  399. }
  400. func (self *BlockChain) GetUnclesInChain(block *types.Block, length int) (uncles []*types.Header) {
  401. for i := 0; block != nil && i < length; i++ {
  402. uncles = append(uncles, block.Uncles()...)
  403. block = self.GetBlock(block.ParentHash())
  404. }
  405. return
  406. }
  407. // setTotalDifficulty updates the TD of the chain manager. Note, this function
  408. // assumes that the `mu` mutex is held!
  409. func (bc *BlockChain) setTotalDifficulty(td *big.Int) {
  410. bc.td = new(big.Int).Set(td)
  411. }
  412. func (bc *BlockChain) Stop() {
  413. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  414. return
  415. }
  416. close(bc.quit)
  417. atomic.StoreInt32(&bc.procInterrupt, 1)
  418. bc.wg.Wait()
  419. glog.V(logger.Info).Infoln("Chain manager stopped")
  420. }
  421. func (self *BlockChain) procFutureBlocks() {
  422. blocks := make([]*types.Block, self.futureBlocks.Len())
  423. for i, hash := range self.futureBlocks.Keys() {
  424. block, _ := self.futureBlocks.Get(hash)
  425. blocks[i] = block.(*types.Block)
  426. }
  427. if len(blocks) > 0 {
  428. types.BlockBy(types.Number).Sort(blocks)
  429. self.InsertChain(blocks)
  430. }
  431. }
  432. type writeStatus byte
  433. const (
  434. NonStatTy writeStatus = iota
  435. CanonStatTy
  436. SplitStatTy
  437. SideStatTy
  438. )
  439. // WriteBlock writes the block to the chain.
  440. func (self *BlockChain) WriteBlock(block *types.Block) (status writeStatus, err error) {
  441. self.wg.Add(1)
  442. defer self.wg.Done()
  443. // Calculate the total difficulty of the block
  444. ptd := self.GetTd(block.ParentHash())
  445. if ptd == nil {
  446. return NonStatTy, ParentError(block.ParentHash())
  447. }
  448. td := new(big.Int).Add(block.Difficulty(), ptd)
  449. self.mu.RLock()
  450. cblock := self.currentBlock
  451. self.mu.RUnlock()
  452. // Compare the TD of the last known block in the canonical chain to make sure it's greater.
  453. // At this point it's possible that a different chain (fork) becomes the new canonical chain.
  454. if td.Cmp(self.Td()) > 0 {
  455. // chain fork
  456. if block.ParentHash() != cblock.Hash() {
  457. // during split we merge two different chains and create the new canonical chain
  458. err := self.reorg(cblock, block)
  459. if err != nil {
  460. return NonStatTy, err
  461. }
  462. }
  463. status = CanonStatTy
  464. self.mu.Lock()
  465. self.setTotalDifficulty(td)
  466. self.insert(block)
  467. self.mu.Unlock()
  468. } else {
  469. status = SideStatTy
  470. }
  471. if err := WriteTd(self.chainDb, block.Hash(), td); err != nil {
  472. glog.Fatalf("failed to write block total difficulty: %v", err)
  473. }
  474. if err := WriteBlock(self.chainDb, block); err != nil {
  475. glog.Fatalf("filed to write block contents: %v", err)
  476. }
  477. // Delete from future blocks
  478. self.futureBlocks.Remove(block.Hash())
  479. return
  480. }
  481. // InsertChain will attempt to insert the given chain in to the canonical chain or, otherwise, create a fork. It an error is returned
  482. // 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).
  483. func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  484. self.wg.Add(1)
  485. defer self.wg.Done()
  486. self.chainmu.Lock()
  487. defer self.chainmu.Unlock()
  488. // A queued approach to delivering events. This is generally
  489. // faster than direct delivery and requires much less mutex
  490. // acquiring.
  491. var (
  492. stats struct{ queued, processed, ignored int }
  493. events = make([]interface{}, 0, len(chain))
  494. tstart = time.Now()
  495. nonceChecked = make([]bool, len(chain))
  496. )
  497. // Start the parallel nonce verifier.
  498. nonceAbort, nonceResults := verifyNoncesFromBlocks(self.pow, chain)
  499. defer close(nonceAbort)
  500. txcount := 0
  501. for i, block := range chain {
  502. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  503. glog.V(logger.Debug).Infoln("Premature abort during chain processing")
  504. break
  505. }
  506. bstart := time.Now()
  507. // Wait for block i's nonce to be verified before processing
  508. // its state transition.
  509. for !nonceChecked[i] {
  510. r := <-nonceResults
  511. nonceChecked[r.index] = true
  512. if !r.valid {
  513. block := chain[r.index]
  514. return r.index, &BlockNonceErr{Hash: block.Hash(), Number: block.Number(), Nonce: block.Nonce()}
  515. }
  516. }
  517. if BadHashes[block.Hash()] {
  518. err := BadHashError(block.Hash())
  519. blockErr(block, err)
  520. return i, err
  521. }
  522. // Call in to the block processor and check for errors. It's likely that if one block fails
  523. // all others will fail too (unless a known block is returned).
  524. logs, receipts, err := self.processor.Process(block)
  525. if err != nil {
  526. if IsKnownBlockErr(err) {
  527. stats.ignored++
  528. continue
  529. }
  530. if err == BlockFutureErr {
  531. // Allow up to MaxFuture second in the future blocks. If this limit
  532. // is exceeded the chain is discarded and processed at a later time
  533. // if given.
  534. max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
  535. if block.Time().Cmp(max) == 1 {
  536. return i, fmt.Errorf("%v: BlockFutureErr, %v > %v", BlockFutureErr, block.Time(), max)
  537. }
  538. self.futureBlocks.Add(block.Hash(), block)
  539. stats.queued++
  540. continue
  541. }
  542. if IsParentErr(err) && self.futureBlocks.Contains(block.ParentHash()) {
  543. self.futureBlocks.Add(block.Hash(), block)
  544. stats.queued++
  545. continue
  546. }
  547. blockErr(block, err)
  548. go ReportBlock(block, err)
  549. return i, err
  550. }
  551. if err := PutBlockReceipts(self.chainDb, block, receipts); err != nil {
  552. glog.V(logger.Warn).Infoln("error writing block receipts:", err)
  553. }
  554. txcount += len(block.Transactions())
  555. // write the block to the chain and get the status
  556. status, err := self.WriteBlock(block)
  557. if err != nil {
  558. return i, err
  559. }
  560. switch status {
  561. case CanonStatTy:
  562. if glog.V(logger.Debug) {
  563. glog.Infof("[%v] inserted block #%d (%d TXs %v G %d UNCs) (%x...). Took %v\n", time.Now().UnixNano(), block.Number(), len(block.Transactions()), block.GasUsed(), len(block.Uncles()), block.Hash().Bytes()[0:4], time.Since(bstart))
  564. }
  565. events = append(events, ChainEvent{block, block.Hash(), logs})
  566. // This puts transactions in a extra db for rpc
  567. PutTransactions(self.chainDb, block, block.Transactions())
  568. // store the receipts
  569. PutReceipts(self.chainDb, receipts)
  570. case SideStatTy:
  571. if glog.V(logger.Detail) {
  572. 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))
  573. }
  574. events = append(events, ChainSideEvent{block, logs})
  575. case SplitStatTy:
  576. events = append(events, ChainSplitEvent{block, logs})
  577. }
  578. stats.processed++
  579. }
  580. if (stats.queued > 0 || stats.processed > 0 || stats.ignored > 0) && bool(glog.V(logger.Info)) {
  581. tend := time.Since(tstart)
  582. start, end := chain[0], chain[len(chain)-1]
  583. 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])
  584. }
  585. go self.postChainEvents(events)
  586. return 0, nil
  587. }
  588. // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  589. // to be part of the new canonical chain and accumulates potential missing transactions and post an
  590. // event about them
  591. func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  592. self.mu.Lock()
  593. defer self.mu.Unlock()
  594. var (
  595. newChain types.Blocks
  596. commonBlock *types.Block
  597. oldStart = oldBlock
  598. newStart = newBlock
  599. deletedTxs types.Transactions
  600. )
  601. // first reduce whoever is higher bound
  602. if oldBlock.NumberU64() > newBlock.NumberU64() {
  603. // reduce old chain
  604. for oldBlock = oldBlock; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = self.GetBlock(oldBlock.ParentHash()) {
  605. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  606. }
  607. } else {
  608. // reduce new chain and append new chain blocks for inserting later on
  609. for newBlock = newBlock; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = self.GetBlock(newBlock.ParentHash()) {
  610. newChain = append(newChain, newBlock)
  611. }
  612. }
  613. if oldBlock == nil {
  614. return fmt.Errorf("Invalid old chain")
  615. }
  616. if newBlock == nil {
  617. return fmt.Errorf("Invalid new chain")
  618. }
  619. numSplit := newBlock.Number()
  620. for {
  621. if oldBlock.Hash() == newBlock.Hash() {
  622. commonBlock = oldBlock
  623. break
  624. }
  625. newChain = append(newChain, newBlock)
  626. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  627. oldBlock, newBlock = self.GetBlock(oldBlock.ParentHash()), self.GetBlock(newBlock.ParentHash())
  628. if oldBlock == nil {
  629. return fmt.Errorf("Invalid old chain")
  630. }
  631. if newBlock == nil {
  632. return fmt.Errorf("Invalid new chain")
  633. }
  634. }
  635. if glog.V(logger.Debug) {
  636. commonHash := commonBlock.Hash()
  637. glog.Infof("Chain split detected @ %x. Reorganising chain from #%v %x to %x", commonHash[:4], numSplit, oldStart.Hash().Bytes()[:4], newStart.Hash().Bytes()[:4])
  638. }
  639. var addedTxs types.Transactions
  640. // insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
  641. for _, block := range newChain {
  642. // insert the block in the canonical way, re-writing history
  643. self.insert(block)
  644. // write canonical receipts and transactions
  645. PutTransactions(self.chainDb, block, block.Transactions())
  646. PutReceipts(self.chainDb, GetBlockReceipts(self.chainDb, block.Hash()))
  647. addedTxs = append(addedTxs, block.Transactions()...)
  648. }
  649. // calculate the difference between deleted and added transactions
  650. diff := types.TxDifference(deletedTxs, addedTxs)
  651. // When transactions get deleted from the database that means the
  652. // receipts that were created in the fork must also be deleted
  653. for _, tx := range diff {
  654. DeleteReceipt(self.chainDb, tx.Hash())
  655. DeleteTransaction(self.chainDb, tx.Hash())
  656. }
  657. // Must be posted in a goroutine because of the transaction pool trying
  658. // to acquire the chain manager lock
  659. go self.eventMux.Post(RemovedTransactionEvent{diff})
  660. return nil
  661. }
  662. // postChainEvents iterates over the events generated by a chain insertion and
  663. // posts them into the event mux.
  664. func (self *BlockChain) postChainEvents(events []interface{}) {
  665. for _, event := range events {
  666. if event, ok := event.(ChainEvent); ok {
  667. // We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
  668. // and in most cases isn't even necessary.
  669. if self.currentBlock.Hash() == event.Hash {
  670. self.currentGasLimit = CalcGasLimit(event.Block)
  671. self.eventMux.Post(ChainHeadEvent{event.Block})
  672. }
  673. }
  674. // Fire the insertion events individually too
  675. self.eventMux.Post(event)
  676. }
  677. }
  678. func (self *BlockChain) update() {
  679. futureTimer := time.Tick(5 * time.Second)
  680. for {
  681. select {
  682. case <-futureTimer:
  683. self.procFutureBlocks()
  684. case <-self.quit:
  685. return
  686. }
  687. }
  688. }
  689. func blockErr(block *types.Block, err error) {
  690. if glog.V(logger.Error) {
  691. glog.Errorf("Bad block #%v (%s)\n", block.Number(), block.Hash().Hex())
  692. glog.Errorf(" %v", err)
  693. }
  694. }