blockchain.go 93 KB

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