blockchain.go 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119
  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. "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/mclock"
  29. "github.com/ethereum/go-ethereum/common/prque"
  30. "github.com/ethereum/go-ethereum/consensus"
  31. "github.com/ethereum/go-ethereum/core/rawdb"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/ethdb"
  36. "github.com/ethereum/go-ethereum/event"
  37. "github.com/ethereum/go-ethereum/log"
  38. "github.com/ethereum/go-ethereum/metrics"
  39. "github.com/ethereum/go-ethereum/params"
  40. "github.com/ethereum/go-ethereum/rlp"
  41. "github.com/ethereum/go-ethereum/trie"
  42. "github.com/hashicorp/golang-lru"
  43. )
  44. var (
  45. accountReadTimer = metrics.NewRegisteredTimer("chain/account/reads", nil)
  46. accountHashTimer = metrics.NewRegisteredTimer("chain/account/hashes", nil)
  47. accountUpdateTimer = metrics.NewRegisteredTimer("chain/account/updates", nil)
  48. accountCommitTimer = metrics.NewRegisteredTimer("chain/account/commits", nil)
  49. storageReadTimer = metrics.NewRegisteredTimer("chain/storage/reads", nil)
  50. storageHashTimer = metrics.NewRegisteredTimer("chain/storage/hashes", nil)
  51. storageUpdateTimer = metrics.NewRegisteredTimer("chain/storage/updates", nil)
  52. storageCommitTimer = metrics.NewRegisteredTimer("chain/storage/commits", nil)
  53. blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil)
  54. blockValidationTimer = metrics.NewRegisteredTimer("chain/validation", nil)
  55. blockExecutionTimer = metrics.NewRegisteredTimer("chain/execution", nil)
  56. blockWriteTimer = metrics.NewRegisteredTimer("chain/write", nil)
  57. blockPrefetchExecuteTimer = metrics.NewRegisteredTimer("chain/prefetch/executes", nil)
  58. blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil)
  59. errInsertionInterrupted = errors.New("insertion is interrupted")
  60. )
  61. const (
  62. bodyCacheLimit = 256
  63. blockCacheLimit = 256
  64. receiptsCacheLimit = 32
  65. maxFutureBlocks = 256
  66. maxTimeFutureBlocks = 30
  67. badBlockLimit = 10
  68. TriesInMemory = 128
  69. // BlockChainVersion ensures that an incompatible database forces a resync from scratch.
  70. //
  71. // Changelog:
  72. //
  73. // - Version 4
  74. // The following incompatible database changes were added:
  75. // * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted
  76. // * the `Bloom` field of receipt is deleted
  77. // * the `BlockIndex` and `TxIndex` fields of txlookup are deleted
  78. // - Version 5
  79. // The following incompatible database changes were added:
  80. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are no longer stored for a receipt
  81. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are computed by looking up the
  82. // receipts' corresponding block
  83. // - Version 6
  84. // The following incompatible database changes were added:
  85. // * Transaction lookup information stores the corresponding block number instead of block hash
  86. // - Version 7
  87. // The following incompatible database changes were added:
  88. // * Use freezer as the ancient database to maintain all ancient data
  89. BlockChainVersion uint64 = 7
  90. )
  91. // CacheConfig contains the configuration values for the trie caching/pruning
  92. // that's resident in a blockchain.
  93. type CacheConfig struct {
  94. TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
  95. TrieCleanNoPrefetch bool // Whether to disable heuristic state prefetching for followup blocks
  96. TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk
  97. TrieDirtyDisabled bool // Whether to disable trie write caching and GC altogether (archive node)
  98. TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
  99. }
  100. // BlockChain represents the canonical chain given a database with a genesis
  101. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  102. //
  103. // Importing blocks in to the block chain happens according to the set of rules
  104. // defined by the two stage Validator. Processing of blocks is done using the
  105. // Processor which processes the included transaction. The validation of the state
  106. // is done in the second part of the Validator. Failing results in aborting of
  107. // the import.
  108. //
  109. // The BlockChain also helps in returning blocks from **any** chain included
  110. // in the database as well as blocks that represents the canonical chain. It's
  111. // important to note that GetBlock can return any block and does not need to be
  112. // included in the canonical one where as GetBlockByNumber always represents the
  113. // canonical chain.
  114. type BlockChain struct {
  115. chainConfig *params.ChainConfig // Chain & network configuration
  116. cacheConfig *CacheConfig // Cache configuration for pruning
  117. db ethdb.Database // Low level persistent database to store final content in
  118. triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
  119. gcproc time.Duration // Accumulates canonical block processing for trie dumping
  120. hc *HeaderChain
  121. rmLogsFeed event.Feed
  122. chainFeed event.Feed
  123. chainSideFeed event.Feed
  124. chainHeadFeed event.Feed
  125. logsFeed event.Feed
  126. blockProcFeed event.Feed
  127. scope event.SubscriptionScope
  128. genesisBlock *types.Block
  129. chainmu sync.RWMutex // blockchain insertion lock
  130. currentBlock atomic.Value // Current head of the block chain
  131. currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
  132. stateCache state.Database // State database to reuse between imports (contains state cache)
  133. bodyCache *lru.Cache // Cache for the most recent block bodies
  134. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  135. receiptsCache *lru.Cache // Cache for the most recent receipts per block
  136. blockCache *lru.Cache // Cache for the most recent entire blocks
  137. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  138. quit chan struct{} // blockchain quit channel
  139. running int32 // running must be called atomically
  140. // procInterrupt must be atomically called
  141. procInterrupt int32 // interrupt signaler for block processing
  142. wg sync.WaitGroup // chain processing wait group for shutting down
  143. engine consensus.Engine
  144. validator Validator // Block and state validator interface
  145. prefetcher Prefetcher // Block state prefetcher interface
  146. processor Processor // Block transaction processor interface
  147. vmConfig vm.Config
  148. badBlocks *lru.Cache // Bad block cache
  149. shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
  150. terminateInsert func(common.Hash, uint64) bool // Testing hook used to terminate ancient receipt chain insertion.
  151. }
  152. // NewBlockChain returns a fully initialised block chain using information
  153. // available in the database. It initialises the default Ethereum Validator and
  154. // Processor.
  155. func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool) (*BlockChain, error) {
  156. if cacheConfig == nil {
  157. cacheConfig = &CacheConfig{
  158. TrieCleanLimit: 256,
  159. TrieDirtyLimit: 256,
  160. TrieTimeLimit: 5 * time.Minute,
  161. }
  162. }
  163. bodyCache, _ := lru.New(bodyCacheLimit)
  164. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  165. receiptsCache, _ := lru.New(receiptsCacheLimit)
  166. blockCache, _ := lru.New(blockCacheLimit)
  167. futureBlocks, _ := lru.New(maxFutureBlocks)
  168. badBlocks, _ := lru.New(badBlockLimit)
  169. bc := &BlockChain{
  170. chainConfig: chainConfig,
  171. cacheConfig: cacheConfig,
  172. db: db,
  173. triegc: prque.New(nil),
  174. stateCache: state.NewDatabaseWithCache(db, cacheConfig.TrieCleanLimit),
  175. quit: make(chan struct{}),
  176. shouldPreserve: shouldPreserve,
  177. bodyCache: bodyCache,
  178. bodyRLPCache: bodyRLPCache,
  179. receiptsCache: receiptsCache,
  180. blockCache: blockCache,
  181. futureBlocks: futureBlocks,
  182. engine: engine,
  183. vmConfig: vmConfig,
  184. badBlocks: badBlocks,
  185. }
  186. bc.validator = NewBlockValidator(chainConfig, bc, engine)
  187. bc.prefetcher = newStatePrefetcher(chainConfig, bc, engine)
  188. bc.processor = NewStateProcessor(chainConfig, bc, engine)
  189. var err error
  190. bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.getProcInterrupt)
  191. if err != nil {
  192. return nil, err
  193. }
  194. bc.genesisBlock = bc.GetBlockByNumber(0)
  195. if bc.genesisBlock == nil {
  196. return nil, ErrNoGenesis
  197. }
  198. // Initialize the chain with ancient data if it isn't empty.
  199. if bc.empty() {
  200. rawdb.InitDatabaseFromFreezer(bc.db)
  201. }
  202. if err := bc.loadLastState(); err != nil {
  203. return nil, err
  204. }
  205. // The first thing the node will do is reconstruct the verification data for
  206. // the head block (ethash cache or clique voting snapshot). Might as well do
  207. // it in advance.
  208. bc.engine.VerifyHeader(bc, bc.CurrentHeader(), true)
  209. if frozen, err := bc.db.Ancients(); err == nil && frozen > 0 {
  210. var (
  211. needRewind bool
  212. low uint64
  213. )
  214. // The head full block may be rolled back to a very low height due to
  215. // blockchain repair. If the head full block is even lower than the ancient
  216. // chain, truncate the ancient store.
  217. fullBlock := bc.CurrentBlock()
  218. if fullBlock != nil && fullBlock != bc.genesisBlock && fullBlock.NumberU64() < frozen-1 {
  219. needRewind = true
  220. low = fullBlock.NumberU64()
  221. }
  222. // In fast sync, it may happen that ancient data has been written to the
  223. // ancient store, but the LastFastBlock has not been updated, truncate the
  224. // extra data here.
  225. fastBlock := bc.CurrentFastBlock()
  226. if fastBlock != nil && fastBlock.NumberU64() < frozen-1 {
  227. needRewind = true
  228. if fastBlock.NumberU64() < low || low == 0 {
  229. low = fastBlock.NumberU64()
  230. }
  231. }
  232. if needRewind {
  233. var hashes []common.Hash
  234. previous := bc.CurrentHeader().Number.Uint64()
  235. for i := low + 1; i <= bc.CurrentHeader().Number.Uint64(); i++ {
  236. hashes = append(hashes, rawdb.ReadCanonicalHash(bc.db, i))
  237. }
  238. bc.Rollback(hashes)
  239. log.Warn("Truncate ancient chain", "from", previous, "to", low)
  240. }
  241. }
  242. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  243. for hash := range BadHashes {
  244. if header := bc.GetHeaderByHash(hash); header != nil {
  245. // get the canonical block corresponding to the offending header's number
  246. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  247. // make sure the headerByNumber (if present) is in our current canonical chain
  248. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  249. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  250. bc.SetHead(header.Number.Uint64() - 1)
  251. log.Error("Chain rewind was successful, resuming normal operation")
  252. }
  253. }
  254. }
  255. // Take ownership of this particular state
  256. go bc.update()
  257. return bc, nil
  258. }
  259. func (bc *BlockChain) getProcInterrupt() bool {
  260. return atomic.LoadInt32(&bc.procInterrupt) == 1
  261. }
  262. // GetVMConfig returns the block chain VM config.
  263. func (bc *BlockChain) GetVMConfig() *vm.Config {
  264. return &bc.vmConfig
  265. }
  266. // empty returns an indicator whether the blockchain is empty.
  267. // Note, it's a special case that we connect a non-empty ancient
  268. // database with an empty node, so that we can plugin the ancient
  269. // into node seamlessly.
  270. func (bc *BlockChain) empty() bool {
  271. genesis := bc.genesisBlock.Hash()
  272. for _, hash := range []common.Hash{rawdb.ReadHeadBlockHash(bc.db), rawdb.ReadHeadHeaderHash(bc.db), rawdb.ReadHeadFastBlockHash(bc.db)} {
  273. if hash != genesis {
  274. return false
  275. }
  276. }
  277. return true
  278. }
  279. // loadLastState loads the last known chain state from the database. This method
  280. // assumes that the chain manager mutex is held.
  281. func (bc *BlockChain) loadLastState() error {
  282. // Restore the last known head block
  283. head := rawdb.ReadHeadBlockHash(bc.db)
  284. if head == (common.Hash{}) {
  285. // Corrupt or empty database, init from scratch
  286. log.Warn("Empty database, resetting chain")
  287. return bc.Reset()
  288. }
  289. // Make sure the entire head block is available
  290. currentBlock := bc.GetBlockByHash(head)
  291. if currentBlock == nil {
  292. // Corrupt or empty database, init from scratch
  293. log.Warn("Head block missing, resetting chain", "hash", head)
  294. return bc.Reset()
  295. }
  296. // Make sure the state associated with the block is available
  297. if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
  298. // Dangling block without a state associated, init from scratch
  299. log.Warn("Head state missing, repairing chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
  300. if err := bc.repair(&currentBlock); err != nil {
  301. return err
  302. }
  303. rawdb.WriteHeadBlockHash(bc.db, currentBlock.Hash())
  304. }
  305. // Everything seems to be fine, set as the head block
  306. bc.currentBlock.Store(currentBlock)
  307. // Restore the last known head header
  308. currentHeader := currentBlock.Header()
  309. if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
  310. if header := bc.GetHeaderByHash(head); header != nil {
  311. currentHeader = header
  312. }
  313. }
  314. bc.hc.SetCurrentHeader(currentHeader)
  315. // Restore the last known head fast block
  316. bc.currentFastBlock.Store(currentBlock)
  317. if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
  318. if block := bc.GetBlockByHash(head); block != nil {
  319. bc.currentFastBlock.Store(block)
  320. }
  321. }
  322. // Issue a status log for the user
  323. currentFastBlock := bc.CurrentFastBlock()
  324. headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  325. blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  326. fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
  327. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time), 0)))
  328. 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)))
  329. 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)))
  330. return nil
  331. }
  332. // SetHead rewinds the local chain to a new head. In the case of headers, everything
  333. // above the new head will be deleted and the new one set. In the case of blocks
  334. // though, the head may be further rewound if block bodies are missing (non-archive
  335. // nodes after a fast sync).
  336. func (bc *BlockChain) SetHead(head uint64) error {
  337. log.Warn("Rewinding blockchain", "target", head)
  338. bc.chainmu.Lock()
  339. defer bc.chainmu.Unlock()
  340. updateFn := func(db ethdb.KeyValueWriter, header *types.Header) {
  341. // Rewind the block chain, ensuring we don't end up with a stateless head block
  342. if currentBlock := bc.CurrentBlock(); currentBlock != nil && header.Number.Uint64() < currentBlock.NumberU64() {
  343. newHeadBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  344. if newHeadBlock == nil {
  345. newHeadBlock = bc.genesisBlock
  346. } else {
  347. if _, err := state.New(newHeadBlock.Root(), bc.stateCache); err != nil {
  348. // Rewound state missing, rolled back to before pivot, reset to genesis
  349. newHeadBlock = bc.genesisBlock
  350. }
  351. }
  352. rawdb.WriteHeadBlockHash(db, newHeadBlock.Hash())
  353. bc.currentBlock.Store(newHeadBlock)
  354. }
  355. // Rewind the fast block in a simpleton way to the target head
  356. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && header.Number.Uint64() < currentFastBlock.NumberU64() {
  357. newHeadFastBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  358. // If either blocks reached nil, reset to the genesis state
  359. if newHeadFastBlock == nil {
  360. newHeadFastBlock = bc.genesisBlock
  361. }
  362. rawdb.WriteHeadFastBlockHash(db, newHeadFastBlock.Hash())
  363. bc.currentFastBlock.Store(newHeadFastBlock)
  364. }
  365. }
  366. // Rewind the header chain, deleting all block bodies until then
  367. delFn := func(db ethdb.KeyValueWriter, hash common.Hash, num uint64) {
  368. // Ignore the error here since light client won't hit this path
  369. frozen, _ := bc.db.Ancients()
  370. if num+1 <= frozen {
  371. // Truncate all relative data(header, total difficulty, body, receipt
  372. // and canonical hash) from ancient store.
  373. if err := bc.db.TruncateAncients(num + 1); err != nil {
  374. log.Crit("Failed to truncate ancient data", "number", num, "err", err)
  375. }
  376. // Remove the hash <-> number mapping from the active store.
  377. rawdb.DeleteHeaderNumber(db, hash)
  378. } else {
  379. // Remove relative body and receipts from the active store.
  380. // The header, total difficulty and canonical hash will be
  381. // removed in the hc.SetHead function.
  382. rawdb.DeleteBody(db, hash, num)
  383. rawdb.DeleteReceipts(db, hash, num)
  384. }
  385. // Todo(rjl493456442) txlookup, bloombits, etc
  386. }
  387. bc.hc.SetHead(head, updateFn, delFn)
  388. // Clear out any stale content from the caches
  389. bc.bodyCache.Purge()
  390. bc.bodyRLPCache.Purge()
  391. bc.receiptsCache.Purge()
  392. bc.blockCache.Purge()
  393. bc.futureBlocks.Purge()
  394. return bc.loadLastState()
  395. }
  396. // FastSyncCommitHead sets the current head block to the one defined by the hash
  397. // irrelevant what the chain contents were prior.
  398. func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  399. // Make sure that both the block as well at its state trie exists
  400. block := bc.GetBlockByHash(hash)
  401. if block == nil {
  402. return fmt.Errorf("non existent block [%x…]", hash[:4])
  403. }
  404. if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB()); err != nil {
  405. return err
  406. }
  407. // If all checks out, manually set the head block
  408. bc.chainmu.Lock()
  409. bc.currentBlock.Store(block)
  410. bc.chainmu.Unlock()
  411. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  412. return nil
  413. }
  414. // GasLimit returns the gas limit of the current HEAD block.
  415. func (bc *BlockChain) GasLimit() uint64 {
  416. return bc.CurrentBlock().GasLimit()
  417. }
  418. // CurrentBlock retrieves the current head block of the canonical chain. The
  419. // block is retrieved from the blockchain's internal cache.
  420. func (bc *BlockChain) CurrentBlock() *types.Block {
  421. return bc.currentBlock.Load().(*types.Block)
  422. }
  423. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  424. // chain. The block is retrieved from the blockchain's internal cache.
  425. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  426. return bc.currentFastBlock.Load().(*types.Block)
  427. }
  428. // Validator returns the current validator.
  429. func (bc *BlockChain) Validator() Validator {
  430. return bc.validator
  431. }
  432. // Processor returns the current processor.
  433. func (bc *BlockChain) Processor() Processor {
  434. return bc.processor
  435. }
  436. // State returns a new mutable state based on the current HEAD block.
  437. func (bc *BlockChain) State() (*state.StateDB, error) {
  438. return bc.StateAt(bc.CurrentBlock().Root())
  439. }
  440. // StateAt returns a new mutable state based on a particular point in time.
  441. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  442. return state.New(root, bc.stateCache)
  443. }
  444. // StateCache returns the caching database underpinning the blockchain instance.
  445. func (bc *BlockChain) StateCache() state.Database {
  446. return bc.stateCache
  447. }
  448. // Reset purges the entire blockchain, restoring it to its genesis state.
  449. func (bc *BlockChain) Reset() error {
  450. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  451. }
  452. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  453. // specified genesis state.
  454. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  455. // Dump the entire block chain and purge the caches
  456. if err := bc.SetHead(0); err != nil {
  457. return err
  458. }
  459. bc.chainmu.Lock()
  460. defer bc.chainmu.Unlock()
  461. // Prepare the genesis block and reinitialise the chain
  462. if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  463. log.Crit("Failed to write genesis block TD", "err", err)
  464. }
  465. rawdb.WriteBlock(bc.db, genesis)
  466. bc.genesisBlock = genesis
  467. bc.insert(bc.genesisBlock)
  468. bc.currentBlock.Store(bc.genesisBlock)
  469. bc.hc.SetGenesis(bc.genesisBlock.Header())
  470. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  471. bc.currentFastBlock.Store(bc.genesisBlock)
  472. return nil
  473. }
  474. // repair tries to repair the current blockchain by rolling back the current block
  475. // until one with associated state is found. This is needed to fix incomplete db
  476. // writes caused either by crashes/power outages, or simply non-committed tries.
  477. //
  478. // This method only rolls back the current block. The current header and current
  479. // fast block are left intact.
  480. func (bc *BlockChain) repair(head **types.Block) error {
  481. for {
  482. // Abort if we've rewound to a head block that does have associated state
  483. if _, err := state.New((*head).Root(), bc.stateCache); err == nil {
  484. log.Info("Rewound blockchain to past state", "number", (*head).Number(), "hash", (*head).Hash())
  485. return nil
  486. }
  487. // Otherwise rewind one block and recheck state availability there
  488. block := bc.GetBlock((*head).ParentHash(), (*head).NumberU64()-1)
  489. if block == nil {
  490. return fmt.Errorf("missing block %d [%x]", (*head).NumberU64()-1, (*head).ParentHash())
  491. }
  492. *head = block
  493. }
  494. }
  495. // Export writes the active chain to the given writer.
  496. func (bc *BlockChain) Export(w io.Writer) error {
  497. return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64())
  498. }
  499. // ExportN writes a subset of the active chain to the given writer.
  500. func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  501. bc.chainmu.RLock()
  502. defer bc.chainmu.RUnlock()
  503. if first > last {
  504. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  505. }
  506. log.Info("Exporting batch of blocks", "count", last-first+1)
  507. start, reported := time.Now(), time.Now()
  508. for nr := first; nr <= last; nr++ {
  509. block := bc.GetBlockByNumber(nr)
  510. if block == nil {
  511. return fmt.Errorf("export failed on #%d: not found", nr)
  512. }
  513. if err := block.EncodeRLP(w); err != nil {
  514. return err
  515. }
  516. if time.Since(reported) >= statsReportLimit {
  517. log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
  518. reported = time.Now()
  519. }
  520. }
  521. return nil
  522. }
  523. // insert injects a new head block into the current block chain. This method
  524. // assumes that the block is indeed a true head. It will also reset the head
  525. // header and the head fast sync block to this very same block if they are older
  526. // or if they are on a different side chain.
  527. //
  528. // Note, this function assumes that the `mu` mutex is held!
  529. func (bc *BlockChain) insert(block *types.Block) {
  530. // If the block is on a side chain or an unknown one, force other heads onto it too
  531. updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()
  532. // Add the block to the canonical chain number scheme and mark as the head
  533. rawdb.WriteCanonicalHash(bc.db, block.Hash(), block.NumberU64())
  534. rawdb.WriteHeadBlockHash(bc.db, block.Hash())
  535. bc.currentBlock.Store(block)
  536. // If the block is better than our head or is on a different chain, force update heads
  537. if updateHeads {
  538. bc.hc.SetCurrentHeader(block.Header())
  539. rawdb.WriteHeadFastBlockHash(bc.db, block.Hash())
  540. bc.currentFastBlock.Store(block)
  541. }
  542. }
  543. // Genesis retrieves the chain's genesis block.
  544. func (bc *BlockChain) Genesis() *types.Block {
  545. return bc.genesisBlock
  546. }
  547. // GetBody retrieves a block body (transactions and uncles) from the database by
  548. // hash, caching it if found.
  549. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  550. // Short circuit if the body's already in the cache, retrieve otherwise
  551. if cached, ok := bc.bodyCache.Get(hash); ok {
  552. body := cached.(*types.Body)
  553. return body
  554. }
  555. number := bc.hc.GetBlockNumber(hash)
  556. if number == nil {
  557. return nil
  558. }
  559. body := rawdb.ReadBody(bc.db, hash, *number)
  560. if body == nil {
  561. return nil
  562. }
  563. // Cache the found body for next time and return
  564. bc.bodyCache.Add(hash, body)
  565. return body
  566. }
  567. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  568. // caching it if found.
  569. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  570. // Short circuit if the body's already in the cache, retrieve otherwise
  571. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  572. return cached.(rlp.RawValue)
  573. }
  574. number := bc.hc.GetBlockNumber(hash)
  575. if number == nil {
  576. return nil
  577. }
  578. body := rawdb.ReadBodyRLP(bc.db, hash, *number)
  579. if len(body) == 0 {
  580. return nil
  581. }
  582. // Cache the found body for next time and return
  583. bc.bodyRLPCache.Add(hash, body)
  584. return body
  585. }
  586. // HasBlock checks if a block is fully present in the database or not.
  587. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  588. if bc.blockCache.Contains(hash) {
  589. return true
  590. }
  591. return rawdb.HasBody(bc.db, hash, number)
  592. }
  593. // HasFastBlock checks if a fast block is fully present in the database or not.
  594. func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool {
  595. if !bc.HasBlock(hash, number) {
  596. return false
  597. }
  598. if bc.receiptsCache.Contains(hash) {
  599. return true
  600. }
  601. return rawdb.HasReceipts(bc.db, hash, number)
  602. }
  603. // HasState checks if state trie is fully present in the database or not.
  604. func (bc *BlockChain) HasState(hash common.Hash) bool {
  605. _, err := bc.stateCache.OpenTrie(hash)
  606. return err == nil
  607. }
  608. // HasBlockAndState checks if a block and associated state trie is fully present
  609. // in the database or not, caching it if present.
  610. func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
  611. // Check first that the block itself is known
  612. block := bc.GetBlock(hash, number)
  613. if block == nil {
  614. return false
  615. }
  616. return bc.HasState(block.Root())
  617. }
  618. // GetBlock retrieves a block from the database by hash and number,
  619. // caching it if found.
  620. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  621. // Short circuit if the block's already in the cache, retrieve otherwise
  622. if block, ok := bc.blockCache.Get(hash); ok {
  623. return block.(*types.Block)
  624. }
  625. block := rawdb.ReadBlock(bc.db, hash, number)
  626. if block == nil {
  627. return nil
  628. }
  629. // Cache the found block for next time and return
  630. bc.blockCache.Add(block.Hash(), block)
  631. return block
  632. }
  633. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  634. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  635. number := bc.hc.GetBlockNumber(hash)
  636. if number == nil {
  637. return nil
  638. }
  639. return bc.GetBlock(hash, *number)
  640. }
  641. // GetBlockByNumber retrieves a block from the database by number, caching it
  642. // (associated with its hash) if found.
  643. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  644. hash := rawdb.ReadCanonicalHash(bc.db, number)
  645. if hash == (common.Hash{}) {
  646. return nil
  647. }
  648. return bc.GetBlock(hash, number)
  649. }
  650. // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
  651. func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
  652. if receipts, ok := bc.receiptsCache.Get(hash); ok {
  653. return receipts.(types.Receipts)
  654. }
  655. number := rawdb.ReadHeaderNumber(bc.db, hash)
  656. if number == nil {
  657. return nil
  658. }
  659. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  660. if receipts == nil {
  661. return nil
  662. }
  663. bc.receiptsCache.Add(hash, receipts)
  664. return receipts
  665. }
  666. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  667. // [deprecated by eth/62]
  668. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  669. number := bc.hc.GetBlockNumber(hash)
  670. if number == nil {
  671. return nil
  672. }
  673. for i := 0; i < n; i++ {
  674. block := bc.GetBlock(hash, *number)
  675. if block == nil {
  676. break
  677. }
  678. blocks = append(blocks, block)
  679. hash = block.ParentHash()
  680. *number--
  681. }
  682. return
  683. }
  684. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  685. // a specific distance is reached.
  686. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  687. uncles := []*types.Header{}
  688. for i := 0; block != nil && i < length; i++ {
  689. uncles = append(uncles, block.Uncles()...)
  690. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  691. }
  692. return uncles
  693. }
  694. // TrieNode retrieves a blob of data associated with a trie node (or code hash)
  695. // either from ephemeral in-memory cache, or from persistent storage.
  696. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  697. return bc.stateCache.TrieDB().Node(hash)
  698. }
  699. // Stop stops the blockchain service. If any imports are currently in progress
  700. // it will abort them using the procInterrupt.
  701. func (bc *BlockChain) Stop() {
  702. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  703. return
  704. }
  705. // Unsubscribe all subscriptions registered from blockchain
  706. bc.scope.Close()
  707. close(bc.quit)
  708. atomic.StoreInt32(&bc.procInterrupt, 1)
  709. bc.wg.Wait()
  710. // Ensure the state of a recent block is also stored to disk before exiting.
  711. // We're writing three different states to catch different restart scenarios:
  712. // - HEAD: So we don't need to reprocess any blocks in the general case
  713. // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle
  714. // - HEAD-127: So we have a hard limit on the number of blocks reexecuted
  715. if !bc.cacheConfig.TrieDirtyDisabled {
  716. triedb := bc.stateCache.TrieDB()
  717. for _, offset := range []uint64{0, 1, TriesInMemory - 1} {
  718. if number := bc.CurrentBlock().NumberU64(); number > offset {
  719. recent := bc.GetBlockByNumber(number - offset)
  720. log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
  721. if err := triedb.Commit(recent.Root(), true); err != nil {
  722. log.Error("Failed to commit recent state trie", "err", err)
  723. }
  724. }
  725. }
  726. for !bc.triegc.Empty() {
  727. triedb.Dereference(bc.triegc.PopItem().(common.Hash))
  728. }
  729. if size, _ := triedb.Size(); size != 0 {
  730. log.Error("Dangling trie nodes after full cleanup")
  731. }
  732. }
  733. log.Info("Blockchain manager stopped")
  734. }
  735. func (bc *BlockChain) procFutureBlocks() {
  736. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  737. for _, hash := range bc.futureBlocks.Keys() {
  738. if block, exist := bc.futureBlocks.Peek(hash); exist {
  739. blocks = append(blocks, block.(*types.Block))
  740. }
  741. }
  742. if len(blocks) > 0 {
  743. types.BlockBy(types.Number).Sort(blocks)
  744. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  745. for i := range blocks {
  746. bc.InsertChain(blocks[i : i+1])
  747. }
  748. }
  749. }
  750. // WriteStatus status of write
  751. type WriteStatus byte
  752. const (
  753. NonStatTy WriteStatus = iota
  754. CanonStatTy
  755. SideStatTy
  756. )
  757. // Rollback is designed to remove a chain of links from the database that aren't
  758. // certain enough to be valid.
  759. func (bc *BlockChain) Rollback(chain []common.Hash) {
  760. bc.chainmu.Lock()
  761. defer bc.chainmu.Unlock()
  762. for i := len(chain) - 1; i >= 0; i-- {
  763. hash := chain[i]
  764. currentHeader := bc.hc.CurrentHeader()
  765. if currentHeader.Hash() == hash {
  766. bc.hc.SetCurrentHeader(bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
  767. }
  768. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock.Hash() == hash {
  769. newFastBlock := bc.GetBlock(currentFastBlock.ParentHash(), currentFastBlock.NumberU64()-1)
  770. rawdb.WriteHeadFastBlockHash(bc.db, newFastBlock.Hash())
  771. bc.currentFastBlock.Store(newFastBlock)
  772. }
  773. if currentBlock := bc.CurrentBlock(); currentBlock.Hash() == hash {
  774. newBlock := bc.GetBlock(currentBlock.ParentHash(), currentBlock.NumberU64()-1)
  775. rawdb.WriteHeadBlockHash(bc.db, newBlock.Hash())
  776. bc.currentBlock.Store(newBlock)
  777. }
  778. }
  779. // Truncate ancient data which exceeds the current header.
  780. //
  781. // Notably, it can happen that system crashes without truncating the ancient data
  782. // but the head indicator has been updated in the active store. Regarding this issue,
  783. // system will self recovery by truncating the extra data during the setup phase.
  784. if err := bc.truncateAncient(bc.hc.CurrentHeader().Number.Uint64()); err != nil {
  785. log.Crit("Truncate ancient store failed", "err", err)
  786. }
  787. }
  788. // truncateAncient rewinds the blockchain to the specified header and deletes all
  789. // data in the ancient store that exceeds the specified header.
  790. func (bc *BlockChain) truncateAncient(head uint64) error {
  791. frozen, err := bc.db.Ancients()
  792. if err != nil {
  793. return err
  794. }
  795. // Short circuit if there is no data to truncate in ancient store.
  796. if frozen <= head+1 {
  797. return nil
  798. }
  799. // Truncate all the data in the freezer beyond the specified head
  800. if err := bc.db.TruncateAncients(head + 1); err != nil {
  801. return err
  802. }
  803. // Clear out any stale content from the caches
  804. bc.hc.headerCache.Purge()
  805. bc.hc.tdCache.Purge()
  806. bc.hc.numberCache.Purge()
  807. // Clear out any stale content from the caches
  808. bc.bodyCache.Purge()
  809. bc.bodyRLPCache.Purge()
  810. bc.receiptsCache.Purge()
  811. bc.blockCache.Purge()
  812. bc.futureBlocks.Purge()
  813. log.Info("Rewind ancient data", "number", head)
  814. return nil
  815. }
  816. // InsertReceiptChain attempts to complete an already existing header chain with
  817. // transaction and receipt data.
  818. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts, ancientLimit uint64) (int, error) {
  819. bc.wg.Add(1)
  820. defer bc.wg.Done()
  821. var (
  822. ancientBlocks, liveBlocks types.Blocks
  823. ancientReceipts, liveReceipts []types.Receipts
  824. )
  825. // Do a sanity check that the provided chain is actually ordered and linked
  826. for i := 0; i < len(blockChain); i++ {
  827. if i != 0 {
  828. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  829. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  830. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  831. 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(),
  832. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  833. }
  834. }
  835. if blockChain[i].NumberU64() <= ancientLimit {
  836. ancientBlocks, ancientReceipts = append(ancientBlocks, blockChain[i]), append(ancientReceipts, receiptChain[i])
  837. } else {
  838. liveBlocks, liveReceipts = append(liveBlocks, blockChain[i]), append(liveReceipts, receiptChain[i])
  839. }
  840. }
  841. var (
  842. stats = struct{ processed, ignored int32 }{}
  843. start = time.Now()
  844. size = 0
  845. )
  846. // updateHead updates the head fast sync block if the inserted blocks are better
  847. // and returns a indicator whether the inserted blocks are canonical.
  848. updateHead := func(head *types.Block) bool {
  849. var isCanonical bool
  850. bc.chainmu.Lock()
  851. if td := bc.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case
  852. currentFastBlock := bc.CurrentFastBlock()
  853. if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
  854. rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
  855. bc.currentFastBlock.Store(head)
  856. isCanonical = true
  857. }
  858. }
  859. bc.chainmu.Unlock()
  860. return isCanonical
  861. }
  862. // writeAncient writes blockchain and corresponding receipt chain into ancient store.
  863. //
  864. // this function only accepts canonical chain data. All side chain will be reverted
  865. // eventually.
  866. writeAncient := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  867. var (
  868. previous = bc.CurrentFastBlock()
  869. batch = bc.db.NewBatch()
  870. )
  871. // If any error occurs before updating the head or we are inserting a side chain,
  872. // all the data written this time wll be rolled back.
  873. defer func() {
  874. if previous != nil {
  875. if err := bc.truncateAncient(previous.NumberU64()); err != nil {
  876. log.Crit("Truncate ancient store failed", "err", err)
  877. }
  878. }
  879. }()
  880. var deleted types.Blocks
  881. for i, block := range blockChain {
  882. // Short circuit insertion if shutting down or processing failed
  883. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  884. return 0, errInsertionInterrupted
  885. }
  886. // Short circuit insertion if it is required(used in testing only)
  887. if bc.terminateInsert != nil && bc.terminateInsert(block.Hash(), block.NumberU64()) {
  888. return i, errors.New("insertion is terminated for testing purpose")
  889. }
  890. // Short circuit if the owner header is unknown
  891. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  892. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  893. }
  894. var (
  895. start = time.Now()
  896. logged = time.Now()
  897. count int
  898. )
  899. // Migrate all ancient blocks. This can happen if someone upgrades from Geth
  900. // 1.8.x to 1.9.x mid-fast-sync. Perhaps we can get rid of this path in the
  901. // long term.
  902. for {
  903. // We can ignore the error here since light client won't hit this code path.
  904. frozen, _ := bc.db.Ancients()
  905. if frozen >= block.NumberU64() {
  906. break
  907. }
  908. h := rawdb.ReadCanonicalHash(bc.db, frozen)
  909. b := rawdb.ReadBlock(bc.db, h, frozen)
  910. size += rawdb.WriteAncientBlock(bc.db, b, rawdb.ReadReceipts(bc.db, h, frozen, bc.chainConfig), rawdb.ReadTd(bc.db, h, frozen))
  911. count += 1
  912. // Always keep genesis block in active database.
  913. if b.NumberU64() != 0 {
  914. deleted = append(deleted, b)
  915. }
  916. if time.Since(logged) > 8*time.Second {
  917. log.Info("Migrating ancient blocks", "count", count, "elapsed", common.PrettyDuration(time.Since(start)))
  918. logged = time.Now()
  919. }
  920. }
  921. if count > 0 {
  922. log.Info("Migrated ancient blocks", "count", count, "elapsed", common.PrettyDuration(time.Since(start)))
  923. }
  924. // Flush data into ancient database.
  925. size += rawdb.WriteAncientBlock(bc.db, block, receiptChain[i], bc.GetTd(block.Hash(), block.NumberU64()))
  926. rawdb.WriteTxLookupEntries(batch, block)
  927. stats.processed++
  928. }
  929. // Flush all tx-lookup index data.
  930. size += batch.ValueSize()
  931. if err := batch.Write(); err != nil {
  932. return 0, err
  933. }
  934. batch.Reset()
  935. // Sync the ancient store explicitly to ensure all data has been flushed to disk.
  936. if err := bc.db.Sync(); err != nil {
  937. return 0, err
  938. }
  939. if !updateHead(blockChain[len(blockChain)-1]) {
  940. return 0, errors.New("side blocks can't be accepted as the ancient chain data")
  941. }
  942. previous = nil // disable rollback explicitly
  943. // Wipe out canonical block data.
  944. for _, block := range append(deleted, blockChain...) {
  945. // Always keep genesis block in active database.
  946. if block.NumberU64() != 0 {
  947. rawdb.DeleteBlockWithoutNumber(batch, block.Hash(), block.NumberU64())
  948. rawdb.DeleteCanonicalHash(batch, block.NumberU64())
  949. }
  950. }
  951. if err := batch.Write(); err != nil {
  952. return 0, err
  953. }
  954. batch.Reset()
  955. // Wipe out side chain too.
  956. for _, block := range append(deleted, blockChain...) {
  957. // Always keep genesis block in active database.
  958. if block.NumberU64() != 0 {
  959. for _, hash := range rawdb.ReadAllHashes(bc.db, block.NumberU64()) {
  960. rawdb.DeleteBlock(batch, hash, block.NumberU64())
  961. }
  962. }
  963. }
  964. if err := batch.Write(); err != nil {
  965. return 0, err
  966. }
  967. return 0, nil
  968. }
  969. // writeLive writes blockchain and corresponding receipt chain into active store.
  970. writeLive := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  971. batch := bc.db.NewBatch()
  972. for i, block := range blockChain {
  973. // Short circuit insertion if shutting down or processing failed
  974. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  975. return 0, errInsertionInterrupted
  976. }
  977. // Short circuit if the owner header is unknown
  978. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  979. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  980. }
  981. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  982. stats.ignored++
  983. continue
  984. }
  985. // Write all the data out into the database
  986. rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
  987. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receiptChain[i])
  988. rawdb.WriteTxLookupEntries(batch, block)
  989. stats.processed++
  990. if batch.ValueSize() >= ethdb.IdealBatchSize {
  991. if err := batch.Write(); err != nil {
  992. return 0, err
  993. }
  994. size += batch.ValueSize()
  995. batch.Reset()
  996. }
  997. }
  998. if batch.ValueSize() > 0 {
  999. size += batch.ValueSize()
  1000. if err := batch.Write(); err != nil {
  1001. return 0, err
  1002. }
  1003. }
  1004. updateHead(blockChain[len(blockChain)-1])
  1005. return 0, nil
  1006. }
  1007. // Write downloaded chain data and corresponding receipt chain data.
  1008. if len(ancientBlocks) > 0 {
  1009. if n, err := writeAncient(ancientBlocks, ancientReceipts); err != nil {
  1010. if err == errInsertionInterrupted {
  1011. return 0, nil
  1012. }
  1013. return n, err
  1014. }
  1015. }
  1016. if len(liveBlocks) > 0 {
  1017. if n, err := writeLive(liveBlocks, liveReceipts); err != nil {
  1018. if err == errInsertionInterrupted {
  1019. return 0, nil
  1020. }
  1021. return n, err
  1022. }
  1023. }
  1024. head := blockChain[len(blockChain)-1]
  1025. context := []interface{}{
  1026. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  1027. "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(int64(head.Time()), 0)),
  1028. "size", common.StorageSize(size),
  1029. }
  1030. if stats.ignored > 0 {
  1031. context = append(context, []interface{}{"ignored", stats.ignored}...)
  1032. }
  1033. log.Info("Imported new block receipts", context...)
  1034. return 0, nil
  1035. }
  1036. var lastWrite uint64
  1037. // writeBlockWithoutState writes only the block and its metadata to the database,
  1038. // but does not write any state. This is used to construct competing side forks
  1039. // up to the point where they exceed the canonical total difficulty.
  1040. func (bc *BlockChain) writeBlockWithoutState(block *types.Block, td *big.Int) (err error) {
  1041. bc.wg.Add(1)
  1042. defer bc.wg.Done()
  1043. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), td); err != nil {
  1044. return err
  1045. }
  1046. rawdb.WriteBlock(bc.db, block)
  1047. return nil
  1048. }
  1049. // writeKnownBlock updates the head block flag with a known block
  1050. // and introduces chain reorg if necessary.
  1051. func (bc *BlockChain) writeKnownBlock(block *types.Block) error {
  1052. bc.wg.Add(1)
  1053. defer bc.wg.Done()
  1054. current := bc.CurrentBlock()
  1055. if block.ParentHash() != current.Hash() {
  1056. if err := bc.reorg(current, block); err != nil {
  1057. return err
  1058. }
  1059. }
  1060. // Write the positional metadata for transaction/receipt lookups.
  1061. // Preimages here is empty, ignore it.
  1062. rawdb.WriteTxLookupEntries(bc.db, block)
  1063. bc.insert(block)
  1064. return nil
  1065. }
  1066. // WriteBlockWithState writes the block and all associated state to the database.
  1067. func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  1068. bc.chainmu.Lock()
  1069. defer bc.chainmu.Unlock()
  1070. return bc.writeBlockWithState(block, receipts, state)
  1071. }
  1072. // writeBlockWithState writes the block and all associated state to the database,
  1073. // but is expects the chain mutex to be held.
  1074. func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  1075. bc.wg.Add(1)
  1076. defer bc.wg.Done()
  1077. // Calculate the total difficulty of the block
  1078. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1079. if ptd == nil {
  1080. return NonStatTy, consensus.ErrUnknownAncestor
  1081. }
  1082. // Make sure no inconsistent state is leaked during insertion
  1083. currentBlock := bc.CurrentBlock()
  1084. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  1085. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  1086. // Irrelevant of the canonical status, write the block itself to the database
  1087. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
  1088. return NonStatTy, err
  1089. }
  1090. rawdb.WriteBlock(bc.db, block)
  1091. root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
  1092. if err != nil {
  1093. return NonStatTy, err
  1094. }
  1095. triedb := bc.stateCache.TrieDB()
  1096. // If we're running an archive node, always flush
  1097. if bc.cacheConfig.TrieDirtyDisabled {
  1098. if err := triedb.Commit(root, false); err != nil {
  1099. return NonStatTy, err
  1100. }
  1101. } else {
  1102. // Full but not archive node, do proper garbage collection
  1103. triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
  1104. bc.triegc.Push(root, -int64(block.NumberU64()))
  1105. if current := block.NumberU64(); current > TriesInMemory {
  1106. // If we exceeded our memory allowance, flush matured singleton nodes to disk
  1107. var (
  1108. nodes, imgs = triedb.Size()
  1109. limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
  1110. )
  1111. if nodes > limit || imgs > 4*1024*1024 {
  1112. triedb.Cap(limit - ethdb.IdealBatchSize)
  1113. }
  1114. // Find the next state trie we need to commit
  1115. chosen := current - TriesInMemory
  1116. // If we exceeded out time allowance, flush an entire trie to disk
  1117. if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
  1118. // If the header is missing (canonical chain behind), we're reorging a low
  1119. // diff sidechain. Suspend committing until this operation is completed.
  1120. header := bc.GetHeaderByNumber(chosen)
  1121. if header == nil {
  1122. log.Warn("Reorg in progress, trie commit postponed", "number", chosen)
  1123. } else {
  1124. // If we're exceeding limits but haven't reached a large enough memory gap,
  1125. // warn the user that the system is becoming unstable.
  1126. if chosen < lastWrite+TriesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
  1127. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/TriesInMemory)
  1128. }
  1129. // Flush an entire trie and restart the counters
  1130. triedb.Commit(header.Root, true)
  1131. lastWrite = chosen
  1132. bc.gcproc = 0
  1133. }
  1134. }
  1135. // Garbage collect anything below our required write retention
  1136. for !bc.triegc.Empty() {
  1137. root, number := bc.triegc.Pop()
  1138. if uint64(-number) > chosen {
  1139. bc.triegc.Push(root, number)
  1140. break
  1141. }
  1142. triedb.Dereference(root.(common.Hash))
  1143. }
  1144. }
  1145. }
  1146. // Write other block data using a batch.
  1147. batch := bc.db.NewBatch()
  1148. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  1149. // If the total difficulty is higher than our known, add it to the canonical chain
  1150. // Second clause in the if statement reduces the vulnerability to selfish mining.
  1151. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  1152. reorg := externTd.Cmp(localTd) > 0
  1153. currentBlock = bc.CurrentBlock()
  1154. if !reorg && externTd.Cmp(localTd) == 0 {
  1155. // Split same-difficulty blocks by number, then preferentially select
  1156. // the block generated by the local miner as the canonical block.
  1157. if block.NumberU64() < currentBlock.NumberU64() {
  1158. reorg = true
  1159. } else if block.NumberU64() == currentBlock.NumberU64() {
  1160. var currentPreserve, blockPreserve bool
  1161. if bc.shouldPreserve != nil {
  1162. currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  1163. }
  1164. reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  1165. }
  1166. }
  1167. if reorg {
  1168. // Reorganise the chain if the parent is not the head block
  1169. if block.ParentHash() != currentBlock.Hash() {
  1170. if err := bc.reorg(currentBlock, block); err != nil {
  1171. return NonStatTy, err
  1172. }
  1173. }
  1174. // Write the positional metadata for transaction/receipt lookups and preimages
  1175. rawdb.WriteTxLookupEntries(batch, block)
  1176. rawdb.WritePreimages(batch, state.Preimages())
  1177. status = CanonStatTy
  1178. } else {
  1179. status = SideStatTy
  1180. }
  1181. if err := batch.Write(); err != nil {
  1182. return NonStatTy, err
  1183. }
  1184. // Set new head.
  1185. if status == CanonStatTy {
  1186. bc.insert(block)
  1187. }
  1188. bc.futureBlocks.Remove(block.Hash())
  1189. return status, nil
  1190. }
  1191. // addFutureBlock checks if the block is within the max allowed window to get
  1192. // accepted for future processing, and returns an error if the block is too far
  1193. // ahead and was not added.
  1194. func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  1195. max := uint64(time.Now().Unix() + maxTimeFutureBlocks)
  1196. if block.Time() > max {
  1197. return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  1198. }
  1199. bc.futureBlocks.Add(block.Hash(), block)
  1200. return nil
  1201. }
  1202. // InsertChain attempts to insert the given batch of blocks in to the canonical
  1203. // chain or, otherwise, create a fork. If an error is returned it will return
  1204. // the index number of the failing block as well an error describing what went
  1205. // wrong.
  1206. //
  1207. // After insertion is done, all accumulated events will be fired.
  1208. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  1209. // Sanity check that we have something meaningful to import
  1210. if len(chain) == 0 {
  1211. return 0, nil
  1212. }
  1213. bc.blockProcFeed.Send(true)
  1214. defer bc.blockProcFeed.Send(false)
  1215. // Remove already known canon-blocks
  1216. var (
  1217. block, prev *types.Block
  1218. )
  1219. // Do a sanity check that the provided chain is actually ordered and linked
  1220. for i := 1; i < len(chain); i++ {
  1221. block = chain[i]
  1222. prev = chain[i-1]
  1223. if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() {
  1224. // Chain broke ancestry, log a message (programming error) and skip insertion
  1225. log.Error("Non contiguous block insert", "number", block.Number(), "hash", block.Hash(),
  1226. "parent", block.ParentHash(), "prevnumber", prev.Number(), "prevhash", prev.Hash())
  1227. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, prev.NumberU64(),
  1228. prev.Hash().Bytes()[:4], i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4])
  1229. }
  1230. }
  1231. // Pre-checks passed, start the full block imports
  1232. bc.wg.Add(1)
  1233. bc.chainmu.Lock()
  1234. n, events, logs, err := bc.insertChain(chain, true)
  1235. bc.chainmu.Unlock()
  1236. bc.wg.Done()
  1237. bc.PostChainEvents(events, logs)
  1238. return n, err
  1239. }
  1240. // insertChain is the internal implementation of InsertChain, which assumes that
  1241. // 1) chains are contiguous, and 2) The chain mutex is held.
  1242. //
  1243. // This method is split out so that import batches that require re-injecting
  1244. // historical blocks can do so without releasing the lock, which could lead to
  1245. // racey behaviour. If a sidechain import is in progress, and the historic state
  1246. // is imported, but then new canon-head is added before the actual sidechain
  1247. // completes, then the historic state could be pruned again
  1248. func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []interface{}, []*types.Log, error) {
  1249. // If the chain is terminating, don't even bother starting up
  1250. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1251. return 0, nil, nil, nil
  1252. }
  1253. // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  1254. senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  1255. // A queued approach to delivering events. This is generally
  1256. // faster than direct delivery and requires much less mutex
  1257. // acquiring.
  1258. var (
  1259. stats = insertStats{startTime: mclock.Now()}
  1260. events = make([]interface{}, 0, len(chain))
  1261. lastCanon *types.Block
  1262. coalescedLogs []*types.Log
  1263. )
  1264. // Start the parallel header verifier
  1265. headers := make([]*types.Header, len(chain))
  1266. seals := make([]bool, len(chain))
  1267. for i, block := range chain {
  1268. headers[i] = block.Header()
  1269. seals[i] = verifySeals
  1270. }
  1271. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1272. defer close(abort)
  1273. // Peek the error for the first block to decide the directing import logic
  1274. it := newInsertIterator(chain, results, bc.validator)
  1275. block, err := it.next()
  1276. // Left-trim all the known blocks
  1277. if err == ErrKnownBlock {
  1278. // First block (and state) is known
  1279. // 1. We did a roll-back, and should now do a re-import
  1280. // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1281. // from the canonical chain, which has not been verified.
  1282. // Skip all known blocks that are behind us
  1283. var (
  1284. current = bc.CurrentBlock()
  1285. localTd = bc.GetTd(current.Hash(), current.NumberU64())
  1286. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1) // The first block can't be nil
  1287. )
  1288. for block != nil && err == ErrKnownBlock {
  1289. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1290. if localTd.Cmp(externTd) < 0 {
  1291. break
  1292. }
  1293. log.Debug("Ignoring already known block", "number", block.Number(), "hash", block.Hash())
  1294. stats.ignored++
  1295. block, err = it.next()
  1296. }
  1297. // The remaining blocks are still known blocks, the only scenario here is:
  1298. // During the fast sync, the pivot point is already submitted but rollback
  1299. // happens. Then node resets the head full block to a lower height via `rollback`
  1300. // and leaves a few known blocks in the database.
  1301. //
  1302. // When node runs a fast sync again, it can re-import a batch of known blocks via
  1303. // `insertChain` while a part of them have higher total difficulty than current
  1304. // head full block(new pivot point).
  1305. for block != nil && err == ErrKnownBlock {
  1306. log.Debug("Writing previously known block", "number", block.Number(), "hash", block.Hash())
  1307. if err := bc.writeKnownBlock(block); err != nil {
  1308. return it.index, nil, nil, err
  1309. }
  1310. lastCanon = block
  1311. block, err = it.next()
  1312. }
  1313. // Falls through to the block import
  1314. }
  1315. switch {
  1316. // First block is pruned, insert as sidechain and reorg only if TD grows enough
  1317. case err == consensus.ErrPrunedAncestor:
  1318. log.Debug("Pruned ancestor, inserting as sidechain", "number", block.Number(), "hash", block.Hash())
  1319. return bc.insertSideChain(block, it)
  1320. // First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1321. case err == consensus.ErrFutureBlock || (err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(it.first().ParentHash())):
  1322. for block != nil && (it.index == 0 || err == consensus.ErrUnknownAncestor) {
  1323. log.Debug("Future block, postponing import", "number", block.Number(), "hash", block.Hash())
  1324. if err := bc.addFutureBlock(block); err != nil {
  1325. return it.index, events, coalescedLogs, err
  1326. }
  1327. block, err = it.next()
  1328. }
  1329. stats.queued += it.processed()
  1330. stats.ignored += it.remaining()
  1331. // If there are any still remaining, mark as ignored
  1332. return it.index, events, coalescedLogs, err
  1333. // Some other error occurred, abort
  1334. case err != nil:
  1335. stats.ignored += len(it.chain)
  1336. bc.reportBlock(block, nil, err)
  1337. return it.index, events, coalescedLogs, err
  1338. }
  1339. // No validation errors for the first block (or chain prefix skipped)
  1340. for ; block != nil && err == nil || err == ErrKnownBlock; block, err = it.next() {
  1341. // If the chain is terminating, stop processing blocks
  1342. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1343. log.Debug("Premature abort during blocks processing")
  1344. break
  1345. }
  1346. // If the header is a banned one, straight out abort
  1347. if BadHashes[block.Hash()] {
  1348. bc.reportBlock(block, nil, ErrBlacklistedHash)
  1349. return it.index, events, coalescedLogs, ErrBlacklistedHash
  1350. }
  1351. // If the block is known (in the middle of the chain), it's a special case for
  1352. // Clique blocks where they can share state among each other, so importing an
  1353. // older block might complete the state of the subsequent one. In this case,
  1354. // just skip the block (we already validated it once fully (and crashed), since
  1355. // its header and body was already in the database).
  1356. if err == ErrKnownBlock {
  1357. logger := log.Debug
  1358. if bc.chainConfig.Clique == nil {
  1359. logger = log.Warn
  1360. }
  1361. logger("Inserted known block", "number", block.Number(), "hash", block.Hash(),
  1362. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1363. "root", block.Root())
  1364. if err := bc.writeKnownBlock(block); err != nil {
  1365. return it.index, nil, nil, err
  1366. }
  1367. stats.processed++
  1368. // We can assume that logs are empty here, since the only way for consecutive
  1369. // Clique blocks to have the same state is if there are no transactions.
  1370. events = append(events, ChainEvent{block, block.Hash(), nil})
  1371. lastCanon = block
  1372. continue
  1373. }
  1374. // Retrieve the parent block and it's state to execute on top
  1375. start := time.Now()
  1376. parent := it.previous()
  1377. if parent == nil {
  1378. parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
  1379. }
  1380. statedb, err := state.New(parent.Root, bc.stateCache)
  1381. if err != nil {
  1382. return it.index, events, coalescedLogs, err
  1383. }
  1384. // If we have a followup block, run that against the current state to pre-cache
  1385. // transactions and probabilistically some of the account/storage trie nodes.
  1386. var followupInterrupt uint32
  1387. if !bc.cacheConfig.TrieCleanNoPrefetch {
  1388. if followup, err := it.peek(); followup != nil && err == nil {
  1389. go func(start time.Time) {
  1390. throwaway, _ := state.New(parent.Root, bc.stateCache)
  1391. bc.prefetcher.Prefetch(followup, throwaway, bc.vmConfig, &followupInterrupt)
  1392. blockPrefetchExecuteTimer.Update(time.Since(start))
  1393. if atomic.LoadUint32(&followupInterrupt) == 1 {
  1394. blockPrefetchInterruptMeter.Mark(1)
  1395. }
  1396. }(time.Now())
  1397. }
  1398. }
  1399. // Process block using the parent state as reference point
  1400. substart := time.Now()
  1401. receipts, logs, usedGas, err := bc.processor.Process(block, statedb, bc.vmConfig)
  1402. if err != nil {
  1403. bc.reportBlock(block, receipts, err)
  1404. atomic.StoreUint32(&followupInterrupt, 1)
  1405. return it.index, events, coalescedLogs, err
  1406. }
  1407. // Update the metrics touched during block processing
  1408. accountReadTimer.Update(statedb.AccountReads) // Account reads are complete, we can mark them
  1409. storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete, we can mark them
  1410. accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete, we can mark them
  1411. storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them
  1412. triehash := statedb.AccountHashes + statedb.StorageHashes // Save to not double count in validation
  1413. trieproc := statedb.AccountReads + statedb.AccountUpdates
  1414. trieproc += statedb.StorageReads + statedb.StorageUpdates
  1415. blockExecutionTimer.Update(time.Since(substart) - trieproc - triehash)
  1416. // Validate the state using the default validator
  1417. substart = time.Now()
  1418. if err := bc.validator.ValidateState(block, statedb, receipts, usedGas); err != nil {
  1419. bc.reportBlock(block, receipts, err)
  1420. atomic.StoreUint32(&followupInterrupt, 1)
  1421. return it.index, events, coalescedLogs, err
  1422. }
  1423. proctime := time.Since(start)
  1424. // Update the metrics touched during block validation
  1425. accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete, we can mark them
  1426. storageHashTimer.Update(statedb.StorageHashes) // Storage hashes are complete, we can mark them
  1427. blockValidationTimer.Update(time.Since(substart) - (statedb.AccountHashes + statedb.StorageHashes - triehash))
  1428. // Write the block to the chain and get the status.
  1429. substart = time.Now()
  1430. status, err := bc.writeBlockWithState(block, receipts, statedb)
  1431. if err != nil {
  1432. atomic.StoreUint32(&followupInterrupt, 1)
  1433. return it.index, events, coalescedLogs, err
  1434. }
  1435. atomic.StoreUint32(&followupInterrupt, 1)
  1436. // Update the metrics touched during block commit
  1437. accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them
  1438. storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them
  1439. blockWriteTimer.Update(time.Since(substart) - statedb.AccountCommits - statedb.StorageCommits)
  1440. blockInsertTimer.UpdateSince(start)
  1441. switch status {
  1442. case CanonStatTy:
  1443. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1444. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1445. "elapsed", common.PrettyDuration(time.Since(start)),
  1446. "root", block.Root())
  1447. coalescedLogs = append(coalescedLogs, logs...)
  1448. events = append(events, ChainEvent{block, block.Hash(), logs})
  1449. lastCanon = block
  1450. // Only count canonical blocks for GC processing time
  1451. bc.gcproc += proctime
  1452. case SideStatTy:
  1453. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1454. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1455. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1456. "root", block.Root())
  1457. events = append(events, ChainSideEvent{block})
  1458. default:
  1459. // This in theory is impossible, but lets be nice to our future selves and leave
  1460. // a log, instead of trying to track down blocks imports that don't emit logs.
  1461. log.Warn("Inserted block with unknown status", "number", block.Number(), "hash", block.Hash(),
  1462. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1463. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1464. "root", block.Root())
  1465. }
  1466. stats.processed++
  1467. stats.usedGas += usedGas
  1468. dirty, _ := bc.stateCache.TrieDB().Size()
  1469. stats.report(chain, it.index, dirty)
  1470. }
  1471. // Any blocks remaining here? The only ones we care about are the future ones
  1472. if block != nil && err == consensus.ErrFutureBlock {
  1473. if err := bc.addFutureBlock(block); err != nil {
  1474. return it.index, events, coalescedLogs, err
  1475. }
  1476. block, err = it.next()
  1477. for ; block != nil && err == consensus.ErrUnknownAncestor; block, err = it.next() {
  1478. if err := bc.addFutureBlock(block); err != nil {
  1479. return it.index, events, coalescedLogs, err
  1480. }
  1481. stats.queued++
  1482. }
  1483. }
  1484. stats.ignored += it.remaining()
  1485. // Append a single chain head event if we've progressed the chain
  1486. if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1487. events = append(events, ChainHeadEvent{lastCanon})
  1488. }
  1489. return it.index, events, coalescedLogs, err
  1490. }
  1491. // insertSideChain is called when an import batch hits upon a pruned ancestor
  1492. // error, which happens when a sidechain with a sufficiently old fork-block is
  1493. // found.
  1494. //
  1495. // The method writes all (header-and-body-valid) blocks to disk, then tries to
  1496. // switch over to the new chain if the TD exceeded the current chain.
  1497. func (bc *BlockChain) insertSideChain(block *types.Block, it *insertIterator) (int, []interface{}, []*types.Log, error) {
  1498. var (
  1499. externTd *big.Int
  1500. current = bc.CurrentBlock()
  1501. )
  1502. // The first sidechain block error is already verified to be ErrPrunedAncestor.
  1503. // Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  1504. // ones. Any other errors means that the block is invalid, and should not be written
  1505. // to disk.
  1506. err := consensus.ErrPrunedAncestor
  1507. for ; block != nil && (err == consensus.ErrPrunedAncestor); block, err = it.next() {
  1508. // Check the canonical state root for that number
  1509. if number := block.NumberU64(); current.NumberU64() >= number {
  1510. canonical := bc.GetBlockByNumber(number)
  1511. if canonical != nil && canonical.Hash() == block.Hash() {
  1512. // Not a sidechain block, this is a re-import of a canon block which has it's state pruned
  1513. continue
  1514. }
  1515. if canonical != nil && canonical.Root() == block.Root() {
  1516. // This is most likely a shadow-state attack. When a fork is imported into the
  1517. // database, and it eventually reaches a block height which is not pruned, we
  1518. // just found that the state already exist! This means that the sidechain block
  1519. // refers to a state which already exists in our canon chain.
  1520. //
  1521. // If left unchecked, we would now proceed importing the blocks, without actually
  1522. // having verified the state of the previous blocks.
  1523. log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  1524. // If someone legitimately side-mines blocks, they would still be imported as usual. However,
  1525. // we cannot risk writing unverified blocks to disk when they obviously target the pruning
  1526. // mechanism.
  1527. return it.index, nil, nil, errors.New("sidechain ghost-state attack")
  1528. }
  1529. }
  1530. if externTd == nil {
  1531. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1532. }
  1533. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1534. if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  1535. start := time.Now()
  1536. if err := bc.writeBlockWithoutState(block, externTd); err != nil {
  1537. return it.index, nil, nil, err
  1538. }
  1539. log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(),
  1540. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1541. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1542. "root", block.Root())
  1543. }
  1544. }
  1545. // At this point, we've written all sidechain blocks to database. Loop ended
  1546. // either on some other error or all were processed. If there was some other
  1547. // error, we can ignore the rest of those blocks.
  1548. //
  1549. // If the externTd was larger than our local TD, we now need to reimport the previous
  1550. // blocks to regenerate the required state
  1551. localTd := bc.GetTd(current.Hash(), current.NumberU64())
  1552. if localTd.Cmp(externTd) > 0 {
  1553. log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().Number, "sidetd", externTd, "localtd", localTd)
  1554. return it.index, nil, nil, err
  1555. }
  1556. // Gather all the sidechain hashes (full blocks may be memory heavy)
  1557. var (
  1558. hashes []common.Hash
  1559. numbers []uint64
  1560. )
  1561. parent := it.previous()
  1562. for parent != nil && !bc.HasState(parent.Root) {
  1563. hashes = append(hashes, parent.Hash())
  1564. numbers = append(numbers, parent.Number.Uint64())
  1565. parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  1566. }
  1567. if parent == nil {
  1568. return it.index, nil, nil, errors.New("missing parent")
  1569. }
  1570. // Import all the pruned blocks to make the state available
  1571. var (
  1572. blocks []*types.Block
  1573. memory common.StorageSize
  1574. )
  1575. for i := len(hashes) - 1; i >= 0; i-- {
  1576. // Append the next block to our batch
  1577. block := bc.GetBlock(hashes[i], numbers[i])
  1578. blocks = append(blocks, block)
  1579. memory += block.Size()
  1580. // If memory use grew too large, import and continue. Sadly we need to discard
  1581. // all raised events and logs from notifications since we're too heavy on the
  1582. // memory here.
  1583. if len(blocks) >= 2048 || memory > 64*1024*1024 {
  1584. log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  1585. if _, _, _, err := bc.insertChain(blocks, false); err != nil {
  1586. return 0, nil, nil, err
  1587. }
  1588. blocks, memory = blocks[:0], 0
  1589. // If the chain is terminating, stop processing blocks
  1590. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1591. log.Debug("Premature abort during blocks processing")
  1592. return 0, nil, nil, nil
  1593. }
  1594. }
  1595. }
  1596. if len(blocks) > 0 {
  1597. log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  1598. return bc.insertChain(blocks, false)
  1599. }
  1600. return 0, nil, nil, nil
  1601. }
  1602. // reorg takes two blocks, an old chain and a new chain and will reconstruct the
  1603. // blocks and inserts them to be part of the new canonical chain and accumulates
  1604. // potential missing transactions and post an event about them.
  1605. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1606. var (
  1607. newChain types.Blocks
  1608. oldChain types.Blocks
  1609. commonBlock *types.Block
  1610. deletedTxs types.Transactions
  1611. addedTxs types.Transactions
  1612. deletedLogs []*types.Log
  1613. rebirthLogs []*types.Log
  1614. // collectLogs collects the logs that were generated during the
  1615. // processing of the block that corresponds with the given hash.
  1616. // These logs are later announced as deleted or reborn
  1617. collectLogs = func(hash common.Hash, removed bool) {
  1618. number := bc.hc.GetBlockNumber(hash)
  1619. if number == nil {
  1620. return
  1621. }
  1622. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  1623. for _, receipt := range receipts {
  1624. for _, log := range receipt.Logs {
  1625. l := *log
  1626. if removed {
  1627. l.Removed = true
  1628. deletedLogs = append(deletedLogs, &l)
  1629. } else {
  1630. rebirthLogs = append(rebirthLogs, &l)
  1631. }
  1632. }
  1633. }
  1634. }
  1635. )
  1636. // Reduce the longer chain to the same number as the shorter one
  1637. if oldBlock.NumberU64() > newBlock.NumberU64() {
  1638. // Old chain is longer, gather all transactions and logs as deleted ones
  1639. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  1640. oldChain = append(oldChain, oldBlock)
  1641. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1642. collectLogs(oldBlock.Hash(), true)
  1643. }
  1644. } else {
  1645. // New chain is longer, stash all blocks away for subsequent insertion
  1646. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1647. newChain = append(newChain, newBlock)
  1648. }
  1649. }
  1650. if oldBlock == nil {
  1651. return fmt.Errorf("invalid old chain")
  1652. }
  1653. if newBlock == nil {
  1654. return fmt.Errorf("invalid new chain")
  1655. }
  1656. // Both sides of the reorg are at the same number, reduce both until the common
  1657. // ancestor is found
  1658. for {
  1659. // If the common ancestor was found, bail out
  1660. if oldBlock.Hash() == newBlock.Hash() {
  1661. commonBlock = oldBlock
  1662. break
  1663. }
  1664. // Remove an old block as well as stash away a new block
  1665. oldChain = append(oldChain, oldBlock)
  1666. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1667. collectLogs(oldBlock.Hash(), true)
  1668. newChain = append(newChain, newBlock)
  1669. // Step back with both chains
  1670. oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1)
  1671. if oldBlock == nil {
  1672. return fmt.Errorf("invalid old chain")
  1673. }
  1674. newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1675. if newBlock == nil {
  1676. return fmt.Errorf("invalid new chain")
  1677. }
  1678. }
  1679. // Ensure the user sees large reorgs
  1680. if len(oldChain) > 0 && len(newChain) > 0 {
  1681. logFn := log.Debug
  1682. if len(oldChain) > 63 {
  1683. logFn = log.Warn
  1684. }
  1685. logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1686. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1687. } else {
  1688. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1689. }
  1690. // Insert the new chain(except the head block(reverse order)),
  1691. // taking care of the proper incremental order.
  1692. for i := len(newChain) - 1; i >= 1; i-- {
  1693. // Insert the block in the canonical way, re-writing history
  1694. bc.insert(newChain[i])
  1695. // Collect reborn logs due to chain reorg
  1696. collectLogs(newChain[i].Hash(), false)
  1697. // Write lookup entries for hash based transaction/receipt searches
  1698. rawdb.WriteTxLookupEntries(bc.db, newChain[i])
  1699. addedTxs = append(addedTxs, newChain[i].Transactions()...)
  1700. }
  1701. // When transactions get deleted from the database, the receipts that were
  1702. // created in the fork must also be deleted
  1703. batch := bc.db.NewBatch()
  1704. for _, tx := range types.TxDifference(deletedTxs, addedTxs) {
  1705. rawdb.DeleteTxLookupEntry(batch, tx.Hash())
  1706. }
  1707. // Delete any canonical number assignments above the new head
  1708. number := bc.CurrentBlock().NumberU64()
  1709. for i := number + 1; ; i++ {
  1710. hash := rawdb.ReadCanonicalHash(bc.db, i)
  1711. if hash == (common.Hash{}) {
  1712. break
  1713. }
  1714. rawdb.DeleteCanonicalHash(batch, i)
  1715. }
  1716. batch.Write()
  1717. // If any logs need to be fired, do it now. In theory we could avoid creating
  1718. // this goroutine if there are no events to fire, but realistcally that only
  1719. // ever happens if we're reorging empty blocks, which will only happen on idle
  1720. // networks where performance is not an issue either way.
  1721. //
  1722. // TODO(karalabe): Can we get rid of the goroutine somehow to guarantee correct
  1723. // event ordering?
  1724. go func() {
  1725. if len(deletedLogs) > 0 {
  1726. bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs})
  1727. }
  1728. if len(rebirthLogs) > 0 {
  1729. bc.logsFeed.Send(rebirthLogs)
  1730. }
  1731. if len(oldChain) > 0 {
  1732. for _, block := range oldChain {
  1733. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1734. }
  1735. }
  1736. }()
  1737. return nil
  1738. }
  1739. // PostChainEvents iterates over the events generated by a chain insertion and
  1740. // posts them into the event feed.
  1741. // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.
  1742. func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) {
  1743. // post event logs for further processing
  1744. if logs != nil {
  1745. bc.logsFeed.Send(logs)
  1746. }
  1747. for _, event := range events {
  1748. switch ev := event.(type) {
  1749. case ChainEvent:
  1750. bc.chainFeed.Send(ev)
  1751. case ChainHeadEvent:
  1752. bc.chainHeadFeed.Send(ev)
  1753. case ChainSideEvent:
  1754. bc.chainSideFeed.Send(ev)
  1755. }
  1756. }
  1757. }
  1758. func (bc *BlockChain) update() {
  1759. futureTimer := time.NewTicker(5 * time.Second)
  1760. defer futureTimer.Stop()
  1761. for {
  1762. select {
  1763. case <-futureTimer.C:
  1764. bc.procFutureBlocks()
  1765. case <-bc.quit:
  1766. return
  1767. }
  1768. }
  1769. }
  1770. // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1771. func (bc *BlockChain) BadBlocks() []*types.Block {
  1772. blocks := make([]*types.Block, 0, bc.badBlocks.Len())
  1773. for _, hash := range bc.badBlocks.Keys() {
  1774. if blk, exist := bc.badBlocks.Peek(hash); exist {
  1775. block := blk.(*types.Block)
  1776. blocks = append(blocks, block)
  1777. }
  1778. }
  1779. return blocks
  1780. }
  1781. // addBadBlock adds a bad block to the bad-block LRU cache
  1782. func (bc *BlockChain) addBadBlock(block *types.Block) {
  1783. bc.badBlocks.Add(block.Hash(), block)
  1784. }
  1785. // reportBlock logs a bad block error.
  1786. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1787. bc.addBadBlock(block)
  1788. var receiptString string
  1789. for i, receipt := range receipts {
  1790. receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  1791. i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  1792. receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  1793. }
  1794. log.Error(fmt.Sprintf(`
  1795. ########## BAD BLOCK #########
  1796. Chain config: %v
  1797. Number: %v
  1798. Hash: 0x%x
  1799. %v
  1800. Error: %v
  1801. ##############################
  1802. `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  1803. }
  1804. // InsertHeaderChain attempts to insert the given header chain in to the local
  1805. // chain, possibly creating a reorg. If an error is returned, it will return the
  1806. // index number of the failing header as well an error describing what went wrong.
  1807. //
  1808. // The verify parameter can be used to fine tune whether nonce verification
  1809. // should be done or not. The reason behind the optional check is because some
  1810. // of the header retrieval mechanisms already need to verify nonces, as well as
  1811. // because nonces can be verified sparsely, not needing to check each.
  1812. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1813. start := time.Now()
  1814. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1815. return i, err
  1816. }
  1817. // Make sure only one thread manipulates the chain at once
  1818. bc.chainmu.Lock()
  1819. defer bc.chainmu.Unlock()
  1820. bc.wg.Add(1)
  1821. defer bc.wg.Done()
  1822. whFunc := func(header *types.Header) error {
  1823. _, err := bc.hc.WriteHeader(header)
  1824. return err
  1825. }
  1826. return bc.hc.InsertHeaderChain(chain, whFunc, start)
  1827. }
  1828. // CurrentHeader retrieves the current head header of the canonical chain. The
  1829. // header is retrieved from the HeaderChain's internal cache.
  1830. func (bc *BlockChain) CurrentHeader() *types.Header {
  1831. return bc.hc.CurrentHeader()
  1832. }
  1833. // GetTd retrieves a block's total difficulty in the canonical chain from the
  1834. // database by hash and number, caching it if found.
  1835. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1836. return bc.hc.GetTd(hash, number)
  1837. }
  1838. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1839. // database by hash, caching it if found.
  1840. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1841. return bc.hc.GetTdByHash(hash)
  1842. }
  1843. // GetHeader retrieves a block header from the database by hash and number,
  1844. // caching it if found.
  1845. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1846. return bc.hc.GetHeader(hash, number)
  1847. }
  1848. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1849. // found.
  1850. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1851. return bc.hc.GetHeaderByHash(hash)
  1852. }
  1853. // HasHeader checks if a block header is present in the database or not, caching
  1854. // it if present.
  1855. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  1856. return bc.hc.HasHeader(hash, number)
  1857. }
  1858. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1859. // hash, fetching towards the genesis block.
  1860. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1861. return bc.hc.GetBlockHashesFromHash(hash, max)
  1862. }
  1863. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  1864. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  1865. // number of blocks to be individually checked before we reach the canonical chain.
  1866. //
  1867. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  1868. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  1869. bc.chainmu.RLock()
  1870. defer bc.chainmu.RUnlock()
  1871. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  1872. }
  1873. // GetHeaderByNumber retrieves a block header from the database by number,
  1874. // caching it (associated with its hash) if found.
  1875. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1876. return bc.hc.GetHeaderByNumber(number)
  1877. }
  1878. // Config retrieves the blockchain's chain configuration.
  1879. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  1880. // Engine retrieves the blockchain's consensus engine.
  1881. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  1882. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  1883. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  1884. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  1885. }
  1886. // SubscribeChainEvent registers a subscription of ChainEvent.
  1887. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  1888. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  1889. }
  1890. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  1891. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  1892. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  1893. }
  1894. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  1895. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  1896. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  1897. }
  1898. // SubscribeLogsEvent registers a subscription of []*types.Log.
  1899. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  1900. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  1901. }
  1902. // SubscribeBlockProcessingEvent registers a subscription of bool where true means
  1903. // block processing has started while false means it has stopped.
  1904. func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription {
  1905. return bc.scope.Track(bc.blockProcFeed.Subscribe(ch))
  1906. }