blockchain.go 97 KB

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