blockchain.go 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613
  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. "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/mclock"
  29. "github.com/ethereum/go-ethereum/common/prque"
  30. "github.com/ethereum/go-ethereum/consensus"
  31. "github.com/ethereum/go-ethereum/core/rawdb"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/crypto"
  36. "github.com/ethereum/go-ethereum/ethdb"
  37. "github.com/ethereum/go-ethereum/event"
  38. "github.com/ethereum/go-ethereum/log"
  39. "github.com/ethereum/go-ethereum/metrics"
  40. "github.com/ethereum/go-ethereum/params"
  41. "github.com/ethereum/go-ethereum/rlp"
  42. "github.com/ethereum/go-ethereum/trie"
  43. "github.com/hashicorp/golang-lru"
  44. )
  45. var (
  46. blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil)
  47. ErrNoGenesis = errors.New("Genesis not found in chain")
  48. )
  49. const (
  50. bodyCacheLimit = 256
  51. blockCacheLimit = 256
  52. receiptsCacheLimit = 32
  53. maxFutureBlocks = 256
  54. maxTimeFutureBlocks = 30
  55. badBlockLimit = 10
  56. triesInMemory = 128
  57. // BlockChainVersion ensures that an incompatible database forces a resync from scratch.
  58. BlockChainVersion = 3
  59. )
  60. // CacheConfig contains the configuration values for the trie caching/pruning
  61. // that's resident in a blockchain.
  62. type CacheConfig struct {
  63. Disabled bool // Whether to disable trie write caching (archive node)
  64. TrieNodeLimit int // Memory limit (MB) at which to flush the current in-memory trie to disk
  65. TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
  66. }
  67. // BlockChain represents the canonical chain given a database with a genesis
  68. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  69. //
  70. // Importing blocks in to the block chain happens according to the set of rules
  71. // defined by the two stage Validator. Processing of blocks is done using the
  72. // Processor which processes the included transaction. The validation of the state
  73. // is done in the second part of the Validator. Failing results in aborting of
  74. // the import.
  75. //
  76. // The BlockChain also helps in returning blocks from **any** chain included
  77. // in the database as well as blocks that represents the canonical chain. It's
  78. // important to note that GetBlock can return any block and does not need to be
  79. // included in the canonical one where as GetBlockByNumber always represents the
  80. // canonical chain.
  81. type BlockChain struct {
  82. chainConfig *params.ChainConfig // Chain & network configuration
  83. cacheConfig *CacheConfig // Cache configuration for pruning
  84. db ethdb.Database // Low level persistent database to store final content in
  85. triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
  86. gcproc time.Duration // Accumulates canonical block processing for trie dumping
  87. hc *HeaderChain
  88. rmLogsFeed event.Feed
  89. chainFeed event.Feed
  90. chainSideFeed event.Feed
  91. chainHeadFeed event.Feed
  92. logsFeed event.Feed
  93. scope event.SubscriptionScope
  94. genesisBlock *types.Block
  95. mu sync.RWMutex // global mutex for locking chain operations
  96. chainmu sync.RWMutex // blockchain insertion lock
  97. procmu sync.RWMutex // block processor lock
  98. checkpoint int // checkpoint counts towards the new checkpoint
  99. currentBlock atomic.Value // Current head of the block chain
  100. currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
  101. stateCache state.Database // State database to reuse between imports (contains state cache)
  102. bodyCache *lru.Cache // Cache for the most recent block bodies
  103. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  104. receiptsCache *lru.Cache // Cache for the most recent receipts per block
  105. blockCache *lru.Cache // Cache for the most recent entire blocks
  106. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  107. quit chan struct{} // blockchain quit channel
  108. running int32 // running must be called atomically
  109. // procInterrupt must be atomically called
  110. procInterrupt int32 // interrupt signaler for block processing
  111. wg sync.WaitGroup // chain processing wait group for shutting down
  112. engine consensus.Engine
  113. processor Processor // block processor interface
  114. validator Validator // block and state validator interface
  115. vmConfig vm.Config
  116. badBlocks *lru.Cache // Bad block cache
  117. shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
  118. }
  119. // NewBlockChain returns a fully initialised block chain using information
  120. // available in the database. It initialises the default Ethereum Validator and
  121. // Processor.
  122. func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool) (*BlockChain, error) {
  123. if cacheConfig == nil {
  124. cacheConfig = &CacheConfig{
  125. TrieNodeLimit: 256 * 1024 * 1024,
  126. TrieTimeLimit: 5 * time.Minute,
  127. }
  128. }
  129. bodyCache, _ := lru.New(bodyCacheLimit)
  130. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  131. receiptsCache, _ := lru.New(receiptsCacheLimit)
  132. blockCache, _ := lru.New(blockCacheLimit)
  133. futureBlocks, _ := lru.New(maxFutureBlocks)
  134. badBlocks, _ := lru.New(badBlockLimit)
  135. bc := &BlockChain{
  136. chainConfig: chainConfig,
  137. cacheConfig: cacheConfig,
  138. db: db,
  139. triegc: prque.New(nil),
  140. stateCache: state.NewDatabase(db),
  141. quit: make(chan struct{}),
  142. shouldPreserve: shouldPreserve,
  143. bodyCache: bodyCache,
  144. bodyRLPCache: bodyRLPCache,
  145. receiptsCache: receiptsCache,
  146. blockCache: blockCache,
  147. futureBlocks: futureBlocks,
  148. engine: engine,
  149. vmConfig: vmConfig,
  150. badBlocks: badBlocks,
  151. }
  152. bc.SetValidator(NewBlockValidator(chainConfig, bc, engine))
  153. bc.SetProcessor(NewStateProcessor(chainConfig, bc, engine))
  154. var err error
  155. bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.getProcInterrupt)
  156. if err != nil {
  157. return nil, err
  158. }
  159. bc.genesisBlock = bc.GetBlockByNumber(0)
  160. if bc.genesisBlock == nil {
  161. return nil, ErrNoGenesis
  162. }
  163. if err := bc.loadLastState(); err != nil {
  164. return nil, err
  165. }
  166. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  167. for hash := range BadHashes {
  168. if header := bc.GetHeaderByHash(hash); header != nil {
  169. // get the canonical block corresponding to the offending header's number
  170. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  171. // make sure the headerByNumber (if present) is in our current canonical chain
  172. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  173. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  174. bc.SetHead(header.Number.Uint64() - 1)
  175. log.Error("Chain rewind was successful, resuming normal operation")
  176. }
  177. }
  178. }
  179. // Take ownership of this particular state
  180. go bc.update()
  181. return bc, nil
  182. }
  183. func (bc *BlockChain) getProcInterrupt() bool {
  184. return atomic.LoadInt32(&bc.procInterrupt) == 1
  185. }
  186. // loadLastState loads the last known chain state from the database. This method
  187. // assumes that the chain manager mutex is held.
  188. func (bc *BlockChain) loadLastState() error {
  189. // Restore the last known head block
  190. head := rawdb.ReadHeadBlockHash(bc.db)
  191. if head == (common.Hash{}) {
  192. // Corrupt or empty database, init from scratch
  193. log.Warn("Empty database, resetting chain")
  194. return bc.Reset()
  195. }
  196. // Make sure the entire head block is available
  197. currentBlock := bc.GetBlockByHash(head)
  198. if currentBlock == nil {
  199. // Corrupt or empty database, init from scratch
  200. log.Warn("Head block missing, resetting chain", "hash", head)
  201. return bc.Reset()
  202. }
  203. // Make sure the state associated with the block is available
  204. if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
  205. // Dangling block without a state associated, init from scratch
  206. log.Warn("Head state missing, repairing chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
  207. if err := bc.repair(&currentBlock); err != nil {
  208. return err
  209. }
  210. }
  211. // Everything seems to be fine, set as the head block
  212. bc.currentBlock.Store(currentBlock)
  213. // Restore the last known head header
  214. currentHeader := currentBlock.Header()
  215. if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
  216. if header := bc.GetHeaderByHash(head); header != nil {
  217. currentHeader = header
  218. }
  219. }
  220. bc.hc.SetCurrentHeader(currentHeader)
  221. // Restore the last known head fast block
  222. bc.currentFastBlock.Store(currentBlock)
  223. if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
  224. if block := bc.GetBlockByHash(head); block != nil {
  225. bc.currentFastBlock.Store(block)
  226. }
  227. }
  228. // Issue a status log for the user
  229. currentFastBlock := bc.CurrentFastBlock()
  230. headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  231. blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  232. fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
  233. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(currentHeader.Time.Int64(), 0)))
  234. log.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(currentBlock.Time().Int64(), 0)))
  235. log.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(currentFastBlock.Time().Int64(), 0)))
  236. return nil
  237. }
  238. // SetHead rewinds the local chain to a new head. In the case of headers, everything
  239. // above the new head will be deleted and the new one set. In the case of blocks
  240. // though, the head may be further rewound if block bodies are missing (non-archive
  241. // nodes after a fast sync).
  242. func (bc *BlockChain) SetHead(head uint64) error {
  243. log.Warn("Rewinding blockchain", "target", head)
  244. bc.mu.Lock()
  245. defer bc.mu.Unlock()
  246. // Rewind the header chain, deleting all block bodies until then
  247. delFn := func(db rawdb.DatabaseDeleter, hash common.Hash, num uint64) {
  248. rawdb.DeleteBody(db, hash, num)
  249. }
  250. bc.hc.SetHead(head, delFn)
  251. currentHeader := bc.hc.CurrentHeader()
  252. // Clear out any stale content from the caches
  253. bc.bodyCache.Purge()
  254. bc.bodyRLPCache.Purge()
  255. bc.receiptsCache.Purge()
  256. bc.blockCache.Purge()
  257. bc.futureBlocks.Purge()
  258. // Rewind the block chain, ensuring we don't end up with a stateless head block
  259. if currentBlock := bc.CurrentBlock(); currentBlock != nil && currentHeader.Number.Uint64() < currentBlock.NumberU64() {
  260. bc.currentBlock.Store(bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()))
  261. }
  262. if currentBlock := bc.CurrentBlock(); currentBlock != nil {
  263. if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
  264. // Rewound state missing, rolled back to before pivot, reset to genesis
  265. bc.currentBlock.Store(bc.genesisBlock)
  266. }
  267. }
  268. // Rewind the fast block in a simpleton way to the target head
  269. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && currentHeader.Number.Uint64() < currentFastBlock.NumberU64() {
  270. bc.currentFastBlock.Store(bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()))
  271. }
  272. // If either blocks reached nil, reset to the genesis state
  273. if currentBlock := bc.CurrentBlock(); currentBlock == nil {
  274. bc.currentBlock.Store(bc.genesisBlock)
  275. }
  276. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock == nil {
  277. bc.currentFastBlock.Store(bc.genesisBlock)
  278. }
  279. currentBlock := bc.CurrentBlock()
  280. currentFastBlock := bc.CurrentFastBlock()
  281. rawdb.WriteHeadBlockHash(bc.db, currentBlock.Hash())
  282. rawdb.WriteHeadFastBlockHash(bc.db, currentFastBlock.Hash())
  283. return bc.loadLastState()
  284. }
  285. // FastSyncCommitHead sets the current head block to the one defined by the hash
  286. // irrelevant what the chain contents were prior.
  287. func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  288. // Make sure that both the block as well at its state trie exists
  289. block := bc.GetBlockByHash(hash)
  290. if block == nil {
  291. return fmt.Errorf("non existent block [%x…]", hash[:4])
  292. }
  293. if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB(), 0); err != nil {
  294. return err
  295. }
  296. // If all checks out, manually set the head block
  297. bc.mu.Lock()
  298. bc.currentBlock.Store(block)
  299. bc.mu.Unlock()
  300. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  301. return nil
  302. }
  303. // GasLimit returns the gas limit of the current HEAD block.
  304. func (bc *BlockChain) GasLimit() uint64 {
  305. return bc.CurrentBlock().GasLimit()
  306. }
  307. // CurrentBlock retrieves the current head block of the canonical chain. The
  308. // block is retrieved from the blockchain's internal cache.
  309. func (bc *BlockChain) CurrentBlock() *types.Block {
  310. return bc.currentBlock.Load().(*types.Block)
  311. }
  312. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  313. // chain. The block is retrieved from the blockchain's internal cache.
  314. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  315. return bc.currentFastBlock.Load().(*types.Block)
  316. }
  317. // SetProcessor sets the processor required for making state modifications.
  318. func (bc *BlockChain) SetProcessor(processor Processor) {
  319. bc.procmu.Lock()
  320. defer bc.procmu.Unlock()
  321. bc.processor = processor
  322. }
  323. // SetValidator sets the validator which is used to validate incoming blocks.
  324. func (bc *BlockChain) SetValidator(validator Validator) {
  325. bc.procmu.Lock()
  326. defer bc.procmu.Unlock()
  327. bc.validator = validator
  328. }
  329. // Validator returns the current validator.
  330. func (bc *BlockChain) Validator() Validator {
  331. bc.procmu.RLock()
  332. defer bc.procmu.RUnlock()
  333. return bc.validator
  334. }
  335. // Processor returns the current processor.
  336. func (bc *BlockChain) Processor() Processor {
  337. bc.procmu.RLock()
  338. defer bc.procmu.RUnlock()
  339. return bc.processor
  340. }
  341. // State returns a new mutable state based on the current HEAD block.
  342. func (bc *BlockChain) State() (*state.StateDB, error) {
  343. return bc.StateAt(bc.CurrentBlock().Root())
  344. }
  345. // StateAt returns a new mutable state based on a particular point in time.
  346. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  347. return state.New(root, bc.stateCache)
  348. }
  349. // Reset purges the entire blockchain, restoring it to its genesis state.
  350. func (bc *BlockChain) Reset() error {
  351. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  352. }
  353. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  354. // specified genesis state.
  355. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  356. // Dump the entire block chain and purge the caches
  357. if err := bc.SetHead(0); err != nil {
  358. return err
  359. }
  360. bc.mu.Lock()
  361. defer bc.mu.Unlock()
  362. // Prepare the genesis block and reinitialise the chain
  363. if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  364. log.Crit("Failed to write genesis block TD", "err", err)
  365. }
  366. rawdb.WriteBlock(bc.db, genesis)
  367. bc.genesisBlock = genesis
  368. bc.insert(bc.genesisBlock)
  369. bc.currentBlock.Store(bc.genesisBlock)
  370. bc.hc.SetGenesis(bc.genesisBlock.Header())
  371. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  372. bc.currentFastBlock.Store(bc.genesisBlock)
  373. return nil
  374. }
  375. // repair tries to repair the current blockchain by rolling back the current block
  376. // until one with associated state is found. This is needed to fix incomplete db
  377. // writes caused either by crashes/power outages, or simply non-committed tries.
  378. //
  379. // This method only rolls back the current block. The current header and current
  380. // fast block are left intact.
  381. func (bc *BlockChain) repair(head **types.Block) error {
  382. for {
  383. // Abort if we've rewound to a head block that does have associated state
  384. if _, err := state.New((*head).Root(), bc.stateCache); err == nil {
  385. log.Info("Rewound blockchain to past state", "number", (*head).Number(), "hash", (*head).Hash())
  386. return nil
  387. }
  388. // Otherwise rewind one block and recheck state availability there
  389. (*head) = bc.GetBlock((*head).ParentHash(), (*head).NumberU64()-1)
  390. }
  391. }
  392. // Export writes the active chain to the given writer.
  393. func (bc *BlockChain) Export(w io.Writer) error {
  394. return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64())
  395. }
  396. // ExportN writes a subset of the active chain to the given writer.
  397. func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  398. bc.mu.RLock()
  399. defer bc.mu.RUnlock()
  400. if first > last {
  401. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  402. }
  403. log.Info("Exporting batch of blocks", "count", last-first+1)
  404. start, reported := time.Now(), time.Now()
  405. for nr := first; nr <= last; nr++ {
  406. block := bc.GetBlockByNumber(nr)
  407. if block == nil {
  408. return fmt.Errorf("export failed on #%d: not found", nr)
  409. }
  410. if err := block.EncodeRLP(w); err != nil {
  411. return err
  412. }
  413. if time.Since(reported) >= statsReportLimit {
  414. log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
  415. reported = time.Now()
  416. }
  417. }
  418. return nil
  419. }
  420. // insert injects a new head block into the current block chain. This method
  421. // assumes that the block is indeed a true head. It will also reset the head
  422. // header and the head fast sync block to this very same block if they are older
  423. // or if they are on a different side chain.
  424. //
  425. // Note, this function assumes that the `mu` mutex is held!
  426. func (bc *BlockChain) insert(block *types.Block) {
  427. // If the block is on a side chain or an unknown one, force other heads onto it too
  428. updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()
  429. // Add the block to the canonical chain number scheme and mark as the head
  430. rawdb.WriteCanonicalHash(bc.db, block.Hash(), block.NumberU64())
  431. rawdb.WriteHeadBlockHash(bc.db, block.Hash())
  432. bc.currentBlock.Store(block)
  433. // If the block is better than our head or is on a different chain, force update heads
  434. if updateHeads {
  435. bc.hc.SetCurrentHeader(block.Header())
  436. rawdb.WriteHeadFastBlockHash(bc.db, block.Hash())
  437. bc.currentFastBlock.Store(block)
  438. }
  439. }
  440. // Genesis retrieves the chain's genesis block.
  441. func (bc *BlockChain) Genesis() *types.Block {
  442. return bc.genesisBlock
  443. }
  444. // GetBody retrieves a block body (transactions and uncles) from the database by
  445. // hash, caching it if found.
  446. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  447. // Short circuit if the body's already in the cache, retrieve otherwise
  448. if cached, ok := bc.bodyCache.Get(hash); ok {
  449. body := cached.(*types.Body)
  450. return body
  451. }
  452. number := bc.hc.GetBlockNumber(hash)
  453. if number == nil {
  454. return nil
  455. }
  456. body := rawdb.ReadBody(bc.db, hash, *number)
  457. if body == nil {
  458. return nil
  459. }
  460. // Cache the found body for next time and return
  461. bc.bodyCache.Add(hash, body)
  462. return body
  463. }
  464. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  465. // caching it if found.
  466. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  467. // Short circuit if the body's already in the cache, retrieve otherwise
  468. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  469. return cached.(rlp.RawValue)
  470. }
  471. number := bc.hc.GetBlockNumber(hash)
  472. if number == nil {
  473. return nil
  474. }
  475. body := rawdb.ReadBodyRLP(bc.db, hash, *number)
  476. if len(body) == 0 {
  477. return nil
  478. }
  479. // Cache the found body for next time and return
  480. bc.bodyRLPCache.Add(hash, body)
  481. return body
  482. }
  483. // HasBlock checks if a block is fully present in the database or not.
  484. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  485. if bc.blockCache.Contains(hash) {
  486. return true
  487. }
  488. return rawdb.HasBody(bc.db, hash, number)
  489. }
  490. // HasState checks if state trie is fully present in the database or not.
  491. func (bc *BlockChain) HasState(hash common.Hash) bool {
  492. _, err := bc.stateCache.OpenTrie(hash)
  493. return err == nil
  494. }
  495. // HasBlockAndState checks if a block and associated state trie is fully present
  496. // in the database or not, caching it if present.
  497. func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
  498. // Check first that the block itself is known
  499. block := bc.GetBlock(hash, number)
  500. if block == nil {
  501. return false
  502. }
  503. return bc.HasState(block.Root())
  504. }
  505. // GetBlock retrieves a block from the database by hash and number,
  506. // caching it if found.
  507. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  508. // Short circuit if the block's already in the cache, retrieve otherwise
  509. if block, ok := bc.blockCache.Get(hash); ok {
  510. return block.(*types.Block)
  511. }
  512. block := rawdb.ReadBlock(bc.db, hash, number)
  513. if block == nil {
  514. return nil
  515. }
  516. // Cache the found block for next time and return
  517. bc.blockCache.Add(block.Hash(), block)
  518. return block
  519. }
  520. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  521. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  522. number := bc.hc.GetBlockNumber(hash)
  523. if number == nil {
  524. return nil
  525. }
  526. return bc.GetBlock(hash, *number)
  527. }
  528. // GetBlockByNumber retrieves a block from the database by number, caching it
  529. // (associated with its hash) if found.
  530. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  531. hash := rawdb.ReadCanonicalHash(bc.db, number)
  532. if hash == (common.Hash{}) {
  533. return nil
  534. }
  535. return bc.GetBlock(hash, number)
  536. }
  537. // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
  538. func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
  539. if receipts, ok := bc.receiptsCache.Get(hash); ok {
  540. return receipts.(types.Receipts)
  541. }
  542. number := rawdb.ReadHeaderNumber(bc.db, hash)
  543. if number == nil {
  544. return nil
  545. }
  546. receipts := rawdb.ReadReceipts(bc.db, hash, *number)
  547. bc.receiptsCache.Add(hash, receipts)
  548. return receipts
  549. }
  550. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  551. // [deprecated by eth/62]
  552. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  553. number := bc.hc.GetBlockNumber(hash)
  554. if number == nil {
  555. return nil
  556. }
  557. for i := 0; i < n; i++ {
  558. block := bc.GetBlock(hash, *number)
  559. if block == nil {
  560. break
  561. }
  562. blocks = append(blocks, block)
  563. hash = block.ParentHash()
  564. *number--
  565. }
  566. return
  567. }
  568. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  569. // a specific distance is reached.
  570. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  571. uncles := []*types.Header{}
  572. for i := 0; block != nil && i < length; i++ {
  573. uncles = append(uncles, block.Uncles()...)
  574. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  575. }
  576. return uncles
  577. }
  578. // TrieNode retrieves a blob of data associated with a trie node (or code hash)
  579. // either from ephemeral in-memory cache, or from persistent storage.
  580. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  581. return bc.stateCache.TrieDB().Node(hash)
  582. }
  583. // Stop stops the blockchain service. If any imports are currently in progress
  584. // it will abort them using the procInterrupt.
  585. func (bc *BlockChain) Stop() {
  586. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  587. return
  588. }
  589. // Unsubscribe all subscriptions registered from blockchain
  590. bc.scope.Close()
  591. close(bc.quit)
  592. atomic.StoreInt32(&bc.procInterrupt, 1)
  593. bc.wg.Wait()
  594. // Ensure the state of a recent block is also stored to disk before exiting.
  595. // We're writing three different states to catch different restart scenarios:
  596. // - HEAD: So we don't need to reprocess any blocks in the general case
  597. // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle
  598. // - HEAD-127: So we have a hard limit on the number of blocks reexecuted
  599. if !bc.cacheConfig.Disabled {
  600. triedb := bc.stateCache.TrieDB()
  601. for _, offset := range []uint64{0, 1, triesInMemory - 1} {
  602. if number := bc.CurrentBlock().NumberU64(); number > offset {
  603. recent := bc.GetBlockByNumber(number - offset)
  604. log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
  605. if err := triedb.Commit(recent.Root(), true); err != nil {
  606. log.Error("Failed to commit recent state trie", "err", err)
  607. }
  608. }
  609. }
  610. for !bc.triegc.Empty() {
  611. triedb.Dereference(bc.triegc.PopItem().(common.Hash))
  612. }
  613. if size, _ := triedb.Size(); size != 0 {
  614. log.Error("Dangling trie nodes after full cleanup")
  615. }
  616. }
  617. log.Info("Blockchain manager stopped")
  618. }
  619. func (bc *BlockChain) procFutureBlocks() {
  620. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  621. for _, hash := range bc.futureBlocks.Keys() {
  622. if block, exist := bc.futureBlocks.Peek(hash); exist {
  623. blocks = append(blocks, block.(*types.Block))
  624. }
  625. }
  626. if len(blocks) > 0 {
  627. types.BlockBy(types.Number).Sort(blocks)
  628. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  629. for i := range blocks {
  630. bc.InsertChain(blocks[i : i+1])
  631. }
  632. }
  633. }
  634. // WriteStatus status of write
  635. type WriteStatus byte
  636. const (
  637. NonStatTy WriteStatus = iota
  638. CanonStatTy
  639. SideStatTy
  640. )
  641. // Rollback is designed to remove a chain of links from the database that aren't
  642. // certain enough to be valid.
  643. func (bc *BlockChain) Rollback(chain []common.Hash) {
  644. bc.mu.Lock()
  645. defer bc.mu.Unlock()
  646. for i := len(chain) - 1; i >= 0; i-- {
  647. hash := chain[i]
  648. currentHeader := bc.hc.CurrentHeader()
  649. if currentHeader.Hash() == hash {
  650. bc.hc.SetCurrentHeader(bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
  651. }
  652. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock.Hash() == hash {
  653. newFastBlock := bc.GetBlock(currentFastBlock.ParentHash(), currentFastBlock.NumberU64()-1)
  654. bc.currentFastBlock.Store(newFastBlock)
  655. rawdb.WriteHeadFastBlockHash(bc.db, newFastBlock.Hash())
  656. }
  657. if currentBlock := bc.CurrentBlock(); currentBlock.Hash() == hash {
  658. newBlock := bc.GetBlock(currentBlock.ParentHash(), currentBlock.NumberU64()-1)
  659. bc.currentBlock.Store(newBlock)
  660. rawdb.WriteHeadBlockHash(bc.db, newBlock.Hash())
  661. }
  662. }
  663. }
  664. // SetReceiptsData computes all the non-consensus fields of the receipts
  665. func SetReceiptsData(config *params.ChainConfig, block *types.Block, receipts types.Receipts) error {
  666. signer := types.MakeSigner(config, block.Number())
  667. transactions, logIndex := block.Transactions(), uint(0)
  668. if len(transactions) != len(receipts) {
  669. return errors.New("transaction and receipt count mismatch")
  670. }
  671. for j := 0; j < len(receipts); j++ {
  672. // The transaction hash can be retrieved from the transaction itself
  673. receipts[j].TxHash = transactions[j].Hash()
  674. // The contract address can be derived from the transaction itself
  675. if transactions[j].To() == nil {
  676. // Deriving the signer is expensive, only do if it's actually needed
  677. from, _ := types.Sender(signer, transactions[j])
  678. receipts[j].ContractAddress = crypto.CreateAddress(from, transactions[j].Nonce())
  679. }
  680. // The used gas can be calculated based on previous receipts
  681. if j == 0 {
  682. receipts[j].GasUsed = receipts[j].CumulativeGasUsed
  683. } else {
  684. receipts[j].GasUsed = receipts[j].CumulativeGasUsed - receipts[j-1].CumulativeGasUsed
  685. }
  686. // The derived log fields can simply be set from the block and transaction
  687. for k := 0; k < len(receipts[j].Logs); k++ {
  688. receipts[j].Logs[k].BlockNumber = block.NumberU64()
  689. receipts[j].Logs[k].BlockHash = block.Hash()
  690. receipts[j].Logs[k].TxHash = receipts[j].TxHash
  691. receipts[j].Logs[k].TxIndex = uint(j)
  692. receipts[j].Logs[k].Index = logIndex
  693. logIndex++
  694. }
  695. }
  696. return nil
  697. }
  698. // InsertReceiptChain attempts to complete an already existing header chain with
  699. // transaction and receipt data.
  700. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  701. bc.wg.Add(1)
  702. defer bc.wg.Done()
  703. // Do a sanity check that the provided chain is actually ordered and linked
  704. for i := 1; i < len(blockChain); i++ {
  705. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  706. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  707. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  708. 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(),
  709. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  710. }
  711. }
  712. var (
  713. stats = struct{ processed, ignored int32 }{}
  714. start = time.Now()
  715. bytes = 0
  716. batch = bc.db.NewBatch()
  717. )
  718. for i, block := range blockChain {
  719. receipts := receiptChain[i]
  720. // Short circuit insertion if shutting down or processing failed
  721. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  722. return 0, nil
  723. }
  724. // Short circuit if the owner header is unknown
  725. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  726. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  727. }
  728. // Skip if the entire data is already known
  729. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  730. stats.ignored++
  731. continue
  732. }
  733. // Compute all the non-consensus fields of the receipts
  734. if err := SetReceiptsData(bc.chainConfig, block, receipts); err != nil {
  735. return i, fmt.Errorf("failed to set receipts data: %v", err)
  736. }
  737. // Write all the data out into the database
  738. rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
  739. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  740. rawdb.WriteTxLookupEntries(batch, block)
  741. stats.processed++
  742. if batch.ValueSize() >= ethdb.IdealBatchSize {
  743. if err := batch.Write(); err != nil {
  744. return 0, err
  745. }
  746. bytes += batch.ValueSize()
  747. batch.Reset()
  748. }
  749. }
  750. if batch.ValueSize() > 0 {
  751. bytes += batch.ValueSize()
  752. if err := batch.Write(); err != nil {
  753. return 0, err
  754. }
  755. }
  756. // Update the head fast sync block if better
  757. bc.mu.Lock()
  758. head := blockChain[len(blockChain)-1]
  759. if td := bc.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case
  760. currentFastBlock := bc.CurrentFastBlock()
  761. if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
  762. rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
  763. bc.currentFastBlock.Store(head)
  764. }
  765. }
  766. bc.mu.Unlock()
  767. context := []interface{}{
  768. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  769. "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(head.Time().Int64(), 0)),
  770. "size", common.StorageSize(bytes),
  771. }
  772. if stats.ignored > 0 {
  773. context = append(context, []interface{}{"ignored", stats.ignored}...)
  774. }
  775. log.Info("Imported new block receipts", context...)
  776. return 0, nil
  777. }
  778. var lastWrite uint64
  779. // WriteBlockWithoutState writes only the block and its metadata to the database,
  780. // but does not write any state. This is used to construct competing side forks
  781. // up to the point where they exceed the canonical total difficulty.
  782. func (bc *BlockChain) WriteBlockWithoutState(block *types.Block, td *big.Int) (err error) {
  783. bc.wg.Add(1)
  784. defer bc.wg.Done()
  785. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), td); err != nil {
  786. return err
  787. }
  788. rawdb.WriteBlock(bc.db, block)
  789. return nil
  790. }
  791. // WriteBlockWithState writes the block and all associated state to the database.
  792. func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  793. bc.wg.Add(1)
  794. defer bc.wg.Done()
  795. // Calculate the total difficulty of the block
  796. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  797. if ptd == nil {
  798. return NonStatTy, consensus.ErrUnknownAncestor
  799. }
  800. // Make sure no inconsistent state is leaked during insertion
  801. bc.mu.Lock()
  802. defer bc.mu.Unlock()
  803. currentBlock := bc.CurrentBlock()
  804. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  805. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  806. // Irrelevant of the canonical status, write the block itself to the database
  807. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
  808. return NonStatTy, err
  809. }
  810. rawdb.WriteBlock(bc.db, block)
  811. root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
  812. if err != nil {
  813. return NonStatTy, err
  814. }
  815. triedb := bc.stateCache.TrieDB()
  816. // If we're running an archive node, always flush
  817. if bc.cacheConfig.Disabled {
  818. if err := triedb.Commit(root, false); err != nil {
  819. return NonStatTy, err
  820. }
  821. } else {
  822. // Full but not archive node, do proper garbage collection
  823. triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
  824. bc.triegc.Push(root, -int64(block.NumberU64()))
  825. if current := block.NumberU64(); current > triesInMemory {
  826. // If we exceeded our memory allowance, flush matured singleton nodes to disk
  827. var (
  828. nodes, imgs = triedb.Size()
  829. limit = common.StorageSize(bc.cacheConfig.TrieNodeLimit) * 1024 * 1024
  830. )
  831. if nodes > limit || imgs > 4*1024*1024 {
  832. triedb.Cap(limit - ethdb.IdealBatchSize)
  833. }
  834. // Find the next state trie we need to commit
  835. header := bc.GetHeaderByNumber(current - triesInMemory)
  836. chosen := header.Number.Uint64()
  837. // If we exceeded out time allowance, flush an entire trie to disk
  838. if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
  839. // If we're exceeding limits but haven't reached a large enough memory gap,
  840. // warn the user that the system is becoming unstable.
  841. if chosen < lastWrite+triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
  842. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/triesInMemory)
  843. }
  844. // Flush an entire trie and restart the counters
  845. triedb.Commit(header.Root, true)
  846. lastWrite = chosen
  847. bc.gcproc = 0
  848. }
  849. // Garbage collect anything below our required write retention
  850. for !bc.triegc.Empty() {
  851. root, number := bc.triegc.Pop()
  852. if uint64(-number) > chosen {
  853. bc.triegc.Push(root, number)
  854. break
  855. }
  856. triedb.Dereference(root.(common.Hash))
  857. }
  858. }
  859. }
  860. // Write other block data using a batch.
  861. batch := bc.db.NewBatch()
  862. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  863. // If the total difficulty is higher than our known, add it to the canonical chain
  864. // Second clause in the if statement reduces the vulnerability to selfish mining.
  865. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  866. reorg := externTd.Cmp(localTd) > 0
  867. currentBlock = bc.CurrentBlock()
  868. if !reorg && externTd.Cmp(localTd) == 0 {
  869. // Split same-difficulty blocks by number, then preferentially select
  870. // the block generated by the local miner as the canonical block.
  871. if block.NumberU64() < currentBlock.NumberU64() {
  872. reorg = true
  873. } else if block.NumberU64() == currentBlock.NumberU64() {
  874. var currentPreserve, blockPreserve bool
  875. if bc.shouldPreserve != nil {
  876. currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  877. }
  878. reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  879. }
  880. }
  881. if reorg {
  882. // Reorganise the chain if the parent is not the head block
  883. if block.ParentHash() != currentBlock.Hash() {
  884. if err := bc.reorg(currentBlock, block); err != nil {
  885. return NonStatTy, err
  886. }
  887. }
  888. // Write the positional metadata for transaction/receipt lookups and preimages
  889. rawdb.WriteTxLookupEntries(batch, block)
  890. rawdb.WritePreimages(batch, block.NumberU64(), state.Preimages())
  891. status = CanonStatTy
  892. } else {
  893. status = SideStatTy
  894. }
  895. if err := batch.Write(); err != nil {
  896. return NonStatTy, err
  897. }
  898. // Set new head.
  899. if status == CanonStatTy {
  900. bc.insert(block)
  901. }
  902. bc.futureBlocks.Remove(block.Hash())
  903. return status, nil
  904. }
  905. // InsertChain attempts to insert the given batch of blocks in to the canonical
  906. // chain or, otherwise, create a fork. If an error is returned it will return
  907. // the index number of the failing block as well an error describing what went
  908. // wrong.
  909. //
  910. // After insertion is done, all accumulated events will be fired.
  911. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  912. n, events, logs, err := bc.insertChain(chain)
  913. bc.PostChainEvents(events, logs)
  914. return n, err
  915. }
  916. // insertChain will execute the actual chain insertion and event aggregation. The
  917. // only reason this method exists as a separate one is to make locking cleaner
  918. // with deferred statements.
  919. func (bc *BlockChain) insertChain(chain types.Blocks) (int, []interface{}, []*types.Log, error) {
  920. // Sanity check that we have something meaningful to import
  921. if len(chain) == 0 {
  922. return 0, nil, nil, nil
  923. }
  924. // Do a sanity check that the provided chain is actually ordered and linked
  925. for i := 1; i < len(chain); i++ {
  926. if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
  927. // Chain broke ancestry, log a message (programming error) and skip insertion
  928. log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(),
  929. "parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash())
  930. return 0, nil, nil, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(),
  931. chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
  932. }
  933. }
  934. // Pre-checks passed, start the full block imports
  935. bc.wg.Add(1)
  936. defer bc.wg.Done()
  937. bc.chainmu.Lock()
  938. defer bc.chainmu.Unlock()
  939. // A queued approach to delivering events. This is generally
  940. // faster than direct delivery and requires much less mutex
  941. // acquiring.
  942. var (
  943. stats = insertStats{startTime: mclock.Now()}
  944. events = make([]interface{}, 0, len(chain))
  945. lastCanon *types.Block
  946. coalescedLogs []*types.Log
  947. )
  948. // Start the parallel header verifier
  949. headers := make([]*types.Header, len(chain))
  950. seals := make([]bool, len(chain))
  951. for i, block := range chain {
  952. headers[i] = block.Header()
  953. seals[i] = true
  954. }
  955. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  956. defer close(abort)
  957. // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  958. senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  959. // Iterate over the blocks and insert when the verifier permits
  960. for i, block := range chain {
  961. // If the chain is terminating, stop processing blocks
  962. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  963. log.Debug("Premature abort during blocks processing")
  964. break
  965. }
  966. // If the header is a banned one, straight out abort
  967. if BadHashes[block.Hash()] {
  968. bc.reportBlock(block, nil, ErrBlacklistedHash)
  969. return i, events, coalescedLogs, ErrBlacklistedHash
  970. }
  971. // Wait for the block's verification to complete
  972. bstart := time.Now()
  973. err := <-results
  974. if err == nil {
  975. err = bc.Validator().ValidateBody(block)
  976. }
  977. switch {
  978. case err == ErrKnownBlock:
  979. // Block and state both already known. However if the current block is below
  980. // this number we did a rollback and we should reimport it nonetheless.
  981. if bc.CurrentBlock().NumberU64() >= block.NumberU64() {
  982. stats.ignored++
  983. continue
  984. }
  985. case err == consensus.ErrFutureBlock:
  986. // Allow up to MaxFuture second in the future blocks. If this limit is exceeded
  987. // the chain is discarded and processed at a later time if given.
  988. max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
  989. if block.Time().Cmp(max) > 0 {
  990. return i, events, coalescedLogs, fmt.Errorf("future block: %v > %v", block.Time(), max)
  991. }
  992. bc.futureBlocks.Add(block.Hash(), block)
  993. stats.queued++
  994. continue
  995. case err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(block.ParentHash()):
  996. bc.futureBlocks.Add(block.Hash(), block)
  997. stats.queued++
  998. continue
  999. case err == consensus.ErrPrunedAncestor:
  1000. // Block competing with the canonical chain, store in the db, but don't process
  1001. // until the competitor TD goes above the canonical TD
  1002. currentBlock := bc.CurrentBlock()
  1003. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  1004. externTd := new(big.Int).Add(bc.GetTd(block.ParentHash(), block.NumberU64()-1), block.Difficulty())
  1005. if localTd.Cmp(externTd) > 0 {
  1006. if err = bc.WriteBlockWithoutState(block, externTd); err != nil {
  1007. return i, events, coalescedLogs, err
  1008. }
  1009. continue
  1010. }
  1011. // Competitor chain beat canonical, gather all blocks from the common ancestor
  1012. var winner []*types.Block
  1013. parent := bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  1014. for !bc.HasState(parent.Root()) {
  1015. winner = append(winner, parent)
  1016. parent = bc.GetBlock(parent.ParentHash(), parent.NumberU64()-1)
  1017. }
  1018. for j := 0; j < len(winner)/2; j++ {
  1019. winner[j], winner[len(winner)-1-j] = winner[len(winner)-1-j], winner[j]
  1020. }
  1021. // Import all the pruned blocks to make the state available
  1022. bc.chainmu.Unlock()
  1023. _, evs, logs, err := bc.insertChain(winner)
  1024. bc.chainmu.Lock()
  1025. events, coalescedLogs = evs, logs
  1026. if err != nil {
  1027. return i, events, coalescedLogs, err
  1028. }
  1029. case err != nil:
  1030. bc.reportBlock(block, nil, err)
  1031. return i, events, coalescedLogs, err
  1032. }
  1033. // Create a new statedb using the parent block and report an
  1034. // error if it fails.
  1035. var parent *types.Block
  1036. if i == 0 {
  1037. parent = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  1038. } else {
  1039. parent = chain[i-1]
  1040. }
  1041. state, err := state.New(parent.Root(), bc.stateCache)
  1042. if err != nil {
  1043. return i, events, coalescedLogs, err
  1044. }
  1045. // Process block using the parent state as reference point.
  1046. receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
  1047. if err != nil {
  1048. bc.reportBlock(block, receipts, err)
  1049. return i, events, coalescedLogs, err
  1050. }
  1051. // Validate the state using the default validator
  1052. err = bc.Validator().ValidateState(block, parent, state, receipts, usedGas)
  1053. if err != nil {
  1054. bc.reportBlock(block, receipts, err)
  1055. return i, events, coalescedLogs, err
  1056. }
  1057. proctime := time.Since(bstart)
  1058. // Write the block to the chain and get the status.
  1059. status, err := bc.WriteBlockWithState(block, receipts, state)
  1060. if err != nil {
  1061. return i, events, coalescedLogs, err
  1062. }
  1063. switch status {
  1064. case CanonStatTy:
  1065. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(), "uncles", len(block.Uncles()),
  1066. "txs", len(block.Transactions()), "gas", block.GasUsed(), "elapsed", common.PrettyDuration(time.Since(bstart)))
  1067. coalescedLogs = append(coalescedLogs, logs...)
  1068. blockInsertTimer.UpdateSince(bstart)
  1069. events = append(events, ChainEvent{block, block.Hash(), logs})
  1070. lastCanon = block
  1071. // Only count canonical blocks for GC processing time
  1072. bc.gcproc += proctime
  1073. case SideStatTy:
  1074. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(), "diff", block.Difficulty(), "elapsed",
  1075. common.PrettyDuration(time.Since(bstart)), "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()))
  1076. blockInsertTimer.UpdateSince(bstart)
  1077. events = append(events, ChainSideEvent{block})
  1078. }
  1079. stats.processed++
  1080. stats.usedGas += usedGas
  1081. cache, _ := bc.stateCache.TrieDB().Size()
  1082. stats.report(chain, i, cache)
  1083. }
  1084. // Append a single chain head event if we've progressed the chain
  1085. if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1086. events = append(events, ChainHeadEvent{lastCanon})
  1087. }
  1088. return 0, events, coalescedLogs, nil
  1089. }
  1090. // insertStats tracks and reports on block insertion.
  1091. type insertStats struct {
  1092. queued, processed, ignored int
  1093. usedGas uint64
  1094. lastIndex int
  1095. startTime mclock.AbsTime
  1096. }
  1097. // statsReportLimit is the time limit during import and export after which we
  1098. // always print out progress. This avoids the user wondering what's going on.
  1099. const statsReportLimit = 8 * time.Second
  1100. // report prints statistics if some number of blocks have been processed
  1101. // or more than a few seconds have passed since the last message.
  1102. func (st *insertStats) report(chain []*types.Block, index int, cache common.StorageSize) {
  1103. // Fetch the timings for the batch
  1104. var (
  1105. now = mclock.Now()
  1106. elapsed = time.Duration(now) - time.Duration(st.startTime)
  1107. )
  1108. // If we're at the last block of the batch or report period reached, log
  1109. if index == len(chain)-1 || elapsed >= statsReportLimit {
  1110. var (
  1111. end = chain[index]
  1112. txs = countTransactions(chain[st.lastIndex : index+1])
  1113. )
  1114. context := []interface{}{
  1115. "blocks", st.processed, "txs", txs, "mgas", float64(st.usedGas) / 1000000,
  1116. "elapsed", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed),
  1117. "number", end.Number(), "hash", end.Hash(),
  1118. }
  1119. if timestamp := time.Unix(end.Time().Int64(), 0); time.Since(timestamp) > time.Minute {
  1120. context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...)
  1121. }
  1122. context = append(context, []interface{}{"cache", cache}...)
  1123. if st.queued > 0 {
  1124. context = append(context, []interface{}{"queued", st.queued}...)
  1125. }
  1126. if st.ignored > 0 {
  1127. context = append(context, []interface{}{"ignored", st.ignored}...)
  1128. }
  1129. log.Info("Imported new chain segment", context...)
  1130. *st = insertStats{startTime: now, lastIndex: index + 1}
  1131. }
  1132. }
  1133. func countTransactions(chain []*types.Block) (c int) {
  1134. for _, b := range chain {
  1135. c += len(b.Transactions())
  1136. }
  1137. return c
  1138. }
  1139. // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  1140. // to be part of the new canonical chain and accumulates potential missing transactions and post an
  1141. // event about them
  1142. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1143. var (
  1144. newChain types.Blocks
  1145. oldChain types.Blocks
  1146. commonBlock *types.Block
  1147. deletedTxs types.Transactions
  1148. deletedLogs []*types.Log
  1149. // collectLogs collects the logs that were generated during the
  1150. // processing of the block that corresponds with the given hash.
  1151. // These logs are later announced as deleted.
  1152. collectLogs = func(hash common.Hash) {
  1153. // Coalesce logs and set 'Removed'.
  1154. number := bc.hc.GetBlockNumber(hash)
  1155. if number == nil {
  1156. return
  1157. }
  1158. receipts := rawdb.ReadReceipts(bc.db, hash, *number)
  1159. for _, receipt := range receipts {
  1160. for _, log := range receipt.Logs {
  1161. del := *log
  1162. del.Removed = true
  1163. deletedLogs = append(deletedLogs, &del)
  1164. }
  1165. }
  1166. }
  1167. )
  1168. // first reduce whoever is higher bound
  1169. if oldBlock.NumberU64() > newBlock.NumberU64() {
  1170. // reduce old chain
  1171. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  1172. oldChain = append(oldChain, oldBlock)
  1173. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1174. collectLogs(oldBlock.Hash())
  1175. }
  1176. } else {
  1177. // reduce new chain and append new chain blocks for inserting later on
  1178. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1179. newChain = append(newChain, newBlock)
  1180. }
  1181. }
  1182. if oldBlock == nil {
  1183. return fmt.Errorf("Invalid old chain")
  1184. }
  1185. if newBlock == nil {
  1186. return fmt.Errorf("Invalid new chain")
  1187. }
  1188. for {
  1189. if oldBlock.Hash() == newBlock.Hash() {
  1190. commonBlock = oldBlock
  1191. break
  1192. }
  1193. oldChain = append(oldChain, oldBlock)
  1194. newChain = append(newChain, newBlock)
  1195. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1196. collectLogs(oldBlock.Hash())
  1197. oldBlock, newBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1198. if oldBlock == nil {
  1199. return fmt.Errorf("Invalid old chain")
  1200. }
  1201. if newBlock == nil {
  1202. return fmt.Errorf("Invalid new chain")
  1203. }
  1204. }
  1205. // Ensure the user sees large reorgs
  1206. if len(oldChain) > 0 && len(newChain) > 0 {
  1207. logFn := log.Debug
  1208. if len(oldChain) > 63 {
  1209. logFn = log.Warn
  1210. }
  1211. logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1212. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1213. } else {
  1214. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1215. }
  1216. // Insert the new chain, taking care of the proper incremental order
  1217. var addedTxs types.Transactions
  1218. for i := len(newChain) - 1; i >= 0; i-- {
  1219. // insert the block in the canonical way, re-writing history
  1220. bc.insert(newChain[i])
  1221. // write lookup entries for hash based transaction/receipt searches
  1222. rawdb.WriteTxLookupEntries(bc.db, newChain[i])
  1223. addedTxs = append(addedTxs, newChain[i].Transactions()...)
  1224. }
  1225. // calculate the difference between deleted and added transactions
  1226. diff := types.TxDifference(deletedTxs, addedTxs)
  1227. // When transactions get deleted from the database that means the
  1228. // receipts that were created in the fork must also be deleted
  1229. batch := bc.db.NewBatch()
  1230. for _, tx := range diff {
  1231. rawdb.DeleteTxLookupEntry(batch, tx.Hash())
  1232. }
  1233. batch.Write()
  1234. if len(deletedLogs) > 0 {
  1235. go bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs})
  1236. }
  1237. if len(oldChain) > 0 {
  1238. go func() {
  1239. for _, block := range oldChain {
  1240. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1241. }
  1242. }()
  1243. }
  1244. return nil
  1245. }
  1246. // PostChainEvents iterates over the events generated by a chain insertion and
  1247. // posts them into the event feed.
  1248. // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.
  1249. func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) {
  1250. // post event logs for further processing
  1251. if logs != nil {
  1252. bc.logsFeed.Send(logs)
  1253. }
  1254. for _, event := range events {
  1255. switch ev := event.(type) {
  1256. case ChainEvent:
  1257. bc.chainFeed.Send(ev)
  1258. case ChainHeadEvent:
  1259. bc.chainHeadFeed.Send(ev)
  1260. case ChainSideEvent:
  1261. bc.chainSideFeed.Send(ev)
  1262. }
  1263. }
  1264. }
  1265. func (bc *BlockChain) update() {
  1266. futureTimer := time.NewTicker(5 * time.Second)
  1267. defer futureTimer.Stop()
  1268. for {
  1269. select {
  1270. case <-futureTimer.C:
  1271. bc.procFutureBlocks()
  1272. case <-bc.quit:
  1273. return
  1274. }
  1275. }
  1276. }
  1277. // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1278. func (bc *BlockChain) BadBlocks() []*types.Block {
  1279. blocks := make([]*types.Block, 0, bc.badBlocks.Len())
  1280. for _, hash := range bc.badBlocks.Keys() {
  1281. if blk, exist := bc.badBlocks.Peek(hash); exist {
  1282. block := blk.(*types.Block)
  1283. blocks = append(blocks, block)
  1284. }
  1285. }
  1286. return blocks
  1287. }
  1288. // addBadBlock adds a bad block to the bad-block LRU cache
  1289. func (bc *BlockChain) addBadBlock(block *types.Block) {
  1290. bc.badBlocks.Add(block.Hash(), block)
  1291. }
  1292. // reportBlock logs a bad block error.
  1293. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1294. bc.addBadBlock(block)
  1295. var receiptString string
  1296. for _, receipt := range receipts {
  1297. receiptString += fmt.Sprintf("\t%v\n", receipt)
  1298. }
  1299. log.Error(fmt.Sprintf(`
  1300. ########## BAD BLOCK #########
  1301. Chain config: %v
  1302. Number: %v
  1303. Hash: 0x%x
  1304. %v
  1305. Error: %v
  1306. ##############################
  1307. `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  1308. }
  1309. // InsertHeaderChain attempts to insert the given header chain in to the local
  1310. // chain, possibly creating a reorg. If an error is returned, it will return the
  1311. // index number of the failing header as well an error describing what went wrong.
  1312. //
  1313. // The verify parameter can be used to fine tune whether nonce verification
  1314. // should be done or not. The reason behind the optional check is because some
  1315. // of the header retrieval mechanisms already need to verify nonces, as well as
  1316. // because nonces can be verified sparsely, not needing to check each.
  1317. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1318. start := time.Now()
  1319. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1320. return i, err
  1321. }
  1322. // Make sure only one thread manipulates the chain at once
  1323. bc.chainmu.Lock()
  1324. defer bc.chainmu.Unlock()
  1325. bc.wg.Add(1)
  1326. defer bc.wg.Done()
  1327. whFunc := func(header *types.Header) error {
  1328. bc.mu.Lock()
  1329. defer bc.mu.Unlock()
  1330. _, err := bc.hc.WriteHeader(header)
  1331. return err
  1332. }
  1333. return bc.hc.InsertHeaderChain(chain, whFunc, start)
  1334. }
  1335. // writeHeader writes a header into the local chain, given that its parent is
  1336. // already known. If the total difficulty of the newly inserted header becomes
  1337. // greater than the current known TD, the canonical chain is re-routed.
  1338. //
  1339. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  1340. // into the chain, as side effects caused by reorganisations cannot be emulated
  1341. // without the real blocks. Hence, writing headers directly should only be done
  1342. // in two scenarios: pure-header mode of operation (light clients), or properly
  1343. // separated header/block phases (non-archive clients).
  1344. func (bc *BlockChain) writeHeader(header *types.Header) error {
  1345. bc.wg.Add(1)
  1346. defer bc.wg.Done()
  1347. bc.mu.Lock()
  1348. defer bc.mu.Unlock()
  1349. _, err := bc.hc.WriteHeader(header)
  1350. return err
  1351. }
  1352. // CurrentHeader retrieves the current head header of the canonical chain. The
  1353. // header is retrieved from the HeaderChain's internal cache.
  1354. func (bc *BlockChain) CurrentHeader() *types.Header {
  1355. return bc.hc.CurrentHeader()
  1356. }
  1357. // GetTd retrieves a block's total difficulty in the canonical chain from the
  1358. // database by hash and number, caching it if found.
  1359. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1360. return bc.hc.GetTd(hash, number)
  1361. }
  1362. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1363. // database by hash, caching it if found.
  1364. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1365. return bc.hc.GetTdByHash(hash)
  1366. }
  1367. // GetHeader retrieves a block header from the database by hash and number,
  1368. // caching it if found.
  1369. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1370. return bc.hc.GetHeader(hash, number)
  1371. }
  1372. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1373. // found.
  1374. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1375. return bc.hc.GetHeaderByHash(hash)
  1376. }
  1377. // HasHeader checks if a block header is present in the database or not, caching
  1378. // it if present.
  1379. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  1380. return bc.hc.HasHeader(hash, number)
  1381. }
  1382. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1383. // hash, fetching towards the genesis block.
  1384. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1385. return bc.hc.GetBlockHashesFromHash(hash, max)
  1386. }
  1387. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  1388. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  1389. // number of blocks to be individually checked before we reach the canonical chain.
  1390. //
  1391. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  1392. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  1393. bc.chainmu.Lock()
  1394. defer bc.chainmu.Unlock()
  1395. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  1396. }
  1397. // GetHeaderByNumber retrieves a block header from the database by number,
  1398. // caching it (associated with its hash) if found.
  1399. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1400. return bc.hc.GetHeaderByNumber(number)
  1401. }
  1402. // Config retrieves the blockchain's chain configuration.
  1403. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  1404. // Engine retrieves the blockchain's consensus engine.
  1405. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  1406. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  1407. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  1408. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  1409. }
  1410. // SubscribeChainEvent registers a subscription of ChainEvent.
  1411. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  1412. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  1413. }
  1414. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  1415. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  1416. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  1417. }
  1418. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  1419. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  1420. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  1421. }
  1422. // SubscribeLogsEvent registers a subscription of []*types.Log.
  1423. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  1424. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  1425. }