blockchain.go 96 KB

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