blockchain.go 97 KB

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