blockchain.go 92 KB

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