blockchain.go 93 KB

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