blockchain.go 97 KB

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