blockchain.go 92 KB

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