blockchain.go 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552
  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. "sort"
  25. "sync"
  26. "sync/atomic"
  27. "time"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/mclock"
  30. "github.com/ethereum/go-ethereum/common/prque"
  31. "github.com/ethereum/go-ethereum/consensus"
  32. "github.com/ethereum/go-ethereum/core/rawdb"
  33. "github.com/ethereum/go-ethereum/core/state"
  34. "github.com/ethereum/go-ethereum/core/state/snapshot"
  35. "github.com/ethereum/go-ethereum/core/types"
  36. "github.com/ethereum/go-ethereum/core/vm"
  37. "github.com/ethereum/go-ethereum/ethdb"
  38. "github.com/ethereum/go-ethereum/event"
  39. "github.com/ethereum/go-ethereum/log"
  40. "github.com/ethereum/go-ethereum/metrics"
  41. "github.com/ethereum/go-ethereum/params"
  42. "github.com/ethereum/go-ethereum/rlp"
  43. "github.com/ethereum/go-ethereum/trie"
  44. lru "github.com/hashicorp/golang-lru"
  45. )
  46. var (
  47. headBlockGauge = metrics.NewRegisteredGauge("chain/head/block", nil)
  48. headHeaderGauge = metrics.NewRegisteredGauge("chain/head/header", nil)
  49. headFastBlockGauge = metrics.NewRegisteredGauge("chain/head/receipt", nil)
  50. accountReadTimer = metrics.NewRegisteredTimer("chain/account/reads", nil)
  51. accountHashTimer = metrics.NewRegisteredTimer("chain/account/hashes", nil)
  52. accountUpdateTimer = metrics.NewRegisteredTimer("chain/account/updates", nil)
  53. accountCommitTimer = metrics.NewRegisteredTimer("chain/account/commits", nil)
  54. storageReadTimer = metrics.NewRegisteredTimer("chain/storage/reads", nil)
  55. storageHashTimer = metrics.NewRegisteredTimer("chain/storage/hashes", nil)
  56. storageUpdateTimer = metrics.NewRegisteredTimer("chain/storage/updates", nil)
  57. storageCommitTimer = metrics.NewRegisteredTimer("chain/storage/commits", nil)
  58. snapshotAccountReadTimer = metrics.NewRegisteredTimer("chain/snapshot/account/reads", nil)
  59. snapshotStorageReadTimer = metrics.NewRegisteredTimer("chain/snapshot/storage/reads", nil)
  60. snapshotCommitTimer = metrics.NewRegisteredTimer("chain/snapshot/commits", nil)
  61. blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil)
  62. blockValidationTimer = metrics.NewRegisteredTimer("chain/validation", nil)
  63. blockExecutionTimer = metrics.NewRegisteredTimer("chain/execution", nil)
  64. blockWriteTimer = metrics.NewRegisteredTimer("chain/write", nil)
  65. blockReorgMeter = metrics.NewRegisteredMeter("chain/reorg/executes", nil)
  66. blockReorgAddMeter = metrics.NewRegisteredMeter("chain/reorg/add", nil)
  67. blockReorgDropMeter = metrics.NewRegisteredMeter("chain/reorg/drop", nil)
  68. blockReorgInvalidatedTx = metrics.NewRegisteredMeter("chain/reorg/invalidTx", nil)
  69. blockPrefetchExecuteTimer = metrics.NewRegisteredTimer("chain/prefetch/executes", nil)
  70. blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil)
  71. errInsertionInterrupted = errors.New("insertion is interrupted")
  72. )
  73. const (
  74. bodyCacheLimit = 256
  75. blockCacheLimit = 256
  76. receiptsCacheLimit = 32
  77. txLookupCacheLimit = 1024
  78. maxFutureBlocks = 256
  79. maxTimeFutureBlocks = 30
  80. TriesInMemory = 128
  81. // BlockChainVersion ensures that an incompatible database forces a resync from scratch.
  82. //
  83. // Changelog:
  84. //
  85. // - Version 4
  86. // The following incompatible database changes were added:
  87. // * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted
  88. // * the `Bloom` field of receipt is deleted
  89. // * the `BlockIndex` and `TxIndex` fields of txlookup are deleted
  90. // - Version 5
  91. // The following incompatible database changes were added:
  92. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are no longer stored for a receipt
  93. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are computed by looking up the
  94. // receipts' corresponding block
  95. // - Version 6
  96. // The following incompatible database changes were added:
  97. // * Transaction lookup information stores the corresponding block number instead of block hash
  98. // - Version 7
  99. // The following incompatible database changes were added:
  100. // * Use freezer as the ancient database to maintain all ancient data
  101. // - Version 8
  102. // The following incompatible database changes were added:
  103. // * New scheme for contract code in order to separate the codes and trie nodes
  104. BlockChainVersion uint64 = 8
  105. )
  106. // CacheConfig contains the configuration values for the trie caching/pruning
  107. // that's resident in a blockchain.
  108. type CacheConfig struct {
  109. TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
  110. TrieCleanJournal string // Disk journal for saving clean cache entries.
  111. TrieCleanRejournal time.Duration // Time interval to dump clean cache to disk periodically
  112. TrieCleanNoPrefetch bool // Whether to disable heuristic state prefetching for followup blocks
  113. TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk
  114. TrieDirtyDisabled bool // Whether to disable trie write caching and GC altogether (archive node)
  115. TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
  116. SnapshotLimit int // Memory allowance (MB) to use for caching snapshot entries in memory
  117. Preimages bool // Whether to store preimage of trie key to the disk
  118. SnapshotWait bool // Wait for snapshot construction on startup. TODO(karalabe): This is a dirty hack for testing, nuke it
  119. }
  120. // defaultCacheConfig are the default caching values if none are specified by the
  121. // user (also used during testing).
  122. var defaultCacheConfig = &CacheConfig{
  123. TrieCleanLimit: 256,
  124. TrieDirtyLimit: 256,
  125. TrieTimeLimit: 5 * time.Minute,
  126. SnapshotLimit: 256,
  127. SnapshotWait: true,
  128. }
  129. // BlockChain represents the canonical chain given a database with a genesis
  130. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  131. //
  132. // Importing blocks in to the block chain happens according to the set of rules
  133. // defined by the two stage Validator. Processing of blocks is done using the
  134. // Processor which processes the included transaction. The validation of the state
  135. // is done in the second part of the Validator. Failing results in aborting of
  136. // the import.
  137. //
  138. // The BlockChain also helps in returning blocks from **any** chain included
  139. // in the database as well as blocks that represents the canonical chain. It's
  140. // important to note that GetBlock can return any block and does not need to be
  141. // included in the canonical one where as GetBlockByNumber always represents the
  142. // canonical chain.
  143. type BlockChain struct {
  144. chainConfig *params.ChainConfig // Chain & network configuration
  145. cacheConfig *CacheConfig // Cache configuration for pruning
  146. db ethdb.Database // Low level persistent database to store final content in
  147. snaps *snapshot.Tree // Snapshot tree for fast trie leaf access
  148. triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
  149. gcproc time.Duration // Accumulates canonical block processing for trie dumping
  150. // txLookupLimit is the maximum number of blocks from head whose tx indices
  151. // are reserved:
  152. // * 0: means no limit and regenerate any missing indexes
  153. // * N: means N block limit [HEAD-N+1, HEAD] and delete extra indexes
  154. // * nil: disable tx reindexer/deleter, but still index new blocks
  155. txLookupLimit uint64
  156. hc *HeaderChain
  157. rmLogsFeed event.Feed
  158. chainFeed event.Feed
  159. chainSideFeed event.Feed
  160. chainHeadFeed event.Feed
  161. logsFeed event.Feed
  162. blockProcFeed event.Feed
  163. scope event.SubscriptionScope
  164. genesisBlock *types.Block
  165. chainmu sync.RWMutex // blockchain insertion lock
  166. currentBlock atomic.Value // Current head of the block chain
  167. currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
  168. stateCache state.Database // State database to reuse between imports (contains state cache)
  169. bodyCache *lru.Cache // Cache for the most recent block bodies
  170. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  171. receiptsCache *lru.Cache // Cache for the most recent receipts per block
  172. blockCache *lru.Cache // Cache for the most recent entire blocks
  173. txLookupCache *lru.Cache // Cache for the most recent transaction lookup data.
  174. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  175. quit chan struct{} // blockchain quit channel
  176. wg sync.WaitGroup // chain processing wait group for shutting down
  177. running int32 // 0 if chain is running, 1 when stopped
  178. procInterrupt int32 // interrupt signaler for block processing
  179. engine consensus.Engine
  180. validator Validator // Block and state validator interface
  181. prefetcher Prefetcher
  182. processor Processor // Block transaction processor interface
  183. vmConfig vm.Config
  184. shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
  185. terminateInsert func(common.Hash, uint64) bool // Testing hook used to terminate ancient receipt chain insertion.
  186. writeLegacyJournal bool // Testing flag used to flush the snapshot journal in legacy format.
  187. }
  188. // NewBlockChain returns a fully initialised block chain using information
  189. // available in the database. It initialises the default Ethereum Validator and
  190. // Processor.
  191. func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool, txLookupLimit *uint64) (*BlockChain, error) {
  192. if cacheConfig == nil {
  193. cacheConfig = defaultCacheConfig
  194. }
  195. bodyCache, _ := lru.New(bodyCacheLimit)
  196. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  197. receiptsCache, _ := lru.New(receiptsCacheLimit)
  198. blockCache, _ := lru.New(blockCacheLimit)
  199. txLookupCache, _ := lru.New(txLookupCacheLimit)
  200. futureBlocks, _ := lru.New(maxFutureBlocks)
  201. bc := &BlockChain{
  202. chainConfig: chainConfig,
  203. cacheConfig: cacheConfig,
  204. db: db,
  205. triegc: prque.New(nil),
  206. stateCache: state.NewDatabaseWithConfig(db, &trie.Config{
  207. Cache: cacheConfig.TrieCleanLimit,
  208. Journal: cacheConfig.TrieCleanJournal,
  209. Preimages: cacheConfig.Preimages,
  210. }),
  211. quit: make(chan struct{}),
  212. shouldPreserve: shouldPreserve,
  213. bodyCache: bodyCache,
  214. bodyRLPCache: bodyRLPCache,
  215. receiptsCache: receiptsCache,
  216. blockCache: blockCache,
  217. txLookupCache: txLookupCache,
  218. futureBlocks: futureBlocks,
  219. engine: engine,
  220. vmConfig: vmConfig,
  221. }
  222. bc.validator = NewBlockValidator(chainConfig, bc, engine)
  223. bc.prefetcher = newStatePrefetcher(chainConfig, bc, engine)
  224. bc.processor = NewStateProcessor(chainConfig, bc, engine)
  225. var err error
  226. bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.insertStopped)
  227. if err != nil {
  228. return nil, err
  229. }
  230. bc.genesisBlock = bc.GetBlockByNumber(0)
  231. if bc.genesisBlock == nil {
  232. return nil, ErrNoGenesis
  233. }
  234. var nilBlock *types.Block
  235. bc.currentBlock.Store(nilBlock)
  236. bc.currentFastBlock.Store(nilBlock)
  237. // Initialize the chain with ancient data if it isn't empty.
  238. var txIndexBlock uint64
  239. if bc.empty() {
  240. rawdb.InitDatabaseFromFreezer(bc.db)
  241. // If ancient database is not empty, reconstruct all missing
  242. // indices in the background.
  243. frozen, _ := bc.db.Ancients()
  244. if frozen > 0 {
  245. txIndexBlock = frozen
  246. }
  247. }
  248. if err := bc.loadLastState(); err != nil {
  249. return nil, err
  250. }
  251. // Make sure the state associated with the block is available
  252. head := bc.CurrentBlock()
  253. if _, err := state.New(head.Root(), bc.stateCache, bc.snaps); err != nil {
  254. // Head state is missing, before the state recovery, find out the
  255. // disk layer point of snapshot(if it's enabled). Make sure the
  256. // rewound point is lower than disk layer.
  257. var diskRoot common.Hash
  258. if bc.cacheConfig.SnapshotLimit > 0 {
  259. diskRoot = rawdb.ReadSnapshotRoot(bc.db)
  260. }
  261. if diskRoot != (common.Hash{}) {
  262. log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash(), "snaproot", diskRoot)
  263. snapDisk, err := bc.SetHeadBeyondRoot(head.NumberU64(), diskRoot)
  264. if err != nil {
  265. return nil, err
  266. }
  267. // Chain rewound, persist old snapshot number to indicate recovery procedure
  268. if snapDisk != 0 {
  269. rawdb.WriteSnapshotRecoveryNumber(bc.db, snapDisk)
  270. }
  271. } else {
  272. log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash())
  273. if err := bc.SetHead(head.NumberU64()); err != nil {
  274. return nil, err
  275. }
  276. }
  277. }
  278. // Ensure that a previous crash in SetHead doesn't leave extra ancients
  279. if frozen, err := bc.db.Ancients(); err == nil && frozen > 0 {
  280. var (
  281. needRewind bool
  282. low uint64
  283. )
  284. // The head full block may be rolled back to a very low height due to
  285. // blockchain repair. If the head full block is even lower than the ancient
  286. // chain, truncate the ancient store.
  287. fullBlock := bc.CurrentBlock()
  288. if fullBlock != nil && fullBlock.Hash() != bc.genesisBlock.Hash() && fullBlock.NumberU64() < frozen-1 {
  289. needRewind = true
  290. low = fullBlock.NumberU64()
  291. }
  292. // In fast sync, it may happen that ancient data has been written to the
  293. // ancient store, but the LastFastBlock has not been updated, truncate the
  294. // extra data here.
  295. fastBlock := bc.CurrentFastBlock()
  296. if fastBlock != nil && fastBlock.NumberU64() < frozen-1 {
  297. needRewind = true
  298. if fastBlock.NumberU64() < low || low == 0 {
  299. low = fastBlock.NumberU64()
  300. }
  301. }
  302. if needRewind {
  303. log.Error("Truncating ancient chain", "from", bc.CurrentHeader().Number.Uint64(), "to", low)
  304. if err := bc.SetHead(low); err != nil {
  305. return nil, err
  306. }
  307. }
  308. }
  309. // The first thing the node will do is reconstruct the verification data for
  310. // the head block (ethash cache or clique voting snapshot). Might as well do
  311. // it in advance.
  312. bc.engine.VerifyHeader(bc, bc.CurrentHeader(), true)
  313. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  314. for hash := range BadHashes {
  315. if header := bc.GetHeaderByHash(hash); header != nil {
  316. // get the canonical block corresponding to the offending header's number
  317. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  318. // make sure the headerByNumber (if present) is in our current canonical chain
  319. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  320. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  321. if err := bc.SetHead(header.Number.Uint64() - 1); err != nil {
  322. return nil, err
  323. }
  324. log.Error("Chain rewind was successful, resuming normal operation")
  325. }
  326. }
  327. }
  328. // Load any existing snapshot, regenerating it if loading failed
  329. if bc.cacheConfig.SnapshotLimit > 0 {
  330. // If the chain was rewound past the snapshot persistent layer (causing
  331. // a recovery block number to be persisted to disk), check if we're still
  332. // in recovery mode and in that case, don't invalidate the snapshot on a
  333. // head mismatch.
  334. var recover bool
  335. head := bc.CurrentBlock()
  336. if layer := rawdb.ReadSnapshotRecoveryNumber(bc.db); layer != nil && *layer > head.NumberU64() {
  337. log.Warn("Enabling snapshot recovery", "chainhead", head.NumberU64(), "diskbase", *layer)
  338. recover = true
  339. }
  340. bc.snaps, _ = snapshot.New(bc.db, bc.stateCache.TrieDB(), bc.cacheConfig.SnapshotLimit, head.Root(), !bc.cacheConfig.SnapshotWait, true, recover)
  341. }
  342. // Take ownership of this particular state
  343. go bc.update()
  344. if txLookupLimit != nil {
  345. bc.txLookupLimit = *txLookupLimit
  346. bc.wg.Add(1)
  347. go bc.maintainTxIndex(txIndexBlock)
  348. }
  349. // If periodic cache journal is required, spin it up.
  350. if bc.cacheConfig.TrieCleanRejournal > 0 {
  351. if bc.cacheConfig.TrieCleanRejournal < time.Minute {
  352. log.Warn("Sanitizing invalid trie cache journal time", "provided", bc.cacheConfig.TrieCleanRejournal, "updated", time.Minute)
  353. bc.cacheConfig.TrieCleanRejournal = time.Minute
  354. }
  355. triedb := bc.stateCache.TrieDB()
  356. bc.wg.Add(1)
  357. go func() {
  358. defer bc.wg.Done()
  359. triedb.SaveCachePeriodically(bc.cacheConfig.TrieCleanJournal, bc.cacheConfig.TrieCleanRejournal, bc.quit)
  360. }()
  361. }
  362. return bc, nil
  363. }
  364. // GetVMConfig returns the block chain VM config.
  365. func (bc *BlockChain) GetVMConfig() *vm.Config {
  366. return &bc.vmConfig
  367. }
  368. // empty returns an indicator whether the blockchain is empty.
  369. // Note, it's a special case that we connect a non-empty ancient
  370. // database with an empty node, so that we can plugin the ancient
  371. // into node seamlessly.
  372. func (bc *BlockChain) empty() bool {
  373. genesis := bc.genesisBlock.Hash()
  374. for _, hash := range []common.Hash{rawdb.ReadHeadBlockHash(bc.db), rawdb.ReadHeadHeaderHash(bc.db), rawdb.ReadHeadFastBlockHash(bc.db)} {
  375. if hash != genesis {
  376. return false
  377. }
  378. }
  379. return true
  380. }
  381. // loadLastState loads the last known chain state from the database. This method
  382. // assumes that the chain manager mutex is held.
  383. func (bc *BlockChain) loadLastState() error {
  384. // Restore the last known head block
  385. head := rawdb.ReadHeadBlockHash(bc.db)
  386. if head == (common.Hash{}) {
  387. // Corrupt or empty database, init from scratch
  388. log.Warn("Empty database, resetting chain")
  389. return bc.Reset()
  390. }
  391. // Make sure the entire head block is available
  392. currentBlock := bc.GetBlockByHash(head)
  393. if currentBlock == nil {
  394. // Corrupt or empty database, init from scratch
  395. log.Warn("Head block missing, resetting chain", "hash", head)
  396. return bc.Reset()
  397. }
  398. // Everything seems to be fine, set as the head block
  399. bc.currentBlock.Store(currentBlock)
  400. headBlockGauge.Update(int64(currentBlock.NumberU64()))
  401. // Restore the last known head header
  402. currentHeader := currentBlock.Header()
  403. if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
  404. if header := bc.GetHeaderByHash(head); header != nil {
  405. currentHeader = header
  406. }
  407. }
  408. bc.hc.SetCurrentHeader(currentHeader)
  409. // Restore the last known head fast block
  410. bc.currentFastBlock.Store(currentBlock)
  411. headFastBlockGauge.Update(int64(currentBlock.NumberU64()))
  412. if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
  413. if block := bc.GetBlockByHash(head); block != nil {
  414. bc.currentFastBlock.Store(block)
  415. headFastBlockGauge.Update(int64(block.NumberU64()))
  416. }
  417. }
  418. // Issue a status log for the user
  419. currentFastBlock := bc.CurrentFastBlock()
  420. headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  421. blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  422. fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
  423. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time), 0)))
  424. 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)))
  425. 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)))
  426. if pivot := rawdb.ReadLastPivotNumber(bc.db); pivot != nil {
  427. log.Info("Loaded last fast-sync pivot marker", "number", *pivot)
  428. }
  429. return nil
  430. }
  431. // SetHead rewinds the local chain to a new head. Depending on whether the node
  432. // was fast synced or full synced and in which state, the method will try to
  433. // delete minimal data from disk whilst retaining chain consistency.
  434. func (bc *BlockChain) SetHead(head uint64) error {
  435. _, err := bc.SetHeadBeyondRoot(head, common.Hash{})
  436. return err
  437. }
  438. // SetHeadBeyondRoot rewinds the local chain to a new head with the extra condition
  439. // that the rewind must pass the specified state root. This method is meant to be
  440. // used when rewiding with snapshots enabled to ensure that we go back further than
  441. // persistent disk layer. Depending on whether the node was fast synced or full, and
  442. // in which state, the method will try to delete minimal data from disk whilst
  443. // retaining chain consistency.
  444. //
  445. // The method returns the block number where the requested root cap was found.
  446. func (bc *BlockChain) SetHeadBeyondRoot(head uint64, root common.Hash) (uint64, error) {
  447. bc.chainmu.Lock()
  448. defer bc.chainmu.Unlock()
  449. // Track the block number of the requested root hash
  450. var rootNumber uint64 // (no root == always 0)
  451. // Retrieve the last pivot block to short circuit rollbacks beyond it and the
  452. // current freezer limit to start nuking id underflown
  453. pivot := rawdb.ReadLastPivotNumber(bc.db)
  454. frozen, _ := bc.db.Ancients()
  455. updateFn := func(db ethdb.KeyValueWriter, header *types.Header) (uint64, bool) {
  456. // Rewind the block chain, ensuring we don't end up with a stateless head
  457. // block. Note, depth equality is permitted to allow using SetHead as a
  458. // chain reparation mechanism without deleting any data!
  459. if currentBlock := bc.CurrentBlock(); currentBlock != nil && header.Number.Uint64() <= currentBlock.NumberU64() {
  460. newHeadBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  461. if newHeadBlock == nil {
  462. log.Error("Gap in the chain, rewinding to genesis", "number", header.Number, "hash", header.Hash())
  463. newHeadBlock = bc.genesisBlock
  464. } else {
  465. // Block exists, keep rewinding until we find one with state,
  466. // keeping rewinding until we exceed the optional threshold
  467. // root hash
  468. beyondRoot := (root == common.Hash{}) // Flag whether we're beyond the requested root (no root, always true)
  469. for {
  470. // If a root threshold was requested but not yet crossed, check
  471. if root != (common.Hash{}) && !beyondRoot && newHeadBlock.Root() == root {
  472. beyondRoot, rootNumber = true, newHeadBlock.NumberU64()
  473. }
  474. if _, err := state.New(newHeadBlock.Root(), bc.stateCache, bc.snaps); err != nil {
  475. log.Trace("Block state missing, rewinding further", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash())
  476. if pivot == nil || newHeadBlock.NumberU64() > *pivot {
  477. parent := bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1)
  478. if parent != nil {
  479. newHeadBlock = parent
  480. continue
  481. }
  482. log.Error("Missing block in the middle, aiming genesis", "number", newHeadBlock.NumberU64()-1, "hash", newHeadBlock.ParentHash())
  483. newHeadBlock = bc.genesisBlock
  484. } else {
  485. log.Trace("Rewind passed pivot, aiming genesis", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash(), "pivot", *pivot)
  486. newHeadBlock = bc.genesisBlock
  487. }
  488. }
  489. if beyondRoot || newHeadBlock.NumberU64() == 0 {
  490. log.Debug("Rewound to block with state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash())
  491. break
  492. }
  493. log.Debug("Skipping block with threshold state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash(), "root", newHeadBlock.Root())
  494. newHeadBlock = bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1) // Keep rewinding
  495. }
  496. }
  497. rawdb.WriteHeadBlockHash(db, newHeadBlock.Hash())
  498. // Degrade the chain markers if they are explicitly reverted.
  499. // In theory we should update all in-memory markers in the
  500. // last step, however the direction of SetHead is from high
  501. // to low, so it's safe the update in-memory markers directly.
  502. bc.currentBlock.Store(newHeadBlock)
  503. headBlockGauge.Update(int64(newHeadBlock.NumberU64()))
  504. }
  505. // Rewind the fast block in a simpleton way to the target head
  506. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && header.Number.Uint64() < currentFastBlock.NumberU64() {
  507. newHeadFastBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  508. // If either blocks reached nil, reset to the genesis state
  509. if newHeadFastBlock == nil {
  510. newHeadFastBlock = bc.genesisBlock
  511. }
  512. rawdb.WriteHeadFastBlockHash(db, newHeadFastBlock.Hash())
  513. // Degrade the chain markers if they are explicitly reverted.
  514. // In theory we should update all in-memory markers in the
  515. // last step, however the direction of SetHead is from high
  516. // to low, so it's safe the update in-memory markers directly.
  517. bc.currentFastBlock.Store(newHeadFastBlock)
  518. headFastBlockGauge.Update(int64(newHeadFastBlock.NumberU64()))
  519. }
  520. head := bc.CurrentBlock().NumberU64()
  521. // If setHead underflown the freezer threshold and the block processing
  522. // intent afterwards is full block importing, delete the chain segment
  523. // between the stateful-block and the sethead target.
  524. var wipe bool
  525. if head+1 < frozen {
  526. wipe = pivot == nil || head >= *pivot
  527. }
  528. return head, wipe // Only force wipe if full synced
  529. }
  530. // Rewind the header chain, deleting all block bodies until then
  531. delFn := func(db ethdb.KeyValueWriter, hash common.Hash, num uint64) {
  532. // Ignore the error here since light client won't hit this path
  533. frozen, _ := bc.db.Ancients()
  534. if num+1 <= frozen {
  535. // Truncate all relative data(header, total difficulty, body, receipt
  536. // and canonical hash) from ancient store.
  537. if err := bc.db.TruncateAncients(num); err != nil {
  538. log.Crit("Failed to truncate ancient data", "number", num, "err", err)
  539. }
  540. // Remove the hash <-> number mapping from the active store.
  541. rawdb.DeleteHeaderNumber(db, hash)
  542. } else {
  543. // Remove relative body and receipts from the active store.
  544. // The header, total difficulty and canonical hash will be
  545. // removed in the hc.SetHead function.
  546. rawdb.DeleteBody(db, hash, num)
  547. rawdb.DeleteReceipts(db, hash, num)
  548. }
  549. // Todo(rjl493456442) txlookup, bloombits, etc
  550. }
  551. // If SetHead was only called as a chain reparation method, try to skip
  552. // touching the header chain altogether, unless the freezer is broken
  553. if block := bc.CurrentBlock(); block.NumberU64() == head {
  554. if target, force := updateFn(bc.db, block.Header()); force {
  555. bc.hc.SetHead(target, updateFn, delFn)
  556. }
  557. } else {
  558. // Rewind the chain to the requested head and keep going backwards until a
  559. // block with a state is found or fast sync pivot is passed
  560. log.Warn("Rewinding blockchain", "target", head)
  561. bc.hc.SetHead(head, updateFn, delFn)
  562. }
  563. // Clear out any stale content from the caches
  564. bc.bodyCache.Purge()
  565. bc.bodyRLPCache.Purge()
  566. bc.receiptsCache.Purge()
  567. bc.blockCache.Purge()
  568. bc.txLookupCache.Purge()
  569. bc.futureBlocks.Purge()
  570. return rootNumber, bc.loadLastState()
  571. }
  572. // FastSyncCommitHead sets the current head block to the one defined by the hash
  573. // irrelevant what the chain contents were prior.
  574. func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  575. // Make sure that both the block as well at its state trie exists
  576. block := bc.GetBlockByHash(hash)
  577. if block == nil {
  578. return fmt.Errorf("non existent block [%x…]", hash[:4])
  579. }
  580. if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB()); err != nil {
  581. return err
  582. }
  583. // If all checks out, manually set the head block
  584. bc.chainmu.Lock()
  585. bc.currentBlock.Store(block)
  586. headBlockGauge.Update(int64(block.NumberU64()))
  587. bc.chainmu.Unlock()
  588. // Destroy any existing state snapshot and regenerate it in the background
  589. if bc.snaps != nil {
  590. bc.snaps.Rebuild(block.Root())
  591. }
  592. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  593. return nil
  594. }
  595. // GasLimit returns the gas limit of the current HEAD block.
  596. func (bc *BlockChain) GasLimit() uint64 {
  597. return bc.CurrentBlock().GasLimit()
  598. }
  599. // CurrentBlock retrieves the current head block of the canonical chain. The
  600. // block is retrieved from the blockchain's internal cache.
  601. func (bc *BlockChain) CurrentBlock() *types.Block {
  602. return bc.currentBlock.Load().(*types.Block)
  603. }
  604. // Snapshots returns the blockchain snapshot tree.
  605. func (bc *BlockChain) Snapshots() *snapshot.Tree {
  606. return bc.snaps
  607. }
  608. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  609. // chain. The block is retrieved from the blockchain's internal cache.
  610. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  611. return bc.currentFastBlock.Load().(*types.Block)
  612. }
  613. // Validator returns the current validator.
  614. func (bc *BlockChain) Validator() Validator {
  615. return bc.validator
  616. }
  617. // Processor returns the current processor.
  618. func (bc *BlockChain) Processor() Processor {
  619. return bc.processor
  620. }
  621. // State returns a new mutable state based on the current HEAD block.
  622. func (bc *BlockChain) State() (*state.StateDB, error) {
  623. return bc.StateAt(bc.CurrentBlock().Root())
  624. }
  625. // StateAt returns a new mutable state based on a particular point in time.
  626. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  627. return state.New(root, bc.stateCache, bc.snaps)
  628. }
  629. // StateCache returns the caching database underpinning the blockchain instance.
  630. func (bc *BlockChain) StateCache() state.Database {
  631. return bc.stateCache
  632. }
  633. // Reset purges the entire blockchain, restoring it to its genesis state.
  634. func (bc *BlockChain) Reset() error {
  635. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  636. }
  637. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  638. // specified genesis state.
  639. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  640. // Dump the entire block chain and purge the caches
  641. if err := bc.SetHead(0); err != nil {
  642. return err
  643. }
  644. bc.chainmu.Lock()
  645. defer bc.chainmu.Unlock()
  646. // Prepare the genesis block and reinitialise the chain
  647. batch := bc.db.NewBatch()
  648. rawdb.WriteTd(batch, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty())
  649. rawdb.WriteBlock(batch, genesis)
  650. if err := batch.Write(); err != nil {
  651. log.Crit("Failed to write genesis block", "err", err)
  652. }
  653. bc.writeHeadBlock(genesis)
  654. // Last update all in-memory chain markers
  655. bc.genesisBlock = genesis
  656. bc.currentBlock.Store(bc.genesisBlock)
  657. headBlockGauge.Update(int64(bc.genesisBlock.NumberU64()))
  658. bc.hc.SetGenesis(bc.genesisBlock.Header())
  659. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  660. bc.currentFastBlock.Store(bc.genesisBlock)
  661. headFastBlockGauge.Update(int64(bc.genesisBlock.NumberU64()))
  662. return nil
  663. }
  664. // Export writes the active chain to the given writer.
  665. func (bc *BlockChain) Export(w io.Writer) error {
  666. return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64())
  667. }
  668. // ExportN writes a subset of the active chain to the given writer.
  669. func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  670. bc.chainmu.RLock()
  671. defer bc.chainmu.RUnlock()
  672. if first > last {
  673. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  674. }
  675. log.Info("Exporting batch of blocks", "count", last-first+1)
  676. start, reported := time.Now(), time.Now()
  677. for nr := first; nr <= last; nr++ {
  678. block := bc.GetBlockByNumber(nr)
  679. if block == nil {
  680. return fmt.Errorf("export failed on #%d: not found", nr)
  681. }
  682. if err := block.EncodeRLP(w); err != nil {
  683. return err
  684. }
  685. if time.Since(reported) >= statsReportLimit {
  686. log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
  687. reported = time.Now()
  688. }
  689. }
  690. return nil
  691. }
  692. // writeHeadBlock injects a new head block into the current block chain. This method
  693. // assumes that the block is indeed a true head. It will also reset the head
  694. // header and the head fast sync block to this very same block if they are older
  695. // or if they are on a different side chain.
  696. //
  697. // Note, this function assumes that the `mu` mutex is held!
  698. func (bc *BlockChain) writeHeadBlock(block *types.Block) {
  699. // If the block is on a side chain or an unknown one, force other heads onto it too
  700. updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()
  701. // Add the block to the canonical chain number scheme and mark as the head
  702. batch := bc.db.NewBatch()
  703. rawdb.WriteCanonicalHash(batch, block.Hash(), block.NumberU64())
  704. rawdb.WriteTxLookupEntriesByBlock(batch, block)
  705. rawdb.WriteHeadBlockHash(batch, block.Hash())
  706. // If the block is better than our head or is on a different chain, force update heads
  707. if updateHeads {
  708. rawdb.WriteHeadHeaderHash(batch, block.Hash())
  709. rawdb.WriteHeadFastBlockHash(batch, block.Hash())
  710. }
  711. // Flush the whole batch into the disk, exit the node if failed
  712. if err := batch.Write(); err != nil {
  713. log.Crit("Failed to update chain indexes and markers", "err", err)
  714. }
  715. // Update all in-memory chain markers in the last step
  716. if updateHeads {
  717. bc.hc.SetCurrentHeader(block.Header())
  718. bc.currentFastBlock.Store(block)
  719. headFastBlockGauge.Update(int64(block.NumberU64()))
  720. }
  721. bc.currentBlock.Store(block)
  722. headBlockGauge.Update(int64(block.NumberU64()))
  723. }
  724. // Genesis retrieves the chain's genesis block.
  725. func (bc *BlockChain) Genesis() *types.Block {
  726. return bc.genesisBlock
  727. }
  728. // GetBody retrieves a block body (transactions and uncles) from the database by
  729. // hash, caching it if found.
  730. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  731. // Short circuit if the body's already in the cache, retrieve otherwise
  732. if cached, ok := bc.bodyCache.Get(hash); ok {
  733. body := cached.(*types.Body)
  734. return body
  735. }
  736. number := bc.hc.GetBlockNumber(hash)
  737. if number == nil {
  738. return nil
  739. }
  740. body := rawdb.ReadBody(bc.db, hash, *number)
  741. if body == nil {
  742. return nil
  743. }
  744. // Cache the found body for next time and return
  745. bc.bodyCache.Add(hash, body)
  746. return body
  747. }
  748. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  749. // caching it if found.
  750. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  751. // Short circuit if the body's already in the cache, retrieve otherwise
  752. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  753. return cached.(rlp.RawValue)
  754. }
  755. number := bc.hc.GetBlockNumber(hash)
  756. if number == nil {
  757. return nil
  758. }
  759. body := rawdb.ReadBodyRLP(bc.db, hash, *number)
  760. if len(body) == 0 {
  761. return nil
  762. }
  763. // Cache the found body for next time and return
  764. bc.bodyRLPCache.Add(hash, body)
  765. return body
  766. }
  767. // HasBlock checks if a block is fully present in the database or not.
  768. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  769. if bc.blockCache.Contains(hash) {
  770. return true
  771. }
  772. return rawdb.HasBody(bc.db, hash, number)
  773. }
  774. // HasFastBlock checks if a fast block is fully present in the database or not.
  775. func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool {
  776. if !bc.HasBlock(hash, number) {
  777. return false
  778. }
  779. if bc.receiptsCache.Contains(hash) {
  780. return true
  781. }
  782. return rawdb.HasReceipts(bc.db, hash, number)
  783. }
  784. // HasState checks if state trie is fully present in the database or not.
  785. func (bc *BlockChain) HasState(hash common.Hash) bool {
  786. _, err := bc.stateCache.OpenTrie(hash)
  787. return err == nil
  788. }
  789. // HasBlockAndState checks if a block and associated state trie is fully present
  790. // in the database or not, caching it if present.
  791. func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
  792. // Check first that the block itself is known
  793. block := bc.GetBlock(hash, number)
  794. if block == nil {
  795. return false
  796. }
  797. return bc.HasState(block.Root())
  798. }
  799. // GetBlock retrieves a block from the database by hash and number,
  800. // caching it if found.
  801. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  802. // Short circuit if the block's already in the cache, retrieve otherwise
  803. if block, ok := bc.blockCache.Get(hash); ok {
  804. return block.(*types.Block)
  805. }
  806. block := rawdb.ReadBlock(bc.db, hash, number)
  807. if block == nil {
  808. return nil
  809. }
  810. // Cache the found block for next time and return
  811. bc.blockCache.Add(block.Hash(), block)
  812. return block
  813. }
  814. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  815. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  816. number := bc.hc.GetBlockNumber(hash)
  817. if number == nil {
  818. return nil
  819. }
  820. return bc.GetBlock(hash, *number)
  821. }
  822. // GetBlockByNumber retrieves a block from the database by number, caching it
  823. // (associated with its hash) if found.
  824. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  825. hash := rawdb.ReadCanonicalHash(bc.db, number)
  826. if hash == (common.Hash{}) {
  827. return nil
  828. }
  829. return bc.GetBlock(hash, number)
  830. }
  831. // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
  832. func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
  833. if receipts, ok := bc.receiptsCache.Get(hash); ok {
  834. return receipts.(types.Receipts)
  835. }
  836. number := rawdb.ReadHeaderNumber(bc.db, hash)
  837. if number == nil {
  838. return nil
  839. }
  840. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  841. if receipts == nil {
  842. return nil
  843. }
  844. bc.receiptsCache.Add(hash, receipts)
  845. return receipts
  846. }
  847. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  848. // [deprecated by eth/62]
  849. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  850. number := bc.hc.GetBlockNumber(hash)
  851. if number == nil {
  852. return nil
  853. }
  854. for i := 0; i < n; i++ {
  855. block := bc.GetBlock(hash, *number)
  856. if block == nil {
  857. break
  858. }
  859. blocks = append(blocks, block)
  860. hash = block.ParentHash()
  861. *number--
  862. }
  863. return
  864. }
  865. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  866. // a specific distance is reached.
  867. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  868. uncles := []*types.Header{}
  869. for i := 0; block != nil && i < length; i++ {
  870. uncles = append(uncles, block.Uncles()...)
  871. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  872. }
  873. return uncles
  874. }
  875. // TrieNode retrieves a blob of data associated with a trie node
  876. // either from ephemeral in-memory cache, or from persistent storage.
  877. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  878. return bc.stateCache.TrieDB().Node(hash)
  879. }
  880. // ContractCode retrieves a blob of data associated with a contract hash
  881. // either from ephemeral in-memory cache, or from persistent storage.
  882. func (bc *BlockChain) ContractCode(hash common.Hash) ([]byte, error) {
  883. return bc.stateCache.ContractCode(common.Hash{}, hash)
  884. }
  885. // ContractCodeWithPrefix retrieves a blob of data associated with a contract
  886. // hash either from ephemeral in-memory cache, or from persistent storage.
  887. //
  888. // If the code doesn't exist in the in-memory cache, check the storage with
  889. // new code scheme.
  890. func (bc *BlockChain) ContractCodeWithPrefix(hash common.Hash) ([]byte, error) {
  891. type codeReader interface {
  892. ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error)
  893. }
  894. return bc.stateCache.(codeReader).ContractCodeWithPrefix(common.Hash{}, hash)
  895. }
  896. // Stop stops the blockchain service. If any imports are currently in progress
  897. // it will abort them using the procInterrupt.
  898. func (bc *BlockChain) Stop() {
  899. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  900. return
  901. }
  902. // Unsubscribe all subscriptions registered from blockchain
  903. bc.scope.Close()
  904. close(bc.quit)
  905. bc.StopInsert()
  906. bc.wg.Wait()
  907. // Ensure that the entirety of the state snapshot is journalled to disk.
  908. var snapBase common.Hash
  909. if bc.snaps != nil {
  910. var err error
  911. if bc.writeLegacyJournal {
  912. if snapBase, err = bc.snaps.LegacyJournal(bc.CurrentBlock().Root()); err != nil {
  913. log.Error("Failed to journal state snapshot", "err", err)
  914. }
  915. } else {
  916. if snapBase, err = bc.snaps.Journal(bc.CurrentBlock().Root()); err != nil {
  917. log.Error("Failed to journal state snapshot", "err", err)
  918. }
  919. }
  920. }
  921. // Ensure the state of a recent block is also stored to disk before exiting.
  922. // We're writing three different states to catch different restart scenarios:
  923. // - HEAD: So we don't need to reprocess any blocks in the general case
  924. // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle
  925. // - HEAD-127: So we have a hard limit on the number of blocks reexecuted
  926. if !bc.cacheConfig.TrieDirtyDisabled {
  927. triedb := bc.stateCache.TrieDB()
  928. for _, offset := range []uint64{0, 1, TriesInMemory - 1} {
  929. if number := bc.CurrentBlock().NumberU64(); number > offset {
  930. recent := bc.GetBlockByNumber(number - offset)
  931. log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
  932. if err := triedb.Commit(recent.Root(), true, nil); err != nil {
  933. log.Error("Failed to commit recent state trie", "err", err)
  934. }
  935. }
  936. }
  937. if snapBase != (common.Hash{}) {
  938. log.Info("Writing snapshot state to disk", "root", snapBase)
  939. if err := triedb.Commit(snapBase, true, nil); err != nil {
  940. log.Error("Failed to commit recent state trie", "err", err)
  941. }
  942. }
  943. for !bc.triegc.Empty() {
  944. triedb.Dereference(bc.triegc.PopItem().(common.Hash))
  945. }
  946. if size, _ := triedb.Size(); size != 0 {
  947. log.Error("Dangling trie nodes after full cleanup")
  948. }
  949. }
  950. // Ensure all live cached entries be saved into disk, so that we can skip
  951. // cache warmup when node restarts.
  952. if bc.cacheConfig.TrieCleanJournal != "" {
  953. triedb := bc.stateCache.TrieDB()
  954. triedb.SaveCache(bc.cacheConfig.TrieCleanJournal)
  955. }
  956. log.Info("Blockchain stopped")
  957. }
  958. // StopInsert interrupts all insertion methods, causing them to return
  959. // errInsertionInterrupted as soon as possible. Insertion is permanently disabled after
  960. // calling this method.
  961. func (bc *BlockChain) StopInsert() {
  962. atomic.StoreInt32(&bc.procInterrupt, 1)
  963. }
  964. // insertStopped returns true after StopInsert has been called.
  965. func (bc *BlockChain) insertStopped() bool {
  966. return atomic.LoadInt32(&bc.procInterrupt) == 1
  967. }
  968. func (bc *BlockChain) procFutureBlocks() {
  969. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  970. for _, hash := range bc.futureBlocks.Keys() {
  971. if block, exist := bc.futureBlocks.Peek(hash); exist {
  972. blocks = append(blocks, block.(*types.Block))
  973. }
  974. }
  975. if len(blocks) > 0 {
  976. sort.Slice(blocks, func(i, j int) bool {
  977. return blocks[i].NumberU64() < blocks[j].NumberU64()
  978. })
  979. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  980. for i := range blocks {
  981. bc.InsertChain(blocks[i : i+1])
  982. }
  983. }
  984. }
  985. // WriteStatus status of write
  986. type WriteStatus byte
  987. const (
  988. NonStatTy WriteStatus = iota
  989. CanonStatTy
  990. SideStatTy
  991. )
  992. // truncateAncient rewinds the blockchain to the specified header and deletes all
  993. // data in the ancient store that exceeds the specified header.
  994. func (bc *BlockChain) truncateAncient(head uint64) error {
  995. frozen, err := bc.db.Ancients()
  996. if err != nil {
  997. return err
  998. }
  999. // Short circuit if there is no data to truncate in ancient store.
  1000. if frozen <= head+1 {
  1001. return nil
  1002. }
  1003. // Truncate all the data in the freezer beyond the specified head
  1004. if err := bc.db.TruncateAncients(head + 1); err != nil {
  1005. return err
  1006. }
  1007. // Clear out any stale content from the caches
  1008. bc.hc.headerCache.Purge()
  1009. bc.hc.tdCache.Purge()
  1010. bc.hc.numberCache.Purge()
  1011. // Clear out any stale content from the caches
  1012. bc.bodyCache.Purge()
  1013. bc.bodyRLPCache.Purge()
  1014. bc.receiptsCache.Purge()
  1015. bc.blockCache.Purge()
  1016. bc.txLookupCache.Purge()
  1017. bc.futureBlocks.Purge()
  1018. log.Info("Rewind ancient data", "number", head)
  1019. return nil
  1020. }
  1021. // numberHash is just a container for a number and a hash, to represent a block
  1022. type numberHash struct {
  1023. number uint64
  1024. hash common.Hash
  1025. }
  1026. // InsertReceiptChain attempts to complete an already existing header chain with
  1027. // transaction and receipt data.
  1028. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts, ancientLimit uint64) (int, error) {
  1029. // We don't require the chainMu here since we want to maximize the
  1030. // concurrency of header insertion and receipt insertion.
  1031. bc.wg.Add(1)
  1032. defer bc.wg.Done()
  1033. var (
  1034. ancientBlocks, liveBlocks types.Blocks
  1035. ancientReceipts, liveReceipts []types.Receipts
  1036. )
  1037. // Do a sanity check that the provided chain is actually ordered and linked
  1038. for i := 0; i < len(blockChain); i++ {
  1039. if i != 0 {
  1040. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  1041. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  1042. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  1043. 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(),
  1044. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  1045. }
  1046. }
  1047. if blockChain[i].NumberU64() <= ancientLimit {
  1048. ancientBlocks, ancientReceipts = append(ancientBlocks, blockChain[i]), append(ancientReceipts, receiptChain[i])
  1049. } else {
  1050. liveBlocks, liveReceipts = append(liveBlocks, blockChain[i]), append(liveReceipts, receiptChain[i])
  1051. }
  1052. }
  1053. var (
  1054. stats = struct{ processed, ignored int32 }{}
  1055. start = time.Now()
  1056. size = 0
  1057. )
  1058. // updateHead updates the head fast sync block if the inserted blocks are better
  1059. // and returns an indicator whether the inserted blocks are canonical.
  1060. updateHead := func(head *types.Block) bool {
  1061. bc.chainmu.Lock()
  1062. // Rewind may have occurred, skip in that case.
  1063. if bc.CurrentHeader().Number.Cmp(head.Number()) >= 0 {
  1064. currentFastBlock, td := bc.CurrentFastBlock(), bc.GetTd(head.Hash(), head.NumberU64())
  1065. if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
  1066. rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
  1067. bc.currentFastBlock.Store(head)
  1068. headFastBlockGauge.Update(int64(head.NumberU64()))
  1069. bc.chainmu.Unlock()
  1070. return true
  1071. }
  1072. }
  1073. bc.chainmu.Unlock()
  1074. return false
  1075. }
  1076. // writeAncient writes blockchain and corresponding receipt chain into ancient store.
  1077. //
  1078. // this function only accepts canonical chain data. All side chain will be reverted
  1079. // eventually.
  1080. writeAncient := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  1081. var (
  1082. previous = bc.CurrentFastBlock()
  1083. batch = bc.db.NewBatch()
  1084. )
  1085. // If any error occurs before updating the head or we are inserting a side chain,
  1086. // all the data written this time wll be rolled back.
  1087. defer func() {
  1088. if previous != nil {
  1089. if err := bc.truncateAncient(previous.NumberU64()); err != nil {
  1090. log.Crit("Truncate ancient store failed", "err", err)
  1091. }
  1092. }
  1093. }()
  1094. var deleted []*numberHash
  1095. for i, block := range blockChain {
  1096. // Short circuit insertion if shutting down or processing failed
  1097. if bc.insertStopped() {
  1098. return 0, errInsertionInterrupted
  1099. }
  1100. // Short circuit insertion if it is required(used in testing only)
  1101. if bc.terminateInsert != nil && bc.terminateInsert(block.Hash(), block.NumberU64()) {
  1102. return i, errors.New("insertion is terminated for testing purpose")
  1103. }
  1104. // Short circuit if the owner header is unknown
  1105. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  1106. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  1107. }
  1108. var (
  1109. start = time.Now()
  1110. logged = time.Now()
  1111. count int
  1112. )
  1113. // Migrate all ancient blocks. This can happen if someone upgrades from Geth
  1114. // 1.8.x to 1.9.x mid-fast-sync. Perhaps we can get rid of this path in the
  1115. // long term.
  1116. for {
  1117. // We can ignore the error here since light client won't hit this code path.
  1118. frozen, _ := bc.db.Ancients()
  1119. if frozen >= block.NumberU64() {
  1120. break
  1121. }
  1122. h := rawdb.ReadCanonicalHash(bc.db, frozen)
  1123. b := rawdb.ReadBlock(bc.db, h, frozen)
  1124. size += rawdb.WriteAncientBlock(bc.db, b, rawdb.ReadReceipts(bc.db, h, frozen, bc.chainConfig), rawdb.ReadTd(bc.db, h, frozen))
  1125. count += 1
  1126. // Always keep genesis block in active database.
  1127. if b.NumberU64() != 0 {
  1128. deleted = append(deleted, &numberHash{b.NumberU64(), b.Hash()})
  1129. }
  1130. if time.Since(logged) > 8*time.Second {
  1131. log.Info("Migrating ancient blocks", "count", count, "elapsed", common.PrettyDuration(time.Since(start)))
  1132. logged = time.Now()
  1133. }
  1134. // Don't collect too much in-memory, write it out every 100K blocks
  1135. if len(deleted) > 100000 {
  1136. // Sync the ancient store explicitly to ensure all data has been flushed to disk.
  1137. if err := bc.db.Sync(); err != nil {
  1138. return 0, err
  1139. }
  1140. // Wipe out canonical block data.
  1141. for _, nh := range deleted {
  1142. rawdb.DeleteBlockWithoutNumber(batch, nh.hash, nh.number)
  1143. rawdb.DeleteCanonicalHash(batch, nh.number)
  1144. }
  1145. if err := batch.Write(); err != nil {
  1146. return 0, err
  1147. }
  1148. batch.Reset()
  1149. // Wipe out side chain too.
  1150. for _, nh := range deleted {
  1151. for _, hash := range rawdb.ReadAllHashes(bc.db, nh.number) {
  1152. rawdb.DeleteBlock(batch, hash, nh.number)
  1153. }
  1154. }
  1155. if err := batch.Write(); err != nil {
  1156. return 0, err
  1157. }
  1158. batch.Reset()
  1159. deleted = deleted[0:]
  1160. }
  1161. }
  1162. if count > 0 {
  1163. log.Info("Migrated ancient blocks", "count", count, "elapsed", common.PrettyDuration(time.Since(start)))
  1164. }
  1165. // Flush data into ancient database.
  1166. size += rawdb.WriteAncientBlock(bc.db, block, receiptChain[i], bc.GetTd(block.Hash(), block.NumberU64()))
  1167. // Write tx indices if any condition is satisfied:
  1168. // * If user requires to reserve all tx indices(txlookuplimit=0)
  1169. // * If all ancient tx indices are required to be reserved(txlookuplimit is even higher than ancientlimit)
  1170. // * If block number is large enough to be regarded as a recent block
  1171. // It means blocks below the ancientLimit-txlookupLimit won't be indexed.
  1172. //
  1173. // But if the `TxIndexTail` is not nil, e.g. Geth is initialized with
  1174. // an external ancient database, during the setup, blockchain will start
  1175. // a background routine to re-indexed all indices in [ancients - txlookupLimit, ancients)
  1176. // range. In this case, all tx indices of newly imported blocks should be
  1177. // generated.
  1178. if bc.txLookupLimit == 0 || ancientLimit <= bc.txLookupLimit || block.NumberU64() >= ancientLimit-bc.txLookupLimit {
  1179. rawdb.WriteTxLookupEntriesByBlock(batch, block)
  1180. } else if rawdb.ReadTxIndexTail(bc.db) != nil {
  1181. rawdb.WriteTxLookupEntriesByBlock(batch, block)
  1182. }
  1183. stats.processed++
  1184. }
  1185. // Flush all tx-lookup index data.
  1186. size += batch.ValueSize()
  1187. if err := batch.Write(); err != nil {
  1188. return 0, err
  1189. }
  1190. batch.Reset()
  1191. // Sync the ancient store explicitly to ensure all data has been flushed to disk.
  1192. if err := bc.db.Sync(); err != nil {
  1193. return 0, err
  1194. }
  1195. if !updateHead(blockChain[len(blockChain)-1]) {
  1196. return 0, errors.New("side blocks can't be accepted as the ancient chain data")
  1197. }
  1198. previous = nil // disable rollback explicitly
  1199. // Wipe out canonical block data.
  1200. for _, nh := range deleted {
  1201. rawdb.DeleteBlockWithoutNumber(batch, nh.hash, nh.number)
  1202. rawdb.DeleteCanonicalHash(batch, nh.number)
  1203. }
  1204. for _, block := range blockChain {
  1205. // Always keep genesis block in active database.
  1206. if block.NumberU64() != 0 {
  1207. rawdb.DeleteBlockWithoutNumber(batch, block.Hash(), block.NumberU64())
  1208. rawdb.DeleteCanonicalHash(batch, block.NumberU64())
  1209. }
  1210. }
  1211. if err := batch.Write(); err != nil {
  1212. return 0, err
  1213. }
  1214. batch.Reset()
  1215. // Wipe out side chain too.
  1216. for _, nh := range deleted {
  1217. for _, hash := range rawdb.ReadAllHashes(bc.db, nh.number) {
  1218. rawdb.DeleteBlock(batch, hash, nh.number)
  1219. }
  1220. }
  1221. for _, block := range blockChain {
  1222. // Always keep genesis block in active database.
  1223. if block.NumberU64() != 0 {
  1224. for _, hash := range rawdb.ReadAllHashes(bc.db, block.NumberU64()) {
  1225. rawdb.DeleteBlock(batch, hash, block.NumberU64())
  1226. }
  1227. }
  1228. }
  1229. if err := batch.Write(); err != nil {
  1230. return 0, err
  1231. }
  1232. return 0, nil
  1233. }
  1234. // writeLive writes blockchain and corresponding receipt chain into active store.
  1235. writeLive := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  1236. skipPresenceCheck := false
  1237. batch := bc.db.NewBatch()
  1238. for i, block := range blockChain {
  1239. // Short circuit insertion if shutting down or processing failed
  1240. if bc.insertStopped() {
  1241. return 0, errInsertionInterrupted
  1242. }
  1243. // Short circuit if the owner header is unknown
  1244. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  1245. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  1246. }
  1247. if !skipPresenceCheck {
  1248. // Ignore if the entire data is already known
  1249. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  1250. stats.ignored++
  1251. continue
  1252. } else {
  1253. // If block N is not present, neither are the later blocks.
  1254. // This should be true, but if we are mistaken, the shortcut
  1255. // here will only cause overwriting of some existing data
  1256. skipPresenceCheck = true
  1257. }
  1258. }
  1259. // Write all the data out into the database
  1260. rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
  1261. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receiptChain[i])
  1262. rawdb.WriteTxLookupEntriesByBlock(batch, block) // Always write tx indices for live blocks, we assume they are needed
  1263. // Write everything belongs to the blocks into the database. So that
  1264. // we can ensure all components of body is completed(body, receipts,
  1265. // tx indexes)
  1266. if batch.ValueSize() >= ethdb.IdealBatchSize {
  1267. if err := batch.Write(); err != nil {
  1268. return 0, err
  1269. }
  1270. size += batch.ValueSize()
  1271. batch.Reset()
  1272. }
  1273. stats.processed++
  1274. }
  1275. // Write everything belongs to the blocks into the database. So that
  1276. // we can ensure all components of body is completed(body, receipts,
  1277. // tx indexes)
  1278. if batch.ValueSize() > 0 {
  1279. size += batch.ValueSize()
  1280. if err := batch.Write(); err != nil {
  1281. return 0, err
  1282. }
  1283. }
  1284. updateHead(blockChain[len(blockChain)-1])
  1285. return 0, nil
  1286. }
  1287. // Write downloaded chain data and corresponding receipt chain data
  1288. if len(ancientBlocks) > 0 {
  1289. if n, err := writeAncient(ancientBlocks, ancientReceipts); err != nil {
  1290. if err == errInsertionInterrupted {
  1291. return 0, nil
  1292. }
  1293. return n, err
  1294. }
  1295. }
  1296. // Write the tx index tail (block number from where we index) before write any live blocks
  1297. if len(liveBlocks) > 0 && liveBlocks[0].NumberU64() == ancientLimit+1 {
  1298. // The tx index tail can only be one of the following two options:
  1299. // * 0: all ancient blocks have been indexed
  1300. // * ancient-limit: the indices of blocks before ancient-limit are ignored
  1301. if tail := rawdb.ReadTxIndexTail(bc.db); tail == nil {
  1302. if bc.txLookupLimit == 0 || ancientLimit <= bc.txLookupLimit {
  1303. rawdb.WriteTxIndexTail(bc.db, 0)
  1304. } else {
  1305. rawdb.WriteTxIndexTail(bc.db, ancientLimit-bc.txLookupLimit)
  1306. }
  1307. }
  1308. }
  1309. if len(liveBlocks) > 0 {
  1310. if n, err := writeLive(liveBlocks, liveReceipts); err != nil {
  1311. if err == errInsertionInterrupted {
  1312. return 0, nil
  1313. }
  1314. return n, err
  1315. }
  1316. }
  1317. head := blockChain[len(blockChain)-1]
  1318. context := []interface{}{
  1319. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  1320. "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(int64(head.Time()), 0)),
  1321. "size", common.StorageSize(size),
  1322. }
  1323. if stats.ignored > 0 {
  1324. context = append(context, []interface{}{"ignored", stats.ignored}...)
  1325. }
  1326. log.Info("Imported new block receipts", context...)
  1327. return 0, nil
  1328. }
  1329. // SetTxLookupLimit is responsible for updating the txlookup limit to the
  1330. // original one stored in db if the new mismatches with the old one.
  1331. func (bc *BlockChain) SetTxLookupLimit(limit uint64) {
  1332. bc.txLookupLimit = limit
  1333. }
  1334. // TxLookupLimit retrieves the txlookup limit used by blockchain to prune
  1335. // stale transaction indices.
  1336. func (bc *BlockChain) TxLookupLimit() uint64 {
  1337. return bc.txLookupLimit
  1338. }
  1339. var lastWrite uint64
  1340. // writeBlockWithoutState writes only the block and its metadata to the database,
  1341. // but does not write any state. This is used to construct competing side forks
  1342. // up to the point where they exceed the canonical total difficulty.
  1343. func (bc *BlockChain) writeBlockWithoutState(block *types.Block, td *big.Int) (err error) {
  1344. bc.wg.Add(1)
  1345. defer bc.wg.Done()
  1346. batch := bc.db.NewBatch()
  1347. rawdb.WriteTd(batch, block.Hash(), block.NumberU64(), td)
  1348. rawdb.WriteBlock(batch, block)
  1349. if err := batch.Write(); err != nil {
  1350. log.Crit("Failed to write block into disk", "err", err)
  1351. }
  1352. return nil
  1353. }
  1354. // writeKnownBlock updates the head block flag with a known block
  1355. // and introduces chain reorg if necessary.
  1356. func (bc *BlockChain) writeKnownBlock(block *types.Block) error {
  1357. bc.wg.Add(1)
  1358. defer bc.wg.Done()
  1359. current := bc.CurrentBlock()
  1360. if block.ParentHash() != current.Hash() {
  1361. if err := bc.reorg(current, block); err != nil {
  1362. return err
  1363. }
  1364. }
  1365. bc.writeHeadBlock(block)
  1366. return nil
  1367. }
  1368. // WriteBlockWithState writes the block and all associated state to the database.
  1369. func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, emitHeadEvent bool) (status WriteStatus, err error) {
  1370. bc.chainmu.Lock()
  1371. defer bc.chainmu.Unlock()
  1372. return bc.writeBlockWithState(block, receipts, logs, state, emitHeadEvent)
  1373. }
  1374. // writeBlockWithState writes the block and all associated state to the database,
  1375. // but is expects the chain mutex to be held.
  1376. func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, emitHeadEvent bool) (status WriteStatus, err error) {
  1377. bc.wg.Add(1)
  1378. defer bc.wg.Done()
  1379. // Calculate the total difficulty of the block
  1380. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1381. if ptd == nil {
  1382. return NonStatTy, consensus.ErrUnknownAncestor
  1383. }
  1384. // Make sure no inconsistent state is leaked during insertion
  1385. currentBlock := bc.CurrentBlock()
  1386. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  1387. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  1388. // Irrelevant of the canonical status, write the block itself to the database.
  1389. //
  1390. // Note all the components of block(td, hash->number map, header, body, receipts)
  1391. // should be written atomically. BlockBatch is used for containing all components.
  1392. blockBatch := bc.db.NewBatch()
  1393. rawdb.WriteTd(blockBatch, block.Hash(), block.NumberU64(), externTd)
  1394. rawdb.WriteBlock(blockBatch, block)
  1395. rawdb.WriteReceipts(blockBatch, block.Hash(), block.NumberU64(), receipts)
  1396. rawdb.WritePreimages(blockBatch, state.Preimages())
  1397. if err := blockBatch.Write(); err != nil {
  1398. log.Crit("Failed to write block into disk", "err", err)
  1399. }
  1400. // Commit all cached state changes into underlying memory database.
  1401. root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
  1402. if err != nil {
  1403. return NonStatTy, err
  1404. }
  1405. triedb := bc.stateCache.TrieDB()
  1406. // If we're running an archive node, always flush
  1407. if bc.cacheConfig.TrieDirtyDisabled {
  1408. if err := triedb.Commit(root, false, nil); err != nil {
  1409. return NonStatTy, err
  1410. }
  1411. } else {
  1412. // Full but not archive node, do proper garbage collection
  1413. triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
  1414. bc.triegc.Push(root, -int64(block.NumberU64()))
  1415. if current := block.NumberU64(); current > TriesInMemory {
  1416. // If we exceeded our memory allowance, flush matured singleton nodes to disk
  1417. var (
  1418. nodes, imgs = triedb.Size()
  1419. limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
  1420. )
  1421. if nodes > limit || imgs > 4*1024*1024 {
  1422. triedb.Cap(limit - ethdb.IdealBatchSize)
  1423. }
  1424. // Find the next state trie we need to commit
  1425. chosen := current - TriesInMemory
  1426. // If we exceeded out time allowance, flush an entire trie to disk
  1427. if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
  1428. // If the header is missing (canonical chain behind), we're reorging a low
  1429. // diff sidechain. Suspend committing until this operation is completed.
  1430. header := bc.GetHeaderByNumber(chosen)
  1431. if header == nil {
  1432. log.Warn("Reorg in progress, trie commit postponed", "number", chosen)
  1433. } else {
  1434. // If we're exceeding limits but haven't reached a large enough memory gap,
  1435. // warn the user that the system is becoming unstable.
  1436. if chosen < lastWrite+TriesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
  1437. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/TriesInMemory)
  1438. }
  1439. // Flush an entire trie and restart the counters
  1440. triedb.Commit(header.Root, true, nil)
  1441. lastWrite = chosen
  1442. bc.gcproc = 0
  1443. }
  1444. }
  1445. // Garbage collect anything below our required write retention
  1446. for !bc.triegc.Empty() {
  1447. root, number := bc.triegc.Pop()
  1448. if uint64(-number) > chosen {
  1449. bc.triegc.Push(root, number)
  1450. break
  1451. }
  1452. triedb.Dereference(root.(common.Hash))
  1453. }
  1454. }
  1455. }
  1456. // If the total difficulty is higher than our known, add it to the canonical chain
  1457. // Second clause in the if statement reduces the vulnerability to selfish mining.
  1458. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  1459. reorg := externTd.Cmp(localTd) > 0
  1460. currentBlock = bc.CurrentBlock()
  1461. if !reorg && externTd.Cmp(localTd) == 0 {
  1462. // Split same-difficulty blocks by number, then preferentially select
  1463. // the block generated by the local miner as the canonical block.
  1464. if block.NumberU64() < currentBlock.NumberU64() {
  1465. reorg = true
  1466. } else if block.NumberU64() == currentBlock.NumberU64() {
  1467. var currentPreserve, blockPreserve bool
  1468. if bc.shouldPreserve != nil {
  1469. currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  1470. }
  1471. reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  1472. }
  1473. }
  1474. if reorg {
  1475. // Reorganise the chain if the parent is not the head block
  1476. if block.ParentHash() != currentBlock.Hash() {
  1477. if err := bc.reorg(currentBlock, block); err != nil {
  1478. return NonStatTy, err
  1479. }
  1480. }
  1481. status = CanonStatTy
  1482. } else {
  1483. status = SideStatTy
  1484. }
  1485. // Set new head.
  1486. if status == CanonStatTy {
  1487. bc.writeHeadBlock(block)
  1488. }
  1489. bc.futureBlocks.Remove(block.Hash())
  1490. if status == CanonStatTy {
  1491. bc.chainFeed.Send(ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
  1492. if len(logs) > 0 {
  1493. bc.logsFeed.Send(logs)
  1494. }
  1495. // In theory we should fire a ChainHeadEvent when we inject
  1496. // a canonical block, but sometimes we can insert a batch of
  1497. // canonicial blocks. Avoid firing too much ChainHeadEvents,
  1498. // we will fire an accumulated ChainHeadEvent and disable fire
  1499. // event here.
  1500. if emitHeadEvent {
  1501. bc.chainHeadFeed.Send(ChainHeadEvent{Block: block})
  1502. }
  1503. } else {
  1504. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1505. }
  1506. return status, nil
  1507. }
  1508. // addFutureBlock checks if the block is within the max allowed window to get
  1509. // accepted for future processing, and returns an error if the block is too far
  1510. // ahead and was not added.
  1511. func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  1512. max := uint64(time.Now().Unix() + maxTimeFutureBlocks)
  1513. if block.Time() > max {
  1514. return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  1515. }
  1516. bc.futureBlocks.Add(block.Hash(), block)
  1517. return nil
  1518. }
  1519. // InsertChain attempts to insert the given batch of blocks in to the canonical
  1520. // chain or, otherwise, create a fork. If an error is returned it will return
  1521. // the index number of the failing block as well an error describing what went
  1522. // wrong.
  1523. //
  1524. // After insertion is done, all accumulated events will be fired.
  1525. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  1526. // Sanity check that we have something meaningful to import
  1527. if len(chain) == 0 {
  1528. return 0, nil
  1529. }
  1530. bc.blockProcFeed.Send(true)
  1531. defer bc.blockProcFeed.Send(false)
  1532. // Remove already known canon-blocks
  1533. var (
  1534. block, prev *types.Block
  1535. )
  1536. // Do a sanity check that the provided chain is actually ordered and linked
  1537. for i := 1; i < len(chain); i++ {
  1538. block = chain[i]
  1539. prev = chain[i-1]
  1540. if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() {
  1541. // Chain broke ancestry, log a message (programming error) and skip insertion
  1542. log.Error("Non contiguous block insert", "number", block.Number(), "hash", block.Hash(),
  1543. "parent", block.ParentHash(), "prevnumber", prev.Number(), "prevhash", prev.Hash())
  1544. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, prev.NumberU64(),
  1545. prev.Hash().Bytes()[:4], i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4])
  1546. }
  1547. }
  1548. // Pre-checks passed, start the full block imports
  1549. bc.wg.Add(1)
  1550. bc.chainmu.Lock()
  1551. n, err := bc.insertChain(chain, true)
  1552. bc.chainmu.Unlock()
  1553. bc.wg.Done()
  1554. return n, err
  1555. }
  1556. // insertChain is the internal implementation of InsertChain, which assumes that
  1557. // 1) chains are contiguous, and 2) The chain mutex is held.
  1558. //
  1559. // This method is split out so that import batches that require re-injecting
  1560. // historical blocks can do so without releasing the lock, which could lead to
  1561. // racey behaviour. If a sidechain import is in progress, and the historic state
  1562. // is imported, but then new canon-head is added before the actual sidechain
  1563. // completes, then the historic state could be pruned again
  1564. func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, error) {
  1565. // If the chain is terminating, don't even bother starting up
  1566. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1567. return 0, nil
  1568. }
  1569. // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  1570. senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  1571. var (
  1572. stats = insertStats{startTime: mclock.Now()}
  1573. lastCanon *types.Block
  1574. )
  1575. // Fire a single chain head event if we've progressed the chain
  1576. defer func() {
  1577. if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1578. bc.chainHeadFeed.Send(ChainHeadEvent{lastCanon})
  1579. }
  1580. }()
  1581. // Start the parallel header verifier
  1582. headers := make([]*types.Header, len(chain))
  1583. seals := make([]bool, len(chain))
  1584. for i, block := range chain {
  1585. headers[i] = block.Header()
  1586. seals[i] = verifySeals
  1587. }
  1588. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1589. defer close(abort)
  1590. // Peek the error for the first block to decide the directing import logic
  1591. it := newInsertIterator(chain, results, bc.validator)
  1592. block, err := it.next()
  1593. // Left-trim all the known blocks
  1594. if err == ErrKnownBlock {
  1595. // First block (and state) is known
  1596. // 1. We did a roll-back, and should now do a re-import
  1597. // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1598. // from the canonical chain, which has not been verified.
  1599. // Skip all known blocks that are behind us
  1600. var (
  1601. current = bc.CurrentBlock()
  1602. localTd = bc.GetTd(current.Hash(), current.NumberU64())
  1603. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1) // The first block can't be nil
  1604. )
  1605. for block != nil && err == ErrKnownBlock {
  1606. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1607. if localTd.Cmp(externTd) < 0 {
  1608. break
  1609. }
  1610. log.Debug("Ignoring already known block", "number", block.Number(), "hash", block.Hash())
  1611. stats.ignored++
  1612. block, err = it.next()
  1613. }
  1614. // The remaining blocks are still known blocks, the only scenario here is:
  1615. // During the fast sync, the pivot point is already submitted but rollback
  1616. // happens. Then node resets the head full block to a lower height via `rollback`
  1617. // and leaves a few known blocks in the database.
  1618. //
  1619. // When node runs a fast sync again, it can re-import a batch of known blocks via
  1620. // `insertChain` while a part of them have higher total difficulty than current
  1621. // head full block(new pivot point).
  1622. for block != nil && err == ErrKnownBlock {
  1623. log.Debug("Writing previously known block", "number", block.Number(), "hash", block.Hash())
  1624. if err := bc.writeKnownBlock(block); err != nil {
  1625. return it.index, err
  1626. }
  1627. lastCanon = block
  1628. block, err = it.next()
  1629. }
  1630. // Falls through to the block import
  1631. }
  1632. switch {
  1633. // First block is pruned, insert as sidechain and reorg only if TD grows enough
  1634. case errors.Is(err, consensus.ErrPrunedAncestor):
  1635. log.Debug("Pruned ancestor, inserting as sidechain", "number", block.Number(), "hash", block.Hash())
  1636. return bc.insertSideChain(block, it)
  1637. // First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1638. case errors.Is(err, consensus.ErrFutureBlock) || (errors.Is(err, consensus.ErrUnknownAncestor) && bc.futureBlocks.Contains(it.first().ParentHash())):
  1639. for block != nil && (it.index == 0 || errors.Is(err, consensus.ErrUnknownAncestor)) {
  1640. log.Debug("Future block, postponing import", "number", block.Number(), "hash", block.Hash())
  1641. if err := bc.addFutureBlock(block); err != nil {
  1642. return it.index, err
  1643. }
  1644. block, err = it.next()
  1645. }
  1646. stats.queued += it.processed()
  1647. stats.ignored += it.remaining()
  1648. // If there are any still remaining, mark as ignored
  1649. return it.index, err
  1650. // Some other error occurred, abort
  1651. case err != nil:
  1652. bc.futureBlocks.Remove(block.Hash())
  1653. stats.ignored += len(it.chain)
  1654. bc.reportBlock(block, nil, err)
  1655. return it.index, err
  1656. }
  1657. // No validation errors for the first block (or chain prefix skipped)
  1658. var activeState *state.StateDB
  1659. defer func() {
  1660. // The chain importer is starting and stopping trie prefetchers. If a bad
  1661. // block or other error is hit however, an early return may not properly
  1662. // terminate the background threads. This defer ensures that we clean up
  1663. // and dangling prefetcher, without defering each and holding on live refs.
  1664. if activeState != nil {
  1665. activeState.StopPrefetcher()
  1666. }
  1667. }()
  1668. for ; block != nil && err == nil || err == ErrKnownBlock; block, err = it.next() {
  1669. // If the chain is terminating, stop processing blocks
  1670. if bc.insertStopped() {
  1671. log.Debug("Abort during block processing")
  1672. break
  1673. }
  1674. // If the header is a banned one, straight out abort
  1675. if BadHashes[block.Hash()] {
  1676. bc.reportBlock(block, nil, ErrBlacklistedHash)
  1677. return it.index, ErrBlacklistedHash
  1678. }
  1679. // If the block is known (in the middle of the chain), it's a special case for
  1680. // Clique blocks where they can share state among each other, so importing an
  1681. // older block might complete the state of the subsequent one. In this case,
  1682. // just skip the block (we already validated it once fully (and crashed), since
  1683. // its header and body was already in the database).
  1684. if err == ErrKnownBlock {
  1685. logger := log.Debug
  1686. if bc.chainConfig.Clique == nil {
  1687. logger = log.Warn
  1688. }
  1689. logger("Inserted known block", "number", block.Number(), "hash", block.Hash(),
  1690. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1691. "root", block.Root())
  1692. // Special case. Commit the empty receipt slice if we meet the known
  1693. // block in the middle. It can only happen in the clique chain. Whenever
  1694. // we insert blocks via `insertSideChain`, we only commit `td`, `header`
  1695. // and `body` if it's non-existent. Since we don't have receipts without
  1696. // reexecution, so nothing to commit. But if the sidechain will be adpoted
  1697. // as the canonical chain eventually, it needs to be reexecuted for missing
  1698. // state, but if it's this special case here(skip reexecution) we will lose
  1699. // the empty receipt entry.
  1700. if len(block.Transactions()) == 0 {
  1701. rawdb.WriteReceipts(bc.db, block.Hash(), block.NumberU64(), nil)
  1702. } else {
  1703. log.Error("Please file an issue, skip known block execution without receipt",
  1704. "hash", block.Hash(), "number", block.NumberU64())
  1705. }
  1706. if err := bc.writeKnownBlock(block); err != nil {
  1707. return it.index, err
  1708. }
  1709. stats.processed++
  1710. // We can assume that logs are empty here, since the only way for consecutive
  1711. // Clique blocks to have the same state is if there are no transactions.
  1712. lastCanon = block
  1713. continue
  1714. }
  1715. // Retrieve the parent block and it's state to execute on top
  1716. start := time.Now()
  1717. parent := it.previous()
  1718. if parent == nil {
  1719. parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
  1720. }
  1721. statedb, err := state.New(parent.Root, bc.stateCache, bc.snaps)
  1722. if err != nil {
  1723. return it.index, err
  1724. }
  1725. // Enable prefetching to pull in trie node paths while processing transactions
  1726. statedb.StartPrefetcher("chain")
  1727. activeState = statedb
  1728. // If we have a followup block, run that against the current state to pre-cache
  1729. // transactions and probabilistically some of the account/storage trie nodes.
  1730. var followupInterrupt uint32
  1731. if !bc.cacheConfig.TrieCleanNoPrefetch {
  1732. if followup, err := it.peek(); followup != nil && err == nil {
  1733. throwaway, _ := state.New(parent.Root, bc.stateCache, bc.snaps)
  1734. go func(start time.Time, followup *types.Block, throwaway *state.StateDB, interrupt *uint32) {
  1735. bc.prefetcher.Prefetch(followup, throwaway, bc.vmConfig, &followupInterrupt)
  1736. blockPrefetchExecuteTimer.Update(time.Since(start))
  1737. if atomic.LoadUint32(interrupt) == 1 {
  1738. blockPrefetchInterruptMeter.Mark(1)
  1739. }
  1740. }(time.Now(), followup, throwaway, &followupInterrupt)
  1741. }
  1742. }
  1743. // Process block using the parent state as reference point
  1744. substart := time.Now()
  1745. receipts, logs, usedGas, err := bc.processor.Process(block, statedb, bc.vmConfig)
  1746. if err != nil {
  1747. bc.reportBlock(block, receipts, err)
  1748. atomic.StoreUint32(&followupInterrupt, 1)
  1749. return it.index, err
  1750. }
  1751. // Update the metrics touched during block processing
  1752. accountReadTimer.Update(statedb.AccountReads) // Account reads are complete, we can mark them
  1753. storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete, we can mark them
  1754. accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete, we can mark them
  1755. storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them
  1756. snapshotAccountReadTimer.Update(statedb.SnapshotAccountReads) // Account reads are complete, we can mark them
  1757. snapshotStorageReadTimer.Update(statedb.SnapshotStorageReads) // Storage reads are complete, we can mark them
  1758. triehash := statedb.AccountHashes + statedb.StorageHashes // Save to not double count in validation
  1759. trieproc := statedb.SnapshotAccountReads + statedb.AccountReads + statedb.AccountUpdates
  1760. trieproc += statedb.SnapshotStorageReads + statedb.StorageReads + statedb.StorageUpdates
  1761. blockExecutionTimer.Update(time.Since(substart) - trieproc - triehash)
  1762. // Validate the state using the default validator
  1763. substart = time.Now()
  1764. if err := bc.validator.ValidateState(block, statedb, receipts, usedGas); err != nil {
  1765. bc.reportBlock(block, receipts, err)
  1766. atomic.StoreUint32(&followupInterrupt, 1)
  1767. return it.index, err
  1768. }
  1769. proctime := time.Since(start)
  1770. // Update the metrics touched during block validation
  1771. accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete, we can mark them
  1772. storageHashTimer.Update(statedb.StorageHashes) // Storage hashes are complete, we can mark them
  1773. blockValidationTimer.Update(time.Since(substart) - (statedb.AccountHashes + statedb.StorageHashes - triehash))
  1774. // Write the block to the chain and get the status.
  1775. substart = time.Now()
  1776. status, err := bc.writeBlockWithState(block, receipts, logs, statedb, false)
  1777. atomic.StoreUint32(&followupInterrupt, 1)
  1778. if err != nil {
  1779. return it.index, err
  1780. }
  1781. // Update the metrics touched during block commit
  1782. accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them
  1783. storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them
  1784. snapshotCommitTimer.Update(statedb.SnapshotCommits) // Snapshot commits are complete, we can mark them
  1785. blockWriteTimer.Update(time.Since(substart) - statedb.AccountCommits - statedb.StorageCommits - statedb.SnapshotCommits)
  1786. blockInsertTimer.UpdateSince(start)
  1787. switch status {
  1788. case CanonStatTy:
  1789. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1790. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1791. "elapsed", common.PrettyDuration(time.Since(start)),
  1792. "root", block.Root())
  1793. lastCanon = block
  1794. // Only count canonical blocks for GC processing time
  1795. bc.gcproc += proctime
  1796. case SideStatTy:
  1797. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1798. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1799. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1800. "root", block.Root())
  1801. default:
  1802. // This in theory is impossible, but lets be nice to our future selves and leave
  1803. // a log, instead of trying to track down blocks imports that don't emit logs.
  1804. log.Warn("Inserted block with unknown status", "number", block.Number(), "hash", block.Hash(),
  1805. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1806. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1807. "root", block.Root())
  1808. }
  1809. stats.processed++
  1810. stats.usedGas += usedGas
  1811. dirty, _ := bc.stateCache.TrieDB().Size()
  1812. stats.report(chain, it.index, dirty)
  1813. }
  1814. // Any blocks remaining here? The only ones we care about are the future ones
  1815. if block != nil && errors.Is(err, consensus.ErrFutureBlock) {
  1816. if err := bc.addFutureBlock(block); err != nil {
  1817. return it.index, err
  1818. }
  1819. block, err = it.next()
  1820. for ; block != nil && errors.Is(err, consensus.ErrUnknownAncestor); block, err = it.next() {
  1821. if err := bc.addFutureBlock(block); err != nil {
  1822. return it.index, err
  1823. }
  1824. stats.queued++
  1825. }
  1826. }
  1827. stats.ignored += it.remaining()
  1828. return it.index, err
  1829. }
  1830. // insertSideChain is called when an import batch hits upon a pruned ancestor
  1831. // error, which happens when a sidechain with a sufficiently old fork-block is
  1832. // found.
  1833. //
  1834. // The method writes all (header-and-body-valid) blocks to disk, then tries to
  1835. // switch over to the new chain if the TD exceeded the current chain.
  1836. func (bc *BlockChain) insertSideChain(block *types.Block, it *insertIterator) (int, error) {
  1837. var (
  1838. externTd *big.Int
  1839. current = bc.CurrentBlock()
  1840. )
  1841. // The first sidechain block error is already verified to be ErrPrunedAncestor.
  1842. // Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  1843. // ones. Any other errors means that the block is invalid, and should not be written
  1844. // to disk.
  1845. err := consensus.ErrPrunedAncestor
  1846. for ; block != nil && errors.Is(err, consensus.ErrPrunedAncestor); block, err = it.next() {
  1847. // Check the canonical state root for that number
  1848. if number := block.NumberU64(); current.NumberU64() >= number {
  1849. canonical := bc.GetBlockByNumber(number)
  1850. if canonical != nil && canonical.Hash() == block.Hash() {
  1851. // Not a sidechain block, this is a re-import of a canon block which has it's state pruned
  1852. // Collect the TD of the block. Since we know it's a canon one,
  1853. // we can get it directly, and not (like further below) use
  1854. // the parent and then add the block on top
  1855. externTd = bc.GetTd(block.Hash(), block.NumberU64())
  1856. continue
  1857. }
  1858. if canonical != nil && canonical.Root() == block.Root() {
  1859. // This is most likely a shadow-state attack. When a fork is imported into the
  1860. // database, and it eventually reaches a block height which is not pruned, we
  1861. // just found that the state already exist! This means that the sidechain block
  1862. // refers to a state which already exists in our canon chain.
  1863. //
  1864. // If left unchecked, we would now proceed importing the blocks, without actually
  1865. // having verified the state of the previous blocks.
  1866. log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  1867. // If someone legitimately side-mines blocks, they would still be imported as usual. However,
  1868. // we cannot risk writing unverified blocks to disk when they obviously target the pruning
  1869. // mechanism.
  1870. return it.index, errors.New("sidechain ghost-state attack")
  1871. }
  1872. }
  1873. if externTd == nil {
  1874. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1875. }
  1876. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1877. if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  1878. start := time.Now()
  1879. if err := bc.writeBlockWithoutState(block, externTd); err != nil {
  1880. return it.index, err
  1881. }
  1882. log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(),
  1883. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1884. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1885. "root", block.Root())
  1886. }
  1887. }
  1888. // At this point, we've written all sidechain blocks to database. Loop ended
  1889. // either on some other error or all were processed. If there was some other
  1890. // error, we can ignore the rest of those blocks.
  1891. //
  1892. // If the externTd was larger than our local TD, we now need to reimport the previous
  1893. // blocks to regenerate the required state
  1894. localTd := bc.GetTd(current.Hash(), current.NumberU64())
  1895. if localTd.Cmp(externTd) > 0 {
  1896. log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().Number, "sidetd", externTd, "localtd", localTd)
  1897. return it.index, err
  1898. }
  1899. // Gather all the sidechain hashes (full blocks may be memory heavy)
  1900. var (
  1901. hashes []common.Hash
  1902. numbers []uint64
  1903. )
  1904. parent := it.previous()
  1905. for parent != nil && !bc.HasState(parent.Root) {
  1906. hashes = append(hashes, parent.Hash())
  1907. numbers = append(numbers, parent.Number.Uint64())
  1908. parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  1909. }
  1910. if parent == nil {
  1911. return it.index, errors.New("missing parent")
  1912. }
  1913. // Import all the pruned blocks to make the state available
  1914. var (
  1915. blocks []*types.Block
  1916. memory common.StorageSize
  1917. )
  1918. for i := len(hashes) - 1; i >= 0; i-- {
  1919. // Append the next block to our batch
  1920. block := bc.GetBlock(hashes[i], numbers[i])
  1921. blocks = append(blocks, block)
  1922. memory += block.Size()
  1923. // If memory use grew too large, import and continue. Sadly we need to discard
  1924. // all raised events and logs from notifications since we're too heavy on the
  1925. // memory here.
  1926. if len(blocks) >= 2048 || memory > 64*1024*1024 {
  1927. log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  1928. if _, err := bc.insertChain(blocks, false); err != nil {
  1929. return 0, err
  1930. }
  1931. blocks, memory = blocks[:0], 0
  1932. // If the chain is terminating, stop processing blocks
  1933. if bc.insertStopped() {
  1934. log.Debug("Abort during blocks processing")
  1935. return 0, nil
  1936. }
  1937. }
  1938. }
  1939. if len(blocks) > 0 {
  1940. log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  1941. return bc.insertChain(blocks, false)
  1942. }
  1943. return 0, nil
  1944. }
  1945. // reorg takes two blocks, an old chain and a new chain and will reconstruct the
  1946. // blocks and inserts them to be part of the new canonical chain and accumulates
  1947. // potential missing transactions and post an event about them.
  1948. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1949. var (
  1950. newChain types.Blocks
  1951. oldChain types.Blocks
  1952. commonBlock *types.Block
  1953. deletedTxs types.Transactions
  1954. addedTxs types.Transactions
  1955. deletedLogs [][]*types.Log
  1956. rebirthLogs [][]*types.Log
  1957. // collectLogs collects the logs that were generated or removed during
  1958. // the processing of the block that corresponds with the given hash.
  1959. // These logs are later announced as deleted or reborn
  1960. collectLogs = func(hash common.Hash, removed bool) {
  1961. number := bc.hc.GetBlockNumber(hash)
  1962. if number == nil {
  1963. return
  1964. }
  1965. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  1966. var logs []*types.Log
  1967. for _, receipt := range receipts {
  1968. for _, log := range receipt.Logs {
  1969. l := *log
  1970. if removed {
  1971. l.Removed = true
  1972. } else {
  1973. }
  1974. logs = append(logs, &l)
  1975. }
  1976. }
  1977. if len(logs) > 0 {
  1978. if removed {
  1979. deletedLogs = append(deletedLogs, logs)
  1980. } else {
  1981. rebirthLogs = append(rebirthLogs, logs)
  1982. }
  1983. }
  1984. }
  1985. // mergeLogs returns a merged log slice with specified sort order.
  1986. mergeLogs = func(logs [][]*types.Log, reverse bool) []*types.Log {
  1987. var ret []*types.Log
  1988. if reverse {
  1989. for i := len(logs) - 1; i >= 0; i-- {
  1990. ret = append(ret, logs[i]...)
  1991. }
  1992. } else {
  1993. for i := 0; i < len(logs); i++ {
  1994. ret = append(ret, logs[i]...)
  1995. }
  1996. }
  1997. return ret
  1998. }
  1999. )
  2000. // Reduce the longer chain to the same number as the shorter one
  2001. if oldBlock.NumberU64() > newBlock.NumberU64() {
  2002. // Old chain is longer, gather all transactions and logs as deleted ones
  2003. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  2004. oldChain = append(oldChain, oldBlock)
  2005. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  2006. collectLogs(oldBlock.Hash(), true)
  2007. }
  2008. } else {
  2009. // New chain is longer, stash all blocks away for subsequent insertion
  2010. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  2011. newChain = append(newChain, newBlock)
  2012. }
  2013. }
  2014. if oldBlock == nil {
  2015. return fmt.Errorf("invalid old chain")
  2016. }
  2017. if newBlock == nil {
  2018. return fmt.Errorf("invalid new chain")
  2019. }
  2020. // Both sides of the reorg are at the same number, reduce both until the common
  2021. // ancestor is found
  2022. for {
  2023. // If the common ancestor was found, bail out
  2024. if oldBlock.Hash() == newBlock.Hash() {
  2025. commonBlock = oldBlock
  2026. break
  2027. }
  2028. // Remove an old block as well as stash away a new block
  2029. oldChain = append(oldChain, oldBlock)
  2030. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  2031. collectLogs(oldBlock.Hash(), true)
  2032. newChain = append(newChain, newBlock)
  2033. // Step back with both chains
  2034. oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1)
  2035. if oldBlock == nil {
  2036. return fmt.Errorf("invalid old chain")
  2037. }
  2038. newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  2039. if newBlock == nil {
  2040. return fmt.Errorf("invalid new chain")
  2041. }
  2042. }
  2043. // Ensure the user sees large reorgs
  2044. if len(oldChain) > 0 && len(newChain) > 0 {
  2045. logFn := log.Info
  2046. msg := "Chain reorg detected"
  2047. if len(oldChain) > 63 {
  2048. msg = "Large chain reorg detected"
  2049. logFn = log.Warn
  2050. }
  2051. logFn(msg, "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  2052. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  2053. blockReorgAddMeter.Mark(int64(len(newChain)))
  2054. blockReorgDropMeter.Mark(int64(len(oldChain)))
  2055. blockReorgMeter.Mark(1)
  2056. } else {
  2057. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  2058. }
  2059. // Insert the new chain(except the head block(reverse order)),
  2060. // taking care of the proper incremental order.
  2061. for i := len(newChain) - 1; i >= 1; i-- {
  2062. // Insert the block in the canonical way, re-writing history
  2063. bc.writeHeadBlock(newChain[i])
  2064. // Collect reborn logs due to chain reorg
  2065. collectLogs(newChain[i].Hash(), false)
  2066. // Collect the new added transactions.
  2067. addedTxs = append(addedTxs, newChain[i].Transactions()...)
  2068. }
  2069. // Delete useless indexes right now which includes the non-canonical
  2070. // transaction indexes, canonical chain indexes which above the head.
  2071. indexesBatch := bc.db.NewBatch()
  2072. for _, tx := range types.TxDifference(deletedTxs, addedTxs) {
  2073. rawdb.DeleteTxLookupEntry(indexesBatch, tx.Hash())
  2074. }
  2075. // Delete any canonical number assignments above the new head
  2076. number := bc.CurrentBlock().NumberU64()
  2077. for i := number + 1; ; i++ {
  2078. hash := rawdb.ReadCanonicalHash(bc.db, i)
  2079. if hash == (common.Hash{}) {
  2080. break
  2081. }
  2082. rawdb.DeleteCanonicalHash(indexesBatch, i)
  2083. }
  2084. if err := indexesBatch.Write(); err != nil {
  2085. log.Crit("Failed to delete useless indexes", "err", err)
  2086. }
  2087. // If any logs need to be fired, do it now. In theory we could avoid creating
  2088. // this goroutine if there are no events to fire, but realistcally that only
  2089. // ever happens if we're reorging empty blocks, which will only happen on idle
  2090. // networks where performance is not an issue either way.
  2091. if len(deletedLogs) > 0 {
  2092. bc.rmLogsFeed.Send(RemovedLogsEvent{mergeLogs(deletedLogs, true)})
  2093. }
  2094. if len(rebirthLogs) > 0 {
  2095. bc.logsFeed.Send(mergeLogs(rebirthLogs, false))
  2096. }
  2097. if len(oldChain) > 0 {
  2098. for i := len(oldChain) - 1; i >= 0; i-- {
  2099. bc.chainSideFeed.Send(ChainSideEvent{Block: oldChain[i]})
  2100. }
  2101. }
  2102. return nil
  2103. }
  2104. func (bc *BlockChain) update() {
  2105. futureTimer := time.NewTicker(5 * time.Second)
  2106. defer futureTimer.Stop()
  2107. for {
  2108. select {
  2109. case <-futureTimer.C:
  2110. bc.procFutureBlocks()
  2111. case <-bc.quit:
  2112. return
  2113. }
  2114. }
  2115. }
  2116. // maintainTxIndex is responsible for the construction and deletion of the
  2117. // transaction index.
  2118. //
  2119. // User can use flag `txlookuplimit` to specify a "recentness" block, below
  2120. // which ancient tx indices get deleted. If `txlookuplimit` is 0, it means
  2121. // all tx indices will be reserved.
  2122. //
  2123. // The user can adjust the txlookuplimit value for each launch after fast
  2124. // sync, Geth will automatically construct the missing indices and delete
  2125. // the extra indices.
  2126. func (bc *BlockChain) maintainTxIndex(ancients uint64) {
  2127. defer bc.wg.Done()
  2128. // Before starting the actual maintenance, we need to handle a special case,
  2129. // where user might init Geth with an external ancient database. If so, we
  2130. // need to reindex all necessary transactions before starting to process any
  2131. // pruning requests.
  2132. if ancients > 0 {
  2133. var from = uint64(0)
  2134. if bc.txLookupLimit != 0 && ancients > bc.txLookupLimit {
  2135. from = ancients - bc.txLookupLimit
  2136. }
  2137. rawdb.IndexTransactions(bc.db, from, ancients, bc.quit)
  2138. }
  2139. // indexBlocks reindexes or unindexes transactions depending on user configuration
  2140. indexBlocks := func(tail *uint64, head uint64, done chan struct{}) {
  2141. defer func() { done <- struct{}{} }()
  2142. // If the user just upgraded Geth to a new version which supports transaction
  2143. // index pruning, write the new tail and remove anything older.
  2144. if tail == nil {
  2145. if bc.txLookupLimit == 0 || head < bc.txLookupLimit {
  2146. // Nothing to delete, write the tail and return
  2147. rawdb.WriteTxIndexTail(bc.db, 0)
  2148. } else {
  2149. // Prune all stale tx indices and record the tx index tail
  2150. rawdb.UnindexTransactions(bc.db, 0, head-bc.txLookupLimit+1, bc.quit)
  2151. }
  2152. return
  2153. }
  2154. // If a previous indexing existed, make sure that we fill in any missing entries
  2155. if bc.txLookupLimit == 0 || head < bc.txLookupLimit {
  2156. if *tail > 0 {
  2157. rawdb.IndexTransactions(bc.db, 0, *tail, bc.quit)
  2158. }
  2159. return
  2160. }
  2161. // Update the transaction index to the new chain state
  2162. if head-bc.txLookupLimit+1 < *tail {
  2163. // Reindex a part of missing indices and rewind index tail to HEAD-limit
  2164. rawdb.IndexTransactions(bc.db, head-bc.txLookupLimit+1, *tail, bc.quit)
  2165. } else {
  2166. // Unindex a part of stale indices and forward index tail to HEAD-limit
  2167. rawdb.UnindexTransactions(bc.db, *tail, head-bc.txLookupLimit+1, bc.quit)
  2168. }
  2169. }
  2170. // Any reindexing done, start listening to chain events and moving the index window
  2171. var (
  2172. done chan struct{} // Non-nil if background unindexing or reindexing routine is active.
  2173. headCh = make(chan ChainHeadEvent, 1) // Buffered to avoid locking up the event feed
  2174. )
  2175. sub := bc.SubscribeChainHeadEvent(headCh)
  2176. if sub == nil {
  2177. return
  2178. }
  2179. defer sub.Unsubscribe()
  2180. for {
  2181. select {
  2182. case head := <-headCh:
  2183. if done == nil {
  2184. done = make(chan struct{})
  2185. go indexBlocks(rawdb.ReadTxIndexTail(bc.db), head.Block.NumberU64(), done)
  2186. }
  2187. case <-done:
  2188. done = nil
  2189. case <-bc.quit:
  2190. if done != nil {
  2191. log.Info("Waiting background transaction indexer to exit")
  2192. <-done
  2193. }
  2194. return
  2195. }
  2196. }
  2197. }
  2198. // reportBlock logs a bad block error.
  2199. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  2200. rawdb.WriteBadBlock(bc.db, block)
  2201. var receiptString string
  2202. for i, receipt := range receipts {
  2203. receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  2204. i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  2205. receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  2206. }
  2207. log.Error(fmt.Sprintf(`
  2208. ########## BAD BLOCK #########
  2209. Chain config: %v
  2210. Number: %v
  2211. Hash: 0x%x
  2212. %v
  2213. Error: %v
  2214. ##############################
  2215. `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  2216. }
  2217. // InsertHeaderChain attempts to insert the given header chain in to the local
  2218. // chain, possibly creating a reorg. If an error is returned, it will return the
  2219. // index number of the failing header as well an error describing what went wrong.
  2220. //
  2221. // The verify parameter can be used to fine tune whether nonce verification
  2222. // should be done or not. The reason behind the optional check is because some
  2223. // of the header retrieval mechanisms already need to verify nonces, as well as
  2224. // because nonces can be verified sparsely, not needing to check each.
  2225. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  2226. start := time.Now()
  2227. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  2228. return i, err
  2229. }
  2230. // Make sure only one thread manipulates the chain at once
  2231. bc.chainmu.Lock()
  2232. defer bc.chainmu.Unlock()
  2233. bc.wg.Add(1)
  2234. defer bc.wg.Done()
  2235. _, err := bc.hc.InsertHeaderChain(chain, start)
  2236. return 0, err
  2237. }
  2238. // CurrentHeader retrieves the current head header of the canonical chain. The
  2239. // header is retrieved from the HeaderChain's internal cache.
  2240. func (bc *BlockChain) CurrentHeader() *types.Header {
  2241. return bc.hc.CurrentHeader()
  2242. }
  2243. // GetTd retrieves a block's total difficulty in the canonical chain from the
  2244. // database by hash and number, caching it if found.
  2245. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  2246. return bc.hc.GetTd(hash, number)
  2247. }
  2248. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  2249. // database by hash, caching it if found.
  2250. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  2251. return bc.hc.GetTdByHash(hash)
  2252. }
  2253. // GetHeader retrieves a block header from the database by hash and number,
  2254. // caching it if found.
  2255. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  2256. return bc.hc.GetHeader(hash, number)
  2257. }
  2258. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  2259. // found.
  2260. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  2261. return bc.hc.GetHeaderByHash(hash)
  2262. }
  2263. // HasHeader checks if a block header is present in the database or not, caching
  2264. // it if present.
  2265. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  2266. return bc.hc.HasHeader(hash, number)
  2267. }
  2268. // GetCanonicalHash returns the canonical hash for a given block number
  2269. func (bc *BlockChain) GetCanonicalHash(number uint64) common.Hash {
  2270. return bc.hc.GetCanonicalHash(number)
  2271. }
  2272. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  2273. // hash, fetching towards the genesis block.
  2274. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  2275. return bc.hc.GetBlockHashesFromHash(hash, max)
  2276. }
  2277. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  2278. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  2279. // number of blocks to be individually checked before we reach the canonical chain.
  2280. //
  2281. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  2282. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  2283. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  2284. }
  2285. // GetHeaderByNumber retrieves a block header from the database by number,
  2286. // caching it (associated with its hash) if found.
  2287. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  2288. return bc.hc.GetHeaderByNumber(number)
  2289. }
  2290. // GetTransactionLookup retrieves the lookup associate with the given transaction
  2291. // hash from the cache or database.
  2292. func (bc *BlockChain) GetTransactionLookup(hash common.Hash) *rawdb.LegacyTxLookupEntry {
  2293. // Short circuit if the txlookup already in the cache, retrieve otherwise
  2294. if lookup, exist := bc.txLookupCache.Get(hash); exist {
  2295. return lookup.(*rawdb.LegacyTxLookupEntry)
  2296. }
  2297. tx, blockHash, blockNumber, txIndex := rawdb.ReadTransaction(bc.db, hash)
  2298. if tx == nil {
  2299. return nil
  2300. }
  2301. lookup := &rawdb.LegacyTxLookupEntry{BlockHash: blockHash, BlockIndex: blockNumber, Index: txIndex}
  2302. bc.txLookupCache.Add(hash, lookup)
  2303. return lookup
  2304. }
  2305. // Config retrieves the chain's fork configuration.
  2306. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  2307. // Engine retrieves the blockchain's consensus engine.
  2308. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  2309. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  2310. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  2311. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  2312. }
  2313. // SubscribeChainEvent registers a subscription of ChainEvent.
  2314. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  2315. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  2316. }
  2317. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  2318. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  2319. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  2320. }
  2321. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  2322. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  2323. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  2324. }
  2325. // SubscribeLogsEvent registers a subscription of []*types.Log.
  2326. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  2327. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  2328. }
  2329. // SubscribeBlockProcessingEvent registers a subscription of bool where true means
  2330. // block processing has started while false means it has stopped.
  2331. func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription {
  2332. return bc.scope.Track(bc.blockProcFeed.Subscribe(ch))
  2333. }