blockchain.go 96 KB

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