blockchain.go 96 KB

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