blockchain.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  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. mrand "math/rand"
  24. "runtime"
  25. "sync"
  26. "sync/atomic"
  27. "time"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/mclock"
  30. "github.com/ethereum/go-ethereum/consensus"
  31. "github.com/ethereum/go-ethereum/core/state"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/core/vm"
  34. "github.com/ethereum/go-ethereum/crypto"
  35. "github.com/ethereum/go-ethereum/ethdb"
  36. "github.com/ethereum/go-ethereum/event"
  37. "github.com/ethereum/go-ethereum/log"
  38. "github.com/ethereum/go-ethereum/metrics"
  39. "github.com/ethereum/go-ethereum/params"
  40. "github.com/ethereum/go-ethereum/rlp"
  41. "github.com/ethereum/go-ethereum/trie"
  42. "github.com/hashicorp/golang-lru"
  43. )
  44. var (
  45. blockInsertTimer = metrics.NewTimer("chain/inserts")
  46. ErrNoGenesis = errors.New("Genesis not found in chain")
  47. )
  48. const (
  49. bodyCacheLimit = 256
  50. blockCacheLimit = 256
  51. maxFutureBlocks = 256
  52. maxTimeFutureBlocks = 30
  53. // must be bumped when consensus algorithm is changed, this forces the upgradedb
  54. // command to be run (forces the blocks to be imported again using the new algorithm)
  55. BlockChainVersion = 3
  56. badBlockLimit = 10
  57. )
  58. // BlockChain represents the canonical chain given a database with a genesis
  59. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  60. //
  61. // Importing blocks in to the block chain happens according to the set of rules
  62. // defined by the two stage Validator. Processing of blocks is done using the
  63. // Processor which processes the included transaction. The validation of the state
  64. // is done in the second part of the Validator. Failing results in aborting of
  65. // the import.
  66. //
  67. // The BlockChain also helps in returning blocks from **any** chain included
  68. // in the database as well as blocks that represents the canonical chain. It's
  69. // important to note that GetBlock can return any block and does not need to be
  70. // included in the canonical one where as GetBlockByNumber always represents the
  71. // canonical chain.
  72. type BlockChain struct {
  73. config *params.ChainConfig // chain & network configuration
  74. hc *HeaderChain
  75. chainDb ethdb.Database
  76. eventMux *event.TypeMux
  77. genesisBlock *types.Block
  78. mu sync.RWMutex // global mutex for locking chain operations
  79. chainmu sync.RWMutex // blockchain insertion lock
  80. procmu sync.RWMutex // block processor lock
  81. checkpoint int // checkpoint counts towards the new checkpoint
  82. currentBlock *types.Block // Current head of the block chain
  83. currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!)
  84. stateCache *state.StateDB // State database to reuse between imports (contains state cache)
  85. bodyCache *lru.Cache // Cache for the most recent block bodies
  86. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  87. blockCache *lru.Cache // Cache for the most recent entire blocks
  88. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  89. quit chan struct{} // blockchain quit channel
  90. running int32 // running must be called atomically
  91. // procInterrupt must be atomically called
  92. procInterrupt int32 // interrupt signaler for block processing
  93. wg sync.WaitGroup // chain processing wait group for shutting down
  94. engine consensus.Engine
  95. processor Processor // block processor interface
  96. validator Validator // block and state validator interface
  97. vmConfig vm.Config
  98. badBlocks *lru.Cache // Bad block cache
  99. }
  100. // NewBlockChain returns a fully initialised block chain using information
  101. // available in the database. It initialiser the default Ethereum Validator and
  102. // Processor.
  103. func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, mux *event.TypeMux, vmConfig vm.Config) (*BlockChain, error) {
  104. bodyCache, _ := lru.New(bodyCacheLimit)
  105. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  106. blockCache, _ := lru.New(blockCacheLimit)
  107. futureBlocks, _ := lru.New(maxFutureBlocks)
  108. badBlocks, _ := lru.New(badBlockLimit)
  109. bc := &BlockChain{
  110. config: config,
  111. chainDb: chainDb,
  112. eventMux: mux,
  113. quit: make(chan struct{}),
  114. bodyCache: bodyCache,
  115. bodyRLPCache: bodyRLPCache,
  116. blockCache: blockCache,
  117. futureBlocks: futureBlocks,
  118. engine: engine,
  119. vmConfig: vmConfig,
  120. badBlocks: badBlocks,
  121. }
  122. bc.SetValidator(NewBlockValidator(config, bc, engine))
  123. bc.SetProcessor(NewStateProcessor(config, bc, engine))
  124. var err error
  125. bc.hc, err = NewHeaderChain(chainDb, config, engine, bc.getProcInterrupt)
  126. if err != nil {
  127. return nil, err
  128. }
  129. bc.genesisBlock = bc.GetBlockByNumber(0)
  130. if bc.genesisBlock == nil {
  131. return nil, ErrNoGenesis
  132. }
  133. if err := bc.loadLastState(); err != nil {
  134. return nil, err
  135. }
  136. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  137. for hash := range BadHashes {
  138. if header := bc.GetHeaderByHash(hash); header != nil {
  139. // get the canonical block corresponding to the offending header's number
  140. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  141. // make sure the headerByNumber (if present) is in our current canonical chain
  142. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  143. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  144. bc.SetHead(header.Number.Uint64() - 1)
  145. log.Error("Chain rewind was successful, resuming normal operation")
  146. }
  147. }
  148. }
  149. // Take ownership of this particular state
  150. go bc.update()
  151. return bc, nil
  152. }
  153. func (self *BlockChain) getProcInterrupt() bool {
  154. return atomic.LoadInt32(&self.procInterrupt) == 1
  155. }
  156. // loadLastState loads the last known chain state from the database. This method
  157. // assumes that the chain manager mutex is held.
  158. func (self *BlockChain) loadLastState() error {
  159. // Restore the last known head block
  160. head := GetHeadBlockHash(self.chainDb)
  161. if head == (common.Hash{}) {
  162. // Corrupt or empty database, init from scratch
  163. log.Warn("Empty database, resetting chain")
  164. return self.Reset()
  165. }
  166. // Make sure the entire head block is available
  167. currentBlock := self.GetBlockByHash(head)
  168. if currentBlock == nil {
  169. // Corrupt or empty database, init from scratch
  170. log.Warn("Head block missing, resetting chain", "hash", head)
  171. return self.Reset()
  172. }
  173. // Make sure the state associated with the block is available
  174. if _, err := state.New(currentBlock.Root(), self.chainDb); err != nil {
  175. // Dangling block without a state associated, init from scratch
  176. log.Warn("Head state missing, resetting chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
  177. return self.Reset()
  178. }
  179. // Everything seems to be fine, set as the head block
  180. self.currentBlock = currentBlock
  181. // Restore the last known head header
  182. currentHeader := self.currentBlock.Header()
  183. if head := GetHeadHeaderHash(self.chainDb); head != (common.Hash{}) {
  184. if header := self.GetHeaderByHash(head); header != nil {
  185. currentHeader = header
  186. }
  187. }
  188. self.hc.SetCurrentHeader(currentHeader)
  189. // Restore the last known head fast block
  190. self.currentFastBlock = self.currentBlock
  191. if head := GetHeadFastBlockHash(self.chainDb); head != (common.Hash{}) {
  192. if block := self.GetBlockByHash(head); block != nil {
  193. self.currentFastBlock = block
  194. }
  195. }
  196. // Initialize a statedb cache to ensure singleton account bloom filter generation
  197. statedb, err := state.New(self.currentBlock.Root(), self.chainDb)
  198. if err != nil {
  199. return err
  200. }
  201. self.stateCache = statedb
  202. // Issue a status log for the user
  203. headerTd := self.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  204. blockTd := self.GetTd(self.currentBlock.Hash(), self.currentBlock.NumberU64())
  205. fastTd := self.GetTd(self.currentFastBlock.Hash(), self.currentFastBlock.NumberU64())
  206. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd)
  207. log.Info("Loaded most recent local full block", "number", self.currentBlock.Number(), "hash", self.currentBlock.Hash(), "td", blockTd)
  208. log.Info("Loaded most recent local fast block", "number", self.currentFastBlock.Number(), "hash", self.currentFastBlock.Hash(), "td", fastTd)
  209. return nil
  210. }
  211. // SetHead rewinds the local chain to a new head. In the case of headers, everything
  212. // above the new head will be deleted and the new one set. In the case of blocks
  213. // though, the head may be further rewound if block bodies are missing (non-archive
  214. // nodes after a fast sync).
  215. func (bc *BlockChain) SetHead(head uint64) error {
  216. log.Warn("Rewinding blockchain", "target", head)
  217. bc.mu.Lock()
  218. defer bc.mu.Unlock()
  219. // Rewind the header chain, deleting all block bodies until then
  220. delFn := func(hash common.Hash, num uint64) {
  221. DeleteBody(bc.chainDb, hash, num)
  222. }
  223. bc.hc.SetHead(head, delFn)
  224. currentHeader := bc.hc.CurrentHeader()
  225. // Clear out any stale content from the caches
  226. bc.bodyCache.Purge()
  227. bc.bodyRLPCache.Purge()
  228. bc.blockCache.Purge()
  229. bc.futureBlocks.Purge()
  230. // Rewind the block chain, ensuring we don't end up with a stateless head block
  231. if bc.currentBlock != nil && currentHeader.Number.Uint64() < bc.currentBlock.NumberU64() {
  232. bc.currentBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64())
  233. }
  234. if bc.currentBlock != nil {
  235. if _, err := state.New(bc.currentBlock.Root(), bc.chainDb); err != nil {
  236. // Rewound state missing, rolled back to before pivot, reset to genesis
  237. bc.currentBlock = nil
  238. }
  239. }
  240. // Rewind the fast block in a simpleton way to the target head
  241. if bc.currentFastBlock != nil && currentHeader.Number.Uint64() < bc.currentFastBlock.NumberU64() {
  242. bc.currentFastBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64())
  243. }
  244. // If either blocks reached nil, reset to the genesis state
  245. if bc.currentBlock == nil {
  246. bc.currentBlock = bc.genesisBlock
  247. }
  248. if bc.currentFastBlock == nil {
  249. bc.currentFastBlock = bc.genesisBlock
  250. }
  251. if err := WriteHeadBlockHash(bc.chainDb, bc.currentBlock.Hash()); err != nil {
  252. log.Crit("Failed to reset head full block", "err", err)
  253. }
  254. if err := WriteHeadFastBlockHash(bc.chainDb, bc.currentFastBlock.Hash()); err != nil {
  255. log.Crit("Failed to reset head fast block", "err", err)
  256. }
  257. return bc.loadLastState()
  258. }
  259. // FastSyncCommitHead sets the current head block to the one defined by the hash
  260. // irrelevant what the chain contents were prior.
  261. func (self *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  262. // Make sure that both the block as well at its state trie exists
  263. block := self.GetBlockByHash(hash)
  264. if block == nil {
  265. return fmt.Errorf("non existent block [%x…]", hash[:4])
  266. }
  267. if _, err := trie.NewSecure(block.Root(), self.chainDb, 0); err != nil {
  268. return err
  269. }
  270. // If all checks out, manually set the head block
  271. self.mu.Lock()
  272. self.currentBlock = block
  273. self.mu.Unlock()
  274. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  275. return nil
  276. }
  277. // GasLimit returns the gas limit of the current HEAD block.
  278. func (self *BlockChain) GasLimit() *big.Int {
  279. self.mu.RLock()
  280. defer self.mu.RUnlock()
  281. return self.currentBlock.GasLimit()
  282. }
  283. // LastBlockHash return the hash of the HEAD block.
  284. func (self *BlockChain) LastBlockHash() common.Hash {
  285. self.mu.RLock()
  286. defer self.mu.RUnlock()
  287. return self.currentBlock.Hash()
  288. }
  289. // CurrentBlock retrieves the current head block of the canonical chain. The
  290. // block is retrieved from the blockchain's internal cache.
  291. func (self *BlockChain) CurrentBlock() *types.Block {
  292. self.mu.RLock()
  293. defer self.mu.RUnlock()
  294. return self.currentBlock
  295. }
  296. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  297. // chain. The block is retrieved from the blockchain's internal cache.
  298. func (self *BlockChain) CurrentFastBlock() *types.Block {
  299. self.mu.RLock()
  300. defer self.mu.RUnlock()
  301. return self.currentFastBlock
  302. }
  303. // Status returns status information about the current chain such as the HEAD Td,
  304. // the HEAD hash and the hash of the genesis block.
  305. func (self *BlockChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  306. self.mu.RLock()
  307. defer self.mu.RUnlock()
  308. return self.GetTd(self.currentBlock.Hash(), self.currentBlock.NumberU64()), self.currentBlock.Hash(), self.genesisBlock.Hash()
  309. }
  310. // SetProcessor sets the processor required for making state modifications.
  311. func (self *BlockChain) SetProcessor(processor Processor) {
  312. self.procmu.Lock()
  313. defer self.procmu.Unlock()
  314. self.processor = processor
  315. }
  316. // SetValidator sets the validator which is used to validate incoming blocks.
  317. func (self *BlockChain) SetValidator(validator Validator) {
  318. self.procmu.Lock()
  319. defer self.procmu.Unlock()
  320. self.validator = validator
  321. }
  322. // Validator returns the current validator.
  323. func (self *BlockChain) Validator() Validator {
  324. self.procmu.RLock()
  325. defer self.procmu.RUnlock()
  326. return self.validator
  327. }
  328. // Processor returns the current processor.
  329. func (self *BlockChain) Processor() Processor {
  330. self.procmu.RLock()
  331. defer self.procmu.RUnlock()
  332. return self.processor
  333. }
  334. // State returns a new mutable state based on the current HEAD block.
  335. func (self *BlockChain) State() (*state.StateDB, error) {
  336. return self.StateAt(self.CurrentBlock().Root())
  337. }
  338. // StateAt returns a new mutable state based on a particular point in time.
  339. func (self *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  340. return self.stateCache.New(root)
  341. }
  342. // Reset purges the entire blockchain, restoring it to its genesis state.
  343. func (bc *BlockChain) Reset() error {
  344. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  345. }
  346. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  347. // specified genesis state.
  348. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  349. // Dump the entire block chain and purge the caches
  350. if err := bc.SetHead(0); err != nil {
  351. return err
  352. }
  353. bc.mu.Lock()
  354. defer bc.mu.Unlock()
  355. // Prepare the genesis block and reinitialise the chain
  356. if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  357. log.Crit("Failed to write genesis block TD", "err", err)
  358. }
  359. if err := WriteBlock(bc.chainDb, genesis); err != nil {
  360. log.Crit("Failed to write genesis block", "err", err)
  361. }
  362. bc.genesisBlock = genesis
  363. bc.insert(bc.genesisBlock)
  364. bc.currentBlock = bc.genesisBlock
  365. bc.hc.SetGenesis(bc.genesisBlock.Header())
  366. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  367. bc.currentFastBlock = bc.genesisBlock
  368. return nil
  369. }
  370. // Export writes the active chain to the given writer.
  371. func (self *BlockChain) Export(w io.Writer) error {
  372. return self.ExportN(w, uint64(0), self.currentBlock.NumberU64())
  373. }
  374. // ExportN writes a subset of the active chain to the given writer.
  375. func (self *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  376. self.mu.RLock()
  377. defer self.mu.RUnlock()
  378. if first > last {
  379. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  380. }
  381. log.Info("Exporting batch of blocks", "count", last-first+1)
  382. for nr := first; nr <= last; nr++ {
  383. block := self.GetBlockByNumber(nr)
  384. if block == nil {
  385. return fmt.Errorf("export failed on #%d: not found", nr)
  386. }
  387. if err := block.EncodeRLP(w); err != nil {
  388. return err
  389. }
  390. }
  391. return nil
  392. }
  393. // insert injects a new head block into the current block chain. This method
  394. // assumes that the block is indeed a true head. It will also reset the head
  395. // header and the head fast sync block to this very same block if they are older
  396. // or if they are on a different side chain.
  397. //
  398. // Note, this function assumes that the `mu` mutex is held!
  399. func (bc *BlockChain) insert(block *types.Block) {
  400. // If the block is on a side chain or an unknown one, force other heads onto it too
  401. updateHeads := GetCanonicalHash(bc.chainDb, block.NumberU64()) != block.Hash()
  402. // Add the block to the canonical chain number scheme and mark as the head
  403. if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
  404. log.Crit("Failed to insert block number", "err", err)
  405. }
  406. if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
  407. log.Crit("Failed to insert head block hash", "err", err)
  408. }
  409. bc.currentBlock = block
  410. // If the block is better than out head or is on a different chain, force update heads
  411. if updateHeads {
  412. bc.hc.SetCurrentHeader(block.Header())
  413. if err := WriteHeadFastBlockHash(bc.chainDb, block.Hash()); err != nil {
  414. log.Crit("Failed to insert head fast block hash", "err", err)
  415. }
  416. bc.currentFastBlock = block
  417. }
  418. }
  419. // Accessors
  420. func (bc *BlockChain) Genesis() *types.Block {
  421. return bc.genesisBlock
  422. }
  423. // GetBody retrieves a block body (transactions and uncles) from the database by
  424. // hash, caching it if found.
  425. func (self *BlockChain) GetBody(hash common.Hash) *types.Body {
  426. // Short circuit if the body's already in the cache, retrieve otherwise
  427. if cached, ok := self.bodyCache.Get(hash); ok {
  428. body := cached.(*types.Body)
  429. return body
  430. }
  431. body := GetBody(self.chainDb, hash, self.hc.GetBlockNumber(hash))
  432. if body == nil {
  433. return nil
  434. }
  435. // Cache the found body for next time and return
  436. self.bodyCache.Add(hash, body)
  437. return body
  438. }
  439. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  440. // caching it if found.
  441. func (self *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  442. // Short circuit if the body's already in the cache, retrieve otherwise
  443. if cached, ok := self.bodyRLPCache.Get(hash); ok {
  444. return cached.(rlp.RawValue)
  445. }
  446. body := GetBodyRLP(self.chainDb, hash, self.hc.GetBlockNumber(hash))
  447. if len(body) == 0 {
  448. return nil
  449. }
  450. // Cache the found body for next time and return
  451. self.bodyRLPCache.Add(hash, body)
  452. return body
  453. }
  454. // HasBlock checks if a block is fully present in the database or not, caching
  455. // it if present.
  456. func (bc *BlockChain) HasBlock(hash common.Hash) bool {
  457. return bc.GetBlockByHash(hash) != nil
  458. }
  459. // HasBlockAndState checks if a block and associated state trie is fully present
  460. // in the database or not, caching it if present.
  461. func (bc *BlockChain) HasBlockAndState(hash common.Hash) bool {
  462. // Check first that the block itself is known
  463. block := bc.GetBlockByHash(hash)
  464. if block == nil {
  465. return false
  466. }
  467. // Ensure the associated state is also present
  468. _, err := state.New(block.Root(), bc.chainDb)
  469. return err == nil
  470. }
  471. // GetBlock retrieves a block from the database by hash and number,
  472. // caching it if found.
  473. func (self *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  474. // Short circuit if the block's already in the cache, retrieve otherwise
  475. if block, ok := self.blockCache.Get(hash); ok {
  476. return block.(*types.Block)
  477. }
  478. block := GetBlock(self.chainDb, hash, number)
  479. if block == nil {
  480. return nil
  481. }
  482. // Cache the found block for next time and return
  483. self.blockCache.Add(block.Hash(), block)
  484. return block
  485. }
  486. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  487. func (self *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  488. return self.GetBlock(hash, self.hc.GetBlockNumber(hash))
  489. }
  490. // GetBlockByNumber retrieves a block from the database by number, caching it
  491. // (associated with its hash) if found.
  492. func (self *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  493. hash := GetCanonicalHash(self.chainDb, number)
  494. if hash == (common.Hash{}) {
  495. return nil
  496. }
  497. return self.GetBlock(hash, number)
  498. }
  499. // [deprecated by eth/62]
  500. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  501. func (self *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  502. number := self.hc.GetBlockNumber(hash)
  503. for i := 0; i < n; i++ {
  504. block := self.GetBlock(hash, number)
  505. if block == nil {
  506. break
  507. }
  508. blocks = append(blocks, block)
  509. hash = block.ParentHash()
  510. number--
  511. }
  512. return
  513. }
  514. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  515. // a specific distance is reached.
  516. func (self *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  517. uncles := []*types.Header{}
  518. for i := 0; block != nil && i < length; i++ {
  519. uncles = append(uncles, block.Uncles()...)
  520. block = self.GetBlock(block.ParentHash(), block.NumberU64()-1)
  521. }
  522. return uncles
  523. }
  524. // Stop stops the blockchain service. If any imports are currently in progress
  525. // it will abort them using the procInterrupt.
  526. func (bc *BlockChain) Stop() {
  527. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  528. return
  529. }
  530. close(bc.quit)
  531. atomic.StoreInt32(&bc.procInterrupt, 1)
  532. bc.wg.Wait()
  533. log.Info("Blockchain manager stopped")
  534. }
  535. func (self *BlockChain) procFutureBlocks() {
  536. blocks := make([]*types.Block, 0, self.futureBlocks.Len())
  537. for _, hash := range self.futureBlocks.Keys() {
  538. if block, exist := self.futureBlocks.Peek(hash); exist {
  539. blocks = append(blocks, block.(*types.Block))
  540. }
  541. }
  542. if len(blocks) > 0 {
  543. types.BlockBy(types.Number).Sort(blocks)
  544. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  545. for i := range blocks {
  546. self.InsertChain(blocks[i : i+1])
  547. }
  548. }
  549. }
  550. type WriteStatus byte
  551. const (
  552. NonStatTy WriteStatus = iota
  553. CanonStatTy
  554. SplitStatTy
  555. SideStatTy
  556. )
  557. // Rollback is designed to remove a chain of links from the database that aren't
  558. // certain enough to be valid.
  559. func (self *BlockChain) Rollback(chain []common.Hash) {
  560. self.mu.Lock()
  561. defer self.mu.Unlock()
  562. for i := len(chain) - 1; i >= 0; i-- {
  563. hash := chain[i]
  564. currentHeader := self.hc.CurrentHeader()
  565. if currentHeader.Hash() == hash {
  566. self.hc.SetCurrentHeader(self.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
  567. }
  568. if self.currentFastBlock.Hash() == hash {
  569. self.currentFastBlock = self.GetBlock(self.currentFastBlock.ParentHash(), self.currentFastBlock.NumberU64()-1)
  570. WriteHeadFastBlockHash(self.chainDb, self.currentFastBlock.Hash())
  571. }
  572. if self.currentBlock.Hash() == hash {
  573. self.currentBlock = self.GetBlock(self.currentBlock.ParentHash(), self.currentBlock.NumberU64()-1)
  574. WriteHeadBlockHash(self.chainDb, self.currentBlock.Hash())
  575. }
  576. }
  577. }
  578. // SetReceiptsData computes all the non-consensus fields of the receipts
  579. func SetReceiptsData(config *params.ChainConfig, block *types.Block, receipts types.Receipts) {
  580. signer := types.MakeSigner(config, block.Number())
  581. transactions, logIndex := block.Transactions(), uint(0)
  582. for j := 0; j < len(receipts); j++ {
  583. // The transaction hash can be retrieved from the transaction itself
  584. receipts[j].TxHash = transactions[j].Hash()
  585. tx, _ := transactions[j].AsMessage(signer)
  586. // The contract address can be derived from the transaction itself
  587. if MessageCreatesContract(tx) {
  588. receipts[j].ContractAddress = crypto.CreateAddress(tx.From(), tx.Nonce())
  589. }
  590. // The used gas can be calculated based on previous receipts
  591. if j == 0 {
  592. receipts[j].GasUsed = new(big.Int).Set(receipts[j].CumulativeGasUsed)
  593. } else {
  594. receipts[j].GasUsed = new(big.Int).Sub(receipts[j].CumulativeGasUsed, receipts[j-1].CumulativeGasUsed)
  595. }
  596. // The derived log fields can simply be set from the block and transaction
  597. for k := 0; k < len(receipts[j].Logs); k++ {
  598. receipts[j].Logs[k].BlockNumber = block.NumberU64()
  599. receipts[j].Logs[k].BlockHash = block.Hash()
  600. receipts[j].Logs[k].TxHash = receipts[j].TxHash
  601. receipts[j].Logs[k].TxIndex = uint(j)
  602. receipts[j].Logs[k].Index = logIndex
  603. logIndex++
  604. }
  605. }
  606. }
  607. // InsertReceiptChain attempts to complete an already existing header chain with
  608. // transaction and receipt data.
  609. // XXX should this be moved to the test?
  610. func (self *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  611. // Do a sanity check that the provided chain is actually ordered and linked
  612. for i := 1; i < len(blockChain); i++ {
  613. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  614. // Chain broke ancestry, log a messge (programming error) and skip insertion
  615. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  616. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  617. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, blockChain[i-1].NumberU64(),
  618. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  619. }
  620. }
  621. // Pre-checks passed, start the block body and receipt imports
  622. self.wg.Add(1)
  623. defer self.wg.Done()
  624. // Collect some import statistics to report on
  625. stats := struct{ processed, ignored int32 }{}
  626. start := time.Now()
  627. // Create the block importing task queue and worker functions
  628. tasks := make(chan int, len(blockChain))
  629. for i := 0; i < len(blockChain) && i < len(receiptChain); i++ {
  630. tasks <- i
  631. }
  632. close(tasks)
  633. errs, failed := make([]error, len(tasks)), int32(0)
  634. process := func(worker int) {
  635. for index := range tasks {
  636. block, receipts := blockChain[index], receiptChain[index]
  637. // Short circuit insertion if shutting down or processing failed
  638. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  639. return
  640. }
  641. if atomic.LoadInt32(&failed) > 0 {
  642. return
  643. }
  644. // Short circuit if the owner header is unknown
  645. if !self.HasHeader(block.Hash()) {
  646. errs[index] = fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  647. atomic.AddInt32(&failed, 1)
  648. return
  649. }
  650. // Skip if the entire data is already known
  651. if self.HasBlock(block.Hash()) {
  652. atomic.AddInt32(&stats.ignored, 1)
  653. continue
  654. }
  655. // Compute all the non-consensus fields of the receipts
  656. SetReceiptsData(self.config, block, receipts)
  657. // Write all the data out into the database
  658. if err := WriteBody(self.chainDb, block.Hash(), block.NumberU64(), block.Body()); err != nil {
  659. errs[index] = fmt.Errorf("failed to write block body: %v", err)
  660. atomic.AddInt32(&failed, 1)
  661. log.Crit("Failed to write block body", "err", err)
  662. return
  663. }
  664. if err := WriteBlockReceipts(self.chainDb, block.Hash(), block.NumberU64(), receipts); err != nil {
  665. errs[index] = fmt.Errorf("failed to write block receipts: %v", err)
  666. atomic.AddInt32(&failed, 1)
  667. log.Crit("Failed to write block receipts", "err", err)
  668. return
  669. }
  670. if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil {
  671. errs[index] = fmt.Errorf("failed to write log blooms: %v", err)
  672. atomic.AddInt32(&failed, 1)
  673. log.Crit("Failed to write log blooms", "err", err)
  674. return
  675. }
  676. if err := WriteTransactions(self.chainDb, block); err != nil {
  677. errs[index] = fmt.Errorf("failed to write individual transactions: %v", err)
  678. atomic.AddInt32(&failed, 1)
  679. log.Crit("Failed to write individual transactions", "err", err)
  680. return
  681. }
  682. if err := WriteReceipts(self.chainDb, receipts); err != nil {
  683. errs[index] = fmt.Errorf("failed to write individual receipts: %v", err)
  684. atomic.AddInt32(&failed, 1)
  685. log.Crit("Failed to write individual receipts", "err", err)
  686. return
  687. }
  688. atomic.AddInt32(&stats.processed, 1)
  689. }
  690. }
  691. // Start as many worker threads as goroutines allowed
  692. pending := new(sync.WaitGroup)
  693. for i := 0; i < runtime.GOMAXPROCS(0); i++ {
  694. pending.Add(1)
  695. go func(id int) {
  696. defer pending.Done()
  697. process(id)
  698. }(i)
  699. }
  700. pending.Wait()
  701. // If anything failed, report
  702. if failed > 0 {
  703. for i, err := range errs {
  704. if err != nil {
  705. return i, err
  706. }
  707. }
  708. }
  709. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  710. log.Debug("Premature abort during receipts processing")
  711. return 0, nil
  712. }
  713. // Update the head fast sync block if better
  714. self.mu.Lock()
  715. head := blockChain[len(errs)-1]
  716. if td := self.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case
  717. if self.GetTd(self.currentFastBlock.Hash(), self.currentFastBlock.NumberU64()).Cmp(td) < 0 {
  718. if err := WriteHeadFastBlockHash(self.chainDb, head.Hash()); err != nil {
  719. log.Crit("Failed to update head fast block hash", "err", err)
  720. }
  721. self.currentFastBlock = head
  722. }
  723. }
  724. self.mu.Unlock()
  725. // Report some public statistics so the user has a clue what's going on
  726. last := blockChain[len(blockChain)-1]
  727. log.Info("Imported new block receipts", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  728. "number", last.Number(), "hash", last.Hash(), "ignored", stats.ignored)
  729. return 0, nil
  730. }
  731. // WriteBlock writes the block to the chain.
  732. func (self *BlockChain) WriteBlock(block *types.Block) (status WriteStatus, err error) {
  733. self.wg.Add(1)
  734. defer self.wg.Done()
  735. // Calculate the total difficulty of the block
  736. ptd := self.GetTd(block.ParentHash(), block.NumberU64()-1)
  737. if ptd == nil {
  738. return NonStatTy, consensus.ErrUnknownAncestor
  739. }
  740. // Make sure no inconsistent state is leaked during insertion
  741. self.mu.Lock()
  742. defer self.mu.Unlock()
  743. localTd := self.GetTd(self.currentBlock.Hash(), self.currentBlock.NumberU64())
  744. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  745. // Irrelevant of the canonical status, write the block itself to the database
  746. if err := self.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
  747. log.Crit("Failed to write block total difficulty", "err", err)
  748. }
  749. if err := WriteBlock(self.chainDb, block); err != nil {
  750. log.Crit("Failed to write block contents", "err", err)
  751. }
  752. // If the total difficulty is higher than our known, add it to the canonical chain
  753. // Second clause in the if statement reduces the vulnerability to selfish mining.
  754. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  755. if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
  756. // Reorganise the chain if the parent is not the head block
  757. if block.ParentHash() != self.currentBlock.Hash() {
  758. if err := self.reorg(self.currentBlock, block); err != nil {
  759. return NonStatTy, err
  760. }
  761. }
  762. self.insert(block) // Insert the block as the new head of the chain
  763. status = CanonStatTy
  764. } else {
  765. status = SideStatTy
  766. }
  767. self.futureBlocks.Remove(block.Hash())
  768. return
  769. }
  770. // InsertChain will attempt to insert the given chain in to the canonical chain or, otherwise, create a fork. If an error is returned
  771. // 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).
  772. func (self *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  773. // Do a sanity check that the provided chain is actually ordered and linked
  774. for i := 1; i < len(chain); i++ {
  775. if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
  776. // Chain broke ancestry, log a messge (programming error) and skip insertion
  777. log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(),
  778. "parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash())
  779. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(),
  780. chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
  781. }
  782. }
  783. // Pre-checks passed, start the full block imports
  784. self.wg.Add(1)
  785. defer self.wg.Done()
  786. self.chainmu.Lock()
  787. defer self.chainmu.Unlock()
  788. // A queued approach to delivering events. This is generally
  789. // faster than direct delivery and requires much less mutex
  790. // acquiring.
  791. var (
  792. stats = insertStats{startTime: mclock.Now()}
  793. events = make([]interface{}, 0, len(chain))
  794. coalescedLogs []*types.Log
  795. )
  796. // Start the parallel header verifier
  797. headers := make([]*types.Header, len(chain))
  798. seals := make([]bool, len(chain))
  799. for i, block := range chain {
  800. headers[i] = block.Header()
  801. seals[i] = true
  802. }
  803. abort, results := self.engine.VerifyHeaders(self, headers, seals)
  804. defer close(abort)
  805. // Iterate over the blocks and insert when the verifier permits
  806. for i, block := range chain {
  807. // If the chain is terminating, stop processing blocks
  808. if atomic.LoadInt32(&self.procInterrupt) == 1 {
  809. log.Debug("Premature abort during blocks processing")
  810. break
  811. }
  812. // If the header is a banned one, straight out abort
  813. if BadHashes[block.Hash()] {
  814. self.reportBlock(block, nil, ErrBlacklistedHash)
  815. return i, ErrBlacklistedHash
  816. }
  817. // Wait for the block's verification to complete
  818. bstart := time.Now()
  819. err := <-results
  820. if err == nil {
  821. err = self.Validator().ValidateBody(block)
  822. }
  823. if err != nil {
  824. if err == ErrKnownBlock {
  825. stats.ignored++
  826. continue
  827. }
  828. if err == consensus.ErrFutureBlock {
  829. // Allow up to MaxFuture second in the future blocks. If this limit
  830. // is exceeded the chain is discarded and processed at a later time
  831. // if given.
  832. max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
  833. if block.Time().Cmp(max) > 0 {
  834. return i, fmt.Errorf("future block: %v > %v", block.Time(), max)
  835. }
  836. self.futureBlocks.Add(block.Hash(), block)
  837. stats.queued++
  838. continue
  839. }
  840. if err == consensus.ErrUnknownAncestor && self.futureBlocks.Contains(block.ParentHash()) {
  841. self.futureBlocks.Add(block.Hash(), block)
  842. stats.queued++
  843. continue
  844. }
  845. self.reportBlock(block, nil, err)
  846. return i, err
  847. }
  848. // Create a new statedb using the parent block and report an
  849. // error if it fails.
  850. switch {
  851. case i == 0:
  852. err = self.stateCache.Reset(self.GetBlock(block.ParentHash(), block.NumberU64()-1).Root())
  853. default:
  854. err = self.stateCache.Reset(chain[i-1].Root())
  855. }
  856. if err != nil {
  857. self.reportBlock(block, nil, err)
  858. return i, err
  859. }
  860. // Process block using the parent state as reference point.
  861. receipts, logs, usedGas, err := self.processor.Process(block, self.stateCache, self.vmConfig)
  862. if err != nil {
  863. self.reportBlock(block, receipts, err)
  864. return i, err
  865. }
  866. // Validate the state using the default validator
  867. err = self.Validator().ValidateState(block, self.GetBlock(block.ParentHash(), block.NumberU64()-1), self.stateCache, receipts, usedGas)
  868. if err != nil {
  869. self.reportBlock(block, receipts, err)
  870. return i, err
  871. }
  872. // Write state changes to database
  873. _, err = self.stateCache.Commit(self.config.IsEIP158(block.Number()))
  874. if err != nil {
  875. return i, err
  876. }
  877. // coalesce logs for later processing
  878. coalescedLogs = append(coalescedLogs, logs...)
  879. if err = WriteBlockReceipts(self.chainDb, block.Hash(), block.NumberU64(), receipts); err != nil {
  880. return i, err
  881. }
  882. // write the block to the chain and get the status
  883. status, err := self.WriteBlock(block)
  884. if err != nil {
  885. return i, err
  886. }
  887. switch status {
  888. case CanonStatTy:
  889. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(), "uncles", len(block.Uncles()),
  890. "txs", len(block.Transactions()), "gas", block.GasUsed(), "elapsed", common.PrettyDuration(time.Since(bstart)))
  891. blockInsertTimer.UpdateSince(bstart)
  892. events = append(events, ChainEvent{block, block.Hash(), logs})
  893. // This puts transactions in a extra db for rpc
  894. if err := WriteTransactions(self.chainDb, block); err != nil {
  895. return i, err
  896. }
  897. // store the receipts
  898. if err := WriteReceipts(self.chainDb, receipts); err != nil {
  899. return i, err
  900. }
  901. // Write map map bloom filters
  902. if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil {
  903. return i, err
  904. }
  905. // Write hash preimages
  906. if err := WritePreimages(self.chainDb, block.NumberU64(), self.stateCache.Preimages()); err != nil {
  907. return i, err
  908. }
  909. case SideStatTy:
  910. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(), "diff", block.Difficulty(), "elapsed",
  911. common.PrettyDuration(time.Since(bstart)), "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()))
  912. blockInsertTimer.UpdateSince(bstart)
  913. events = append(events, ChainSideEvent{block})
  914. case SplitStatTy:
  915. events = append(events, ChainSplitEvent{block, logs})
  916. }
  917. stats.processed++
  918. stats.usedGas += usedGas.Uint64()
  919. stats.report(chain, i)
  920. }
  921. go self.postChainEvents(events, coalescedLogs)
  922. return 0, nil
  923. }
  924. // insertStats tracks and reports on block insertion.
  925. type insertStats struct {
  926. queued, processed, ignored int
  927. usedGas uint64
  928. lastIndex int
  929. startTime mclock.AbsTime
  930. }
  931. // statsReportLimit is the time limit during import after which we always print
  932. // out progress. This avoids the user wondering what's going on.
  933. const statsReportLimit = 8 * time.Second
  934. // report prints statistics if some number of blocks have been processed
  935. // or more than a few seconds have passed since the last message.
  936. func (st *insertStats) report(chain []*types.Block, index int) {
  937. // Fetch the timings for the batch
  938. var (
  939. now = mclock.Now()
  940. elapsed = time.Duration(now) - time.Duration(st.startTime)
  941. )
  942. // If we're at the last block of the batch or report period reached, log
  943. if index == len(chain)-1 || elapsed >= statsReportLimit {
  944. var (
  945. end = chain[index]
  946. txs = countTransactions(chain[st.lastIndex : index+1])
  947. )
  948. context := []interface{}{
  949. "blocks", st.processed, "txs", txs, "mgas", float64(st.usedGas) / 1000000,
  950. "elapsed", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed),
  951. "number", end.Number(), "hash", end.Hash(),
  952. }
  953. if st.queued > 0 {
  954. context = append(context, []interface{}{"queued", st.queued}...)
  955. }
  956. if st.ignored > 0 {
  957. context = append(context, []interface{}{"ignored", st.ignored}...)
  958. }
  959. log.Info("Imported new chain segment", context...)
  960. *st = insertStats{startTime: now, lastIndex: index}
  961. }
  962. }
  963. func countTransactions(chain []*types.Block) (c int) {
  964. for _, b := range chain {
  965. c += len(b.Transactions())
  966. }
  967. return c
  968. }
  969. // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  970. // to be part of the new canonical chain and accumulates potential missing transactions and post an
  971. // event about them
  972. func (self *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  973. var (
  974. newChain types.Blocks
  975. oldChain types.Blocks
  976. commonBlock *types.Block
  977. deletedTxs types.Transactions
  978. deletedLogs []*types.Log
  979. // collectLogs collects the logs that were generated during the
  980. // processing of the block that corresponds with the given hash.
  981. // These logs are later announced as deleted.
  982. collectLogs = func(h common.Hash) {
  983. // Coalesce logs and set 'Removed'.
  984. receipts := GetBlockReceipts(self.chainDb, h, self.hc.GetBlockNumber(h))
  985. for _, receipt := range receipts {
  986. for _, log := range receipt.Logs {
  987. del := *log
  988. del.Removed = true
  989. deletedLogs = append(deletedLogs, &del)
  990. }
  991. }
  992. }
  993. )
  994. // first reduce whoever is higher bound
  995. if oldBlock.NumberU64() > newBlock.NumberU64() {
  996. // reduce old chain
  997. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = self.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  998. oldChain = append(oldChain, oldBlock)
  999. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1000. collectLogs(oldBlock.Hash())
  1001. }
  1002. } else {
  1003. // reduce new chain and append new chain blocks for inserting later on
  1004. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = self.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1005. newChain = append(newChain, newBlock)
  1006. }
  1007. }
  1008. if oldBlock == nil {
  1009. return fmt.Errorf("Invalid old chain")
  1010. }
  1011. if newBlock == nil {
  1012. return fmt.Errorf("Invalid new chain")
  1013. }
  1014. for {
  1015. if oldBlock.Hash() == newBlock.Hash() {
  1016. commonBlock = oldBlock
  1017. break
  1018. }
  1019. oldChain = append(oldChain, oldBlock)
  1020. newChain = append(newChain, newBlock)
  1021. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1022. collectLogs(oldBlock.Hash())
  1023. oldBlock, newBlock = self.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), self.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1024. if oldBlock == nil {
  1025. return fmt.Errorf("Invalid old chain")
  1026. }
  1027. if newBlock == nil {
  1028. return fmt.Errorf("Invalid new chain")
  1029. }
  1030. }
  1031. // Ensure the user sees large reorgs
  1032. if len(oldChain) > 0 && len(newChain) > 0 {
  1033. logFn := log.Debug
  1034. if len(oldChain) > 63 {
  1035. logFn = log.Warn
  1036. }
  1037. logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1038. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1039. } else {
  1040. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1041. }
  1042. var addedTxs types.Transactions
  1043. // insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
  1044. for _, block := range newChain {
  1045. // insert the block in the canonical way, re-writing history
  1046. self.insert(block)
  1047. // write canonical receipts and transactions
  1048. if err := WriteTransactions(self.chainDb, block); err != nil {
  1049. return err
  1050. }
  1051. receipts := GetBlockReceipts(self.chainDb, block.Hash(), block.NumberU64())
  1052. // write receipts
  1053. if err := WriteReceipts(self.chainDb, receipts); err != nil {
  1054. return err
  1055. }
  1056. // Write map map bloom filters
  1057. if err := WriteMipmapBloom(self.chainDb, block.NumberU64(), receipts); err != nil {
  1058. return err
  1059. }
  1060. addedTxs = append(addedTxs, block.Transactions()...)
  1061. }
  1062. // calculate the difference between deleted and added transactions
  1063. diff := types.TxDifference(deletedTxs, addedTxs)
  1064. // When transactions get deleted from the database that means the
  1065. // receipts that were created in the fork must also be deleted
  1066. for _, tx := range diff {
  1067. DeleteReceipt(self.chainDb, tx.Hash())
  1068. DeleteTransaction(self.chainDb, tx.Hash())
  1069. }
  1070. // Must be posted in a goroutine because of the transaction pool trying
  1071. // to acquire the chain manager lock
  1072. if len(diff) > 0 {
  1073. go self.eventMux.Post(RemovedTransactionEvent{diff})
  1074. }
  1075. if len(deletedLogs) > 0 {
  1076. go self.eventMux.Post(RemovedLogsEvent{deletedLogs})
  1077. }
  1078. if len(oldChain) > 0 {
  1079. go func() {
  1080. for _, block := range oldChain {
  1081. self.eventMux.Post(ChainSideEvent{Block: block})
  1082. }
  1083. }()
  1084. }
  1085. return nil
  1086. }
  1087. // postChainEvents iterates over the events generated by a chain insertion and
  1088. // posts them into the event mux.
  1089. func (self *BlockChain) postChainEvents(events []interface{}, logs []*types.Log) {
  1090. // post event logs for further processing
  1091. self.eventMux.Post(logs)
  1092. for _, event := range events {
  1093. if event, ok := event.(ChainEvent); ok {
  1094. // We need some control over the mining operation. Acquiring locks and waiting for the miner to create new block takes too long
  1095. // and in most cases isn't even necessary.
  1096. if self.LastBlockHash() == event.Hash {
  1097. self.eventMux.Post(ChainHeadEvent{event.Block})
  1098. }
  1099. }
  1100. // Fire the insertion events individually too
  1101. self.eventMux.Post(event)
  1102. }
  1103. }
  1104. func (self *BlockChain) update() {
  1105. futureTimer := time.Tick(5 * time.Second)
  1106. for {
  1107. select {
  1108. case <-futureTimer:
  1109. self.procFutureBlocks()
  1110. case <-self.quit:
  1111. return
  1112. }
  1113. }
  1114. }
  1115. // BadBlockArgs represents the entries in the list returned when bad blocks are queried.
  1116. type BadBlockArgs struct {
  1117. Hash common.Hash `json:"hash"`
  1118. Header *types.Header `json:"header"`
  1119. }
  1120. // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1121. func (bc *BlockChain) BadBlocks() ([]BadBlockArgs, error) {
  1122. headers := make([]BadBlockArgs, 0, bc.badBlocks.Len())
  1123. for _, hash := range bc.badBlocks.Keys() {
  1124. if hdr, exist := bc.badBlocks.Peek(hash); exist {
  1125. header := hdr.(*types.Header)
  1126. headers = append(headers, BadBlockArgs{header.Hash(), header})
  1127. }
  1128. }
  1129. return headers, nil
  1130. }
  1131. // addBadBlock adds a bad block to the bad-block LRU cache
  1132. func (bc *BlockChain) addBadBlock(block *types.Block) {
  1133. bc.badBlocks.Add(block.Header().Hash(), block.Header())
  1134. }
  1135. // reportBlock logs a bad block error.
  1136. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1137. bc.addBadBlock(block)
  1138. var receiptString string
  1139. for _, receipt := range receipts {
  1140. receiptString += fmt.Sprintf("\t%v\n", receipt)
  1141. }
  1142. log.Error(fmt.Sprintf(`
  1143. ########## BAD BLOCK #########
  1144. Chain config: %v
  1145. Number: %v
  1146. Hash: 0x%x
  1147. %v
  1148. Error: %v
  1149. ##############################
  1150. `, bc.config, block.Number(), block.Hash(), receiptString, err))
  1151. }
  1152. // InsertHeaderChain attempts to insert the given header chain in to the local
  1153. // chain, possibly creating a reorg. If an error is returned, it will return the
  1154. // index number of the failing header as well an error describing what went wrong.
  1155. //
  1156. // The verify parameter can be used to fine tune whether nonce verification
  1157. // should be done or not. The reason behind the optional check is because some
  1158. // of the header retrieval mechanisms already need to verify nonces, as well as
  1159. // because nonces can be verified sparsely, not needing to check each.
  1160. func (self *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1161. start := time.Now()
  1162. if i, err := self.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1163. return i, err
  1164. }
  1165. // Make sure only one thread manipulates the chain at once
  1166. self.chainmu.Lock()
  1167. defer self.chainmu.Unlock()
  1168. self.wg.Add(1)
  1169. defer self.wg.Done()
  1170. whFunc := func(header *types.Header) error {
  1171. self.mu.Lock()
  1172. defer self.mu.Unlock()
  1173. _, err := self.hc.WriteHeader(header)
  1174. return err
  1175. }
  1176. return self.hc.InsertHeaderChain(chain, whFunc, start)
  1177. }
  1178. // writeHeader writes a header into the local chain, given that its parent is
  1179. // already known. If the total difficulty of the newly inserted header becomes
  1180. // greater than the current known TD, the canonical chain is re-routed.
  1181. //
  1182. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  1183. // into the chain, as side effects caused by reorganisations cannot be emulated
  1184. // without the real blocks. Hence, writing headers directly should only be done
  1185. // in two scenarios: pure-header mode of operation (light clients), or properly
  1186. // separated header/block phases (non-archive clients).
  1187. func (self *BlockChain) writeHeader(header *types.Header) error {
  1188. self.wg.Add(1)
  1189. defer self.wg.Done()
  1190. self.mu.Lock()
  1191. defer self.mu.Unlock()
  1192. _, err := self.hc.WriteHeader(header)
  1193. return err
  1194. }
  1195. // CurrentHeader retrieves the current head header of the canonical chain. The
  1196. // header is retrieved from the HeaderChain's internal cache.
  1197. func (self *BlockChain) CurrentHeader() *types.Header {
  1198. self.mu.RLock()
  1199. defer self.mu.RUnlock()
  1200. return self.hc.CurrentHeader()
  1201. }
  1202. // GetTd retrieves a block's total difficulty in the canonical chain from the
  1203. // database by hash and number, caching it if found.
  1204. func (self *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1205. return self.hc.GetTd(hash, number)
  1206. }
  1207. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1208. // database by hash, caching it if found.
  1209. func (self *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1210. return self.hc.GetTdByHash(hash)
  1211. }
  1212. // GetHeader retrieves a block header from the database by hash and number,
  1213. // caching it if found.
  1214. func (self *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1215. return self.hc.GetHeader(hash, number)
  1216. }
  1217. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1218. // found.
  1219. func (self *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1220. return self.hc.GetHeaderByHash(hash)
  1221. }
  1222. // HasHeader checks if a block header is present in the database or not, caching
  1223. // it if present.
  1224. func (bc *BlockChain) HasHeader(hash common.Hash) bool {
  1225. return bc.hc.HasHeader(hash)
  1226. }
  1227. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1228. // hash, fetching towards the genesis block.
  1229. func (self *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1230. return self.hc.GetBlockHashesFromHash(hash, max)
  1231. }
  1232. // GetHeaderByNumber retrieves a block header from the database by number,
  1233. // caching it (associated with its hash) if found.
  1234. func (self *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1235. return self.hc.GetHeaderByNumber(number)
  1236. }
  1237. // Config retrieves the blockchain's chain configuration.
  1238. func (self *BlockChain) Config() *params.ChainConfig { return self.config }