blockchain.go 97 KB

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