blockchain.go 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072
  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/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. accountReadTimer = metrics.NewRegisteredTimer("chain/account/reads", nil)
  46. accountHashTimer = metrics.NewRegisteredTimer("chain/account/hashes", nil)
  47. accountUpdateTimer = metrics.NewRegisteredTimer("chain/account/updates", nil)
  48. accountCommitTimer = metrics.NewRegisteredTimer("chain/account/commits", nil)
  49. storageReadTimer = metrics.NewRegisteredTimer("chain/storage/reads", nil)
  50. storageHashTimer = metrics.NewRegisteredTimer("chain/storage/hashes", nil)
  51. storageUpdateTimer = metrics.NewRegisteredTimer("chain/storage/updates", nil)
  52. storageCommitTimer = metrics.NewRegisteredTimer("chain/storage/commits", nil)
  53. blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil)
  54. blockValidationTimer = metrics.NewRegisteredTimer("chain/validation", nil)
  55. blockExecutionTimer = metrics.NewRegisteredTimer("chain/execution", nil)
  56. blockWriteTimer = metrics.NewRegisteredTimer("chain/write", nil)
  57. blockPrefetchExecuteTimer = metrics.NewRegisteredTimer("chain/prefetch/executes", nil)
  58. blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil)
  59. errInsertionInterrupted = errors.New("insertion is interrupted")
  60. )
  61. const (
  62. bodyCacheLimit = 256
  63. blockCacheLimit = 256
  64. receiptsCacheLimit = 32
  65. maxFutureBlocks = 256
  66. maxTimeFutureBlocks = 30
  67. badBlockLimit = 10
  68. triesInMemory = 128
  69. // BlockChainVersion ensures that an incompatible database forces a resync from scratch.
  70. //
  71. // Changelog:
  72. //
  73. // - Version 4
  74. // The following incompatible database changes were added:
  75. // * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted
  76. // * the `Bloom` field of receipt is deleted
  77. // * the `BlockIndex` and `TxIndex` fields of txlookup are deleted
  78. // - Version 5
  79. // The following incompatible database changes were added:
  80. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are no longer stored for a receipt
  81. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are computed by looking up the
  82. // receipts' corresponding block
  83. // - Version 6
  84. // The following incompatible database changes were added:
  85. // * Transaction lookup information stores the corresponding block number instead of block hash
  86. BlockChainVersion uint64 = 6
  87. )
  88. // CacheConfig contains the configuration values for the trie caching/pruning
  89. // that's resident in a blockchain.
  90. type CacheConfig struct {
  91. TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
  92. TrieCleanNoPrefetch bool // Whether to disable heuristic state prefetching for followup blocks
  93. TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk
  94. TrieDirtyDisabled bool // Whether to disable trie write caching and GC altogether (archive node)
  95. TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
  96. }
  97. // BlockChain represents the canonical chain given a database with a genesis
  98. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  99. //
  100. // Importing blocks in to the block chain happens according to the set of rules
  101. // defined by the two stage Validator. Processing of blocks is done using the
  102. // Processor which processes the included transaction. The validation of the state
  103. // is done in the second part of the Validator. Failing results in aborting of
  104. // the import.
  105. //
  106. // The BlockChain also helps in returning blocks from **any** chain included
  107. // in the database as well as blocks that represents the canonical chain. It's
  108. // important to note that GetBlock can return any block and does not need to be
  109. // included in the canonical one where as GetBlockByNumber always represents the
  110. // canonical chain.
  111. type BlockChain struct {
  112. chainConfig *params.ChainConfig // Chain & network configuration
  113. cacheConfig *CacheConfig // Cache configuration for pruning
  114. db ethdb.Database // Low level persistent database to store final content in
  115. triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
  116. gcproc time.Duration // Accumulates canonical block processing for trie dumping
  117. hc *HeaderChain
  118. rmLogsFeed event.Feed
  119. chainFeed event.Feed
  120. chainSideFeed event.Feed
  121. chainHeadFeed event.Feed
  122. logsFeed event.Feed
  123. blockProcFeed event.Feed
  124. scope event.SubscriptionScope
  125. genesisBlock *types.Block
  126. chainmu sync.RWMutex // blockchain insertion lock
  127. currentBlock atomic.Value // Current head of the block chain
  128. currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
  129. stateCache state.Database // State database to reuse between imports (contains state cache)
  130. bodyCache *lru.Cache // Cache for the most recent block bodies
  131. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  132. receiptsCache *lru.Cache // Cache for the most recent receipts per block
  133. blockCache *lru.Cache // Cache for the most recent entire blocks
  134. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  135. quit chan struct{} // blockchain quit channel
  136. running int32 // running must be called atomically
  137. // procInterrupt must be atomically called
  138. procInterrupt int32 // interrupt signaler for block processing
  139. wg sync.WaitGroup // chain processing wait group for shutting down
  140. engine consensus.Engine
  141. validator Validator // Block and state validator interface
  142. prefetcher Prefetcher // Block state prefetcher interface
  143. processor Processor // Block transaction processor interface
  144. vmConfig vm.Config
  145. badBlocks *lru.Cache // Bad block cache
  146. shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
  147. terminateInsert func(common.Hash, uint64) bool // Testing hook used to terminate ancient receipt chain insertion.
  148. }
  149. // NewBlockChain returns a fully initialised block chain using information
  150. // available in the database. It initialises the default Ethereum Validator and
  151. // Processor.
  152. func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool) (*BlockChain, error) {
  153. if cacheConfig == nil {
  154. cacheConfig = &CacheConfig{
  155. TrieCleanLimit: 256,
  156. TrieDirtyLimit: 256,
  157. TrieTimeLimit: 5 * time.Minute,
  158. }
  159. }
  160. bodyCache, _ := lru.New(bodyCacheLimit)
  161. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  162. receiptsCache, _ := lru.New(receiptsCacheLimit)
  163. blockCache, _ := lru.New(blockCacheLimit)
  164. futureBlocks, _ := lru.New(maxFutureBlocks)
  165. badBlocks, _ := lru.New(badBlockLimit)
  166. bc := &BlockChain{
  167. chainConfig: chainConfig,
  168. cacheConfig: cacheConfig,
  169. db: db,
  170. triegc: prque.New(nil),
  171. stateCache: state.NewDatabaseWithCache(db, cacheConfig.TrieCleanLimit),
  172. quit: make(chan struct{}),
  173. shouldPreserve: shouldPreserve,
  174. bodyCache: bodyCache,
  175. bodyRLPCache: bodyRLPCache,
  176. receiptsCache: receiptsCache,
  177. blockCache: blockCache,
  178. futureBlocks: futureBlocks,
  179. engine: engine,
  180. vmConfig: vmConfig,
  181. badBlocks: badBlocks,
  182. }
  183. bc.validator = NewBlockValidator(chainConfig, bc, engine)
  184. bc.prefetcher = newStatePrefetcher(chainConfig, bc, engine)
  185. bc.processor = NewStateProcessor(chainConfig, bc, engine)
  186. var err error
  187. bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.getProcInterrupt)
  188. if err != nil {
  189. return nil, err
  190. }
  191. bc.genesisBlock = bc.GetBlockByNumber(0)
  192. if bc.genesisBlock == nil {
  193. return nil, ErrNoGenesis
  194. }
  195. if err := bc.loadLastState(); err != nil {
  196. return nil, err
  197. }
  198. if frozen, err := bc.db.Ancients(); err == nil && frozen >= 1 {
  199. var (
  200. needRewind bool
  201. low uint64
  202. )
  203. // The head full block may be rolled back to a very low height due to
  204. // blockchain repair. If the head full block is even lower than the ancient
  205. // chain, truncate the ancient store.
  206. fullBlock := bc.CurrentBlock()
  207. if fullBlock != nil && fullBlock != bc.genesisBlock && fullBlock.NumberU64() < frozen-1 {
  208. needRewind = true
  209. low = fullBlock.NumberU64()
  210. }
  211. // In fast sync, it may happen that ancient data has been written to the
  212. // ancient store, but the LastFastBlock has not been updated, truncate the
  213. // extra data here.
  214. fastBlock := bc.CurrentFastBlock()
  215. if fastBlock != nil && fastBlock.NumberU64() < frozen-1 {
  216. needRewind = true
  217. if fastBlock.NumberU64() < low || low == 0 {
  218. low = fastBlock.NumberU64()
  219. }
  220. }
  221. if needRewind {
  222. var hashes []common.Hash
  223. previous := bc.CurrentHeader().Number.Uint64()
  224. for i := low + 1; i <= bc.CurrentHeader().Number.Uint64(); i++ {
  225. hashes = append(hashes, rawdb.ReadCanonicalHash(bc.db, i))
  226. }
  227. bc.Rollback(hashes)
  228. log.Warn("Truncate ancient chain", "from", previous, "to", low)
  229. }
  230. }
  231. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  232. for hash := range BadHashes {
  233. if header := bc.GetHeaderByHash(hash); header != nil {
  234. // get the canonical block corresponding to the offending header's number
  235. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  236. // make sure the headerByNumber (if present) is in our current canonical chain
  237. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  238. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  239. bc.SetHead(header.Number.Uint64() - 1)
  240. log.Error("Chain rewind was successful, resuming normal operation")
  241. }
  242. }
  243. }
  244. // Take ownership of this particular state
  245. go bc.update()
  246. return bc, nil
  247. }
  248. func (bc *BlockChain) getProcInterrupt() bool {
  249. return atomic.LoadInt32(&bc.procInterrupt) == 1
  250. }
  251. // GetVMConfig returns the block chain VM config.
  252. func (bc *BlockChain) GetVMConfig() *vm.Config {
  253. return &bc.vmConfig
  254. }
  255. // loadLastState loads the last known chain state from the database. This method
  256. // assumes that the chain manager mutex is held.
  257. func (bc *BlockChain) loadLastState() error {
  258. // Restore the last known head block
  259. head := rawdb.ReadHeadBlockHash(bc.db)
  260. if head == (common.Hash{}) {
  261. // Corrupt or empty database, init from scratch
  262. log.Warn("Empty database, resetting chain")
  263. return bc.Reset()
  264. }
  265. // Make sure the entire head block is available
  266. currentBlock := bc.GetBlockByHash(head)
  267. if currentBlock == nil {
  268. // Corrupt or empty database, init from scratch
  269. log.Warn("Head block missing, resetting chain", "hash", head)
  270. return bc.Reset()
  271. }
  272. // Make sure the state associated with the block is available
  273. if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
  274. // Dangling block without a state associated, init from scratch
  275. log.Warn("Head state missing, repairing chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
  276. if err := bc.repair(&currentBlock); err != nil {
  277. return err
  278. }
  279. rawdb.WriteHeadBlockHash(bc.db, currentBlock.Hash())
  280. }
  281. // Everything seems to be fine, set as the head block
  282. bc.currentBlock.Store(currentBlock)
  283. // Restore the last known head header
  284. currentHeader := currentBlock.Header()
  285. if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
  286. if header := bc.GetHeaderByHash(head); header != nil {
  287. currentHeader = header
  288. }
  289. }
  290. bc.hc.SetCurrentHeader(currentHeader)
  291. // Restore the last known head fast block
  292. bc.currentFastBlock.Store(currentBlock)
  293. if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
  294. if block := bc.GetBlockByHash(head); block != nil {
  295. bc.currentFastBlock.Store(block)
  296. }
  297. }
  298. // Issue a status log for the user
  299. currentFastBlock := bc.CurrentFastBlock()
  300. headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  301. blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  302. fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
  303. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time), 0)))
  304. log.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(int64(currentBlock.Time()), 0)))
  305. log.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(int64(currentFastBlock.Time()), 0)))
  306. return nil
  307. }
  308. // SetHead rewinds the local chain to a new head. In the case of headers, everything
  309. // above the new head will be deleted and the new one set. In the case of blocks
  310. // though, the head may be further rewound if block bodies are missing (non-archive
  311. // nodes after a fast sync).
  312. func (bc *BlockChain) SetHead(head uint64) error {
  313. log.Warn("Rewinding blockchain", "target", head)
  314. bc.chainmu.Lock()
  315. defer bc.chainmu.Unlock()
  316. updateFn := func(db ethdb.KeyValueWriter, header *types.Header) {
  317. // Rewind the block chain, ensuring we don't end up with a stateless head block
  318. if currentBlock := bc.CurrentBlock(); currentBlock != nil && header.Number.Uint64() < currentBlock.NumberU64() {
  319. newHeadBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  320. if newHeadBlock == nil {
  321. newHeadBlock = bc.genesisBlock
  322. } else {
  323. if _, err := state.New(newHeadBlock.Root(), bc.stateCache); err != nil {
  324. // Rewound state missing, rolled back to before pivot, reset to genesis
  325. newHeadBlock = bc.genesisBlock
  326. }
  327. }
  328. rawdb.WriteHeadBlockHash(db, newHeadBlock.Hash())
  329. bc.currentBlock.Store(newHeadBlock)
  330. }
  331. // Rewind the fast block in a simpleton way to the target head
  332. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && header.Number.Uint64() < currentFastBlock.NumberU64() {
  333. newHeadFastBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  334. // If either blocks reached nil, reset to the genesis state
  335. if newHeadFastBlock == nil {
  336. newHeadFastBlock = bc.genesisBlock
  337. }
  338. rawdb.WriteHeadFastBlockHash(db, newHeadFastBlock.Hash())
  339. bc.currentFastBlock.Store(newHeadFastBlock)
  340. }
  341. }
  342. // Rewind the header chain, deleting all block bodies until then
  343. delFn := func(db ethdb.KeyValueWriter, hash common.Hash, num uint64) {
  344. // Ignore the error here since light client won't hit this path
  345. frozen, _ := bc.db.Ancients()
  346. if num+1 <= frozen {
  347. // Truncate all relative data(header, total difficulty, body, receipt
  348. // and canonical hash) from ancient store.
  349. bc.db.TruncateAncients(num + 1)
  350. // Remove the hash <-> number mapping from the active store.
  351. rawdb.DeleteHeaderNumber(db, hash)
  352. } else {
  353. // Remove relative body and receipts from the active store.
  354. // The header, total difficulty and canonical hash will be
  355. // removed in the hc.SetHead function.
  356. rawdb.DeleteBody(db, hash, num)
  357. rawdb.DeleteReceipts(db, hash, num)
  358. }
  359. // Todo(rjl493456442) txlookup, bloombits, etc
  360. }
  361. bc.hc.SetHead(head, updateFn, delFn)
  362. // Clear out any stale content from the caches
  363. bc.bodyCache.Purge()
  364. bc.bodyRLPCache.Purge()
  365. bc.receiptsCache.Purge()
  366. bc.blockCache.Purge()
  367. bc.futureBlocks.Purge()
  368. return bc.loadLastState()
  369. }
  370. // FastSyncCommitHead sets the current head block to the one defined by the hash
  371. // irrelevant what the chain contents were prior.
  372. func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  373. // Make sure that both the block as well at its state trie exists
  374. block := bc.GetBlockByHash(hash)
  375. if block == nil {
  376. return fmt.Errorf("non existent block [%x…]", hash[:4])
  377. }
  378. if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB()); err != nil {
  379. return err
  380. }
  381. // If all checks out, manually set the head block
  382. bc.chainmu.Lock()
  383. bc.currentBlock.Store(block)
  384. bc.chainmu.Unlock()
  385. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  386. return nil
  387. }
  388. // GasLimit returns the gas limit of the current HEAD block.
  389. func (bc *BlockChain) GasLimit() uint64 {
  390. return bc.CurrentBlock().GasLimit()
  391. }
  392. // CurrentBlock retrieves the current head block of the canonical chain. The
  393. // block is retrieved from the blockchain's internal cache.
  394. func (bc *BlockChain) CurrentBlock() *types.Block {
  395. return bc.currentBlock.Load().(*types.Block)
  396. }
  397. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  398. // chain. The block is retrieved from the blockchain's internal cache.
  399. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  400. return bc.currentFastBlock.Load().(*types.Block)
  401. }
  402. // Validator returns the current validator.
  403. func (bc *BlockChain) Validator() Validator {
  404. return bc.validator
  405. }
  406. // Processor returns the current processor.
  407. func (bc *BlockChain) Processor() Processor {
  408. return bc.processor
  409. }
  410. // State returns a new mutable state based on the current HEAD block.
  411. func (bc *BlockChain) State() (*state.StateDB, error) {
  412. return bc.StateAt(bc.CurrentBlock().Root())
  413. }
  414. // StateAt returns a new mutable state based on a particular point in time.
  415. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  416. return state.New(root, bc.stateCache)
  417. }
  418. // StateCache returns the caching database underpinning the blockchain instance.
  419. func (bc *BlockChain) StateCache() state.Database {
  420. return bc.stateCache
  421. }
  422. // Reset purges the entire blockchain, restoring it to its genesis state.
  423. func (bc *BlockChain) Reset() error {
  424. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  425. }
  426. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  427. // specified genesis state.
  428. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  429. // Dump the entire block chain and purge the caches
  430. if err := bc.SetHead(0); err != nil {
  431. return err
  432. }
  433. bc.chainmu.Lock()
  434. defer bc.chainmu.Unlock()
  435. // Prepare the genesis block and reinitialise the chain
  436. if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  437. log.Crit("Failed to write genesis block TD", "err", err)
  438. }
  439. rawdb.WriteBlock(bc.db, genesis)
  440. bc.genesisBlock = genesis
  441. bc.insert(bc.genesisBlock)
  442. bc.currentBlock.Store(bc.genesisBlock)
  443. bc.hc.SetGenesis(bc.genesisBlock.Header())
  444. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  445. bc.currentFastBlock.Store(bc.genesisBlock)
  446. return nil
  447. }
  448. // repair tries to repair the current blockchain by rolling back the current block
  449. // until one with associated state is found. This is needed to fix incomplete db
  450. // writes caused either by crashes/power outages, or simply non-committed tries.
  451. //
  452. // This method only rolls back the current block. The current header and current
  453. // fast block are left intact.
  454. func (bc *BlockChain) repair(head **types.Block) error {
  455. for {
  456. // Abort if we've rewound to a head block that does have associated state
  457. if _, err := state.New((*head).Root(), bc.stateCache); err == nil {
  458. log.Info("Rewound blockchain to past state", "number", (*head).Number(), "hash", (*head).Hash())
  459. return nil
  460. }
  461. // Otherwise rewind one block and recheck state availability there
  462. block := bc.GetBlock((*head).ParentHash(), (*head).NumberU64()-1)
  463. if block == nil {
  464. return fmt.Errorf("missing block %d [%x]", (*head).NumberU64()-1, (*head).ParentHash())
  465. }
  466. *head = block
  467. }
  468. }
  469. // Export writes the active chain to the given writer.
  470. func (bc *BlockChain) Export(w io.Writer) error {
  471. return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64())
  472. }
  473. // ExportN writes a subset of the active chain to the given writer.
  474. func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  475. bc.chainmu.RLock()
  476. defer bc.chainmu.RUnlock()
  477. if first > last {
  478. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  479. }
  480. log.Info("Exporting batch of blocks", "count", last-first+1)
  481. start, reported := time.Now(), time.Now()
  482. for nr := first; nr <= last; nr++ {
  483. block := bc.GetBlockByNumber(nr)
  484. if block == nil {
  485. return fmt.Errorf("export failed on #%d: not found", nr)
  486. }
  487. if err := block.EncodeRLP(w); err != nil {
  488. return err
  489. }
  490. if time.Since(reported) >= statsReportLimit {
  491. log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
  492. reported = time.Now()
  493. }
  494. }
  495. return nil
  496. }
  497. // insert injects a new head block into the current block chain. This method
  498. // assumes that the block is indeed a true head. It will also reset the head
  499. // header and the head fast sync block to this very same block if they are older
  500. // or if they are on a different side chain.
  501. //
  502. // Note, this function assumes that the `mu` mutex is held!
  503. func (bc *BlockChain) insert(block *types.Block) {
  504. // If the block is on a side chain or an unknown one, force other heads onto it too
  505. updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()
  506. // Add the block to the canonical chain number scheme and mark as the head
  507. rawdb.WriteCanonicalHash(bc.db, block.Hash(), block.NumberU64())
  508. rawdb.WriteHeadBlockHash(bc.db, block.Hash())
  509. bc.currentBlock.Store(block)
  510. // If the block is better than our head or is on a different chain, force update heads
  511. if updateHeads {
  512. bc.hc.SetCurrentHeader(block.Header())
  513. rawdb.WriteHeadFastBlockHash(bc.db, block.Hash())
  514. bc.currentFastBlock.Store(block)
  515. }
  516. }
  517. // Genesis retrieves the chain's genesis block.
  518. func (bc *BlockChain) Genesis() *types.Block {
  519. return bc.genesisBlock
  520. }
  521. // GetBody retrieves a block body (transactions and uncles) from the database by
  522. // hash, caching it if found.
  523. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  524. // Short circuit if the body's already in the cache, retrieve otherwise
  525. if cached, ok := bc.bodyCache.Get(hash); ok {
  526. body := cached.(*types.Body)
  527. return body
  528. }
  529. number := bc.hc.GetBlockNumber(hash)
  530. if number == nil {
  531. return nil
  532. }
  533. body := rawdb.ReadBody(bc.db, hash, *number)
  534. if body == nil {
  535. return nil
  536. }
  537. // Cache the found body for next time and return
  538. bc.bodyCache.Add(hash, body)
  539. return body
  540. }
  541. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  542. // caching it if found.
  543. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  544. // Short circuit if the body's already in the cache, retrieve otherwise
  545. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  546. return cached.(rlp.RawValue)
  547. }
  548. number := bc.hc.GetBlockNumber(hash)
  549. if number == nil {
  550. return nil
  551. }
  552. body := rawdb.ReadBodyRLP(bc.db, hash, *number)
  553. if len(body) == 0 {
  554. return nil
  555. }
  556. // Cache the found body for next time and return
  557. bc.bodyRLPCache.Add(hash, body)
  558. return body
  559. }
  560. // HasBlock checks if a block is fully present in the database or not.
  561. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  562. if bc.blockCache.Contains(hash) {
  563. return true
  564. }
  565. return rawdb.HasBody(bc.db, hash, number)
  566. }
  567. // HasFastBlock checks if a fast block is fully present in the database or not.
  568. func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool {
  569. if !bc.HasBlock(hash, number) {
  570. return false
  571. }
  572. if bc.receiptsCache.Contains(hash) {
  573. return true
  574. }
  575. return rawdb.HasReceipts(bc.db, hash, number)
  576. }
  577. // HasState checks if state trie is fully present in the database or not.
  578. func (bc *BlockChain) HasState(hash common.Hash) bool {
  579. _, err := bc.stateCache.OpenTrie(hash)
  580. return err == nil
  581. }
  582. // HasBlockAndState checks if a block and associated state trie is fully present
  583. // in the database or not, caching it if present.
  584. func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
  585. // Check first that the block itself is known
  586. block := bc.GetBlock(hash, number)
  587. if block == nil {
  588. return false
  589. }
  590. return bc.HasState(block.Root())
  591. }
  592. // GetBlock retrieves a block from the database by hash and number,
  593. // caching it if found.
  594. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  595. // Short circuit if the block's already in the cache, retrieve otherwise
  596. if block, ok := bc.blockCache.Get(hash); ok {
  597. return block.(*types.Block)
  598. }
  599. block := rawdb.ReadBlock(bc.db, hash, number)
  600. if block == nil {
  601. return nil
  602. }
  603. // Cache the found block for next time and return
  604. bc.blockCache.Add(block.Hash(), block)
  605. return block
  606. }
  607. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  608. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  609. number := bc.hc.GetBlockNumber(hash)
  610. if number == nil {
  611. return nil
  612. }
  613. return bc.GetBlock(hash, *number)
  614. }
  615. // GetBlockByNumber retrieves a block from the database by number, caching it
  616. // (associated with its hash) if found.
  617. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  618. hash := rawdb.ReadCanonicalHash(bc.db, number)
  619. if hash == (common.Hash{}) {
  620. return nil
  621. }
  622. return bc.GetBlock(hash, number)
  623. }
  624. // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
  625. func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
  626. if receipts, ok := bc.receiptsCache.Get(hash); ok {
  627. return receipts.(types.Receipts)
  628. }
  629. number := rawdb.ReadHeaderNumber(bc.db, hash)
  630. if number == nil {
  631. return nil
  632. }
  633. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  634. if receipts == nil {
  635. return nil
  636. }
  637. bc.receiptsCache.Add(hash, receipts)
  638. return receipts
  639. }
  640. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  641. // [deprecated by eth/62]
  642. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  643. number := bc.hc.GetBlockNumber(hash)
  644. if number == nil {
  645. return nil
  646. }
  647. for i := 0; i < n; i++ {
  648. block := bc.GetBlock(hash, *number)
  649. if block == nil {
  650. break
  651. }
  652. blocks = append(blocks, block)
  653. hash = block.ParentHash()
  654. *number--
  655. }
  656. return
  657. }
  658. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  659. // a specific distance is reached.
  660. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  661. uncles := []*types.Header{}
  662. for i := 0; block != nil && i < length; i++ {
  663. uncles = append(uncles, block.Uncles()...)
  664. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  665. }
  666. return uncles
  667. }
  668. // TrieNode retrieves a blob of data associated with a trie node (or code hash)
  669. // either from ephemeral in-memory cache, or from persistent storage.
  670. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  671. return bc.stateCache.TrieDB().Node(hash)
  672. }
  673. // Stop stops the blockchain service. If any imports are currently in progress
  674. // it will abort them using the procInterrupt.
  675. func (bc *BlockChain) Stop() {
  676. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  677. return
  678. }
  679. // Unsubscribe all subscriptions registered from blockchain
  680. bc.scope.Close()
  681. close(bc.quit)
  682. atomic.StoreInt32(&bc.procInterrupt, 1)
  683. bc.wg.Wait()
  684. // Ensure the state of a recent block is also stored to disk before exiting.
  685. // We're writing three different states to catch different restart scenarios:
  686. // - HEAD: So we don't need to reprocess any blocks in the general case
  687. // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle
  688. // - HEAD-127: So we have a hard limit on the number of blocks reexecuted
  689. if !bc.cacheConfig.TrieDirtyDisabled {
  690. triedb := bc.stateCache.TrieDB()
  691. for _, offset := range []uint64{0, 1, triesInMemory - 1} {
  692. if number := bc.CurrentBlock().NumberU64(); number > offset {
  693. recent := bc.GetBlockByNumber(number - offset)
  694. log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
  695. if err := triedb.Commit(recent.Root(), true); err != nil {
  696. log.Error("Failed to commit recent state trie", "err", err)
  697. }
  698. }
  699. }
  700. for !bc.triegc.Empty() {
  701. triedb.Dereference(bc.triegc.PopItem().(common.Hash))
  702. }
  703. if size, _ := triedb.Size(); size != 0 {
  704. log.Error("Dangling trie nodes after full cleanup")
  705. }
  706. }
  707. log.Info("Blockchain manager stopped")
  708. }
  709. func (bc *BlockChain) procFutureBlocks() {
  710. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  711. for _, hash := range bc.futureBlocks.Keys() {
  712. if block, exist := bc.futureBlocks.Peek(hash); exist {
  713. blocks = append(blocks, block.(*types.Block))
  714. }
  715. }
  716. if len(blocks) > 0 {
  717. types.BlockBy(types.Number).Sort(blocks)
  718. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  719. for i := range blocks {
  720. bc.InsertChain(blocks[i : i+1])
  721. }
  722. }
  723. }
  724. // WriteStatus status of write
  725. type WriteStatus byte
  726. const (
  727. NonStatTy WriteStatus = iota
  728. CanonStatTy
  729. SideStatTy
  730. )
  731. // Rollback is designed to remove a chain of links from the database that aren't
  732. // certain enough to be valid.
  733. func (bc *BlockChain) Rollback(chain []common.Hash) {
  734. bc.chainmu.Lock()
  735. defer bc.chainmu.Unlock()
  736. for i := len(chain) - 1; i >= 0; i-- {
  737. hash := chain[i]
  738. currentHeader := bc.hc.CurrentHeader()
  739. if currentHeader.Hash() == hash {
  740. bc.hc.SetCurrentHeader(bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
  741. }
  742. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock.Hash() == hash {
  743. newFastBlock := bc.GetBlock(currentFastBlock.ParentHash(), currentFastBlock.NumberU64()-1)
  744. rawdb.WriteHeadFastBlockHash(bc.db, newFastBlock.Hash())
  745. bc.currentFastBlock.Store(newFastBlock)
  746. }
  747. if currentBlock := bc.CurrentBlock(); currentBlock.Hash() == hash {
  748. newBlock := bc.GetBlock(currentBlock.ParentHash(), currentBlock.NumberU64()-1)
  749. rawdb.WriteHeadBlockHash(bc.db, newBlock.Hash())
  750. bc.currentBlock.Store(newBlock)
  751. }
  752. }
  753. // Truncate ancient data which exceeds the current header.
  754. //
  755. // Notably, it can happen that system crashes without truncating the ancient data
  756. // but the head indicator has been updated in the active store. Regarding this issue,
  757. // system will self recovery by truncating the extra data during the setup phase.
  758. if err := bc.truncateAncient(bc.hc.CurrentHeader().Number.Uint64()); err != nil {
  759. log.Crit("Truncate ancient store failed", "err", err)
  760. }
  761. }
  762. // truncateAncient rewinds the blockchain to the specified header and deletes all
  763. // data in the ancient store that exceeds the specified header.
  764. func (bc *BlockChain) truncateAncient(head uint64) error {
  765. frozen, err := bc.db.Ancients()
  766. if err != nil {
  767. return err
  768. }
  769. // Short circuit if there is no data to truncate in ancient store.
  770. if frozen <= head+1 {
  771. return nil
  772. }
  773. // Truncate all the data in the freezer beyond the specified head
  774. if err := bc.db.TruncateAncients(head + 1); err != nil {
  775. return err
  776. }
  777. // Clear out any stale content from the caches
  778. bc.hc.headerCache.Purge()
  779. bc.hc.tdCache.Purge()
  780. bc.hc.numberCache.Purge()
  781. // Clear out any stale content from the caches
  782. bc.bodyCache.Purge()
  783. bc.bodyRLPCache.Purge()
  784. bc.receiptsCache.Purge()
  785. bc.blockCache.Purge()
  786. bc.futureBlocks.Purge()
  787. log.Info("Rewind ancient data", "number", head)
  788. return nil
  789. }
  790. // InsertReceiptChain attempts to complete an already existing header chain with
  791. // transaction and receipt data.
  792. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts, ancientLimit uint64) (int, error) {
  793. bc.wg.Add(1)
  794. defer bc.wg.Done()
  795. var (
  796. ancientBlocks, liveBlocks types.Blocks
  797. ancientReceipts, liveReceipts []types.Receipts
  798. )
  799. // Do a sanity check that the provided chain is actually ordered and linked
  800. for i := 0; i < len(blockChain); i++ {
  801. if i != 0 {
  802. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  803. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  804. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  805. 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(),
  806. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  807. }
  808. }
  809. if blockChain[i].NumberU64() <= ancientLimit {
  810. ancientBlocks, ancientReceipts = append(ancientBlocks, blockChain[i]), append(ancientReceipts, receiptChain[i])
  811. } else {
  812. liveBlocks, liveReceipts = append(liveBlocks, blockChain[i]), append(liveReceipts, receiptChain[i])
  813. }
  814. }
  815. var (
  816. stats = struct{ processed, ignored int32 }{}
  817. start = time.Now()
  818. size = 0
  819. )
  820. // updateHead updates the head fast sync block if the inserted blocks are better
  821. // and returns a indicator whether the inserted blocks are canonical.
  822. updateHead := func(head *types.Block) bool {
  823. var isCanonical bool
  824. bc.chainmu.Lock()
  825. if td := bc.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case
  826. currentFastBlock := bc.CurrentFastBlock()
  827. if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
  828. rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
  829. bc.currentFastBlock.Store(head)
  830. isCanonical = true
  831. }
  832. }
  833. bc.chainmu.Unlock()
  834. return isCanonical
  835. }
  836. // writeAncient writes blockchain and corresponding receipt chain into ancient store.
  837. //
  838. // this function only accepts canonical chain data. All side chain will be reverted
  839. // eventually.
  840. writeAncient := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  841. var (
  842. previous = bc.CurrentFastBlock()
  843. batch = bc.db.NewBatch()
  844. )
  845. // If any error occurs before updating the head or we are inserting a side chain,
  846. // all the data written this time wll be rolled back.
  847. defer func() {
  848. if previous != nil {
  849. if err := bc.truncateAncient(previous.NumberU64()); err != nil {
  850. log.Crit("Truncate ancient store failed", "err", err)
  851. }
  852. }
  853. }()
  854. for i, block := range blockChain {
  855. // Short circuit insertion if shutting down or processing failed
  856. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  857. return 0, errInsertionInterrupted
  858. }
  859. // Short circuit insertion if it is required(used in testing only)
  860. if bc.terminateInsert != nil && bc.terminateInsert(block.Hash(), block.NumberU64()) {
  861. return i, errors.New("insertion is terminated for testing purpose")
  862. }
  863. // Short circuit if the owner header is unknown
  864. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  865. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  866. }
  867. // Compute all the non-consensus fields of the receipts
  868. if err := receiptChain[i].DeriveFields(bc.chainConfig, block.Hash(), block.NumberU64(), block.Transactions()); err != nil {
  869. return i, fmt.Errorf("failed to derive receipts data: %v", err)
  870. }
  871. // Initialize freezer with genesis block first
  872. if frozen, err := bc.db.Ancients(); err == nil && frozen == 0 && block.NumberU64() == 1 {
  873. genesisBlock := rawdb.ReadBlock(bc.db, rawdb.ReadCanonicalHash(bc.db, 0), 0)
  874. size += rawdb.WriteAncientBlock(bc.db, genesisBlock, nil, genesisBlock.Difficulty())
  875. }
  876. // Flush data into ancient store.
  877. size += rawdb.WriteAncientBlock(bc.db, block, receiptChain[i], bc.GetTd(block.Hash(), block.NumberU64()))
  878. rawdb.WriteTxLookupEntries(batch, block)
  879. stats.processed++
  880. }
  881. // Flush all tx-lookup index data.
  882. size += batch.ValueSize()
  883. if err := batch.Write(); err != nil {
  884. return 0, err
  885. }
  886. batch.Reset()
  887. // Sync the ancient store explicitly to ensure all data has been flushed to disk.
  888. if err := bc.db.Sync(); err != nil {
  889. return 0, err
  890. }
  891. if !updateHead(blockChain[len(blockChain)-1]) {
  892. return 0, errors.New("side blocks can't be accepted as the ancient chain data")
  893. }
  894. previous = nil // disable rollback explicitly
  895. // Remove the ancient data from the active store
  896. cleanGenesis := len(blockChain) > 0 && blockChain[0].NumberU64() == 1
  897. if cleanGenesis {
  898. // Migrate genesis block to ancient store too.
  899. rawdb.DeleteBlockWithoutNumber(batch, rawdb.ReadCanonicalHash(bc.db, 0), 0)
  900. rawdb.DeleteCanonicalHash(batch, 0)
  901. }
  902. // Wipe out canonical block data.
  903. for _, block := range blockChain {
  904. rawdb.DeleteBlockWithoutNumber(batch, block.Hash(), block.NumberU64())
  905. rawdb.DeleteCanonicalHash(batch, block.NumberU64())
  906. }
  907. if err := batch.Write(); err != nil {
  908. return 0, err
  909. }
  910. batch.Reset()
  911. // Wipe out side chain too.
  912. for _, block := range blockChain {
  913. for _, hash := range rawdb.ReadAllHashes(bc.db, block.NumberU64()) {
  914. rawdb.DeleteBlock(batch, hash, block.NumberU64())
  915. }
  916. }
  917. if err := batch.Write(); err != nil {
  918. return 0, err
  919. }
  920. return 0, nil
  921. }
  922. // writeLive writes blockchain and corresponding receipt chain into active store.
  923. writeLive := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  924. batch := bc.db.NewBatch()
  925. for i, block := range blockChain {
  926. // Short circuit insertion if shutting down or processing failed
  927. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  928. return 0, errInsertionInterrupted
  929. }
  930. // Short circuit if the owner header is unknown
  931. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  932. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  933. }
  934. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  935. stats.ignored++
  936. continue
  937. }
  938. // Compute all the non-consensus fields of the receipts
  939. if err := receiptChain[i].DeriveFields(bc.chainConfig, block.Hash(), block.NumberU64(), block.Transactions()); err != nil {
  940. return i, fmt.Errorf("failed to derive receipts data: %v", err)
  941. }
  942. // Write all the data out into the database
  943. rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
  944. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receiptChain[i])
  945. rawdb.WriteTxLookupEntries(batch, block)
  946. stats.processed++
  947. if batch.ValueSize() >= ethdb.IdealBatchSize {
  948. if err := batch.Write(); err != nil {
  949. return 0, err
  950. }
  951. size += batch.ValueSize()
  952. batch.Reset()
  953. }
  954. }
  955. if batch.ValueSize() > 0 {
  956. size += batch.ValueSize()
  957. if err := batch.Write(); err != nil {
  958. return 0, err
  959. }
  960. }
  961. updateHead(blockChain[len(blockChain)-1])
  962. return 0, nil
  963. }
  964. // Write downloaded chain data and corresponding receipt chain data.
  965. if len(ancientBlocks) > 0 {
  966. if n, err := writeAncient(ancientBlocks, ancientReceipts); err != nil {
  967. if err == errInsertionInterrupted {
  968. return 0, nil
  969. }
  970. return n, err
  971. }
  972. }
  973. if len(liveBlocks) > 0 {
  974. if n, err := writeLive(liveBlocks, liveReceipts); err != nil {
  975. if err == errInsertionInterrupted {
  976. return 0, nil
  977. }
  978. return n, err
  979. }
  980. }
  981. head := blockChain[len(blockChain)-1]
  982. context := []interface{}{
  983. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  984. "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(int64(head.Time()), 0)),
  985. "size", common.StorageSize(size),
  986. }
  987. if stats.ignored > 0 {
  988. context = append(context, []interface{}{"ignored", stats.ignored}...)
  989. }
  990. log.Info("Imported new block receipts", context...)
  991. return 0, nil
  992. }
  993. var lastWrite uint64
  994. // writeBlockWithoutState writes only the block and its metadata to the database,
  995. // but does not write any state. This is used to construct competing side forks
  996. // up to the point where they exceed the canonical total difficulty.
  997. func (bc *BlockChain) writeBlockWithoutState(block *types.Block, td *big.Int) (err error) {
  998. bc.wg.Add(1)
  999. defer bc.wg.Done()
  1000. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), td); err != nil {
  1001. return err
  1002. }
  1003. rawdb.WriteBlock(bc.db, block)
  1004. return nil
  1005. }
  1006. // writeKnownBlock updates the head block flag with a known block
  1007. // and introduces chain reorg if necessary.
  1008. func (bc *BlockChain) writeKnownBlock(block *types.Block) error {
  1009. bc.wg.Add(1)
  1010. defer bc.wg.Done()
  1011. current := bc.CurrentBlock()
  1012. if block.ParentHash() != current.Hash() {
  1013. if err := bc.reorg(current, block); err != nil {
  1014. return err
  1015. }
  1016. }
  1017. // Write the positional metadata for transaction/receipt lookups.
  1018. // Preimages here is empty, ignore it.
  1019. rawdb.WriteTxLookupEntries(bc.db, block)
  1020. bc.insert(block)
  1021. return nil
  1022. }
  1023. // WriteBlockWithState writes the block and all associated state to the database.
  1024. func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  1025. bc.chainmu.Lock()
  1026. defer bc.chainmu.Unlock()
  1027. return bc.writeBlockWithState(block, receipts, state)
  1028. }
  1029. // writeBlockWithState writes the block and all associated state to the database,
  1030. // but is expects the chain mutex to be held.
  1031. func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  1032. bc.wg.Add(1)
  1033. defer bc.wg.Done()
  1034. // Calculate the total difficulty of the block
  1035. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1036. if ptd == nil {
  1037. return NonStatTy, consensus.ErrUnknownAncestor
  1038. }
  1039. // Make sure no inconsistent state is leaked during insertion
  1040. currentBlock := bc.CurrentBlock()
  1041. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  1042. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  1043. // Irrelevant of the canonical status, write the block itself to the database
  1044. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
  1045. return NonStatTy, err
  1046. }
  1047. rawdb.WriteBlock(bc.db, block)
  1048. root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
  1049. if err != nil {
  1050. return NonStatTy, err
  1051. }
  1052. triedb := bc.stateCache.TrieDB()
  1053. // If we're running an archive node, always flush
  1054. if bc.cacheConfig.TrieDirtyDisabled {
  1055. if err := triedb.Commit(root, false); err != nil {
  1056. return NonStatTy, err
  1057. }
  1058. } else {
  1059. // Full but not archive node, do proper garbage collection
  1060. triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
  1061. bc.triegc.Push(root, -int64(block.NumberU64()))
  1062. if current := block.NumberU64(); current > triesInMemory {
  1063. // If we exceeded our memory allowance, flush matured singleton nodes to disk
  1064. var (
  1065. nodes, imgs = triedb.Size()
  1066. limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
  1067. )
  1068. if nodes > limit || imgs > 4*1024*1024 {
  1069. triedb.Cap(limit - ethdb.IdealBatchSize)
  1070. }
  1071. // Find the next state trie we need to commit
  1072. chosen := current - triesInMemory
  1073. // If we exceeded out time allowance, flush an entire trie to disk
  1074. if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
  1075. // If the header is missing (canonical chain behind), we're reorging a low
  1076. // diff sidechain. Suspend committing until this operation is completed.
  1077. header := bc.GetHeaderByNumber(chosen)
  1078. if header == nil {
  1079. log.Warn("Reorg in progress, trie commit postponed", "number", chosen)
  1080. } else {
  1081. // If we're exceeding limits but haven't reached a large enough memory gap,
  1082. // warn the user that the system is becoming unstable.
  1083. if chosen < lastWrite+triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
  1084. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/triesInMemory)
  1085. }
  1086. // Flush an entire trie and restart the counters
  1087. triedb.Commit(header.Root, true)
  1088. lastWrite = chosen
  1089. bc.gcproc = 0
  1090. }
  1091. }
  1092. // Garbage collect anything below our required write retention
  1093. for !bc.triegc.Empty() {
  1094. root, number := bc.triegc.Pop()
  1095. if uint64(-number) > chosen {
  1096. bc.triegc.Push(root, number)
  1097. break
  1098. }
  1099. triedb.Dereference(root.(common.Hash))
  1100. }
  1101. }
  1102. }
  1103. // Write other block data using a batch.
  1104. batch := bc.db.NewBatch()
  1105. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  1106. // If the total difficulty is higher than our known, add it to the canonical chain
  1107. // Second clause in the if statement reduces the vulnerability to selfish mining.
  1108. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  1109. reorg := externTd.Cmp(localTd) > 0
  1110. currentBlock = bc.CurrentBlock()
  1111. if !reorg && externTd.Cmp(localTd) == 0 {
  1112. // Split same-difficulty blocks by number, then preferentially select
  1113. // the block generated by the local miner as the canonical block.
  1114. if block.NumberU64() < currentBlock.NumberU64() {
  1115. reorg = true
  1116. } else if block.NumberU64() == currentBlock.NumberU64() {
  1117. var currentPreserve, blockPreserve bool
  1118. if bc.shouldPreserve != nil {
  1119. currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  1120. }
  1121. reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  1122. }
  1123. }
  1124. if reorg {
  1125. // Reorganise the chain if the parent is not the head block
  1126. if block.ParentHash() != currentBlock.Hash() {
  1127. if err := bc.reorg(currentBlock, block); err != nil {
  1128. return NonStatTy, err
  1129. }
  1130. }
  1131. // Write the positional metadata for transaction/receipt lookups and preimages
  1132. rawdb.WriteTxLookupEntries(batch, block)
  1133. rawdb.WritePreimages(batch, state.Preimages())
  1134. status = CanonStatTy
  1135. } else {
  1136. status = SideStatTy
  1137. }
  1138. if err := batch.Write(); err != nil {
  1139. return NonStatTy, err
  1140. }
  1141. // Set new head.
  1142. if status == CanonStatTy {
  1143. bc.insert(block)
  1144. }
  1145. bc.futureBlocks.Remove(block.Hash())
  1146. return status, nil
  1147. }
  1148. // addFutureBlock checks if the block is within the max allowed window to get
  1149. // accepted for future processing, and returns an error if the block is too far
  1150. // ahead and was not added.
  1151. func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  1152. max := uint64(time.Now().Unix() + maxTimeFutureBlocks)
  1153. if block.Time() > max {
  1154. return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  1155. }
  1156. bc.futureBlocks.Add(block.Hash(), block)
  1157. return nil
  1158. }
  1159. // InsertChain attempts to insert the given batch of blocks in to the canonical
  1160. // chain or, otherwise, create a fork. If an error is returned it will return
  1161. // the index number of the failing block as well an error describing what went
  1162. // wrong.
  1163. //
  1164. // After insertion is done, all accumulated events will be fired.
  1165. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  1166. // Sanity check that we have something meaningful to import
  1167. if len(chain) == 0 {
  1168. return 0, nil
  1169. }
  1170. bc.blockProcFeed.Send(true)
  1171. defer bc.blockProcFeed.Send(false)
  1172. // Remove already known canon-blocks
  1173. var (
  1174. block, prev *types.Block
  1175. )
  1176. // Do a sanity check that the provided chain is actually ordered and linked
  1177. for i := 1; i < len(chain); i++ {
  1178. block = chain[i]
  1179. prev = chain[i-1]
  1180. if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() {
  1181. // Chain broke ancestry, log a message (programming error) and skip insertion
  1182. log.Error("Non contiguous block insert", "number", block.Number(), "hash", block.Hash(),
  1183. "parent", block.ParentHash(), "prevnumber", prev.Number(), "prevhash", prev.Hash())
  1184. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, prev.NumberU64(),
  1185. prev.Hash().Bytes()[:4], i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4])
  1186. }
  1187. }
  1188. // Pre-checks passed, start the full block imports
  1189. bc.wg.Add(1)
  1190. bc.chainmu.Lock()
  1191. n, events, logs, err := bc.insertChain(chain, true)
  1192. bc.chainmu.Unlock()
  1193. bc.wg.Done()
  1194. bc.PostChainEvents(events, logs)
  1195. return n, err
  1196. }
  1197. // insertChain is the internal implementation of InsertChain, which assumes that
  1198. // 1) chains are contiguous, and 2) The chain mutex is held.
  1199. //
  1200. // This method is split out so that import batches that require re-injecting
  1201. // historical blocks can do so without releasing the lock, which could lead to
  1202. // racey behaviour. If a sidechain import is in progress, and the historic state
  1203. // is imported, but then new canon-head is added before the actual sidechain
  1204. // completes, then the historic state could be pruned again
  1205. func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []interface{}, []*types.Log, error) {
  1206. // If the chain is terminating, don't even bother starting up
  1207. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1208. return 0, nil, nil, nil
  1209. }
  1210. // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  1211. senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  1212. // A queued approach to delivering events. This is generally
  1213. // faster than direct delivery and requires much less mutex
  1214. // acquiring.
  1215. var (
  1216. stats = insertStats{startTime: mclock.Now()}
  1217. events = make([]interface{}, 0, len(chain))
  1218. lastCanon *types.Block
  1219. coalescedLogs []*types.Log
  1220. )
  1221. // Start the parallel header verifier
  1222. headers := make([]*types.Header, len(chain))
  1223. seals := make([]bool, len(chain))
  1224. for i, block := range chain {
  1225. headers[i] = block.Header()
  1226. seals[i] = verifySeals
  1227. }
  1228. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1229. defer close(abort)
  1230. // Peek the error for the first block to decide the directing import logic
  1231. it := newInsertIterator(chain, results, bc.validator)
  1232. block, err := it.next()
  1233. // Left-trim all the known blocks
  1234. if err == ErrKnownBlock {
  1235. // First block (and state) is known
  1236. // 1. We did a roll-back, and should now do a re-import
  1237. // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1238. // from the canonical chain, which has not been verified.
  1239. // Skip all known blocks that are behind us
  1240. var (
  1241. current = bc.CurrentBlock()
  1242. localTd = bc.GetTd(current.Hash(), current.NumberU64())
  1243. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1) // The first block can't be nil
  1244. )
  1245. for block != nil && err == ErrKnownBlock {
  1246. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1247. if localTd.Cmp(externTd) < 0 {
  1248. break
  1249. }
  1250. log.Debug("Ignoring already known block", "number", block.Number(), "hash", block.Hash())
  1251. stats.ignored++
  1252. block, err = it.next()
  1253. }
  1254. // The remaining blocks are still known blocks, the only scenario here is:
  1255. // During the fast sync, the pivot point is already submitted but rollback
  1256. // happens. Then node resets the head full block to a lower height via `rollback`
  1257. // and leaves a few known blocks in the database.
  1258. //
  1259. // When node runs a fast sync again, it can re-import a batch of known blocks via
  1260. // `insertChain` while a part of them have higher total difficulty than current
  1261. // head full block(new pivot point).
  1262. for block != nil && err == ErrKnownBlock {
  1263. log.Debug("Writing previously known block", "number", block.Number(), "hash", block.Hash())
  1264. if err := bc.writeKnownBlock(block); err != nil {
  1265. return it.index, nil, nil, err
  1266. }
  1267. lastCanon = block
  1268. block, err = it.next()
  1269. }
  1270. // Falls through to the block import
  1271. }
  1272. switch {
  1273. // First block is pruned, insert as sidechain and reorg only if TD grows enough
  1274. case err == consensus.ErrPrunedAncestor:
  1275. log.Debug("Pruned ancestor, inserting as sidechain", "number", block.Number(), "hash", block.Hash())
  1276. return bc.insertSideChain(block, it)
  1277. // First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1278. case err == consensus.ErrFutureBlock || (err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(it.first().ParentHash())):
  1279. for block != nil && (it.index == 0 || err == consensus.ErrUnknownAncestor) {
  1280. log.Debug("Future block, postponing import", "number", block.Number(), "hash", block.Hash())
  1281. if err := bc.addFutureBlock(block); err != nil {
  1282. return it.index, events, coalescedLogs, err
  1283. }
  1284. block, err = it.next()
  1285. }
  1286. stats.queued += it.processed()
  1287. stats.ignored += it.remaining()
  1288. // If there are any still remaining, mark as ignored
  1289. return it.index, events, coalescedLogs, err
  1290. // Some other error occurred, abort
  1291. case err != nil:
  1292. stats.ignored += len(it.chain)
  1293. bc.reportBlock(block, nil, err)
  1294. return it.index, events, coalescedLogs, err
  1295. }
  1296. // No validation errors for the first block (or chain prefix skipped)
  1297. for ; block != nil && err == nil || err == ErrKnownBlock; block, err = it.next() {
  1298. // If the chain is terminating, stop processing blocks
  1299. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1300. log.Debug("Premature abort during blocks processing")
  1301. break
  1302. }
  1303. // If the header is a banned one, straight out abort
  1304. if BadHashes[block.Hash()] {
  1305. bc.reportBlock(block, nil, ErrBlacklistedHash)
  1306. return it.index, events, coalescedLogs, ErrBlacklistedHash
  1307. }
  1308. // If the block is known (in the middle of the chain), it's a special case for
  1309. // Clique blocks where they can share state among each other, so importing an
  1310. // older block might complete the state of the subsequent one. In this case,
  1311. // just skip the block (we already validated it once fully (and crashed), since
  1312. // its header and body was already in the database).
  1313. if err == ErrKnownBlock {
  1314. logger := log.Debug
  1315. if bc.chainConfig.Clique == nil {
  1316. logger = log.Warn
  1317. }
  1318. logger("Inserted known block", "number", block.Number(), "hash", block.Hash(),
  1319. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1320. "root", block.Root())
  1321. if err := bc.writeKnownBlock(block); err != nil {
  1322. return it.index, nil, nil, err
  1323. }
  1324. stats.processed++
  1325. // We can assume that logs are empty here, since the only way for consecutive
  1326. // Clique blocks to have the same state is if there are no transactions.
  1327. events = append(events, ChainEvent{block, block.Hash(), nil})
  1328. lastCanon = block
  1329. continue
  1330. }
  1331. // Retrieve the parent block and it's state to execute on top
  1332. start := time.Now()
  1333. parent := it.previous()
  1334. if parent == nil {
  1335. parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
  1336. }
  1337. statedb, err := state.New(parent.Root, bc.stateCache)
  1338. if err != nil {
  1339. return it.index, events, coalescedLogs, err
  1340. }
  1341. // If we have a followup block, run that against the current state to pre-cache
  1342. // transactions and probabilistically some of the account/storage trie nodes.
  1343. var followupInterrupt uint32
  1344. if !bc.cacheConfig.TrieCleanNoPrefetch {
  1345. if followup, err := it.peek(); followup != nil && err == nil {
  1346. go func(start time.Time) {
  1347. throwaway, _ := state.New(parent.Root, bc.stateCache)
  1348. bc.prefetcher.Prefetch(followup, throwaway, bc.vmConfig, &followupInterrupt)
  1349. blockPrefetchExecuteTimer.Update(time.Since(start))
  1350. if atomic.LoadUint32(&followupInterrupt) == 1 {
  1351. blockPrefetchInterruptMeter.Mark(1)
  1352. }
  1353. }(time.Now())
  1354. }
  1355. }
  1356. // Process block using the parent state as reference point
  1357. substart := time.Now()
  1358. receipts, logs, usedGas, err := bc.processor.Process(block, statedb, bc.vmConfig)
  1359. if err != nil {
  1360. bc.reportBlock(block, receipts, err)
  1361. atomic.StoreUint32(&followupInterrupt, 1)
  1362. return it.index, events, coalescedLogs, err
  1363. }
  1364. // Update the metrics touched during block processing
  1365. accountReadTimer.Update(statedb.AccountReads) // Account reads are complete, we can mark them
  1366. storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete, we can mark them
  1367. accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete, we can mark them
  1368. storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them
  1369. triehash := statedb.AccountHashes + statedb.StorageHashes // Save to not double count in validation
  1370. trieproc := statedb.AccountReads + statedb.AccountUpdates
  1371. trieproc += statedb.StorageReads + statedb.StorageUpdates
  1372. blockExecutionTimer.Update(time.Since(substart) - trieproc - triehash)
  1373. // Validate the state using the default validator
  1374. substart = time.Now()
  1375. if err := bc.validator.ValidateState(block, statedb, receipts, usedGas); err != nil {
  1376. bc.reportBlock(block, receipts, err)
  1377. atomic.StoreUint32(&followupInterrupt, 1)
  1378. return it.index, events, coalescedLogs, err
  1379. }
  1380. proctime := time.Since(start)
  1381. // Update the metrics touched during block validation
  1382. accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete, we can mark them
  1383. storageHashTimer.Update(statedb.StorageHashes) // Storage hashes are complete, we can mark them
  1384. blockValidationTimer.Update(time.Since(substart) - (statedb.AccountHashes + statedb.StorageHashes - triehash))
  1385. // Write the block to the chain and get the status.
  1386. substart = time.Now()
  1387. status, err := bc.writeBlockWithState(block, receipts, statedb)
  1388. if err != nil {
  1389. atomic.StoreUint32(&followupInterrupt, 1)
  1390. return it.index, events, coalescedLogs, err
  1391. }
  1392. atomic.StoreUint32(&followupInterrupt, 1)
  1393. // Update the metrics touched during block commit
  1394. accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them
  1395. storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them
  1396. blockWriteTimer.Update(time.Since(substart) - statedb.AccountCommits - statedb.StorageCommits)
  1397. blockInsertTimer.UpdateSince(start)
  1398. switch status {
  1399. case CanonStatTy:
  1400. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1401. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1402. "elapsed", common.PrettyDuration(time.Since(start)),
  1403. "root", block.Root())
  1404. coalescedLogs = append(coalescedLogs, logs...)
  1405. events = append(events, ChainEvent{block, block.Hash(), logs})
  1406. lastCanon = block
  1407. // Only count canonical blocks for GC processing time
  1408. bc.gcproc += proctime
  1409. case SideStatTy:
  1410. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1411. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1412. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1413. "root", block.Root())
  1414. events = append(events, ChainSideEvent{block})
  1415. default:
  1416. // This in theory is impossible, but lets be nice to our future selves and leave
  1417. // a log, instead of trying to track down blocks imports that don't emit logs.
  1418. log.Warn("Inserted block with unknown status", "number", block.Number(), "hash", block.Hash(),
  1419. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1420. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1421. "root", block.Root())
  1422. }
  1423. stats.processed++
  1424. stats.usedGas += usedGas
  1425. dirty, _ := bc.stateCache.TrieDB().Size()
  1426. stats.report(chain, it.index, dirty)
  1427. }
  1428. // Any blocks remaining here? The only ones we care about are the future ones
  1429. if block != nil && err == consensus.ErrFutureBlock {
  1430. if err := bc.addFutureBlock(block); err != nil {
  1431. return it.index, events, coalescedLogs, err
  1432. }
  1433. block, err = it.next()
  1434. for ; block != nil && err == consensus.ErrUnknownAncestor; block, err = it.next() {
  1435. if err := bc.addFutureBlock(block); err != nil {
  1436. return it.index, events, coalescedLogs, err
  1437. }
  1438. stats.queued++
  1439. }
  1440. }
  1441. stats.ignored += it.remaining()
  1442. // Append a single chain head event if we've progressed the chain
  1443. if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1444. events = append(events, ChainHeadEvent{lastCanon})
  1445. }
  1446. return it.index, events, coalescedLogs, err
  1447. }
  1448. // insertSideChain is called when an import batch hits upon a pruned ancestor
  1449. // error, which happens when a sidechain with a sufficiently old fork-block is
  1450. // found.
  1451. //
  1452. // The method writes all (header-and-body-valid) blocks to disk, then tries to
  1453. // switch over to the new chain if the TD exceeded the current chain.
  1454. func (bc *BlockChain) insertSideChain(block *types.Block, it *insertIterator) (int, []interface{}, []*types.Log, error) {
  1455. var (
  1456. externTd *big.Int
  1457. current = bc.CurrentBlock()
  1458. )
  1459. // The first sidechain block error is already verified to be ErrPrunedAncestor.
  1460. // Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  1461. // ones. Any other errors means that the block is invalid, and should not be written
  1462. // to disk.
  1463. err := consensus.ErrPrunedAncestor
  1464. for ; block != nil && (err == consensus.ErrPrunedAncestor); block, err = it.next() {
  1465. // Check the canonical state root for that number
  1466. if number := block.NumberU64(); current.NumberU64() >= number {
  1467. canonical := bc.GetBlockByNumber(number)
  1468. if canonical != nil && canonical.Hash() == block.Hash() {
  1469. // Not a sidechain block, this is a re-import of a canon block which has it's state pruned
  1470. continue
  1471. }
  1472. if canonical != nil && canonical.Root() == block.Root() {
  1473. // This is most likely a shadow-state attack. When a fork is imported into the
  1474. // database, and it eventually reaches a block height which is not pruned, we
  1475. // just found that the state already exist! This means that the sidechain block
  1476. // refers to a state which already exists in our canon chain.
  1477. //
  1478. // If left unchecked, we would now proceed importing the blocks, without actually
  1479. // having verified the state of the previous blocks.
  1480. log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  1481. // If someone legitimately side-mines blocks, they would still be imported as usual. However,
  1482. // we cannot risk writing unverified blocks to disk when they obviously target the pruning
  1483. // mechanism.
  1484. return it.index, nil, nil, errors.New("sidechain ghost-state attack")
  1485. }
  1486. }
  1487. if externTd == nil {
  1488. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1489. }
  1490. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1491. if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  1492. start := time.Now()
  1493. if err := bc.writeBlockWithoutState(block, externTd); err != nil {
  1494. return it.index, nil, nil, err
  1495. }
  1496. log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(),
  1497. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1498. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1499. "root", block.Root())
  1500. }
  1501. }
  1502. // At this point, we've written all sidechain blocks to database. Loop ended
  1503. // either on some other error or all were processed. If there was some other
  1504. // error, we can ignore the rest of those blocks.
  1505. //
  1506. // If the externTd was larger than our local TD, we now need to reimport the previous
  1507. // blocks to regenerate the required state
  1508. localTd := bc.GetTd(current.Hash(), current.NumberU64())
  1509. if localTd.Cmp(externTd) > 0 {
  1510. log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().Number, "sidetd", externTd, "localtd", localTd)
  1511. return it.index, nil, nil, err
  1512. }
  1513. // Gather all the sidechain hashes (full blocks may be memory heavy)
  1514. var (
  1515. hashes []common.Hash
  1516. numbers []uint64
  1517. )
  1518. parent := it.previous()
  1519. for parent != nil && !bc.HasState(parent.Root) {
  1520. hashes = append(hashes, parent.Hash())
  1521. numbers = append(numbers, parent.Number.Uint64())
  1522. parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  1523. }
  1524. if parent == nil {
  1525. return it.index, nil, nil, errors.New("missing parent")
  1526. }
  1527. // Import all the pruned blocks to make the state available
  1528. var (
  1529. blocks []*types.Block
  1530. memory common.StorageSize
  1531. )
  1532. for i := len(hashes) - 1; i >= 0; i-- {
  1533. // Append the next block to our batch
  1534. block := bc.GetBlock(hashes[i], numbers[i])
  1535. blocks = append(blocks, block)
  1536. memory += block.Size()
  1537. // If memory use grew too large, import and continue. Sadly we need to discard
  1538. // all raised events and logs from notifications since we're too heavy on the
  1539. // memory here.
  1540. if len(blocks) >= 2048 || memory > 64*1024*1024 {
  1541. log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  1542. if _, _, _, err := bc.insertChain(blocks, false); err != nil {
  1543. return 0, nil, nil, err
  1544. }
  1545. blocks, memory = blocks[:0], 0
  1546. // If the chain is terminating, stop processing blocks
  1547. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1548. log.Debug("Premature abort during blocks processing")
  1549. return 0, nil, nil, nil
  1550. }
  1551. }
  1552. }
  1553. if len(blocks) > 0 {
  1554. log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  1555. return bc.insertChain(blocks, false)
  1556. }
  1557. return 0, nil, nil, nil
  1558. }
  1559. // reorg takes two blocks, an old chain and a new chain and will reconstruct the
  1560. // blocks and inserts them to be part of the new canonical chain and accumulates
  1561. // potential missing transactions and post an event about them.
  1562. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1563. var (
  1564. newChain types.Blocks
  1565. oldChain types.Blocks
  1566. commonBlock *types.Block
  1567. deletedTxs types.Transactions
  1568. addedTxs types.Transactions
  1569. deletedLogs []*types.Log
  1570. rebirthLogs []*types.Log
  1571. // collectLogs collects the logs that were generated during the
  1572. // processing of the block that corresponds with the given hash.
  1573. // These logs are later announced as deleted or reborn
  1574. collectLogs = func(hash common.Hash, removed bool) {
  1575. number := bc.hc.GetBlockNumber(hash)
  1576. if number == nil {
  1577. return
  1578. }
  1579. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  1580. for _, receipt := range receipts {
  1581. for _, log := range receipt.Logs {
  1582. l := *log
  1583. if removed {
  1584. l.Removed = true
  1585. deletedLogs = append(deletedLogs, &l)
  1586. } else {
  1587. rebirthLogs = append(rebirthLogs, &l)
  1588. }
  1589. }
  1590. }
  1591. }
  1592. )
  1593. // Reduce the longer chain to the same number as the shorter one
  1594. if oldBlock.NumberU64() > newBlock.NumberU64() {
  1595. // Old chain is longer, gather all transactions and logs as deleted ones
  1596. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  1597. oldChain = append(oldChain, oldBlock)
  1598. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1599. collectLogs(oldBlock.Hash(), true)
  1600. }
  1601. } else {
  1602. // New chain is longer, stash all blocks away for subsequent insertion
  1603. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1604. newChain = append(newChain, newBlock)
  1605. }
  1606. }
  1607. if oldBlock == nil {
  1608. return fmt.Errorf("invalid old chain")
  1609. }
  1610. if newBlock == nil {
  1611. return fmt.Errorf("invalid new chain")
  1612. }
  1613. // Both sides of the reorg are at the same number, reduce both until the common
  1614. // ancestor is found
  1615. for {
  1616. // If the common ancestor was found, bail out
  1617. if oldBlock.Hash() == newBlock.Hash() {
  1618. commonBlock = oldBlock
  1619. break
  1620. }
  1621. // Remove an old block as well as stash away a new block
  1622. oldChain = append(oldChain, oldBlock)
  1623. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1624. collectLogs(oldBlock.Hash(), true)
  1625. newChain = append(newChain, newBlock)
  1626. // Step back with both chains
  1627. oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1)
  1628. if oldBlock == nil {
  1629. return fmt.Errorf("invalid old chain")
  1630. }
  1631. newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1632. if newBlock == nil {
  1633. return fmt.Errorf("invalid new chain")
  1634. }
  1635. }
  1636. // Ensure the user sees large reorgs
  1637. if len(oldChain) > 0 && len(newChain) > 0 {
  1638. logFn := log.Debug
  1639. if len(oldChain) > 63 {
  1640. logFn = log.Warn
  1641. }
  1642. logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1643. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1644. } else {
  1645. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1646. }
  1647. // Insert the new chain(except the head block(reverse order)),
  1648. // taking care of the proper incremental order.
  1649. for i := len(newChain) - 1; i >= 1; i-- {
  1650. // Insert the block in the canonical way, re-writing history
  1651. bc.insert(newChain[i])
  1652. // Collect reborn logs due to chain reorg
  1653. collectLogs(newChain[i].Hash(), false)
  1654. // Write lookup entries for hash based transaction/receipt searches
  1655. rawdb.WriteTxLookupEntries(bc.db, newChain[i])
  1656. addedTxs = append(addedTxs, newChain[i].Transactions()...)
  1657. }
  1658. // When transactions get deleted from the database, the receipts that were
  1659. // created in the fork must also be deleted
  1660. batch := bc.db.NewBatch()
  1661. for _, tx := range types.TxDifference(deletedTxs, addedTxs) {
  1662. rawdb.DeleteTxLookupEntry(batch, tx.Hash())
  1663. }
  1664. // Delete any canonical number assignments above the new head
  1665. number := bc.CurrentBlock().NumberU64()
  1666. for i := number + 1; ; i++ {
  1667. hash := rawdb.ReadCanonicalHash(bc.db, i)
  1668. if hash == (common.Hash{}) {
  1669. break
  1670. }
  1671. rawdb.DeleteCanonicalHash(batch, i)
  1672. }
  1673. batch.Write()
  1674. // If any logs need to be fired, do it now. In theory we could avoid creating
  1675. // this goroutine if there are no events to fire, but realistcally that only
  1676. // ever happens if we're reorging empty blocks, which will only happen on idle
  1677. // networks where performance is not an issue either way.
  1678. //
  1679. // TODO(karalabe): Can we get rid of the goroutine somehow to guarantee correct
  1680. // event ordering?
  1681. go func() {
  1682. if len(deletedLogs) > 0 {
  1683. bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs})
  1684. }
  1685. if len(rebirthLogs) > 0 {
  1686. bc.logsFeed.Send(rebirthLogs)
  1687. }
  1688. if len(oldChain) > 0 {
  1689. for _, block := range oldChain {
  1690. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1691. }
  1692. }
  1693. }()
  1694. return nil
  1695. }
  1696. // PostChainEvents iterates over the events generated by a chain insertion and
  1697. // posts them into the event feed.
  1698. // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.
  1699. func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) {
  1700. // post event logs for further processing
  1701. if logs != nil {
  1702. bc.logsFeed.Send(logs)
  1703. }
  1704. for _, event := range events {
  1705. switch ev := event.(type) {
  1706. case ChainEvent:
  1707. bc.chainFeed.Send(ev)
  1708. case ChainHeadEvent:
  1709. bc.chainHeadFeed.Send(ev)
  1710. case ChainSideEvent:
  1711. bc.chainSideFeed.Send(ev)
  1712. }
  1713. }
  1714. }
  1715. func (bc *BlockChain) update() {
  1716. futureTimer := time.NewTicker(5 * time.Second)
  1717. defer futureTimer.Stop()
  1718. for {
  1719. select {
  1720. case <-futureTimer.C:
  1721. bc.procFutureBlocks()
  1722. case <-bc.quit:
  1723. return
  1724. }
  1725. }
  1726. }
  1727. // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1728. func (bc *BlockChain) BadBlocks() []*types.Block {
  1729. blocks := make([]*types.Block, 0, bc.badBlocks.Len())
  1730. for _, hash := range bc.badBlocks.Keys() {
  1731. if blk, exist := bc.badBlocks.Peek(hash); exist {
  1732. block := blk.(*types.Block)
  1733. blocks = append(blocks, block)
  1734. }
  1735. }
  1736. return blocks
  1737. }
  1738. // addBadBlock adds a bad block to the bad-block LRU cache
  1739. func (bc *BlockChain) addBadBlock(block *types.Block) {
  1740. bc.badBlocks.Add(block.Hash(), block)
  1741. }
  1742. // reportBlock logs a bad block error.
  1743. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1744. bc.addBadBlock(block)
  1745. var receiptString string
  1746. for i, receipt := range receipts {
  1747. receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  1748. i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  1749. receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  1750. }
  1751. log.Error(fmt.Sprintf(`
  1752. ########## BAD BLOCK #########
  1753. Chain config: %v
  1754. Number: %v
  1755. Hash: 0x%x
  1756. %v
  1757. Error: %v
  1758. ##############################
  1759. `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  1760. }
  1761. // InsertHeaderChain attempts to insert the given header chain in to the local
  1762. // chain, possibly creating a reorg. If an error is returned, it will return the
  1763. // index number of the failing header as well an error describing what went wrong.
  1764. //
  1765. // The verify parameter can be used to fine tune whether nonce verification
  1766. // should be done or not. The reason behind the optional check is because some
  1767. // of the header retrieval mechanisms already need to verify nonces, as well as
  1768. // because nonces can be verified sparsely, not needing to check each.
  1769. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1770. start := time.Now()
  1771. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1772. return i, err
  1773. }
  1774. // Make sure only one thread manipulates the chain at once
  1775. bc.chainmu.Lock()
  1776. defer bc.chainmu.Unlock()
  1777. bc.wg.Add(1)
  1778. defer bc.wg.Done()
  1779. whFunc := func(header *types.Header) error {
  1780. _, err := bc.hc.WriteHeader(header)
  1781. return err
  1782. }
  1783. return bc.hc.InsertHeaderChain(chain, whFunc, start)
  1784. }
  1785. // CurrentHeader retrieves the current head header of the canonical chain. The
  1786. // header is retrieved from the HeaderChain's internal cache.
  1787. func (bc *BlockChain) CurrentHeader() *types.Header {
  1788. return bc.hc.CurrentHeader()
  1789. }
  1790. // GetTd retrieves a block's total difficulty in the canonical chain from the
  1791. // database by hash and number, caching it if found.
  1792. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1793. return bc.hc.GetTd(hash, number)
  1794. }
  1795. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1796. // database by hash, caching it if found.
  1797. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1798. return bc.hc.GetTdByHash(hash)
  1799. }
  1800. // GetHeader retrieves a block header from the database by hash and number,
  1801. // caching it if found.
  1802. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1803. return bc.hc.GetHeader(hash, number)
  1804. }
  1805. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1806. // found.
  1807. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1808. return bc.hc.GetHeaderByHash(hash)
  1809. }
  1810. // HasHeader checks if a block header is present in the database or not, caching
  1811. // it if present.
  1812. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  1813. return bc.hc.HasHeader(hash, number)
  1814. }
  1815. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1816. // hash, fetching towards the genesis block.
  1817. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1818. return bc.hc.GetBlockHashesFromHash(hash, max)
  1819. }
  1820. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  1821. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  1822. // number of blocks to be individually checked before we reach the canonical chain.
  1823. //
  1824. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  1825. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  1826. bc.chainmu.RLock()
  1827. defer bc.chainmu.RUnlock()
  1828. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  1829. }
  1830. // GetHeaderByNumber retrieves a block header from the database by number,
  1831. // caching it (associated with its hash) if found.
  1832. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1833. return bc.hc.GetHeaderByNumber(number)
  1834. }
  1835. // Config retrieves the blockchain's chain configuration.
  1836. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  1837. // Engine retrieves the blockchain's consensus engine.
  1838. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  1839. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  1840. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  1841. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  1842. }
  1843. // SubscribeChainEvent registers a subscription of ChainEvent.
  1844. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  1845. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  1846. }
  1847. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  1848. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  1849. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  1850. }
  1851. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  1852. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  1853. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  1854. }
  1855. // SubscribeLogsEvent registers a subscription of []*types.Log.
  1856. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  1857. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  1858. }
  1859. // SubscribeBlockProcessingEvent registers a subscription of bool where true means
  1860. // block processing has started while false means it has stopped.
  1861. func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription {
  1862. return bc.scope.Track(bc.blockProcFeed.Subscribe(ch))
  1863. }