blockchain.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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. "math/rand"
  24. "runtime"
  25. "sync"
  26. "sync/atomic"
  27. "time"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/core/state"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/logger"
  35. "github.com/ethereum/go-ethereum/logger/glog"
  36. "github.com/ethereum/go-ethereum/metrics"
  37. "github.com/ethereum/go-ethereum/pow"
  38. "github.com/ethereum/go-ethereum/rlp"
  39. "github.com/ethereum/go-ethereum/trie"
  40. "github.com/hashicorp/golang-lru"
  41. )
  42. var (
  43. chainlogger = logger.NewLogger("CHAIN")
  44. jsonlogger = logger.NewJsonLogger()
  45. blockInsertTimer = metrics.NewTimer("chain/inserts")
  46. ErrNoGenesis = errors.New("Genesis not found in chain")
  47. )
  48. const (
  49. headerCacheLimit = 512
  50. bodyCacheLimit = 256
  51. tdCacheLimit = 1024
  52. blockCacheLimit = 256
  53. maxFutureBlocks = 256
  54. maxTimeFutureBlocks = 30
  55. )
  56. type BlockChain struct {
  57. chainDb ethdb.Database
  58. processor types.BlockProcessor
  59. eventMux *event.TypeMux
  60. genesisBlock *types.Block
  61. // Last known total difficulty
  62. mu sync.RWMutex
  63. chainmu sync.RWMutex
  64. tsmu sync.RWMutex
  65. checkpoint int // checkpoint counts towards the new checkpoint
  66. currentHeader *types.Header // Current head of the header chain (may be above the block chain!)
  67. currentBlock *types.Block // Current head of the block chain
  68. currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!)
  69. headerCache *lru.Cache // Cache for the most recent block headers
  70. bodyCache *lru.Cache // Cache for the most recent block bodies
  71. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  72. tdCache *lru.Cache // Cache for the most recent block total difficulties
  73. blockCache *lru.Cache // Cache for the most recent entire blocks
  74. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  75. quit chan struct{}
  76. running int32 // running must be called automically
  77. // procInterrupt must be atomically called
  78. procInterrupt int32 // interrupt signaler for block processing
  79. wg sync.WaitGroup
  80. pow pow.PoW
  81. }
  82. func NewBlockChain(chainDb ethdb.Database, pow pow.PoW, mux *event.TypeMux) (*BlockChain, error) {
  83. headerCache, _ := lru.New(headerCacheLimit)
  84. bodyCache, _ := lru.New(bodyCacheLimit)
  85. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  86. tdCache, _ := lru.New(tdCacheLimit)
  87. blockCache, _ := lru.New(blockCacheLimit)
  88. futureBlocks, _ := lru.New(maxFutureBlocks)
  89. bc := &BlockChain{
  90. chainDb: chainDb,
  91. eventMux: mux,
  92. quit: make(chan struct{}),
  93. headerCache: headerCache,
  94. bodyCache: bodyCache,
  95. bodyRLPCache: bodyRLPCache,
  96. tdCache: tdCache,
  97. blockCache: blockCache,
  98. futureBlocks: futureBlocks,
  99. pow: pow,
  100. }
  101. bc.genesisBlock = bc.GetBlockByNumber(0)
  102. if bc.genesisBlock == nil {
  103. reader, err := NewDefaultGenesisReader()
  104. if err != nil {
  105. return nil, err
  106. }
  107. bc.genesisBlock, err = WriteGenesisBlock(chainDb, reader)
  108. if err != nil {
  109. return nil, err
  110. }
  111. glog.V(logger.Info).Infoln("WARNING: Wrote default ethereum genesis block")
  112. }
  113. if err := bc.loadLastState(); err != nil {
  114. return nil, err
  115. }
  116. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  117. for hash, _ := range BadHashes {
  118. if header := bc.GetHeader(hash); header != nil {
  119. glog.V(logger.Error).Infof("Found bad hash, rewinding chain to block #%d [%x…]", header.Number, header.ParentHash[:4])
  120. bc.SetHead(header.Number.Uint64() - 1)
  121. glog.V(logger.Error).Infoln("Chain rewind was successful, resuming normal operation")
  122. }
  123. }
  124. // Take ownership of this particular state
  125. go bc.update()
  126. return bc, nil
  127. }
  128. // loadLastState loads the last known chain state from the database. This method
  129. // assumes that the chain manager mutex is held.
  130. func (self *BlockChain) loadLastState() error {
  131. // Restore the last known head block
  132. head := GetHeadBlockHash(self.chainDb)
  133. if head == (common.Hash{}) {
  134. // Corrupt or empty database, init from scratch
  135. self.Reset()
  136. } else {
  137. if block := self.GetBlock(head); block != nil {
  138. // Block found, set as the current head
  139. self.currentBlock = block
  140. } else {
  141. // Corrupt or empty database, init from scratch
  142. self.Reset()
  143. }
  144. }
  145. // Restore the last known head header
  146. self.currentHeader = self.currentBlock.Header()
  147. if head := GetHeadHeaderHash(self.chainDb); head != (common.Hash{}) {
  148. if header := self.GetHeader(head); header != nil {
  149. self.currentHeader = header
  150. }
  151. }
  152. // Restore the last known head fast block
  153. self.currentFastBlock = self.currentBlock
  154. if head := GetHeadFastBlockHash(self.chainDb); head != (common.Hash{}) {
  155. if block := self.GetBlock(head); block != nil {
  156. self.currentFastBlock = block
  157. }
  158. }
  159. // Issue a status log and return
  160. headerTd := self.GetTd(self.currentHeader.Hash())
  161. blockTd := self.GetTd(self.currentBlock.Hash())
  162. fastTd := self.GetTd(self.currentFastBlock.Hash())
  163. glog.V(logger.Info).Infof("Last header: #%d [%x…] TD=%v", self.currentHeader.Number, self.currentHeader.Hash().Bytes()[:4], headerTd)
  164. glog.V(logger.Info).Infof("Fast block: #%d [%x…] TD=%v", self.currentFastBlock.Number(), self.currentFastBlock.Hash().Bytes()[:4], fastTd)
  165. glog.V(logger.Info).Infof("Last block: #%d [%x…] TD=%v", self.currentBlock.Number(), self.currentBlock.Hash().Bytes()[:4], blockTd)
  166. return nil
  167. }
  168. // SetHead rewind the local chain to a new head entity. In the case of headers,
  169. // everything above the new head will be deleted and the new one set. In the case
  170. // of blocks though, the head may be further rewound if block bodies are missing
  171. // (non-archive nodes after a fast sync).
  172. func (bc *BlockChain) SetHead(head uint64) {
  173. bc.mu.Lock()
  174. defer bc.mu.Unlock()
  175. // Figure out the highest known canonical assignment
  176. height := uint64(0)
  177. if bc.currentHeader != nil {
  178. if hh := bc.currentHeader.Number.Uint64(); hh > height {
  179. height = hh
  180. }
  181. }
  182. if bc.currentBlock != nil {
  183. if bh := bc.currentBlock.NumberU64(); bh > height {
  184. height = bh
  185. }
  186. }
  187. if bc.currentFastBlock != nil {
  188. if fbh := bc.currentFastBlock.NumberU64(); fbh > height {
  189. height = fbh
  190. }
  191. }
  192. // Gather all the hashes that need deletion
  193. drop := make(map[common.Hash]struct{})
  194. for bc.currentHeader != nil && bc.currentHeader.Number.Uint64() > head {
  195. drop[bc.currentHeader.Hash()] = struct{}{}
  196. bc.currentHeader = bc.GetHeader(bc.currentHeader.ParentHash)
  197. }
  198. for bc.currentBlock != nil && bc.currentBlock.NumberU64() > head {
  199. drop[bc.currentBlock.Hash()] = struct{}{}
  200. bc.currentBlock = bc.GetBlock(bc.currentBlock.ParentHash())
  201. }
  202. for bc.currentFastBlock != nil && bc.currentFastBlock.NumberU64() > head {
  203. drop[bc.currentFastBlock.Hash()] = struct{}{}
  204. bc.currentFastBlock = bc.GetBlock(bc.currentFastBlock.ParentHash())
  205. }
  206. // Roll back the canonical chain numbering
  207. for i := height; i > head; i-- {
  208. DeleteCanonicalHash(bc.chainDb, i)
  209. }
  210. // Delete everything found by the above rewind
  211. for hash, _ := range drop {
  212. DeleteHeader(bc.chainDb, hash)
  213. DeleteBody(bc.chainDb, hash)
  214. DeleteTd(bc.chainDb, hash)
  215. }
  216. // Clear out any stale content from the caches
  217. bc.headerCache.Purge()
  218. bc.bodyCache.Purge()
  219. bc.bodyRLPCache.Purge()
  220. bc.blockCache.Purge()
  221. bc.futureBlocks.Purge()
  222. // Update all computed fields to the new head
  223. if bc.currentBlock == nil {
  224. bc.currentBlock = bc.genesisBlock
  225. }
  226. bc.insert(bc.currentBlock)
  227. bc.loadLastState()
  228. }
  229. // FastSyncCommitHead sets the current head block to the one defined by the hash
  230. // irrelevant what the chain contents were prior.
  231. func (self *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  232. // Make sure that both the block as well at it's state trie exists
  233. block := self.GetBlock(hash)
  234. if block == nil {
  235. return fmt.Errorf("non existent block [%x…]", hash[:4])
  236. }
  237. if _, err := trie.NewSecure(block.Root(), self.chainDb); err != nil {
  238. return err
  239. }
  240. // If all checks out, manually set the head block
  241. self.mu.Lock()
  242. self.currentBlock = block
  243. self.mu.Unlock()
  244. glog.V(logger.Info).Infof("committed block #%d [%x…] as new head", block.Number(), hash[:4])
  245. return nil
  246. }
  247. func (self *BlockChain) GasLimit() *big.Int {
  248. self.mu.RLock()
  249. defer self.mu.RUnlock()
  250. return self.currentBlock.GasLimit()
  251. }
  252. func (self *BlockChain) LastBlockHash() common.Hash {
  253. self.mu.RLock()
  254. defer self.mu.RUnlock()
  255. return self.currentBlock.Hash()
  256. }
  257. // CurrentHeader retrieves the current head header of the canonical chain. The
  258. // header is retrieved from the chain manager's internal cache.
  259. func (self *BlockChain) CurrentHeader() *types.Header {
  260. self.mu.RLock()
  261. defer self.mu.RUnlock()
  262. return self.currentHeader
  263. }
  264. // CurrentBlock retrieves the current head block of the canonical chain. The
  265. // block is retrieved from the chain manager's internal cache.
  266. func (self *BlockChain) CurrentBlock() *types.Block {
  267. self.mu.RLock()
  268. defer self.mu.RUnlock()
  269. return self.currentBlock
  270. }
  271. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  272. // chain. The block is retrieved from the chain manager's internal cache.
  273. func (self *BlockChain) CurrentFastBlock() *types.Block {
  274. self.mu.RLock()
  275. defer self.mu.RUnlock()
  276. return self.currentFastBlock
  277. }
  278. func (self *BlockChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  279. self.mu.RLock()
  280. defer self.mu.RUnlock()
  281. return self.GetTd(self.currentBlock.Hash()), self.currentBlock.Hash(), self.genesisBlock.Hash()
  282. }
  283. func (self *BlockChain) SetProcessor(proc types.BlockProcessor) {
  284. self.processor = proc
  285. }
  286. func (self *BlockChain) State() (*state.StateDB, error) {
  287. return state.New(self.CurrentBlock().Root(), self.chainDb)
  288. }
  289. // Reset purges the entire blockchain, restoring it to its genesis state.
  290. func (bc *BlockChain) Reset() {
  291. bc.ResetWithGenesisBlock(bc.genesisBlock)
  292. }
  293. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  294. // specified genesis state.
  295. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) {
  296. // Dump the entire block chain and purge the caches
  297. bc.SetHead(0)
  298. bc.mu.Lock()
  299. defer bc.mu.Unlock()
  300. // Prepare the genesis block and reinitialize the chain
  301. if err := WriteTd(bc.chainDb, genesis.Hash(), genesis.Difficulty()); err != nil {
  302. glog.Fatalf("failed to write genesis block TD: %v", err)
  303. }
  304. if err := WriteBlock(bc.chainDb, genesis); err != nil {
  305. glog.Fatalf("failed to write genesis block: %v", err)
  306. }
  307. bc.genesisBlock = genesis
  308. bc.insert(bc.genesisBlock)
  309. bc.currentBlock = bc.genesisBlock
  310. bc.currentHeader = bc.genesisBlock.Header()
  311. bc.currentFastBlock = bc.genesisBlock
  312. }
  313. // Export writes the active chain to the given writer.
  314. func (self *BlockChain) Export(w io.Writer) error {
  315. if err := self.ExportN(w, uint64(0), self.currentBlock.NumberU64()); err != nil {
  316. return err
  317. }
  318. return nil
  319. }
  320. // ExportN writes a subset of the active chain to the given writer.
  321. func (self *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  322. self.mu.RLock()
  323. defer self.mu.RUnlock()
  324. if first > last {
  325. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  326. }
  327. glog.V(logger.Info).Infof("exporting %d blocks...\n", last-first+1)
  328. for nr := first; nr <= last; nr++ {
  329. block := self.GetBlockByNumber(nr)
  330. if block == nil {
  331. return fmt.Errorf("export failed on #%d: not found", nr)
  332. }
  333. if err := block.EncodeRLP(w); err != nil {
  334. return err
  335. }
  336. }
  337. return nil
  338. }
  339. // insert injects a new head block into the current block chain. This method
  340. // assumes that the block is indeed a true head. It will also reset the head
  341. // header and the head fast sync block to this very same block to prevent them
  342. // from diverging on a different header chain.
  343. //
  344. // Note, this function assumes that the `mu` mutex is held!
  345. func (bc *BlockChain) insert(block *types.Block) {
  346. // Add the block to the canonical chain number scheme and mark as the head
  347. if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
  348. glog.Fatalf("failed to insert block number: %v", err)
  349. }
  350. if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
  351. glog.Fatalf("failed to insert head block hash: %v", err)
  352. }
  353. if err := WriteHeadHeaderHash(bc.chainDb, block.Hash()); err != nil {
  354. glog.Fatalf("failed to insert head header hash: %v", err)
  355. }
  356. if err := WriteHeadFastBlockHash(bc.chainDb, block.Hash()); err != nil {
  357. glog.Fatalf("failed to insert head fast block hash: %v", err)
  358. }
  359. // Update the internal state with the head block
  360. bc.currentBlock = block
  361. bc.currentHeader = block.Header()
  362. bc.currentFastBlock = block
  363. }
  364. // Accessors
  365. func (bc *BlockChain) Genesis() *types.Block {
  366. return bc.genesisBlock
  367. }
  368. // HasHeader checks if a block header is present in the database or not, caching
  369. // it if present.
  370. func (bc *BlockChain) HasHeader(hash common.Hash) bool {
  371. return bc.GetHeader(hash) != nil
  372. }
  373. // GetHeader retrieves a block header from the database by hash, caching it if
  374. // found.
  375. func (self *BlockChain) GetHeader(hash common.Hash) *types.Header {
  376. // Short circuit if the header's already in the cache, retrieve otherwise
  377. if header, ok := self.headerCache.Get(hash); ok {
  378. return header.(*types.Header)
  379. }
  380. header := GetHeader(self.chainDb, hash)
  381. if header == nil {
  382. return nil
  383. }
  384. // Cache the found header for next time and return
  385. self.headerCache.Add(header.Hash(), header)
  386. return header
  387. }
  388. // GetHeaderByNumber retrieves a block header from the database by number,
  389. // caching it (associated with its hash) if found.
  390. func (self *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  391. hash := GetCanonicalHash(self.chainDb, number)
  392. if hash == (common.Hash{}) {
  393. return nil
  394. }
  395. return self.GetHeader(hash)
  396. }
  397. // GetBody retrieves a block body (transactions and uncles) from the database by
  398. // hash, caching it if found.
  399. func (self *BlockChain) GetBody(hash common.Hash) *types.Body {
  400. // Short circuit if the body's already in the cache, retrieve otherwise
  401. if cached, ok := self.bodyCache.Get(hash); ok {
  402. body := cached.(*types.Body)
  403. return body
  404. }
  405. body := GetBody(self.chainDb, hash)
  406. if body == nil {
  407. return nil
  408. }
  409. // Cache the found body for next time and return
  410. self.bodyCache.Add(hash, body)
  411. return body
  412. }
  413. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  414. // caching it if found.
  415. func (self *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  416. // Short circuit if the body's already in the cache, retrieve otherwise
  417. if cached, ok := self.bodyRLPCache.Get(hash); ok {
  418. return cached.(rlp.RawValue)
  419. }
  420. body := GetBodyRLP(self.chainDb, hash)
  421. if len(body) == 0 {
  422. return nil
  423. }
  424. // Cache the found body for next time and return
  425. self.bodyRLPCache.Add(hash, body)
  426. return body
  427. }
  428. // GetTd retrieves a block's total difficulty in the canonical chain from the
  429. // database by hash, caching it if found.
  430. func (self *BlockChain) GetTd(hash common.Hash) *big.Int {
  431. // Short circuit if the td's already in the cache, retrieve otherwise
  432. if cached, ok := self.tdCache.Get(hash); ok {
  433. return cached.(*big.Int)
  434. }
  435. td := GetTd(self.chainDb, hash)
  436. if td == nil {
  437. return nil
  438. }
  439. // Cache the found body for next time and return
  440. self.tdCache.Add(hash, td)
  441. return td
  442. }
  443. // HasBlock checks if a block is fully present in the database or not, caching
  444. // it if present.
  445. func (bc *BlockChain) HasBlock(hash common.Hash) bool {
  446. return bc.GetBlock(hash) != nil
  447. }
  448. // GetBlock retrieves a block from the database by hash, caching it if found.
  449. func (self *BlockChain) GetBlock(hash common.Hash) *types.Block {
  450. // Short circuit if the block's already in the cache, retrieve otherwise
  451. if block, ok := self.blockCache.Get(hash); ok {
  452. return block.(*types.Block)
  453. }
  454. block := GetBlock(self.chainDb, hash)
  455. if block == nil {
  456. return nil
  457. }
  458. // Cache the found block for next time and return
  459. self.blockCache.Add(block.Hash(), block)
  460. return block
  461. }
  462. // GetBlockByNumber retrieves a block from the database by number, caching it
  463. // (associated with its hash) if found.
  464. func (self *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  465. hash := GetCanonicalHash(self.chainDb, number)
  466. if hash == (common.Hash{}) {
  467. return nil
  468. }
  469. return self.GetBlock(hash)
  470. }
  471. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  472. // hash, fetching towards the genesis block.
  473. func (self *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  474. // Get the origin header from which to fetch
  475. header := self.GetHeader(hash)
  476. if header == nil {
  477. return nil
  478. }
  479. // Iterate the headers until enough is collected or the genesis reached
  480. chain := make([]common.Hash, 0, max)
  481. for i := uint64(0); i < max; i++ {
  482. if header = self.GetHeader(header.ParentHash); header == nil {
  483. break
  484. }
  485. chain = append(chain, header.Hash())
  486. if header.Number.Cmp(common.Big0) == 0 {
  487. break
  488. }
  489. }
  490. return chain
  491. }
  492. // [deprecated by eth/62]
  493. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  494. func (self *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  495. for i := 0; i < n; i++ {
  496. block := self.GetBlock(hash)
  497. if block == nil {
  498. break
  499. }
  500. blocks = append(blocks, block)
  501. hash = block.ParentHash()
  502. }
  503. return
  504. }
  505. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  506. // a specific distance is reached.
  507. func (self *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  508. uncles := []*types.Header{}
  509. for i := 0; block != nil && i < length; i++ {
  510. uncles = append(uncles, block.Uncles()...)
  511. block = self.GetBlock(block.ParentHash())
  512. }
  513. return uncles
  514. }
  515. func (bc *BlockChain) Stop() {
  516. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  517. return
  518. }
  519. close(bc.quit)
  520. atomic.StoreInt32(&bc.procInterrupt, 1)
  521. bc.wg.Wait()
  522. glog.V(logger.Info).Infoln("Chain manager stopped")
  523. }
  524. func (self *BlockChain) procFutureBlocks() {
  525. blocks := make([]*types.Block, self.futureBlocks.Len())
  526. for i, hash := range self.futureBlocks.Keys() {
  527. block, _ := self.futureBlocks.Get(hash)
  528. blocks[i] = block.(*types.Block)
  529. }
  530. if len(blocks) > 0 {
  531. types.BlockBy(types.Number).Sort(blocks)
  532. self.InsertChain(blocks)
  533. }
  534. }
  535. type writeStatus byte
  536. const (
  537. NonStatTy writeStatus = iota
  538. CanonStatTy
  539. SplitStatTy
  540. SideStatTy
  541. )
  542. // writeHeader writes a header into the local chain, given that its parent is
  543. // already known. If the total difficulty of the newly inserted header becomes
  544. // greater than the old known TD, the canonical chain is re-routed.
  545. //
  546. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  547. // into the chain, as side effects caused by reorganizations cannot be emulated
  548. // without the real blocks. Hence, writing headers directly should only be done
  549. // in two scenarios: pure-header mode of operation (light clients), or properly
  550. // separated header/block phases (non-archive clients).
  551. func (self *BlockChain) writeHeader(header *types.Header) error {
  552. self.wg.Add(1)
  553. defer self.wg.Done()
  554. // Calculate the total difficulty of the header
  555. ptd := self.GetTd(header.ParentHash)
  556. if ptd == nil {
  557. return ParentError(header.ParentHash)
  558. }
  559. td := new(big.Int).Add(header.Difficulty, ptd)
  560. // Make sure no inconsistent state is leaked during insertion
  561. self.mu.Lock()
  562. defer self.mu.Unlock()
  563. // If the total difficulty is higher than our known, add it to the canonical chain
  564. if td.Cmp(self.GetTd(self.currentHeader.Hash())) > 0 {
  565. // Delete any canonical number assignments above the new head
  566. for i := header.Number.Uint64() + 1; GetCanonicalHash(self.chainDb, i) != (common.Hash{}); i++ {
  567. DeleteCanonicalHash(self.chainDb, i)
  568. }
  569. // Overwrite any stale canonical number assignments
  570. head := self.GetHeader(header.ParentHash)
  571. for GetCanonicalHash(self.chainDb, head.Number.Uint64()) != head.Hash() {
  572. WriteCanonicalHash(self.chainDb, head.Hash(), head.Number.Uint64())
  573. head = self.GetHeader(head.ParentHash)
  574. }
  575. // Extend the canonical chain with the new header
  576. if err := WriteCanonicalHash(self.chainDb, header.Hash(), header.Number.Uint64()); err != nil {
  577. glog.Fatalf("failed to insert header number: %v", err)
  578. }
  579. if err := WriteHeadHeaderHash(self.chainDb, header.Hash()); err != nil {
  580. glog.Fatalf("failed to insert head header hash: %v", err)
  581. }
  582. self.currentHeader = types.CopyHeader(header)
  583. }
  584. // Irrelevant of the canonical status, write the header itself to the database
  585. if err := WriteTd(self.chainDb, header.Hash(), td); err != nil {
  586. glog.Fatalf("failed to write header total difficulty: %v", err)
  587. }
  588. if err := WriteHeader(self.chainDb, header); err != nil {
  589. glog.Fatalf("filed to write header contents: %v", err)
  590. }
  591. return nil
  592. }
  593. // InsertHeaderChain will attempt to insert the given header chain in to the
  594. // local chain, possibly creating a fork. If an error is returned, it will
  595. // return the index number of the failing header as well an error describing
  596. // what went wrong.
  597. //
  598. // The verify parameter can be used to fine tune whether nonce verification
  599. // should be done or not. The reason behind the optional check is because some
  600. // of the header retrieval mechanisms already need to verfy nonces, as well as
  601. // because nonces can be verified sparsely, not needing to check each.
  602. func (self *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  603. self.wg.Add(1)
  604. defer self.wg.Done()
  605. // Make sure only one thread manipulates the chain at once
  606. self.chainmu.Lock()
  607. defer self.chainmu.Unlock()
  608. // Collect some import statistics to report on
  609. stats := struct{ processed, ignored int }{}
  610. start := time.Now()
  611. // Generate the list of headers that should be POW verified
  612. verify := make([]bool, len(chain))
  613. for i := 0; i < len(verify)/checkFreq; i++ {
  614. index := i*checkFreq + rand.Intn(checkFreq)
  615. if index >= len(verify) {
  616. index = len(verify) - 1
  617. }
  618. verify[index] = true
  619. }
  620. verify[len(verify)-1] = true // Last should always be verified to avoid junk
  621. // Create the header verification task queue and worker functions
  622. tasks := make(chan int, len(chain))
  623. for i := 0; i < len(chain); i++ {
  624. tasks <- i
  625. }
  626. close(tasks)
  627. errs, failed := make([]error, len(tasks)), int32(0)
  628. process := func(worker int) {
  629. for index := range tasks {
  630. header, hash := chain[index], chain[index].Hash()
  631. // Short circuit insertion if shutting down or processing failed
  632. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  633. return
  634. }
  635. if atomic.LoadInt32(&failed) > 0 {
  636. return
  637. }
  638. // Short circuit if the header is bad or already known
  639. if BadHashes[hash] {
  640. errs[index] = BadHashError(hash)
  641. atomic.AddInt32(&failed, 1)
  642. return
  643. }
  644. if self.HasHeader(hash) {
  645. continue
  646. }
  647. // Verify that the header honors the chain parameters
  648. checkPow := verify[index]
  649. var err error
  650. if index == 0 {
  651. err = self.processor.ValidateHeader(header, checkPow, false)
  652. } else {
  653. err = self.processor.ValidateHeaderWithParent(header, chain[index-1], checkPow, false)
  654. }
  655. if err != nil {
  656. errs[index] = err
  657. atomic.AddInt32(&failed, 1)
  658. return
  659. }
  660. }
  661. }
  662. // Start as many worker threads as goroutines allowed
  663. pending := new(sync.WaitGroup)
  664. for i := 0; i < runtime.GOMAXPROCS(0); i++ {
  665. pending.Add(1)
  666. go func(id int) {
  667. defer pending.Done()
  668. process(id)
  669. }(i)
  670. }
  671. pending.Wait()
  672. // If anything failed, report
  673. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  674. glog.V(logger.Debug).Infoln("premature abort during receipt chain processing")
  675. return 0, nil
  676. }
  677. if failed > 0 {
  678. for i, err := range errs {
  679. if err != nil {
  680. return i, err
  681. }
  682. }
  683. }
  684. // All headers passed verification, import them into the database
  685. for i, header := range chain {
  686. // Short circuit insertion if shutting down
  687. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  688. glog.V(logger.Debug).Infoln("premature abort during header chain processing")
  689. break
  690. }
  691. hash := header.Hash()
  692. // If the header's already known, skip it, otherwise store
  693. if self.HasHeader(hash) {
  694. stats.ignored++
  695. continue
  696. }
  697. if err := self.writeHeader(header); err != nil {
  698. return i, err
  699. }
  700. stats.processed++
  701. }
  702. // Report some public statistics so the user has a clue what's going on
  703. first, last := chain[0], chain[len(chain)-1]
  704. glog.V(logger.Info).Infof("imported %d header(s) (%d ignored) in %v. #%v [%x… / %x…]", stats.processed, stats.ignored,
  705. time.Since(start), last.Number, first.Hash().Bytes()[:4], last.Hash().Bytes()[:4])
  706. return 0, nil
  707. }
  708. // InsertReceiptChain attempts to complete an already existing header chain with
  709. // transaction and receipt data.
  710. func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  711. self.wg.Add(1)
  712. defer self.wg.Done()
  713. // Collect some import statistics to report on
  714. stats := struct{ processed, ignored int32 }{}
  715. start := time.Now()
  716. // Create the block importing task queue and worker functions
  717. tasks := make(chan int, len(blockChain))
  718. for i := 0; i < len(blockChain) && i < len(receiptChain); i++ {
  719. tasks <- i
  720. }
  721. close(tasks)
  722. errs, failed := make([]error, len(tasks)), int32(0)
  723. process := func(worker int) {
  724. for index := range tasks {
  725. block, receipts := blockChain[index], receiptChain[index]
  726. // Short circuit insertion if shutting down or processing failed
  727. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  728. return
  729. }
  730. if atomic.LoadInt32(&failed) > 0 {
  731. return
  732. }
  733. // Short circuit if the owner header is unknown
  734. if !self.HasHeader(block.Hash()) {
  735. errs[index] = fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  736. atomic.AddInt32(&failed, 1)
  737. return
  738. }
  739. // Skip if the entire data is already known
  740. if self.HasBlock(block.Hash()) {
  741. atomic.AddInt32(&stats.ignored, 1)
  742. continue
  743. }
  744. // Compute all the non-consensus fields of the receipts
  745. transactions, logIndex := block.Transactions(), uint(0)
  746. for j := 0; j < len(receipts); j++ {
  747. // The transaction hash can be retrieved from the transaction itself
  748. receipts[j].TxHash = transactions[j].Hash()
  749. // The contract address can be derived from the transaction itself
  750. if MessageCreatesContract(transactions[j]) {
  751. from, _ := transactions[j].From()
  752. receipts[j].ContractAddress = crypto.CreateAddress(from, transactions[j].Nonce())
  753. }
  754. // The used gas can be calculated based on previous receipts
  755. if j == 0 {
  756. receipts[j].GasUsed = new(big.Int).Set(receipts[j].CumulativeGasUsed)
  757. } else {
  758. receipts[j].GasUsed = new(big.Int).Sub(receipts[j].CumulativeGasUsed, receipts[j-1].CumulativeGasUsed)
  759. }
  760. // The derived log fields can simply be set from the block and transaction
  761. for k := 0; k < len(receipts[j].Logs); k++ {
  762. receipts[j].Logs[k].BlockNumber = block.NumberU64()
  763. receipts[j].Logs[k].BlockHash = block.Hash()
  764. receipts[j].Logs[k].TxHash = receipts[j].TxHash
  765. receipts[j].Logs[k].TxIndex = uint(j)
  766. receipts[j].Logs[k].Index = logIndex
  767. logIndex++
  768. }
  769. }
  770. // Write all the data out into the database
  771. if err := WriteBody(self.chainDb, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
  772. errs[index] = fmt.Errorf("failed to write block body: %v", err)
  773. atomic.AddInt32(&failed, 1)
  774. glog.Fatal(errs[index])
  775. return
  776. }
  777. if err := PutBlockReceipts(self.chainDb, block.Hash(), receipts); err != nil {
  778. errs[index] = fmt.Errorf("failed to write block receipts: %v", err)
  779. atomic.AddInt32(&failed, 1)
  780. glog.Fatal(errs[index])
  781. return
  782. }
  783. atomic.AddInt32(&stats.processed, 1)
  784. }
  785. }
  786. // Start as many worker threads as goroutines allowed
  787. pending := new(sync.WaitGroup)
  788. for i := 0; i < runtime.GOMAXPROCS(0); i++ {
  789. pending.Add(1)
  790. go func(id int) {
  791. defer pending.Done()
  792. process(id)
  793. }(i)
  794. }
  795. pending.Wait()
  796. // If anything failed, report
  797. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  798. glog.V(logger.Debug).Infoln("premature abort during receipt chain processing")
  799. return 0, nil
  800. }
  801. if failed > 0 {
  802. for i, err := range errs {
  803. if err != nil {
  804. return i, err
  805. }
  806. }
  807. }
  808. // Update the head fast sync block if better
  809. self.mu.Lock()
  810. head := blockChain[len(errs)-1]
  811. if self.GetTd(self.currentFastBlock.Hash()).Cmp(self.GetTd(head.Hash())) < 0 {
  812. if err := WriteHeadFastBlockHash(self.chainDb, head.Hash()); err != nil {
  813. glog.Fatalf("failed to update head fast block hash: %v", err)
  814. }
  815. self.currentFastBlock = head
  816. }
  817. self.mu.Unlock()
  818. // Report some public statistics so the user has a clue what's going on
  819. first, last := blockChain[0], blockChain[len(blockChain)-1]
  820. glog.V(logger.Info).Infof("imported %d receipt(s) (%d ignored) in %v. #%d [%x… / %x…]", stats.processed, stats.ignored,
  821. time.Since(start), last.Number(), first.Hash().Bytes()[:4], last.Hash().Bytes()[:4])
  822. return 0, nil
  823. }
  824. // WriteBlock writes the block to the chain.
  825. func (self *BlockChain) WriteBlock(block *types.Block) (status writeStatus, err error) {
  826. self.wg.Add(1)
  827. defer self.wg.Done()
  828. // Calculate the total difficulty of the block
  829. ptd := self.GetTd(block.ParentHash())
  830. if ptd == nil {
  831. return NonStatTy, ParentError(block.ParentHash())
  832. }
  833. td := new(big.Int).Add(block.Difficulty(), ptd)
  834. // Make sure no inconsistent state is leaked during insertion
  835. self.mu.Lock()
  836. defer self.mu.Unlock()
  837. // If the total difficulty is higher than our known, add it to the canonical chain
  838. if td.Cmp(self.GetTd(self.currentBlock.Hash())) > 0 {
  839. // Reorganize the chain if the parent is not the head block
  840. if block.ParentHash() != self.currentBlock.Hash() {
  841. if err := self.reorg(self.currentBlock, block); err != nil {
  842. return NonStatTy, err
  843. }
  844. }
  845. // Insert the block as the new head of the chain
  846. self.insert(block)
  847. status = CanonStatTy
  848. } else {
  849. status = SideStatTy
  850. }
  851. // Irrelevant of the canonical status, write the block itself to the database
  852. if err := WriteTd(self.chainDb, block.Hash(), td); err != nil {
  853. glog.Fatalf("failed to write block total difficulty: %v", err)
  854. }
  855. if err := WriteBlock(self.chainDb, block); err != nil {
  856. glog.Fatalf("filed to write block contents: %v", err)
  857. }
  858. self.futureBlocks.Remove(block.Hash())
  859. return
  860. }
  861. // InsertChain will attempt to insert the given chain in to the canonical chain or, otherwise, create a fork. It an error is returned
  862. // 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).
  863. func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  864. self.wg.Add(1)
  865. defer self.wg.Done()
  866. self.chainmu.Lock()
  867. defer self.chainmu.Unlock()
  868. // A queued approach to delivering events. This is generally
  869. // faster than direct delivery and requires much less mutex
  870. // acquiring.
  871. var (
  872. stats struct{ queued, processed, ignored int }
  873. events = make([]interface{}, 0, len(chain))
  874. tstart = time.Now()
  875. nonceChecked = make([]bool, len(chain))
  876. )
  877. // Start the parallel nonce verifier.
  878. nonceAbort, nonceResults := verifyNoncesFromBlocks(self.pow, chain)
  879. defer close(nonceAbort)
  880. txcount := 0
  881. for i, block := range chain {
  882. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  883. glog.V(logger.Debug).Infoln("Premature abort during block chain processing")
  884. break
  885. }
  886. bstart := time.Now()
  887. // Wait for block i's nonce to be verified before processing
  888. // its state transition.
  889. for !nonceChecked[i] {
  890. r := <-nonceResults
  891. nonceChecked[r.index] = true
  892. if !r.valid {
  893. block := chain[r.index]
  894. return r.index, &BlockNonceErr{Hash: block.Hash(), Number: block.Number(), Nonce: block.Nonce()}
  895. }
  896. }
  897. if BadHashes[block.Hash()] {
  898. err := BadHashError(block.Hash())
  899. blockErr(block, err)
  900. return i, err
  901. }
  902. // Call in to the block processor and check for errors. It's likely that if one block fails
  903. // all others will fail too (unless a known block is returned).
  904. logs, receipts, err := self.processor.Process(block)
  905. if err != nil {
  906. if IsKnownBlockErr(err) {
  907. stats.ignored++
  908. continue
  909. }
  910. if err == BlockFutureErr {
  911. // Allow up to MaxFuture second in the future blocks. If this limit
  912. // is exceeded the chain is discarded and processed at a later time
  913. // if given.
  914. max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
  915. if block.Time().Cmp(max) == 1 {
  916. return i, fmt.Errorf("%v: BlockFutureErr, %v > %v", BlockFutureErr, block.Time(), max)
  917. }
  918. self.futureBlocks.Add(block.Hash(), block)
  919. stats.queued++
  920. continue
  921. }
  922. if IsParentErr(err) && self.futureBlocks.Contains(block.ParentHash()) {
  923. self.futureBlocks.Add(block.Hash(), block)
  924. stats.queued++
  925. continue
  926. }
  927. blockErr(block, err)
  928. go ReportBlock(block, err)
  929. return i, err
  930. }
  931. if err := PutBlockReceipts(self.chainDb, block.Hash(), receipts); err != nil {
  932. glog.V(logger.Warn).Infoln("error writing block receipts:", err)
  933. }
  934. txcount += len(block.Transactions())
  935. // write the block to the chain and get the status
  936. status, err := self.WriteBlock(block)
  937. if err != nil {
  938. return i, err
  939. }
  940. switch status {
  941. case CanonStatTy:
  942. if glog.V(logger.Debug) {
  943. 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))
  944. }
  945. events = append(events, ChainEvent{block, block.Hash(), logs})
  946. // This puts transactions in a extra db for rpc
  947. if err := PutTransactions(self.chainDb, block, block.Transactions()); err != nil {
  948. return i, err
  949. }
  950. // store the receipts
  951. if err := PutReceipts(self.chainDb, receipts); err != nil {
  952. return i, err
  953. }
  954. // Write map map bloom filters
  955. if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil {
  956. return i, err
  957. }
  958. case SideStatTy:
  959. if glog.V(logger.Detail) {
  960. 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))
  961. }
  962. events = append(events, ChainSideEvent{block, logs})
  963. case SplitStatTy:
  964. events = append(events, ChainSplitEvent{block, logs})
  965. }
  966. stats.processed++
  967. }
  968. if (stats.queued > 0 || stats.processed > 0 || stats.ignored > 0) && bool(glog.V(logger.Info)) {
  969. tend := time.Since(tstart)
  970. start, end := chain[0], chain[len(chain)-1]
  971. 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])
  972. }
  973. go self.postChainEvents(events)
  974. return 0, nil
  975. }
  976. // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  977. // to be part of the new canonical chain and accumulates potential missing transactions and post an
  978. // event about them
  979. func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  980. var (
  981. newChain types.Blocks
  982. commonBlock *types.Block
  983. oldStart = oldBlock
  984. newStart = newBlock
  985. deletedTxs types.Transactions
  986. )
  987. // first reduce whoever is higher bound
  988. if oldBlock.NumberU64() > newBlock.NumberU64() {
  989. // reduce old chain
  990. for oldBlock = oldBlock; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = self.GetBlock(oldBlock.ParentHash()) {
  991. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  992. }
  993. } else {
  994. // reduce new chain and append new chain blocks for inserting later on
  995. for newBlock = newBlock; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = self.GetBlock(newBlock.ParentHash()) {
  996. newChain = append(newChain, newBlock)
  997. }
  998. }
  999. if oldBlock == nil {
  1000. return fmt.Errorf("Invalid old chain")
  1001. }
  1002. if newBlock == nil {
  1003. return fmt.Errorf("Invalid new chain")
  1004. }
  1005. numSplit := newBlock.Number()
  1006. for {
  1007. if oldBlock.Hash() == newBlock.Hash() {
  1008. commonBlock = oldBlock
  1009. break
  1010. }
  1011. newChain = append(newChain, newBlock)
  1012. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1013. oldBlock, newBlock = self.GetBlock(oldBlock.ParentHash()), self.GetBlock(newBlock.ParentHash())
  1014. if oldBlock == nil {
  1015. return fmt.Errorf("Invalid old chain")
  1016. }
  1017. if newBlock == nil {
  1018. return fmt.Errorf("Invalid new chain")
  1019. }
  1020. }
  1021. if glog.V(logger.Debug) {
  1022. commonHash := commonBlock.Hash()
  1023. glog.Infof("Chain split detected @ %x. Reorganising chain from #%v %x to %x", commonHash[:4], numSplit, oldStart.Hash().Bytes()[:4], newStart.Hash().Bytes()[:4])
  1024. }
  1025. var addedTxs types.Transactions
  1026. // insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
  1027. for _, block := range newChain {
  1028. // insert the block in the canonical way, re-writing history
  1029. self.insert(block)
  1030. // write canonical receipts and transactions
  1031. if err := PutTransactions(self.chainDb, block, block.Transactions()); err != nil {
  1032. return err
  1033. }
  1034. receipts := GetBlockReceipts(self.chainDb, block.Hash())
  1035. // write receipts
  1036. if err := PutReceipts(self.chainDb, receipts); err != nil {
  1037. return err
  1038. }
  1039. // Write map map bloom filters
  1040. if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil {
  1041. return err
  1042. }
  1043. addedTxs = append(addedTxs, block.Transactions()...)
  1044. }
  1045. // calculate the difference between deleted and added transactions
  1046. diff := types.TxDifference(deletedTxs, addedTxs)
  1047. // When transactions get deleted from the database that means the
  1048. // receipts that were created in the fork must also be deleted
  1049. for _, tx := range diff {
  1050. DeleteReceipt(self.chainDb, tx.Hash())
  1051. DeleteTransaction(self.chainDb, tx.Hash())
  1052. }
  1053. // Must be posted in a goroutine because of the transaction pool trying
  1054. // to acquire the chain manager lock
  1055. go self.eventMux.Post(RemovedTransactionEvent{diff})
  1056. return nil
  1057. }
  1058. // postChainEvents iterates over the events generated by a chain insertion and
  1059. // posts them into the event mux.
  1060. func (self *BlockChain) postChainEvents(events []interface{}) {
  1061. for _, event := range events {
  1062. if event, ok := event.(ChainEvent); ok {
  1063. // We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
  1064. // and in most cases isn't even necessary.
  1065. if self.LastBlockHash() == event.Hash {
  1066. self.eventMux.Post(ChainHeadEvent{event.Block})
  1067. }
  1068. }
  1069. // Fire the insertion events individually too
  1070. self.eventMux.Post(event)
  1071. }
  1072. }
  1073. func (self *BlockChain) update() {
  1074. futureTimer := time.Tick(5 * time.Second)
  1075. for {
  1076. select {
  1077. case <-futureTimer:
  1078. self.procFutureBlocks()
  1079. case <-self.quit:
  1080. return
  1081. }
  1082. }
  1083. }
  1084. func blockErr(block *types.Block, err error) {
  1085. if glog.V(logger.Error) {
  1086. glog.Errorf("Bad block #%v (%s)\n", block.Number(), block.Hash().Hex())
  1087. glog.Errorf(" %v", err)
  1088. }
  1089. }