blockchain.go 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017
  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. lru "github.com/hashicorp/golang-lru"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/common/mclock"
  31. "github.com/ethereum/go-ethereum/common/prque"
  32. "github.com/ethereum/go-ethereum/consensus"
  33. "github.com/ethereum/go-ethereum/core/rawdb"
  34. "github.com/ethereum/go-ethereum/core/state"
  35. "github.com/ethereum/go-ethereum/core/state/snapshot"
  36. "github.com/ethereum/go-ethereum/core/types"
  37. "github.com/ethereum/go-ethereum/core/vm"
  38. "github.com/ethereum/go-ethereum/ethdb"
  39. "github.com/ethereum/go-ethereum/event"
  40. "github.com/ethereum/go-ethereum/log"
  41. "github.com/ethereum/go-ethereum/metrics"
  42. "github.com/ethereum/go-ethereum/params"
  43. "github.com/ethereum/go-ethereum/rlp"
  44. "github.com/ethereum/go-ethereum/trie"
  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. blockReorgMeter = metrics.NewRegisteredMeter("chain/reorg/executes", nil)
  66. blockReorgAddMeter = metrics.NewRegisteredMeter("chain/reorg/add", nil)
  67. blockReorgDropMeter = metrics.NewRegisteredMeter("chain/reorg/drop", nil)
  68. blockReorgInvalidatedTx = metrics.NewRegisteredMeter("chain/reorg/invalidTx", nil)
  69. errInsertionInterrupted = errors.New("insertion is interrupted")
  70. )
  71. const (
  72. bodyCacheLimit = 256
  73. blockCacheLimit = 256
  74. diffLayerCacheLimit = 1024
  75. diffLayerRLPCacheLimit = 256
  76. receiptsCacheLimit = 10000
  77. txLookupCacheLimit = 1024
  78. maxFutureBlocks = 256
  79. maxTimeFutureBlocks = 30
  80. maxBeyondBlocks = 2048
  81. prefetchTxNumber = 100
  82. diffLayerFreezerRecheckInterval = 3 * time.Second
  83. diffLayerPruneRecheckInterval = 1 * time.Second // The interval to prune unverified diff layers
  84. maxDiffQueueDist = 2048 // Maximum allowed distance from the chain head to queue diffLayers
  85. maxDiffLimit = 2048 // Maximum number of unique diff layers a peer may have responded
  86. maxDiffForkDist = 11 // Maximum allowed backward distance from the chain head
  87. maxDiffLimitForBroadcast = 128 // Maximum number of unique diff layers a peer may have broadcasted
  88. // BlockChainVersion ensures that an incompatible database forces a resync from scratch.
  89. //
  90. // Changelog:
  91. //
  92. // - Version 4
  93. // The following incompatible database changes were added:
  94. // * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted
  95. // * the `Bloom` field of receipt is deleted
  96. // * the `BlockIndex` and `TxIndex` fields of txlookup are deleted
  97. // - Version 5
  98. // The following incompatible database changes were added:
  99. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are no longer stored for a receipt
  100. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are computed by looking up the
  101. // receipts' corresponding block
  102. // - Version 6
  103. // The following incompatible database changes were added:
  104. // * Transaction lookup information stores the corresponding block number instead of block hash
  105. // - Version 7
  106. // The following incompatible database changes were added:
  107. // * Use freezer as the ancient database to maintain all ancient data
  108. // - Version 8
  109. // The following incompatible database changes were added:
  110. // * New scheme for contract code in order to separate the codes and trie nodes
  111. BlockChainVersion uint64 = 8
  112. )
  113. // CacheConfig contains the configuration values for the trie caching/pruning
  114. // that's resident in a blockchain.
  115. type CacheConfig struct {
  116. TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
  117. TrieCleanJournal string // Disk journal for saving clean cache entries.
  118. TrieCleanRejournal time.Duration // Time interval to dump clean cache to disk periodically
  119. TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk
  120. TrieDirtyDisabled bool // Whether to disable trie write caching and GC altogether (archive node)
  121. TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
  122. SnapshotLimit int // Memory allowance (MB) to use for caching snapshot entries in memory
  123. Preimages bool // Whether to store preimage of trie key to the disk
  124. TriesInMemory uint64 // How many tries keeps in memory
  125. SnapshotWait bool // Wait for snapshot construction on startup. TODO(karalabe): This is a dirty hack for testing, nuke it
  126. }
  127. // To avoid cycle import
  128. type PeerIDer interface {
  129. ID() string
  130. }
  131. // defaultCacheConfig are the default caching values if none are specified by the
  132. // user (also used during testing).
  133. var defaultCacheConfig = &CacheConfig{
  134. TrieCleanLimit: 256,
  135. TrieDirtyLimit: 256,
  136. TrieTimeLimit: 5 * time.Minute,
  137. SnapshotLimit: 256,
  138. TriesInMemory: 128,
  139. SnapshotWait: true,
  140. }
  141. type BlockChainOption func(*BlockChain) *BlockChain
  142. // BlockChain represents the canonical chain given a database with a genesis
  143. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  144. //
  145. // Importing blocks in to the block chain happens according to the set of rules
  146. // defined by the two stage Validator. Processing of blocks is done using the
  147. // Processor which processes the included transaction. The validation of the state
  148. // is done in the second part of the Validator. Failing results in aborting of
  149. // the import.
  150. //
  151. // The BlockChain also helps in returning blocks from **any** chain included
  152. // in the database as well as blocks that represents the canonical chain. It's
  153. // important to note that GetBlock can return any block and does not need to be
  154. // included in the canonical one where as GetBlockByNumber always represents the
  155. // canonical chain.
  156. type BlockChain struct {
  157. chainConfig *params.ChainConfig // Chain & network configuration
  158. cacheConfig *CacheConfig // Cache configuration for pruning
  159. db ethdb.Database // Low level persistent database to store final content in
  160. snaps *snapshot.Tree // Snapshot tree for fast trie leaf access
  161. triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
  162. gcproc time.Duration // Accumulates canonical block processing for trie dumping
  163. // txLookupLimit is the maximum number of blocks from head whose tx indices
  164. // are reserved:
  165. // * 0: means no limit and regenerate any missing indexes
  166. // * N: means N block limit [HEAD-N+1, HEAD] and delete extra indexes
  167. // * nil: disable tx reindexer/deleter, but still index new blocks
  168. txLookupLimit uint64
  169. triesInMemory uint64
  170. hc *HeaderChain
  171. rmLogsFeed event.Feed
  172. chainFeed event.Feed
  173. chainSideFeed event.Feed
  174. chainHeadFeed event.Feed
  175. logsFeed event.Feed
  176. blockProcFeed event.Feed
  177. scope event.SubscriptionScope
  178. genesisBlock *types.Block
  179. chainmu sync.RWMutex // blockchain insertion lock
  180. currentBlock atomic.Value // Current head of the block chain
  181. currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
  182. highestVerifiedHeader atomic.Value
  183. stateCache state.Database // State database to reuse between imports (contains state cache)
  184. bodyCache *lru.Cache // Cache for the most recent block bodies
  185. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  186. receiptsCache *lru.Cache // Cache for the most recent receipts per block
  187. blockCache *lru.Cache // Cache for the most recent entire blocks
  188. txLookupCache *lru.Cache // Cache for the most recent transaction lookup data.
  189. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  190. // trusted diff layers
  191. diffLayerCache *lru.Cache // Cache for the diffLayers
  192. diffLayerRLPCache *lru.Cache // Cache for the rlp encoded diffLayers
  193. diffQueue *prque.Prque // A Priority queue to store recent diff layer
  194. diffQueueBuffer chan *types.DiffLayer
  195. diffLayerFreezerBlockLimit uint64
  196. // untrusted diff layers
  197. diffMux sync.RWMutex
  198. blockHashToDiffLayers map[common.Hash]map[common.Hash]*types.DiffLayer // map[blockHash] map[DiffHash]Diff
  199. diffHashToBlockHash map[common.Hash]common.Hash // map[diffHash]blockHash
  200. diffHashToPeers map[common.Hash]map[string]struct{} // map[diffHash]map[pid]
  201. diffNumToBlockHashes map[uint64]map[common.Hash]struct{} // map[number]map[blockHash]
  202. diffPeersToDiffHashes map[string]map[common.Hash]struct{} // map[pid]map[diffHash]
  203. quit chan struct{} // blockchain quit channel
  204. wg sync.WaitGroup // chain processing wait group for shutting down
  205. running int32 // 0 if chain is running, 1 when stopped
  206. procInterrupt int32 // interrupt signaler for block processing
  207. engine consensus.Engine
  208. prefetcher Prefetcher
  209. validator Validator // Block and state validator interface
  210. processor Processor // Block transaction processor interface
  211. vmConfig vm.Config
  212. shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
  213. terminateInsert func(common.Hash, uint64) bool // Testing hook used to terminate ancient receipt chain insertion.
  214. }
  215. // NewBlockChain returns a fully initialised block chain using information
  216. // available in the database. It initialises the default Ethereum Validator and
  217. // Processor.
  218. func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine,
  219. vmConfig vm.Config, shouldPreserve func(block *types.Block) bool, txLookupLimit *uint64,
  220. options ...BlockChainOption) (*BlockChain, error) {
  221. if cacheConfig == nil {
  222. cacheConfig = defaultCacheConfig
  223. }
  224. if cacheConfig.TriesInMemory != 128 {
  225. log.Warn("TriesInMemory isn't the default value(128), you need specify exact same TriesInMemory when prune data",
  226. "triesInMemory", cacheConfig.TriesInMemory)
  227. }
  228. bodyCache, _ := lru.New(bodyCacheLimit)
  229. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  230. receiptsCache, _ := lru.New(receiptsCacheLimit)
  231. blockCache, _ := lru.New(blockCacheLimit)
  232. txLookupCache, _ := lru.New(txLookupCacheLimit)
  233. futureBlocks, _ := lru.New(maxFutureBlocks)
  234. diffLayerCache, _ := lru.New(diffLayerCacheLimit)
  235. diffLayerRLPCache, _ := lru.New(diffLayerRLPCacheLimit)
  236. bc := &BlockChain{
  237. chainConfig: chainConfig,
  238. cacheConfig: cacheConfig,
  239. db: db,
  240. triegc: prque.New(nil),
  241. stateCache: state.NewDatabaseWithConfigAndCache(db, &trie.Config{
  242. Cache: cacheConfig.TrieCleanLimit,
  243. Journal: cacheConfig.TrieCleanJournal,
  244. Preimages: cacheConfig.Preimages,
  245. }),
  246. triesInMemory: cacheConfig.TriesInMemory,
  247. quit: make(chan struct{}),
  248. shouldPreserve: shouldPreserve,
  249. bodyCache: bodyCache,
  250. bodyRLPCache: bodyRLPCache,
  251. receiptsCache: receiptsCache,
  252. blockCache: blockCache,
  253. diffLayerCache: diffLayerCache,
  254. diffLayerRLPCache: diffLayerRLPCache,
  255. txLookupCache: txLookupCache,
  256. futureBlocks: futureBlocks,
  257. engine: engine,
  258. vmConfig: vmConfig,
  259. diffQueue: prque.New(nil),
  260. diffQueueBuffer: make(chan *types.DiffLayer),
  261. blockHashToDiffLayers: make(map[common.Hash]map[common.Hash]*types.DiffLayer),
  262. diffHashToBlockHash: make(map[common.Hash]common.Hash),
  263. diffHashToPeers: make(map[common.Hash]map[string]struct{}),
  264. diffNumToBlockHashes: make(map[uint64]map[common.Hash]struct{}),
  265. diffPeersToDiffHashes: make(map[string]map[common.Hash]struct{}),
  266. }
  267. bc.prefetcher = NewStatePrefetcher(chainConfig, bc, engine)
  268. bc.validator = NewBlockValidator(chainConfig, bc, engine)
  269. bc.processor = NewStateProcessor(chainConfig, bc, engine)
  270. var err error
  271. bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.insertStopped)
  272. if err != nil {
  273. return nil, err
  274. }
  275. bc.genesisBlock = bc.GetBlockByNumber(0)
  276. if bc.genesisBlock == nil {
  277. return nil, ErrNoGenesis
  278. }
  279. var nilBlock *types.Block
  280. bc.currentBlock.Store(nilBlock)
  281. bc.currentFastBlock.Store(nilBlock)
  282. var nilHeader *types.Header
  283. bc.highestVerifiedHeader.Store(nilHeader)
  284. // Initialize the chain with ancient data if it isn't empty.
  285. var txIndexBlock uint64
  286. if bc.empty() {
  287. rawdb.InitDatabaseFromFreezer(bc.db)
  288. // If ancient database is not empty, reconstruct all missing
  289. // indices in the background.
  290. frozen, _ := bc.db.ItemAmountInAncient()
  291. if frozen > 0 {
  292. txIndexBlock, _ = bc.db.Ancients()
  293. }
  294. }
  295. if err := bc.loadLastState(); err != nil {
  296. return nil, err
  297. }
  298. // Make sure the state associated with the block is available
  299. head := bc.CurrentBlock()
  300. if _, err := state.New(head.Root(), bc.stateCache, bc.snaps); err != nil {
  301. // Head state is missing, before the state recovery, find out the
  302. // disk layer point of snapshot(if it's enabled). Make sure the
  303. // rewound point is lower than disk layer.
  304. var diskRoot common.Hash
  305. if bc.cacheConfig.SnapshotLimit > 0 {
  306. diskRoot = rawdb.ReadSnapshotRoot(bc.db)
  307. }
  308. if diskRoot != (common.Hash{}) {
  309. log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash(), "snaproot", diskRoot)
  310. snapDisk, err := bc.SetHeadBeyondRoot(head.NumberU64(), diskRoot)
  311. if err != nil {
  312. return nil, err
  313. }
  314. // Chain rewound, persist old snapshot number to indicate recovery procedure
  315. if snapDisk != 0 {
  316. rawdb.WriteSnapshotRecoveryNumber(bc.db, snapDisk)
  317. }
  318. } else {
  319. log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash())
  320. if err := bc.SetHead(head.NumberU64()); err != nil {
  321. return nil, err
  322. }
  323. }
  324. }
  325. // Ensure that a previous crash in SetHead doesn't leave extra ancients
  326. if frozen, err := bc.db.ItemAmountInAncient(); err == nil && frozen > 0 {
  327. frozen, err = bc.db.Ancients()
  328. if err != nil {
  329. return nil, err
  330. }
  331. var (
  332. needRewind bool
  333. low uint64
  334. )
  335. // The head full block may be rolled back to a very low height due to
  336. // blockchain repair. If the head full block is even lower than the ancient
  337. // chain, truncate the ancient store.
  338. fullBlock := bc.CurrentBlock()
  339. if fullBlock != nil && fullBlock.Hash() != bc.genesisBlock.Hash() && fullBlock.NumberU64() < frozen-1 {
  340. needRewind = true
  341. low = fullBlock.NumberU64()
  342. }
  343. // In fast sync, it may happen that ancient data has been written to the
  344. // ancient store, but the LastFastBlock has not been updated, truncate the
  345. // extra data here.
  346. fastBlock := bc.CurrentFastBlock()
  347. if fastBlock != nil && fastBlock.NumberU64() < frozen-1 {
  348. needRewind = true
  349. if fastBlock.NumberU64() < low || low == 0 {
  350. low = fastBlock.NumberU64()
  351. }
  352. }
  353. if needRewind {
  354. log.Error("Truncating ancient chain", "from", bc.CurrentHeader().Number.Uint64(), "to", low)
  355. if err := bc.SetHead(low); err != nil {
  356. return nil, err
  357. }
  358. }
  359. }
  360. // The first thing the node will do is reconstruct the verification data for
  361. // the head block (ethash cache or clique voting snapshot). Might as well do
  362. // it in advance.
  363. bc.engine.VerifyHeader(bc, bc.CurrentHeader(), true)
  364. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  365. for hash := range BadHashes {
  366. if header := bc.GetHeaderByHash(hash); header != nil {
  367. // get the canonical block corresponding to the offending header's number
  368. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  369. // make sure the headerByNumber (if present) is in our current canonical chain
  370. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  371. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  372. if err := bc.SetHead(header.Number.Uint64() - 1); err != nil {
  373. return nil, err
  374. }
  375. log.Error("Chain rewind was successful, resuming normal operation")
  376. }
  377. }
  378. }
  379. // Load any existing snapshot, regenerating it if loading failed
  380. if bc.cacheConfig.SnapshotLimit > 0 {
  381. // If the chain was rewound past the snapshot persistent layer (causing
  382. // a recovery block number to be persisted to disk), check if we're still
  383. // in recovery mode and in that case, don't invalidate the snapshot on a
  384. // head mismatch.
  385. var recover bool
  386. head := bc.CurrentBlock()
  387. if layer := rawdb.ReadSnapshotRecoveryNumber(bc.db); layer != nil && *layer > head.NumberU64() {
  388. log.Warn("Enabling snapshot recovery", "chainhead", head.NumberU64(), "diskbase", *layer)
  389. recover = true
  390. }
  391. bc.snaps, _ = snapshot.New(bc.db, bc.stateCache.TrieDB(), bc.cacheConfig.SnapshotLimit, int(bc.cacheConfig.TriesInMemory), head.Root(), !bc.cacheConfig.SnapshotWait, true, recover)
  392. }
  393. // do options before start any routine
  394. for _, option := range options {
  395. bc = option(bc)
  396. }
  397. // Take ownership of this particular state
  398. go bc.update()
  399. if txLookupLimit != nil {
  400. bc.txLookupLimit = *txLookupLimit
  401. bc.wg.Add(1)
  402. go bc.maintainTxIndex(txIndexBlock)
  403. }
  404. // If periodic cache journal is required, spin it up.
  405. if bc.cacheConfig.TrieCleanRejournal > 0 {
  406. if bc.cacheConfig.TrieCleanRejournal < time.Minute {
  407. log.Warn("Sanitizing invalid trie cache journal time", "provided", bc.cacheConfig.TrieCleanRejournal, "updated", time.Minute)
  408. bc.cacheConfig.TrieCleanRejournal = time.Minute
  409. }
  410. triedb := bc.stateCache.TrieDB()
  411. bc.wg.Add(1)
  412. go func() {
  413. defer bc.wg.Done()
  414. triedb.SaveCachePeriodically(bc.cacheConfig.TrieCleanJournal, bc.cacheConfig.TrieCleanRejournal, bc.quit)
  415. }()
  416. }
  417. // Need persist and prune diff layer
  418. if bc.db.DiffStore() != nil {
  419. go bc.trustedDiffLayerLoop()
  420. }
  421. go bc.untrustedDiffLayerPruneLoop()
  422. return bc, nil
  423. }
  424. // GetVMConfig returns the block chain VM config.
  425. func (bc *BlockChain) GetVMConfig() *vm.Config {
  426. return &bc.vmConfig
  427. }
  428. func (bc *BlockChain) cacheReceipts(hash common.Hash, receipts types.Receipts) {
  429. // TODO, This is a hot fix for the block hash of logs is `0x0000000000000000000000000000000000000000000000000000000000000000` for system tx
  430. // Please check details in https://github.com/binance-chain/bsc/issues/443
  431. // This is a temporary fix, the official fix should be a hard fork.
  432. const possibleSystemReceipts = 3 // One slash tx, two reward distribute txs.
  433. numOfReceipts := len(receipts)
  434. for i := numOfReceipts - 1; i >= 0 && i >= numOfReceipts-possibleSystemReceipts; i-- {
  435. for j := 0; j < len(receipts[i].Logs); j++ {
  436. receipts[i].Logs[j].BlockHash = hash
  437. }
  438. }
  439. bc.receiptsCache.Add(hash, receipts)
  440. }
  441. func (bc *BlockChain) cacheDiffLayer(diffLayer *types.DiffLayer) {
  442. if bc.diffLayerCache.Len() >= diffLayerCacheLimit {
  443. bc.diffLayerCache.RemoveOldest()
  444. }
  445. bc.diffLayerCache.Add(diffLayer.BlockHash, diffLayer)
  446. if bc.db.DiffStore() != nil {
  447. // push to priority queue before persisting
  448. bc.diffQueueBuffer <- diffLayer
  449. }
  450. }
  451. func (bc *BlockChain) cacheBlock(hash common.Hash, block *types.Block) {
  452. bc.blockCache.Add(hash, block)
  453. }
  454. // empty returns an indicator whether the blockchain is empty.
  455. // Note, it's a special case that we connect a non-empty ancient
  456. // database with an empty node, so that we can plugin the ancient
  457. // into node seamlessly.
  458. func (bc *BlockChain) empty() bool {
  459. genesis := bc.genesisBlock.Hash()
  460. for _, hash := range []common.Hash{rawdb.ReadHeadBlockHash(bc.db), rawdb.ReadHeadHeaderHash(bc.db), rawdb.ReadHeadFastBlockHash(bc.db)} {
  461. if hash != genesis {
  462. return false
  463. }
  464. }
  465. return true
  466. }
  467. // loadLastState loads the last known chain state from the database. This method
  468. // assumes that the chain manager mutex is held.
  469. func (bc *BlockChain) loadLastState() error {
  470. // Restore the last known head block
  471. head := rawdb.ReadHeadBlockHash(bc.db)
  472. if head == (common.Hash{}) {
  473. // Corrupt or empty database, init from scratch
  474. log.Warn("Empty database, resetting chain")
  475. return bc.Reset()
  476. }
  477. // Make sure the entire head block is available
  478. currentBlock := bc.GetBlockByHash(head)
  479. if currentBlock == nil {
  480. // Corrupt or empty database, init from scratch
  481. log.Warn("Head block missing, resetting chain", "hash", head)
  482. return bc.Reset()
  483. }
  484. // Everything seems to be fine, set as the head block
  485. bc.currentBlock.Store(currentBlock)
  486. headBlockGauge.Update(int64(currentBlock.NumberU64()))
  487. // Restore the last known head header
  488. currentHeader := currentBlock.Header()
  489. if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
  490. if header := bc.GetHeaderByHash(head); header != nil {
  491. currentHeader = header
  492. }
  493. }
  494. bc.hc.SetCurrentHeader(currentHeader)
  495. // Restore the last known head fast block
  496. bc.currentFastBlock.Store(currentBlock)
  497. headFastBlockGauge.Update(int64(currentBlock.NumberU64()))
  498. if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
  499. if block := bc.GetBlockByHash(head); block != nil {
  500. bc.currentFastBlock.Store(block)
  501. headFastBlockGauge.Update(int64(block.NumberU64()))
  502. }
  503. }
  504. // Issue a status log for the user
  505. currentFastBlock := bc.CurrentFastBlock()
  506. headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  507. blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  508. fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
  509. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time), 0)))
  510. 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)))
  511. 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)))
  512. if pivot := rawdb.ReadLastPivotNumber(bc.db); pivot != nil {
  513. log.Info("Loaded last fast-sync pivot marker", "number", *pivot)
  514. }
  515. return nil
  516. }
  517. // SetHead rewinds the local chain to a new head. Depending on whether the node
  518. // was fast synced or full synced and in which state, the method will try to
  519. // delete minimal data from disk whilst retaining chain consistency.
  520. func (bc *BlockChain) SetHead(head uint64) error {
  521. _, err := bc.SetHeadBeyondRoot(head, common.Hash{})
  522. return err
  523. }
  524. // SetHeadBeyondRoot rewinds the local chain to a new head with the extra condition
  525. // that the rewind must pass the specified state root. This method is meant to be
  526. // used when rewinding with snapshots enabled to ensure that we go back further than
  527. // persistent disk layer. Depending on whether the node was fast synced or full, and
  528. // in which state, the method will try to delete minimal data from disk whilst
  529. // retaining chain consistency.
  530. //
  531. // The method returns the block number where the requested root cap was found.
  532. func (bc *BlockChain) SetHeadBeyondRoot(head uint64, root common.Hash) (uint64, error) {
  533. bc.chainmu.Lock()
  534. defer bc.chainmu.Unlock()
  535. // Track the block number of the requested root hash
  536. var rootNumber uint64 // (no root == always 0)
  537. // Retrieve the last pivot block to short circuit rollbacks beyond it and the
  538. // current freezer limit to start nuking id underflown
  539. pivot := rawdb.ReadLastPivotNumber(bc.db)
  540. frozen, _ := bc.db.Ancients()
  541. updateFn := func(db ethdb.KeyValueWriter, header *types.Header) (uint64, bool) {
  542. // Rewind the block chain, ensuring we don't end up with a stateless head
  543. // block. Note, depth equality is permitted to allow using SetHead as a
  544. // chain reparation mechanism without deleting any data!
  545. if currentBlock := bc.CurrentBlock(); currentBlock != nil && header.Number.Uint64() <= currentBlock.NumberU64() {
  546. newHeadBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  547. lastBlockNum := header.Number.Uint64()
  548. if newHeadBlock == nil {
  549. log.Error("Gap in the chain, rewinding to genesis", "number", header.Number, "hash", header.Hash())
  550. newHeadBlock = bc.genesisBlock
  551. } else {
  552. // Block exists, keep rewinding until we find one with state,
  553. // keeping rewinding until we exceed the optional threshold
  554. // root hash
  555. beyondRoot := (root == common.Hash{}) // Flag whether we're beyond the requested root (no root, always true)
  556. enoughBeyondCount := false
  557. beyondCount := 0
  558. for {
  559. beyondCount++
  560. // If a root threshold was requested but not yet crossed, check
  561. if root != (common.Hash{}) && !beyondRoot && newHeadBlock.Root() == root {
  562. beyondRoot, rootNumber = true, newHeadBlock.NumberU64()
  563. }
  564. enoughBeyondCount = beyondCount > maxBeyondBlocks
  565. if _, err := state.New(newHeadBlock.Root(), bc.stateCache, bc.snaps); err != nil {
  566. log.Trace("Block state missing, rewinding further", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash())
  567. if pivot == nil || newHeadBlock.NumberU64() > *pivot {
  568. parent := bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1)
  569. if parent != nil {
  570. newHeadBlock = parent
  571. continue
  572. }
  573. log.Error("Missing block in the middle, aiming genesis", "number", newHeadBlock.NumberU64()-1, "hash", newHeadBlock.ParentHash())
  574. newHeadBlock = bc.genesisBlock
  575. } else {
  576. log.Trace("Rewind passed pivot, aiming genesis", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash(), "pivot", *pivot)
  577. newHeadBlock = bc.genesisBlock
  578. }
  579. }
  580. if beyondRoot || (enoughBeyondCount && root != common.Hash{}) || newHeadBlock.NumberU64() == 0 {
  581. if enoughBeyondCount && (root != common.Hash{}) && rootNumber == 0 {
  582. for {
  583. lastBlockNum++
  584. block := bc.GetBlockByNumber(lastBlockNum)
  585. if block == nil {
  586. break
  587. }
  588. if block.Root() == root {
  589. rootNumber = block.NumberU64()
  590. break
  591. }
  592. }
  593. }
  594. log.Debug("Rewound to block with state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash())
  595. break
  596. }
  597. log.Debug("Skipping block with threshold state", "number", newHeadBlock.NumberU64(), "hash", newHeadBlock.Hash(), "root", newHeadBlock.Root())
  598. newHeadBlock = bc.GetBlock(newHeadBlock.ParentHash(), newHeadBlock.NumberU64()-1) // Keep rewinding
  599. }
  600. }
  601. rawdb.WriteHeadBlockHash(db, newHeadBlock.Hash())
  602. // Degrade the chain markers if they are explicitly reverted.
  603. // In theory we should update all in-memory markers in the
  604. // last step, however the direction of SetHead is from high
  605. // to low, so it's safe the update in-memory markers directly.
  606. bc.currentBlock.Store(newHeadBlock)
  607. headBlockGauge.Update(int64(newHeadBlock.NumberU64()))
  608. }
  609. // Rewind the fast block in a simpleton way to the target head
  610. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && header.Number.Uint64() < currentFastBlock.NumberU64() {
  611. newHeadFastBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  612. // If either blocks reached nil, reset to the genesis state
  613. if newHeadFastBlock == nil {
  614. newHeadFastBlock = bc.genesisBlock
  615. }
  616. rawdb.WriteHeadFastBlockHash(db, newHeadFastBlock.Hash())
  617. // Degrade the chain markers if they are explicitly reverted.
  618. // In theory we should update all in-memory markers in the
  619. // last step, however the direction of SetHead is from high
  620. // to low, so it's safe the update in-memory markers directly.
  621. bc.currentFastBlock.Store(newHeadFastBlock)
  622. headFastBlockGauge.Update(int64(newHeadFastBlock.NumberU64()))
  623. }
  624. head := bc.CurrentBlock().NumberU64()
  625. // If setHead underflown the freezer threshold and the block processing
  626. // intent afterwards is full block importing, delete the chain segment
  627. // between the stateful-block and the sethead target.
  628. var wipe bool
  629. if head+1 < frozen {
  630. wipe = pivot == nil || head >= *pivot
  631. }
  632. return head, wipe // Only force wipe if full synced
  633. }
  634. // Rewind the header chain, deleting all block bodies until then
  635. delFn := func(db ethdb.KeyValueWriter, hash common.Hash, num uint64) {
  636. // Ignore the error here since light client won't hit this path
  637. frozen, _ := bc.db.Ancients()
  638. if num+1 <= frozen {
  639. // Truncate all relative data(header, total difficulty, body, receipt
  640. // and canonical hash) from ancient store.
  641. if err := bc.db.TruncateAncients(num); err != nil {
  642. log.Crit("Failed to truncate ancient data", "number", num, "err", err)
  643. }
  644. // Remove the hash <-> number mapping from the active store.
  645. rawdb.DeleteHeaderNumber(db, hash)
  646. } else {
  647. // Remove relative body and receipts from the active store.
  648. // The header, total difficulty and canonical hash will be
  649. // removed in the hc.SetHead function.
  650. rawdb.DeleteBody(db, hash, num)
  651. rawdb.DeleteReceipts(db, hash, num)
  652. }
  653. // Todo(rjl493456442) txlookup, bloombits, etc
  654. }
  655. // If SetHead was only called as a chain reparation method, try to skip
  656. // touching the header chain altogether, unless the freezer is broken
  657. if block := bc.CurrentBlock(); block.NumberU64() == head {
  658. if target, force := updateFn(bc.db, block.Header()); force {
  659. bc.hc.SetHead(target, updateFn, delFn)
  660. }
  661. } else {
  662. // Rewind the chain to the requested head and keep going backwards until a
  663. // block with a state is found or fast sync pivot is passed
  664. log.Warn("Rewinding blockchain", "target", head)
  665. bc.hc.SetHead(head, updateFn, delFn)
  666. }
  667. // Clear out any stale content from the caches
  668. bc.bodyCache.Purge()
  669. bc.bodyRLPCache.Purge()
  670. bc.receiptsCache.Purge()
  671. bc.blockCache.Purge()
  672. bc.txLookupCache.Purge()
  673. bc.futureBlocks.Purge()
  674. return rootNumber, bc.loadLastState()
  675. }
  676. // FastSyncCommitHead sets the current head block to the one defined by the hash
  677. // irrelevant what the chain contents were prior.
  678. func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  679. // Make sure that both the block as well at its state trie exists
  680. block := bc.GetBlockByHash(hash)
  681. if block == nil {
  682. return fmt.Errorf("non existent block [%x..]", hash[:4])
  683. }
  684. if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB()); err != nil {
  685. return err
  686. }
  687. // If all checks out, manually set the head block
  688. bc.chainmu.Lock()
  689. bc.currentBlock.Store(block)
  690. headBlockGauge.Update(int64(block.NumberU64()))
  691. bc.chainmu.Unlock()
  692. // Destroy any existing state snapshot and regenerate it in the background,
  693. // also resuming the normal maintenance of any previously paused snapshot.
  694. if bc.snaps != nil {
  695. bc.snaps.Rebuild(block.Root())
  696. }
  697. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  698. return nil
  699. }
  700. // GasLimit returns the gas limit of the current HEAD block.
  701. func (bc *BlockChain) GasLimit() uint64 {
  702. return bc.CurrentBlock().GasLimit()
  703. }
  704. // CurrentBlock retrieves the current head block of the canonical chain. The
  705. // block is retrieved from the blockchain's internal cache.
  706. func (bc *BlockChain) CurrentBlock() *types.Block {
  707. return bc.currentBlock.Load().(*types.Block)
  708. }
  709. // Snapshots returns the blockchain snapshot tree.
  710. func (bc *BlockChain) Snapshots() *snapshot.Tree {
  711. return bc.snaps
  712. }
  713. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  714. // chain. The block is retrieved from the blockchain's internal cache.
  715. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  716. return bc.currentFastBlock.Load().(*types.Block)
  717. }
  718. // Validator returns the current validator.
  719. func (bc *BlockChain) Validator() Validator {
  720. return bc.validator
  721. }
  722. // Processor returns the current processor.
  723. func (bc *BlockChain) Processor() Processor {
  724. return bc.processor
  725. }
  726. // State returns a new mutable state based on the current HEAD block.
  727. func (bc *BlockChain) State() (*state.StateDB, error) {
  728. return bc.StateAt(bc.CurrentBlock().Root())
  729. }
  730. // StateAt returns a new mutable state based on a particular point in time.
  731. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  732. return state.New(root, bc.stateCache, bc.snaps)
  733. }
  734. // StateCache returns the caching database underpinning the blockchain instance.
  735. func (bc *BlockChain) StateCache() state.Database {
  736. return bc.stateCache
  737. }
  738. // Reset purges the entire blockchain, restoring it to its genesis state.
  739. func (bc *BlockChain) Reset() error {
  740. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  741. }
  742. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  743. // specified genesis state.
  744. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  745. // Dump the entire block chain and purge the caches
  746. if err := bc.SetHead(0); err != nil {
  747. return err
  748. }
  749. bc.chainmu.Lock()
  750. defer bc.chainmu.Unlock()
  751. // Prepare the genesis block and reinitialise the chain
  752. batch := bc.db.NewBatch()
  753. rawdb.WriteTd(batch, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty())
  754. rawdb.WriteBlock(batch, genesis)
  755. if err := batch.Write(); err != nil {
  756. log.Crit("Failed to write genesis block", "err", err)
  757. }
  758. bc.writeHeadBlock(genesis)
  759. // Last update all in-memory chain markers
  760. bc.genesisBlock = genesis
  761. bc.currentBlock.Store(bc.genesisBlock)
  762. headBlockGauge.Update(int64(bc.genesisBlock.NumberU64()))
  763. bc.hc.SetGenesis(bc.genesisBlock.Header())
  764. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  765. bc.currentFastBlock.Store(bc.genesisBlock)
  766. headFastBlockGauge.Update(int64(bc.genesisBlock.NumberU64()))
  767. return nil
  768. }
  769. // Export writes the active chain to the given writer.
  770. func (bc *BlockChain) Export(w io.Writer) error {
  771. return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64())
  772. }
  773. // ExportN writes a subset of the active chain to the given writer.
  774. func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  775. bc.chainmu.RLock()
  776. defer bc.chainmu.RUnlock()
  777. if first > last {
  778. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  779. }
  780. log.Info("Exporting batch of blocks", "count", last-first+1)
  781. start, reported := time.Now(), time.Now()
  782. for nr := first; nr <= last; nr++ {
  783. block := bc.GetBlockByNumber(nr)
  784. if block == nil {
  785. return fmt.Errorf("export failed on #%d: not found", nr)
  786. }
  787. if err := block.EncodeRLP(w); err != nil {
  788. return err
  789. }
  790. if time.Since(reported) >= statsReportLimit {
  791. log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
  792. reported = time.Now()
  793. }
  794. }
  795. return nil
  796. }
  797. // writeHeadBlock injects a new head block into the current block chain. This method
  798. // assumes that the block is indeed a true head. It will also reset the head
  799. // header and the head fast sync block to this very same block if they are older
  800. // or if they are on a different side chain.
  801. //
  802. // Note, this function assumes that the `mu` mutex is held!
  803. func (bc *BlockChain) writeHeadBlock(block *types.Block) {
  804. // If the block is on a side chain or an unknown one, force other heads onto it too
  805. updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()
  806. // Add the block to the canonical chain number scheme and mark as the head
  807. batch := bc.db.NewBatch()
  808. rawdb.WriteCanonicalHash(batch, block.Hash(), block.NumberU64())
  809. rawdb.WriteTxLookupEntriesByBlock(batch, block)
  810. rawdb.WriteHeadBlockHash(batch, block.Hash())
  811. // If the block is better than our head or is on a different chain, force update heads
  812. if updateHeads {
  813. rawdb.WriteHeadHeaderHash(batch, block.Hash())
  814. rawdb.WriteHeadFastBlockHash(batch, block.Hash())
  815. }
  816. // Flush the whole batch into the disk, exit the node if failed
  817. if err := batch.Write(); err != nil {
  818. log.Crit("Failed to update chain indexes and markers", "err", err)
  819. }
  820. // Update all in-memory chain markers in the last step
  821. if updateHeads {
  822. bc.hc.SetCurrentHeader(block.Header())
  823. bc.currentFastBlock.Store(block)
  824. headFastBlockGauge.Update(int64(block.NumberU64()))
  825. }
  826. bc.currentBlock.Store(block)
  827. headBlockGauge.Update(int64(block.NumberU64()))
  828. }
  829. // Genesis retrieves the chain's genesis block.
  830. func (bc *BlockChain) Genesis() *types.Block {
  831. return bc.genesisBlock
  832. }
  833. // GetBody retrieves a block body (transactions and uncles) from the database by
  834. // hash, caching it if found.
  835. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  836. // Short circuit if the body's already in the cache, retrieve otherwise
  837. if cached, ok := bc.bodyCache.Get(hash); ok {
  838. body := cached.(*types.Body)
  839. return body
  840. }
  841. number := bc.hc.GetBlockNumber(hash)
  842. if number == nil {
  843. return nil
  844. }
  845. body := rawdb.ReadBody(bc.db, hash, *number)
  846. if body == nil {
  847. return nil
  848. }
  849. // Cache the found body for next time and return
  850. bc.bodyCache.Add(hash, body)
  851. return body
  852. }
  853. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  854. // caching it if found.
  855. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  856. // Short circuit if the body's already in the cache, retrieve otherwise
  857. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  858. return cached.(rlp.RawValue)
  859. }
  860. number := bc.hc.GetBlockNumber(hash)
  861. if number == nil {
  862. return nil
  863. }
  864. body := rawdb.ReadBodyRLP(bc.db, hash, *number)
  865. if len(body) == 0 {
  866. return nil
  867. }
  868. // Cache the found body for next time and return
  869. bc.bodyRLPCache.Add(hash, body)
  870. return body
  871. }
  872. // GetDiffLayerRLP retrieves a diff layer in RLP encoding from the cache or database by blockHash
  873. func (bc *BlockChain) GetDiffLayerRLP(blockHash common.Hash) rlp.RawValue {
  874. // Short circuit if the diffLayer's already in the cache, retrieve otherwise
  875. if cached, ok := bc.diffLayerRLPCache.Get(blockHash); ok {
  876. return cached.(rlp.RawValue)
  877. }
  878. if cached, ok := bc.diffLayerCache.Get(blockHash); ok {
  879. diff := cached.(*types.DiffLayer)
  880. bz, err := rlp.EncodeToBytes(diff)
  881. if err != nil {
  882. return nil
  883. }
  884. bc.diffLayerRLPCache.Add(blockHash, rlp.RawValue(bz))
  885. return bz
  886. }
  887. // fallback to untrusted sources.
  888. diff := bc.GetUnTrustedDiffLayer(blockHash, "")
  889. if diff != nil {
  890. bz, err := rlp.EncodeToBytes(diff)
  891. if err != nil {
  892. return nil
  893. }
  894. // No need to cache untrusted data
  895. return bz
  896. }
  897. // fallback to disk
  898. diffStore := bc.db.DiffStore()
  899. if diffStore == nil {
  900. return nil
  901. }
  902. rawData := rawdb.ReadDiffLayerRLP(diffStore, blockHash)
  903. if len(rawData) != 0 {
  904. bc.diffLayerRLPCache.Add(blockHash, rawData)
  905. }
  906. return rawData
  907. }
  908. func (bc *BlockChain) GetDiffAccounts(blockHash common.Hash) ([]common.Address, error) {
  909. var (
  910. accounts []common.Address
  911. diffLayer *types.DiffLayer
  912. )
  913. header := bc.GetHeaderByHash(blockHash)
  914. if header == nil {
  915. return nil, fmt.Errorf("no block found")
  916. }
  917. if cached, ok := bc.diffLayerCache.Get(blockHash); ok {
  918. diffLayer = cached.(*types.DiffLayer)
  919. } else if diffStore := bc.db.DiffStore(); diffStore != nil {
  920. diffLayer = rawdb.ReadDiffLayer(diffStore, blockHash)
  921. }
  922. if diffLayer == nil {
  923. if header.TxHash != types.EmptyRootHash {
  924. return nil, ErrDiffLayerNotFound
  925. }
  926. return nil, nil
  927. }
  928. for _, diffAccounts := range diffLayer.Accounts {
  929. accounts = append(accounts, diffAccounts.Account)
  930. }
  931. if header.TxHash != types.EmptyRootHash && len(accounts) == 0 {
  932. return nil, fmt.Errorf("no diff account in block, maybe bad diff layer")
  933. }
  934. return accounts, nil
  935. }
  936. // HasBlock checks if a block is fully present in the database or not.
  937. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  938. if bc.blockCache.Contains(hash) {
  939. return true
  940. }
  941. return rawdb.HasBody(bc.db, hash, number)
  942. }
  943. // HasFastBlock checks if a fast block is fully present in the database or not.
  944. func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool {
  945. if !bc.HasBlock(hash, number) {
  946. return false
  947. }
  948. if bc.receiptsCache.Contains(hash) {
  949. return true
  950. }
  951. return rawdb.HasReceipts(bc.db, hash, number)
  952. }
  953. // HasState checks if state trie is fully present in the database or not.
  954. func (bc *BlockChain) HasState(hash common.Hash) bool {
  955. _, err := bc.stateCache.OpenTrie(hash)
  956. return err == nil
  957. }
  958. // HasBlockAndState checks if a block and associated state trie is fully present
  959. // in the database or not, caching it if present.
  960. func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
  961. // Check first that the block itself is known
  962. block := bc.GetBlock(hash, number)
  963. if block == nil {
  964. return false
  965. }
  966. return bc.HasState(block.Root())
  967. }
  968. // GetBlock retrieves a block from the database by hash and number,
  969. // caching it if found.
  970. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  971. // Short circuit if the block's already in the cache, retrieve otherwise
  972. if block, ok := bc.blockCache.Get(hash); ok {
  973. return block.(*types.Block)
  974. }
  975. block := rawdb.ReadBlock(bc.db, hash, number)
  976. if block == nil {
  977. return nil
  978. }
  979. // Cache the found block for next time and return
  980. bc.blockCache.Add(block.Hash(), block)
  981. return block
  982. }
  983. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  984. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  985. number := bc.hc.GetBlockNumber(hash)
  986. if number == nil {
  987. return nil
  988. }
  989. return bc.GetBlock(hash, *number)
  990. }
  991. // GetBlockByNumber retrieves a block from the database by number, caching it
  992. // (associated with its hash) if found.
  993. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  994. hash := rawdb.ReadCanonicalHash(bc.db, number)
  995. if hash == (common.Hash{}) {
  996. return nil
  997. }
  998. return bc.GetBlock(hash, number)
  999. }
  1000. // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
  1001. func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
  1002. if receipts, ok := bc.receiptsCache.Get(hash); ok {
  1003. return receipts.(types.Receipts)
  1004. }
  1005. number := rawdb.ReadHeaderNumber(bc.db, hash)
  1006. if number == nil {
  1007. return nil
  1008. }
  1009. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  1010. if receipts == nil {
  1011. return nil
  1012. }
  1013. bc.receiptsCache.Add(hash, receipts)
  1014. return receipts
  1015. }
  1016. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  1017. // [deprecated by eth/62]
  1018. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  1019. number := bc.hc.GetBlockNumber(hash)
  1020. if number == nil {
  1021. return nil
  1022. }
  1023. for i := 0; i < n; i++ {
  1024. block := bc.GetBlock(hash, *number)
  1025. if block == nil {
  1026. break
  1027. }
  1028. blocks = append(blocks, block)
  1029. hash = block.ParentHash()
  1030. *number--
  1031. }
  1032. return
  1033. }
  1034. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  1035. // a specific distance is reached.
  1036. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  1037. uncles := []*types.Header{}
  1038. for i := 0; block != nil && i < length; i++ {
  1039. uncles = append(uncles, block.Uncles()...)
  1040. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  1041. }
  1042. return uncles
  1043. }
  1044. // TrieNode retrieves a blob of data associated with a trie node
  1045. // either from ephemeral in-memory cache, or from persistent storage.
  1046. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  1047. return bc.stateCache.TrieDB().Node(hash)
  1048. }
  1049. // ContractCode retrieves a blob of data associated with a contract hash
  1050. // either from ephemeral in-memory cache, or from persistent storage.
  1051. func (bc *BlockChain) ContractCode(hash common.Hash) ([]byte, error) {
  1052. return bc.stateCache.ContractCode(common.Hash{}, hash)
  1053. }
  1054. // ContractCodeWithPrefix retrieves a blob of data associated with a contract
  1055. // hash either from ephemeral in-memory cache, or from persistent storage.
  1056. //
  1057. // If the code doesn't exist in the in-memory cache, check the storage with
  1058. // new code scheme.
  1059. func (bc *BlockChain) ContractCodeWithPrefix(hash common.Hash) ([]byte, error) {
  1060. type codeReader interface {
  1061. ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error)
  1062. }
  1063. return bc.stateCache.(codeReader).ContractCodeWithPrefix(common.Hash{}, hash)
  1064. }
  1065. // Stop stops the blockchain service. If any imports are currently in progress
  1066. // it will abort them using the procInterrupt.
  1067. func (bc *BlockChain) Stop() {
  1068. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  1069. return
  1070. }
  1071. // Unsubscribe all subscriptions registered from blockchain
  1072. bc.scope.Close()
  1073. close(bc.quit)
  1074. bc.StopInsert()
  1075. bc.wg.Wait()
  1076. // Ensure that the entirety of the state snapshot is journalled to disk.
  1077. var snapBase common.Hash
  1078. if bc.snaps != nil {
  1079. var err error
  1080. if snapBase, err = bc.snaps.Journal(bc.CurrentBlock().Root()); err != nil {
  1081. log.Error("Failed to journal state snapshot", "err", err)
  1082. }
  1083. }
  1084. // Ensure the state of a recent block is also stored to disk before exiting.
  1085. // We're writing three different states to catch different restart scenarios:
  1086. // - HEAD: So we don't need to reprocess any blocks in the general case
  1087. // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle
  1088. // - HEAD-127: So we have a hard limit on the number of blocks reexecuted
  1089. if !bc.cacheConfig.TrieDirtyDisabled {
  1090. triedb := bc.stateCache.TrieDB()
  1091. for _, offset := range []uint64{0, 1, bc.triesInMemory - 1} {
  1092. if number := bc.CurrentBlock().NumberU64(); number > offset {
  1093. recent := bc.GetBlockByNumber(number - offset)
  1094. log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
  1095. if err := triedb.Commit(recent.Root(), true, nil); err != nil {
  1096. log.Error("Failed to commit recent state trie", "err", err)
  1097. }
  1098. }
  1099. }
  1100. if snapBase != (common.Hash{}) {
  1101. log.Info("Writing snapshot state to disk", "root", snapBase)
  1102. if err := triedb.Commit(snapBase, true, nil); err != nil {
  1103. log.Error("Failed to commit recent state trie", "err", err)
  1104. }
  1105. }
  1106. for !bc.triegc.Empty() {
  1107. go triedb.Dereference(bc.triegc.PopItem().(common.Hash))
  1108. }
  1109. if size, _ := triedb.Size(); size != 0 {
  1110. log.Error("Dangling trie nodes after full cleanup")
  1111. }
  1112. }
  1113. // Ensure all live cached entries be saved into disk, so that we can skip
  1114. // cache warmup when node restarts.
  1115. if bc.cacheConfig.TrieCleanJournal != "" {
  1116. triedb := bc.stateCache.TrieDB()
  1117. triedb.SaveCache(bc.cacheConfig.TrieCleanJournal)
  1118. }
  1119. log.Info("Blockchain stopped")
  1120. }
  1121. // StopInsert interrupts all insertion methods, causing them to return
  1122. // errInsertionInterrupted as soon as possible. Insertion is permanently disabled after
  1123. // calling this method.
  1124. func (bc *BlockChain) StopInsert() {
  1125. atomic.StoreInt32(&bc.procInterrupt, 1)
  1126. }
  1127. // insertStopped returns true after StopInsert has been called.
  1128. func (bc *BlockChain) insertStopped() bool {
  1129. return atomic.LoadInt32(&bc.procInterrupt) == 1
  1130. }
  1131. func (bc *BlockChain) procFutureBlocks() {
  1132. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  1133. for _, hash := range bc.futureBlocks.Keys() {
  1134. if block, exist := bc.futureBlocks.Peek(hash); exist {
  1135. blocks = append(blocks, block.(*types.Block))
  1136. }
  1137. }
  1138. if len(blocks) > 0 {
  1139. sort.Slice(blocks, func(i, j int) bool {
  1140. return blocks[i].NumberU64() < blocks[j].NumberU64()
  1141. })
  1142. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  1143. for i := range blocks {
  1144. bc.InsertChain(blocks[i : i+1])
  1145. }
  1146. }
  1147. }
  1148. // WriteStatus status of write
  1149. type WriteStatus byte
  1150. const (
  1151. NonStatTy WriteStatus = iota
  1152. CanonStatTy
  1153. SideStatTy
  1154. )
  1155. // truncateAncient rewinds the blockchain to the specified header and deletes all
  1156. // data in the ancient store that exceeds the specified header.
  1157. func (bc *BlockChain) truncateAncient(head uint64) error {
  1158. frozen, err := bc.db.Ancients()
  1159. if err != nil {
  1160. return err
  1161. }
  1162. // Short circuit if there is no data to truncate in ancient store.
  1163. if frozen <= head+1 {
  1164. return nil
  1165. }
  1166. // Truncate all the data in the freezer beyond the specified head
  1167. if err := bc.db.TruncateAncients(head + 1); err != nil {
  1168. return err
  1169. }
  1170. // Clear out any stale content from the caches
  1171. bc.hc.headerCache.Purge()
  1172. bc.hc.tdCache.Purge()
  1173. bc.hc.numberCache.Purge()
  1174. // Clear out any stale content from the caches
  1175. bc.bodyCache.Purge()
  1176. bc.bodyRLPCache.Purge()
  1177. bc.receiptsCache.Purge()
  1178. bc.blockCache.Purge()
  1179. bc.txLookupCache.Purge()
  1180. bc.futureBlocks.Purge()
  1181. log.Info("Rewind ancient data", "number", head)
  1182. return nil
  1183. }
  1184. // numberHash is just a container for a number and a hash, to represent a block
  1185. type numberHash struct {
  1186. number uint64
  1187. hash common.Hash
  1188. }
  1189. // InsertReceiptChain attempts to complete an already existing header chain with
  1190. // transaction and receipt data.
  1191. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts, ancientLimit uint64) (int, error) {
  1192. // We don't require the chainMu here since we want to maximize the
  1193. // concurrency of header insertion and receipt insertion.
  1194. bc.wg.Add(1)
  1195. defer bc.wg.Done()
  1196. var (
  1197. ancientBlocks, liveBlocks types.Blocks
  1198. ancientReceipts, liveReceipts []types.Receipts
  1199. )
  1200. // Do a sanity check that the provided chain is actually ordered and linked
  1201. for i := 0; i < len(blockChain); i++ {
  1202. if i != 0 {
  1203. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  1204. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  1205. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  1206. 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(),
  1207. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  1208. }
  1209. }
  1210. if blockChain[i].NumberU64() <= ancientLimit {
  1211. ancientBlocks, ancientReceipts = append(ancientBlocks, blockChain[i]), append(ancientReceipts, receiptChain[i])
  1212. } else {
  1213. liveBlocks, liveReceipts = append(liveBlocks, blockChain[i]), append(liveReceipts, receiptChain[i])
  1214. }
  1215. }
  1216. var (
  1217. stats = struct{ processed, ignored int32 }{}
  1218. start = time.Now()
  1219. size = 0
  1220. )
  1221. // updateHead updates the head fast sync block if the inserted blocks are better
  1222. // and returns an indicator whether the inserted blocks are canonical.
  1223. updateHead := func(head *types.Block) bool {
  1224. bc.chainmu.Lock()
  1225. // Rewind may have occurred, skip in that case.
  1226. if bc.CurrentHeader().Number.Cmp(head.Number()) >= 0 {
  1227. currentFastBlock, td := bc.CurrentFastBlock(), bc.GetTd(head.Hash(), head.NumberU64())
  1228. if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
  1229. rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
  1230. bc.currentFastBlock.Store(head)
  1231. headFastBlockGauge.Update(int64(head.NumberU64()))
  1232. bc.chainmu.Unlock()
  1233. return true
  1234. }
  1235. }
  1236. bc.chainmu.Unlock()
  1237. return false
  1238. }
  1239. // writeAncient writes blockchain and corresponding receipt chain into ancient store.
  1240. //
  1241. // this function only accepts canonical chain data. All side chain will be reverted
  1242. // eventually.
  1243. writeAncient := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  1244. var (
  1245. previous = bc.CurrentFastBlock()
  1246. batch = bc.db.NewBatch()
  1247. )
  1248. // If any error occurs before updating the head or we are inserting a side chain,
  1249. // all the data written this time wll be rolled back.
  1250. defer func() {
  1251. if previous != nil {
  1252. if err := bc.truncateAncient(previous.NumberU64()); err != nil {
  1253. log.Crit("Truncate ancient store failed", "err", err)
  1254. }
  1255. }
  1256. }()
  1257. var deleted []*numberHash
  1258. for i, block := range blockChain {
  1259. // Short circuit insertion if shutting down or processing failed
  1260. if bc.insertStopped() {
  1261. return 0, errInsertionInterrupted
  1262. }
  1263. // Short circuit insertion if it is required(used in testing only)
  1264. if bc.terminateInsert != nil && bc.terminateInsert(block.Hash(), block.NumberU64()) {
  1265. return i, errors.New("insertion is terminated for testing purpose")
  1266. }
  1267. // Short circuit if the owner header is unknown
  1268. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  1269. return i, fmt.Errorf("containing header #%d [%x..] unknown", block.Number(), block.Hash().Bytes()[:4])
  1270. }
  1271. if block.NumberU64() == 1 {
  1272. // Make sure to write the genesis into the freezer
  1273. if frozen, _ := bc.db.Ancients(); frozen == 0 {
  1274. h := rawdb.ReadCanonicalHash(bc.db, 0)
  1275. b := rawdb.ReadBlock(bc.db, h, 0)
  1276. size += rawdb.WriteAncientBlock(bc.db, b, rawdb.ReadReceipts(bc.db, h, 0, bc.chainConfig), rawdb.ReadTd(bc.db, h, 0))
  1277. log.Info("Wrote genesis to ancients")
  1278. }
  1279. }
  1280. // Flush data into ancient database.
  1281. size += rawdb.WriteAncientBlock(bc.db, block, receiptChain[i], bc.GetTd(block.Hash(), block.NumberU64()))
  1282. // Write tx indices if any condition is satisfied:
  1283. // * If user requires to reserve all tx indices(txlookuplimit=0)
  1284. // * If all ancient tx indices are required to be reserved(txlookuplimit is even higher than ancientlimit)
  1285. // * If block number is large enough to be regarded as a recent block
  1286. // It means blocks below the ancientLimit-txlookupLimit won't be indexed.
  1287. //
  1288. // But if the `TxIndexTail` is not nil, e.g. Geth is initialized with
  1289. // an external ancient database, during the setup, blockchain will start
  1290. // a background routine to re-indexed all indices in [ancients - txlookupLimit, ancients)
  1291. // range. In this case, all tx indices of newly imported blocks should be
  1292. // generated.
  1293. if bc.txLookupLimit == 0 || ancientLimit <= bc.txLookupLimit || block.NumberU64() >= ancientLimit-bc.txLookupLimit {
  1294. rawdb.WriteTxLookupEntriesByBlock(batch, block)
  1295. } else if rawdb.ReadTxIndexTail(bc.db) != nil {
  1296. rawdb.WriteTxLookupEntriesByBlock(batch, block)
  1297. }
  1298. stats.processed++
  1299. }
  1300. // Flush all tx-lookup index data.
  1301. size += batch.ValueSize()
  1302. if err := batch.Write(); err != nil {
  1303. return 0, err
  1304. }
  1305. batch.Reset()
  1306. // Sync the ancient store explicitly to ensure all data has been flushed to disk.
  1307. if err := bc.db.Sync(); err != nil {
  1308. return 0, err
  1309. }
  1310. if !updateHead(blockChain[len(blockChain)-1]) {
  1311. return 0, errors.New("side blocks can't be accepted as the ancient chain data")
  1312. }
  1313. previous = nil // disable rollback explicitly
  1314. // Wipe out canonical block data.
  1315. for _, nh := range deleted {
  1316. rawdb.DeleteBlockWithoutNumber(batch, nh.hash, nh.number)
  1317. rawdb.DeleteCanonicalHash(batch, nh.number)
  1318. }
  1319. for _, block := range blockChain {
  1320. // Always keep genesis block in active database.
  1321. if block.NumberU64() != 0 {
  1322. rawdb.DeleteBlockWithoutNumber(batch, block.Hash(), block.NumberU64())
  1323. rawdb.DeleteCanonicalHash(batch, block.NumberU64())
  1324. }
  1325. }
  1326. if err := batch.Write(); err != nil {
  1327. return 0, err
  1328. }
  1329. batch.Reset()
  1330. // Wipe out side chain too.
  1331. for _, nh := range deleted {
  1332. for _, hash := range rawdb.ReadAllHashes(bc.db, nh.number) {
  1333. rawdb.DeleteBlock(batch, hash, nh.number)
  1334. }
  1335. }
  1336. for _, block := range blockChain {
  1337. // Always keep genesis block in active database.
  1338. if block.NumberU64() != 0 {
  1339. for _, hash := range rawdb.ReadAllHashes(bc.db, block.NumberU64()) {
  1340. rawdb.DeleteBlock(batch, hash, block.NumberU64())
  1341. }
  1342. }
  1343. }
  1344. if err := batch.Write(); err != nil {
  1345. return 0, err
  1346. }
  1347. return 0, nil
  1348. }
  1349. // writeLive writes blockchain and corresponding receipt chain into active store.
  1350. writeLive := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  1351. skipPresenceCheck := false
  1352. batch := bc.db.NewBatch()
  1353. for i, block := range blockChain {
  1354. // Short circuit insertion if shutting down or processing failed
  1355. if bc.insertStopped() {
  1356. return 0, errInsertionInterrupted
  1357. }
  1358. // Short circuit if the owner header is unknown
  1359. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  1360. return i, fmt.Errorf("containing header #%d [%x..] unknown", block.Number(), block.Hash().Bytes()[:4])
  1361. }
  1362. if !skipPresenceCheck {
  1363. // Ignore if the entire data is already known
  1364. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  1365. stats.ignored++
  1366. continue
  1367. } else {
  1368. // If block N is not present, neither are the later blocks.
  1369. // This should be true, but if we are mistaken, the shortcut
  1370. // here will only cause overwriting of some existing data
  1371. skipPresenceCheck = true
  1372. }
  1373. }
  1374. // Write all the data out into the database
  1375. rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
  1376. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receiptChain[i])
  1377. rawdb.WriteTxLookupEntriesByBlock(batch, block) // Always write tx indices for live blocks, we assume they are needed
  1378. // Write everything belongs to the blocks into the database. So that
  1379. // we can ensure all components of body is completed(body, receipts,
  1380. // tx indexes)
  1381. if batch.ValueSize() >= ethdb.IdealBatchSize {
  1382. if err := batch.Write(); err != nil {
  1383. return 0, err
  1384. }
  1385. size += batch.ValueSize()
  1386. batch.Reset()
  1387. }
  1388. stats.processed++
  1389. }
  1390. // Write everything belongs to the blocks into the database. So that
  1391. // we can ensure all components of body is completed(body, receipts,
  1392. // tx indexes)
  1393. if batch.ValueSize() > 0 {
  1394. size += batch.ValueSize()
  1395. if err := batch.Write(); err != nil {
  1396. return 0, err
  1397. }
  1398. }
  1399. updateHead(blockChain[len(blockChain)-1])
  1400. return 0, nil
  1401. }
  1402. // Write downloaded chain data and corresponding receipt chain data
  1403. if len(ancientBlocks) > 0 {
  1404. if n, err := writeAncient(ancientBlocks, ancientReceipts); err != nil {
  1405. if err == errInsertionInterrupted {
  1406. return 0, nil
  1407. }
  1408. return n, err
  1409. }
  1410. }
  1411. // Write the tx index tail (block number from where we index) before write any live blocks
  1412. if len(liveBlocks) > 0 && liveBlocks[0].NumberU64() == ancientLimit+1 {
  1413. // The tx index tail can only be one of the following two options:
  1414. // * 0: all ancient blocks have been indexed
  1415. // * ancient-limit: the indices of blocks before ancient-limit are ignored
  1416. if tail := rawdb.ReadTxIndexTail(bc.db); tail == nil {
  1417. if bc.txLookupLimit == 0 || ancientLimit <= bc.txLookupLimit {
  1418. rawdb.WriteTxIndexTail(bc.db, 0)
  1419. } else {
  1420. rawdb.WriteTxIndexTail(bc.db, ancientLimit-bc.txLookupLimit)
  1421. }
  1422. }
  1423. }
  1424. if len(liveBlocks) > 0 {
  1425. if n, err := writeLive(liveBlocks, liveReceipts); err != nil {
  1426. if err == errInsertionInterrupted {
  1427. return 0, nil
  1428. }
  1429. return n, err
  1430. }
  1431. }
  1432. head := blockChain[len(blockChain)-1]
  1433. context := []interface{}{
  1434. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  1435. "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(int64(head.Time()), 0)),
  1436. "size", common.StorageSize(size),
  1437. }
  1438. if stats.ignored > 0 {
  1439. context = append(context, []interface{}{"ignored", stats.ignored}...)
  1440. }
  1441. log.Info("Imported new block receipts", context...)
  1442. return 0, nil
  1443. }
  1444. // SetTxLookupLimit is responsible for updating the txlookup limit to the
  1445. // original one stored in db if the new mismatches with the old one.
  1446. func (bc *BlockChain) SetTxLookupLimit(limit uint64) {
  1447. bc.txLookupLimit = limit
  1448. }
  1449. // TxLookupLimit retrieves the txlookup limit used by blockchain to prune
  1450. // stale transaction indices.
  1451. func (bc *BlockChain) TxLookupLimit() uint64 {
  1452. return bc.txLookupLimit
  1453. }
  1454. var lastWrite uint64
  1455. // writeBlockWithoutState writes only the block and its metadata to the database,
  1456. // but does not write any state. This is used to construct competing side forks
  1457. // up to the point where they exceed the canonical total difficulty.
  1458. func (bc *BlockChain) writeBlockWithoutState(block *types.Block, td *big.Int) (err error) {
  1459. bc.wg.Add(1)
  1460. defer bc.wg.Done()
  1461. batch := bc.db.NewBatch()
  1462. rawdb.WriteTd(batch, block.Hash(), block.NumberU64(), td)
  1463. rawdb.WriteBlock(batch, block)
  1464. if err := batch.Write(); err != nil {
  1465. log.Crit("Failed to write block into disk", "err", err)
  1466. }
  1467. return nil
  1468. }
  1469. // writeKnownBlock updates the head block flag with a known block
  1470. // and introduces chain reorg if necessary.
  1471. func (bc *BlockChain) writeKnownBlock(block *types.Block) error {
  1472. bc.wg.Add(1)
  1473. defer bc.wg.Done()
  1474. current := bc.CurrentBlock()
  1475. if block.ParentHash() != current.Hash() {
  1476. if err := bc.reorg(current, block); err != nil {
  1477. return err
  1478. }
  1479. }
  1480. bc.writeHeadBlock(block)
  1481. return nil
  1482. }
  1483. // WriteBlockWithState writes the block and all associated state to the database.
  1484. func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, emitHeadEvent bool) (status WriteStatus, err error) {
  1485. bc.chainmu.Lock()
  1486. defer bc.chainmu.Unlock()
  1487. return bc.writeBlockWithState(block, receipts, logs, state, emitHeadEvent)
  1488. }
  1489. // writeBlockWithState writes the block and all associated state to the database,
  1490. // but is expects the chain mutex to be held.
  1491. func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, emitHeadEvent bool) (status WriteStatus, err error) {
  1492. bc.wg.Add(1)
  1493. defer bc.wg.Done()
  1494. // Calculate the total difficulty of the block
  1495. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1496. if ptd == nil {
  1497. return NonStatTy, consensus.ErrUnknownAncestor
  1498. }
  1499. // Make sure no inconsistent state is leaked during insertion
  1500. currentBlock := bc.CurrentBlock()
  1501. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  1502. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  1503. // Irrelevant of the canonical status, write the block itself to the database.
  1504. //
  1505. // Note all the components of block(td, hash->number map, header, body, receipts)
  1506. // should be written atomically. BlockBatch is used for containing all components.
  1507. wg := sync.WaitGroup{}
  1508. wg.Add(1)
  1509. go func() {
  1510. blockBatch := bc.db.NewBatch()
  1511. rawdb.WriteTd(blockBatch, block.Hash(), block.NumberU64(), externTd)
  1512. rawdb.WriteBlock(blockBatch, block)
  1513. rawdb.WriteReceipts(blockBatch, block.Hash(), block.NumberU64(), receipts)
  1514. rawdb.WritePreimages(blockBatch, state.Preimages())
  1515. if err := blockBatch.Write(); err != nil {
  1516. log.Crit("Failed to write block into disk", "err", err)
  1517. }
  1518. wg.Done()
  1519. }()
  1520. // Commit all cached state changes into underlying memory database.
  1521. root, diffLayer, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
  1522. if err != nil {
  1523. return NonStatTy, err
  1524. }
  1525. // Ensure no empty block body
  1526. if diffLayer != nil && block.Header().TxHash != types.EmptyRootHash {
  1527. // Filling necessary field
  1528. diffLayer.Receipts = receipts
  1529. diffLayer.BlockHash = block.Hash()
  1530. diffLayer.Number = block.NumberU64()
  1531. bc.cacheDiffLayer(diffLayer)
  1532. }
  1533. triedb := bc.stateCache.TrieDB()
  1534. // If we're running an archive node, always flush
  1535. if bc.cacheConfig.TrieDirtyDisabled {
  1536. if err := triedb.Commit(root, false, nil); err != nil {
  1537. return NonStatTy, err
  1538. }
  1539. } else {
  1540. // Full but not archive node, do proper garbage collection
  1541. triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
  1542. bc.triegc.Push(root, -int64(block.NumberU64()))
  1543. if current := block.NumberU64(); current > bc.triesInMemory {
  1544. // If we exceeded our memory allowance, flush matured singleton nodes to disk
  1545. var (
  1546. nodes, imgs = triedb.Size()
  1547. limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
  1548. )
  1549. if nodes > limit || imgs > 4*1024*1024 {
  1550. triedb.Cap(limit - ethdb.IdealBatchSize)
  1551. }
  1552. // Find the next state trie we need to commit
  1553. chosen := current - bc.triesInMemory
  1554. // If we exceeded out time allowance, flush an entire trie to disk
  1555. if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
  1556. canWrite := true
  1557. if posa, ok := bc.engine.(consensus.PoSA); ok {
  1558. if !posa.EnoughDistance(bc, block.Header()) {
  1559. canWrite = false
  1560. }
  1561. }
  1562. if canWrite {
  1563. // If the header is missing (canonical chain behind), we're reorging a low
  1564. // diff sidechain. Suspend committing until this operation is completed.
  1565. header := bc.GetHeaderByNumber(chosen)
  1566. if header == nil {
  1567. log.Warn("Reorg in progress, trie commit postponed", "number", chosen)
  1568. } else {
  1569. // If we're exceeding limits but haven't reached a large enough memory gap,
  1570. // warn the user that the system is becoming unstable.
  1571. if chosen < lastWrite+bc.triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
  1572. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/float64(bc.triesInMemory))
  1573. }
  1574. // Flush an entire trie and restart the counters
  1575. triedb.Commit(header.Root, true, nil)
  1576. lastWrite = chosen
  1577. bc.gcproc = 0
  1578. }
  1579. }
  1580. }
  1581. // Garbage collect anything below our required write retention
  1582. for !bc.triegc.Empty() {
  1583. root, number := bc.triegc.Pop()
  1584. if uint64(-number) > chosen {
  1585. bc.triegc.Push(root, number)
  1586. break
  1587. }
  1588. go triedb.Dereference(root.(common.Hash))
  1589. }
  1590. }
  1591. }
  1592. wg.Wait()
  1593. // If the total difficulty is higher than our known, add it to the canonical chain
  1594. // Second clause in the if statement reduces the vulnerability to selfish mining.
  1595. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  1596. reorg := externTd.Cmp(localTd) > 0
  1597. currentBlock = bc.CurrentBlock()
  1598. if !reorg && externTd.Cmp(localTd) == 0 {
  1599. // Split same-difficulty blocks by number, then preferentially select
  1600. // the block generated by the local miner as the canonical block.
  1601. if block.NumberU64() < currentBlock.NumberU64() || block.Time() < currentBlock.Time() {
  1602. reorg = true
  1603. } else if p, ok := bc.engine.(consensus.PoSA); ok && p.IsLocalBlock(currentBlock.Header()) {
  1604. reorg = true
  1605. } else if block.NumberU64() == currentBlock.NumberU64() {
  1606. var currentPreserve, blockPreserve bool
  1607. if bc.shouldPreserve != nil {
  1608. currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  1609. }
  1610. reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  1611. }
  1612. }
  1613. if reorg {
  1614. // Reorganise the chain if the parent is not the head block
  1615. if block.ParentHash() != currentBlock.Hash() {
  1616. if err := bc.reorg(currentBlock, block); err != nil {
  1617. return NonStatTy, err
  1618. }
  1619. }
  1620. status = CanonStatTy
  1621. } else {
  1622. status = SideStatTy
  1623. }
  1624. // Set new head.
  1625. if status == CanonStatTy {
  1626. bc.writeHeadBlock(block)
  1627. }
  1628. bc.futureBlocks.Remove(block.Hash())
  1629. if status == CanonStatTy {
  1630. bc.chainFeed.Send(ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
  1631. if len(logs) > 0 {
  1632. bc.logsFeed.Send(logs)
  1633. }
  1634. // In theory we should fire a ChainHeadEvent when we inject
  1635. // a canonical block, but sometimes we can insert a batch of
  1636. // canonicial blocks. Avoid firing too much ChainHeadEvents,
  1637. // we will fire an accumulated ChainHeadEvent and disable fire
  1638. // event here.
  1639. if emitHeadEvent {
  1640. bc.chainHeadFeed.Send(ChainHeadEvent{Block: block})
  1641. }
  1642. } else {
  1643. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1644. }
  1645. return status, nil
  1646. }
  1647. // addFutureBlock checks if the block is within the max allowed window to get
  1648. // accepted for future processing, and returns an error if the block is too far
  1649. // ahead and was not added.
  1650. func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  1651. max := uint64(time.Now().Unix() + maxTimeFutureBlocks)
  1652. if block.Time() > max {
  1653. return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  1654. }
  1655. bc.futureBlocks.Add(block.Hash(), block)
  1656. return nil
  1657. }
  1658. // InsertChain attempts to insert the given batch of blocks in to the canonical
  1659. // chain or, otherwise, create a fork. If an error is returned it will return
  1660. // the index number of the failing block as well an error describing what went
  1661. // wrong.
  1662. //
  1663. // After insertion is done, all accumulated events will be fired.
  1664. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  1665. // Sanity check that we have something meaningful to import
  1666. if len(chain) == 0 {
  1667. return 0, nil
  1668. }
  1669. bc.blockProcFeed.Send(true)
  1670. defer bc.blockProcFeed.Send(false)
  1671. // Remove already known canon-blocks
  1672. var (
  1673. block, prev *types.Block
  1674. )
  1675. // Do a sanity check that the provided chain is actually ordered and linked
  1676. for i := 1; i < len(chain); i++ {
  1677. block = chain[i]
  1678. prev = chain[i-1]
  1679. if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() {
  1680. // Chain broke ancestry, log a message (programming error) and skip insertion
  1681. log.Error("Non contiguous block insert", "number", block.Number(), "hash", block.Hash(),
  1682. "parent", block.ParentHash(), "prevnumber", prev.Number(), "prevhash", prev.Hash())
  1683. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x..], item %d is #%d [%x..] (parent [%x..])", i-1, prev.NumberU64(),
  1684. prev.Hash().Bytes()[:4], i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4])
  1685. }
  1686. }
  1687. // Pre-checks passed, start the full block imports
  1688. bc.wg.Add(1)
  1689. bc.chainmu.Lock()
  1690. n, err := bc.insertChain(chain, true)
  1691. bc.chainmu.Unlock()
  1692. bc.wg.Done()
  1693. return n, err
  1694. }
  1695. // InsertChainWithoutSealVerification works exactly the same
  1696. // except for seal verification, seal verification is omitted
  1697. func (bc *BlockChain) InsertChainWithoutSealVerification(block *types.Block) (int, error) {
  1698. bc.blockProcFeed.Send(true)
  1699. defer bc.blockProcFeed.Send(false)
  1700. // Pre-checks passed, start the full block imports
  1701. bc.wg.Add(1)
  1702. bc.chainmu.Lock()
  1703. n, err := bc.insertChain(types.Blocks([]*types.Block{block}), false)
  1704. bc.chainmu.Unlock()
  1705. bc.wg.Done()
  1706. return n, err
  1707. }
  1708. // insertChain is the internal implementation of InsertChain, which assumes that
  1709. // 1) chains are contiguous, and 2) The chain mutex is held.
  1710. //
  1711. // This method is split out so that import batches that require re-injecting
  1712. // historical blocks can do so without releasing the lock, which could lead to
  1713. // racey behaviour. If a sidechain import is in progress, and the historic state
  1714. // is imported, but then new canon-head is added before the actual sidechain
  1715. // completes, then the historic state could be pruned again
  1716. func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, error) {
  1717. // If the chain is terminating, don't even bother starting up
  1718. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1719. return 0, nil
  1720. }
  1721. // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  1722. signer := types.MakeSigner(bc.chainConfig, chain[0].Number())
  1723. go senderCacher.recoverFromBlocks(signer, chain)
  1724. var (
  1725. stats = insertStats{startTime: mclock.Now()}
  1726. lastCanon *types.Block
  1727. )
  1728. // Fire a single chain head event if we've progressed the chain
  1729. defer func() {
  1730. if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1731. bc.chainHeadFeed.Send(ChainHeadEvent{lastCanon})
  1732. }
  1733. }()
  1734. // Start the parallel header verifier
  1735. headers := make([]*types.Header, len(chain))
  1736. seals := make([]bool, len(chain))
  1737. for i, block := range chain {
  1738. headers[i] = block.Header()
  1739. seals[i] = verifySeals
  1740. }
  1741. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1742. defer close(abort)
  1743. // Peek the error for the first block to decide the directing import logic
  1744. it := newInsertIterator(chain, results, bc.validator)
  1745. block, err := it.next()
  1746. // Left-trim all the known blocks
  1747. if err == ErrKnownBlock {
  1748. // First block (and state) is known
  1749. // 1. We did a roll-back, and should now do a re-import
  1750. // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1751. // from the canonical chain, which has not been verified.
  1752. // Skip all known blocks that are behind us
  1753. var (
  1754. current = bc.CurrentBlock()
  1755. localTd = bc.GetTd(current.Hash(), current.NumberU64())
  1756. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1) // The first block can't be nil
  1757. )
  1758. for block != nil && err == ErrKnownBlock {
  1759. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1760. if localTd.Cmp(externTd) < 0 {
  1761. break
  1762. }
  1763. log.Debug("Ignoring already known block", "number", block.Number(), "hash", block.Hash())
  1764. stats.ignored++
  1765. block, err = it.next()
  1766. }
  1767. // The remaining blocks are still known blocks, the only scenario here is:
  1768. // During the fast sync, the pivot point is already submitted but rollback
  1769. // happens. Then node resets the head full block to a lower height via `rollback`
  1770. // and leaves a few known blocks in the database.
  1771. //
  1772. // When node runs a fast sync again, it can re-import a batch of known blocks via
  1773. // `insertChain` while a part of them have higher total difficulty than current
  1774. // head full block(new pivot point).
  1775. for block != nil && err == ErrKnownBlock {
  1776. log.Debug("Writing previously known block", "number", block.Number(), "hash", block.Hash())
  1777. if err := bc.writeKnownBlock(block); err != nil {
  1778. return it.index, err
  1779. }
  1780. lastCanon = block
  1781. block, err = it.next()
  1782. }
  1783. // Falls through to the block import
  1784. }
  1785. switch {
  1786. // First block is pruned, insert as sidechain and reorg only if TD grows enough
  1787. case errors.Is(err, consensus.ErrPrunedAncestor):
  1788. log.Debug("Pruned ancestor, inserting as sidechain", "number", block.Number(), "hash", block.Hash())
  1789. return bc.insertSideChain(block, it)
  1790. // First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1791. case errors.Is(err, consensus.ErrFutureBlock) || (errors.Is(err, consensus.ErrUnknownAncestor) && bc.futureBlocks.Contains(it.first().ParentHash())):
  1792. for block != nil && (it.index == 0 || errors.Is(err, consensus.ErrUnknownAncestor)) {
  1793. log.Debug("Future block, postponing import", "number", block.Number(), "hash", block.Hash())
  1794. if err := bc.addFutureBlock(block); err != nil {
  1795. return it.index, err
  1796. }
  1797. block, err = it.next()
  1798. }
  1799. stats.queued += it.processed()
  1800. stats.ignored += it.remaining()
  1801. // If there are any still remaining, mark as ignored
  1802. return it.index, err
  1803. // Some other error occurred, abort
  1804. case err != nil:
  1805. bc.futureBlocks.Remove(block.Hash())
  1806. stats.ignored += len(it.chain)
  1807. bc.reportBlock(block, nil, err)
  1808. return it.index, err
  1809. }
  1810. // No validation errors for the first block (or chain prefix skipped)
  1811. var activeState *state.StateDB
  1812. defer func() {
  1813. // The chain importer is starting and stopping trie prefetchers. If a bad
  1814. // block or other error is hit however, an early return may not properly
  1815. // terminate the background threads. This defer ensures that we clean up
  1816. // and dangling prefetcher, without defering each and holding on live refs.
  1817. if activeState != nil {
  1818. activeState.StopPrefetcher()
  1819. }
  1820. }()
  1821. for ; block != nil && err == nil || err == ErrKnownBlock; block, err = it.next() {
  1822. // If the chain is terminating, stop processing blocks
  1823. if bc.insertStopped() {
  1824. log.Debug("Abort during block processing")
  1825. break
  1826. }
  1827. // If the header is a banned one, straight out abort
  1828. if BadHashes[block.Hash()] {
  1829. bc.reportBlock(block, nil, ErrBlacklistedHash)
  1830. return it.index, ErrBlacklistedHash
  1831. }
  1832. // If the block is known (in the middle of the chain), it's a special case for
  1833. // Clique blocks where they can share state among each other, so importing an
  1834. // older block might complete the state of the subsequent one. In this case,
  1835. // just skip the block (we already validated it once fully (and crashed), since
  1836. // its header and body was already in the database).
  1837. if err == ErrKnownBlock {
  1838. logger := log.Debug
  1839. if bc.chainConfig.Clique == nil {
  1840. logger = log.Warn
  1841. }
  1842. logger("Inserted known block", "number", block.Number(), "hash", block.Hash(),
  1843. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1844. "root", block.Root())
  1845. // Special case. Commit the empty receipt slice if we meet the known
  1846. // block in the middle. It can only happen in the clique chain. Whenever
  1847. // we insert blocks via `insertSideChain`, we only commit `td`, `header`
  1848. // and `body` if it's non-existent. Since we don't have receipts without
  1849. // reexecution, so nothing to commit. But if the sidechain will be adpoted
  1850. // as the canonical chain eventually, it needs to be reexecuted for missing
  1851. // state, but if it's this special case here(skip reexecution) we will lose
  1852. // the empty receipt entry.
  1853. if len(block.Transactions()) == 0 {
  1854. rawdb.WriteReceipts(bc.db, block.Hash(), block.NumberU64(), nil)
  1855. } else {
  1856. log.Error("Please file an issue, skip known block execution without receipt",
  1857. "hash", block.Hash(), "number", block.NumberU64())
  1858. }
  1859. if err := bc.writeKnownBlock(block); err != nil {
  1860. return it.index, err
  1861. }
  1862. stats.processed++
  1863. // We can assume that logs are empty here, since the only way for consecutive
  1864. // Clique blocks to have the same state is if there are no transactions.
  1865. lastCanon = block
  1866. continue
  1867. }
  1868. // Retrieve the parent block and it's state to execute on top
  1869. start := time.Now()
  1870. parent := it.previous()
  1871. if parent == nil {
  1872. parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
  1873. }
  1874. statedb, err := state.New(parent.Root, bc.stateCache, bc.snaps)
  1875. if err != nil {
  1876. return it.index, err
  1877. }
  1878. bc.updateHighestVerifiedHeader(block.Header())
  1879. // Enable prefetching to pull in trie node paths while processing transactions
  1880. statedb.StartPrefetcher("chain")
  1881. var followupInterrupt uint32
  1882. // For diff sync, it may fallback to full sync, so we still do prefetch
  1883. if len(block.Transactions()) >= prefetchTxNumber {
  1884. throwaway := statedb.Copy()
  1885. go func(start time.Time, followup *types.Block, throwaway *state.StateDB, interrupt *uint32) {
  1886. bc.prefetcher.Prefetch(followup, throwaway, bc.vmConfig, &followupInterrupt)
  1887. }(time.Now(), block, throwaway, &followupInterrupt)
  1888. }
  1889. //Process block using the parent state as reference point
  1890. substart := time.Now()
  1891. statedb, receipts, logs, usedGas, err := bc.processor.Process(block, statedb, bc.vmConfig)
  1892. atomic.StoreUint32(&followupInterrupt, 1)
  1893. activeState = statedb
  1894. if err != nil {
  1895. bc.reportBlock(block, receipts, err)
  1896. return it.index, err
  1897. }
  1898. // Update the metrics touched during block processing
  1899. accountReadTimer.Update(statedb.AccountReads) // Account reads are complete, we can mark them
  1900. storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete, we can mark them
  1901. accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete, we can mark them
  1902. storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them
  1903. snapshotAccountReadTimer.Update(statedb.SnapshotAccountReads) // Account reads are complete, we can mark them
  1904. snapshotStorageReadTimer.Update(statedb.SnapshotStorageReads) // Storage reads are complete, we can mark them
  1905. blockExecutionTimer.Update(time.Since(substart))
  1906. // Validate the state using the default validator
  1907. substart = time.Now()
  1908. if !statedb.IsLightProcessed() {
  1909. if err := bc.validator.ValidateState(block, statedb, receipts, usedGas); err != nil {
  1910. log.Error("validate state failed", "error", err)
  1911. bc.reportBlock(block, receipts, err)
  1912. return it.index, err
  1913. }
  1914. }
  1915. bc.cacheReceipts(block.Hash(), receipts)
  1916. bc.cacheBlock(block.Hash(), block)
  1917. proctime := time.Since(start)
  1918. // Update the metrics touched during block validation
  1919. accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete, we can mark them
  1920. storageHashTimer.Update(statedb.StorageHashes) // Storage hashes are complete, we can mark them
  1921. blockValidationTimer.Update(time.Since(substart))
  1922. // Write the block to the chain and get the status.
  1923. substart = time.Now()
  1924. status, err := bc.writeBlockWithState(block, receipts, logs, statedb, false)
  1925. if err != nil {
  1926. return it.index, err
  1927. }
  1928. // Update the metrics touched during block commit
  1929. accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them
  1930. storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them
  1931. snapshotCommitTimer.Update(statedb.SnapshotCommits) // Snapshot commits are complete, we can mark them
  1932. blockWriteTimer.Update(time.Since(substart))
  1933. blockInsertTimer.UpdateSince(start)
  1934. switch status {
  1935. case CanonStatTy:
  1936. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1937. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1938. "elapsed", common.PrettyDuration(time.Since(start)),
  1939. "root", block.Root())
  1940. lastCanon = block
  1941. // Only count canonical blocks for GC processing time
  1942. bc.gcproc += proctime
  1943. case SideStatTy:
  1944. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1945. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1946. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1947. "root", block.Root())
  1948. default:
  1949. // This in theory is impossible, but lets be nice to our future selves and leave
  1950. // a log, instead of trying to track down blocks imports that don't emit logs.
  1951. log.Warn("Inserted block with unknown status", "number", block.Number(), "hash", block.Hash(),
  1952. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1953. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1954. "root", block.Root())
  1955. }
  1956. stats.processed++
  1957. stats.usedGas += usedGas
  1958. dirty, _ := bc.stateCache.TrieDB().Size()
  1959. stats.report(chain, it.index, dirty)
  1960. }
  1961. // Any blocks remaining here? The only ones we care about are the future ones
  1962. if block != nil && errors.Is(err, consensus.ErrFutureBlock) {
  1963. if err := bc.addFutureBlock(block); err != nil {
  1964. return it.index, err
  1965. }
  1966. block, err = it.next()
  1967. for ; block != nil && errors.Is(err, consensus.ErrUnknownAncestor); block, err = it.next() {
  1968. if err := bc.addFutureBlock(block); err != nil {
  1969. return it.index, err
  1970. }
  1971. stats.queued++
  1972. }
  1973. }
  1974. stats.ignored += it.remaining()
  1975. return it.index, err
  1976. }
  1977. func (bc *BlockChain) updateHighestVerifiedHeader(header *types.Header) {
  1978. if header == nil || header.Number == nil {
  1979. return
  1980. }
  1981. currentHeader := bc.highestVerifiedHeader.Load().(*types.Header)
  1982. if currentHeader == nil {
  1983. bc.highestVerifiedHeader.Store(types.CopyHeader(header))
  1984. return
  1985. }
  1986. newParentTD := bc.GetTdByHash(header.ParentHash)
  1987. if newParentTD == nil {
  1988. newParentTD = big.NewInt(0)
  1989. }
  1990. oldParentTD := bc.GetTdByHash(currentHeader.ParentHash)
  1991. if oldParentTD == nil {
  1992. oldParentTD = big.NewInt(0)
  1993. }
  1994. newTD := big.NewInt(0).Add(newParentTD, header.Difficulty)
  1995. oldTD := big.NewInt(0).Add(oldParentTD, currentHeader.Difficulty)
  1996. if newTD.Cmp(oldTD) > 0 {
  1997. bc.highestVerifiedHeader.Store(types.CopyHeader(header))
  1998. return
  1999. }
  2000. }
  2001. func (bc *BlockChain) GetHighestVerifiedHeader() *types.Header {
  2002. return bc.highestVerifiedHeader.Load().(*types.Header)
  2003. }
  2004. // insertSideChain is called when an import batch hits upon a pruned ancestor
  2005. // error, which happens when a sidechain with a sufficiently old fork-block is
  2006. // found.
  2007. //
  2008. // The method writes all (header-and-body-valid) blocks to disk, then tries to
  2009. // switch over to the new chain if the TD exceeded the current chain.
  2010. func (bc *BlockChain) insertSideChain(block *types.Block, it *insertIterator) (int, error) {
  2011. var (
  2012. externTd *big.Int
  2013. current = bc.CurrentBlock()
  2014. )
  2015. // The first sidechain block error is already verified to be ErrPrunedAncestor.
  2016. // Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  2017. // ones. Any other errors means that the block is invalid, and should not be written
  2018. // to disk.
  2019. err := consensus.ErrPrunedAncestor
  2020. for ; block != nil && errors.Is(err, consensus.ErrPrunedAncestor); block, err = it.next() {
  2021. // Check the canonical state root for that number
  2022. if number := block.NumberU64(); current.NumberU64() >= number {
  2023. canonical := bc.GetBlockByNumber(number)
  2024. if canonical != nil && canonical.Hash() == block.Hash() {
  2025. // Not a sidechain block, this is a re-import of a canon block which has it's state pruned
  2026. // Collect the TD of the block. Since we know it's a canon one,
  2027. // we can get it directly, and not (like further below) use
  2028. // the parent and then add the block on top
  2029. externTd = bc.GetTd(block.Hash(), block.NumberU64())
  2030. continue
  2031. }
  2032. if canonical != nil && canonical.Root() == block.Root() {
  2033. // This is most likely a shadow-state attack. When a fork is imported into the
  2034. // database, and it eventually reaches a block height which is not pruned, we
  2035. // just found that the state already exist! This means that the sidechain block
  2036. // refers to a state which already exists in our canon chain.
  2037. //
  2038. // If left unchecked, we would now proceed importing the blocks, without actually
  2039. // having verified the state of the previous blocks.
  2040. log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  2041. // If someone legitimately side-mines blocks, they would still be imported as usual. However,
  2042. // we cannot risk writing unverified blocks to disk when they obviously target the pruning
  2043. // mechanism.
  2044. return it.index, errors.New("sidechain ghost-state attack")
  2045. }
  2046. }
  2047. if externTd == nil {
  2048. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  2049. }
  2050. externTd = new(big.Int).Add(externTd, block.Difficulty())
  2051. if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  2052. start := time.Now()
  2053. if err := bc.writeBlockWithoutState(block, externTd); err != nil {
  2054. return it.index, err
  2055. }
  2056. log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(),
  2057. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  2058. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  2059. "root", block.Root())
  2060. }
  2061. }
  2062. // At this point, we've written all sidechain blocks to database. Loop ended
  2063. // either on some other error or all were processed. If there was some other
  2064. // error, we can ignore the rest of those blocks.
  2065. //
  2066. // If the externTd was larger than our local TD, we now need to reimport the previous
  2067. // blocks to regenerate the required state
  2068. localTd := bc.GetTd(current.Hash(), current.NumberU64())
  2069. if localTd.Cmp(externTd) > 0 {
  2070. log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().Number, "sidetd", externTd, "localtd", localTd)
  2071. return it.index, err
  2072. }
  2073. // Gather all the sidechain hashes (full blocks may be memory heavy)
  2074. var (
  2075. hashes []common.Hash
  2076. numbers []uint64
  2077. )
  2078. parent := it.previous()
  2079. for parent != nil && !bc.HasState(parent.Root) {
  2080. hashes = append(hashes, parent.Hash())
  2081. numbers = append(numbers, parent.Number.Uint64())
  2082. parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  2083. }
  2084. if parent == nil {
  2085. return it.index, errors.New("missing parent")
  2086. }
  2087. // Import all the pruned blocks to make the state available
  2088. var (
  2089. blocks []*types.Block
  2090. memory common.StorageSize
  2091. )
  2092. for i := len(hashes) - 1; i >= 0; i-- {
  2093. // Append the next block to our batch
  2094. block := bc.GetBlock(hashes[i], numbers[i])
  2095. blocks = append(blocks, block)
  2096. memory += block.Size()
  2097. // If memory use grew too large, import and continue. Sadly we need to discard
  2098. // all raised events and logs from notifications since we're too heavy on the
  2099. // memory here.
  2100. if len(blocks) >= 2048 || memory > 64*1024*1024 {
  2101. log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  2102. if _, err := bc.insertChain(blocks, false); err != nil {
  2103. return 0, err
  2104. }
  2105. blocks, memory = blocks[:0], 0
  2106. // If the chain is terminating, stop processing blocks
  2107. if bc.insertStopped() {
  2108. log.Debug("Abort during blocks processing")
  2109. return 0, nil
  2110. }
  2111. }
  2112. }
  2113. if len(blocks) > 0 {
  2114. log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  2115. return bc.insertChain(blocks, false)
  2116. }
  2117. return 0, nil
  2118. }
  2119. // reorg takes two blocks, an old chain and a new chain and will reconstruct the
  2120. // blocks and inserts them to be part of the new canonical chain and accumulates
  2121. // potential missing transactions and post an event about them.
  2122. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  2123. var (
  2124. newChain types.Blocks
  2125. oldChain types.Blocks
  2126. commonBlock *types.Block
  2127. deletedTxs types.Transactions
  2128. addedTxs types.Transactions
  2129. deletedLogs [][]*types.Log
  2130. rebirthLogs [][]*types.Log
  2131. // collectLogs collects the logs that were generated or removed during
  2132. // the processing of the block that corresponds with the given hash.
  2133. // These logs are later announced as deleted or reborn
  2134. collectLogs = func(hash common.Hash, removed bool) {
  2135. number := bc.hc.GetBlockNumber(hash)
  2136. if number == nil {
  2137. return
  2138. }
  2139. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  2140. var logs []*types.Log
  2141. for _, receipt := range receipts {
  2142. for _, log := range receipt.Logs {
  2143. l := *log
  2144. if removed {
  2145. l.Removed = true
  2146. }
  2147. logs = append(logs, &l)
  2148. }
  2149. }
  2150. if len(logs) > 0 {
  2151. if removed {
  2152. deletedLogs = append(deletedLogs, logs)
  2153. } else {
  2154. rebirthLogs = append(rebirthLogs, logs)
  2155. }
  2156. }
  2157. }
  2158. // mergeLogs returns a merged log slice with specified sort order.
  2159. mergeLogs = func(logs [][]*types.Log, reverse bool) []*types.Log {
  2160. var ret []*types.Log
  2161. if reverse {
  2162. for i := len(logs) - 1; i >= 0; i-- {
  2163. ret = append(ret, logs[i]...)
  2164. }
  2165. } else {
  2166. for i := 0; i < len(logs); i++ {
  2167. ret = append(ret, logs[i]...)
  2168. }
  2169. }
  2170. return ret
  2171. }
  2172. )
  2173. // Reduce the longer chain to the same number as the shorter one
  2174. if oldBlock.NumberU64() > newBlock.NumberU64() {
  2175. // Old chain is longer, gather all transactions and logs as deleted ones
  2176. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  2177. oldChain = append(oldChain, oldBlock)
  2178. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  2179. collectLogs(oldBlock.Hash(), true)
  2180. }
  2181. } else {
  2182. // New chain is longer, stash all blocks away for subsequent insertion
  2183. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  2184. newChain = append(newChain, newBlock)
  2185. }
  2186. }
  2187. if oldBlock == nil {
  2188. return fmt.Errorf("invalid old chain")
  2189. }
  2190. if newBlock == nil {
  2191. return fmt.Errorf("invalid new chain")
  2192. }
  2193. // Both sides of the reorg are at the same number, reduce both until the common
  2194. // ancestor is found
  2195. for {
  2196. // If the common ancestor was found, bail out
  2197. if oldBlock.Hash() == newBlock.Hash() {
  2198. commonBlock = oldBlock
  2199. break
  2200. }
  2201. // Remove an old block as well as stash away a new block
  2202. oldChain = append(oldChain, oldBlock)
  2203. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  2204. collectLogs(oldBlock.Hash(), true)
  2205. newChain = append(newChain, newBlock)
  2206. // Step back with both chains
  2207. oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1)
  2208. if oldBlock == nil {
  2209. return fmt.Errorf("invalid old chain")
  2210. }
  2211. newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  2212. if newBlock == nil {
  2213. return fmt.Errorf("invalid new chain")
  2214. }
  2215. }
  2216. // Ensure the user sees large reorgs
  2217. if len(oldChain) > 0 && len(newChain) > 0 {
  2218. logFn := log.Info
  2219. msg := "Chain reorg detected"
  2220. if len(oldChain) > 63 {
  2221. msg = "Large chain reorg detected"
  2222. logFn = log.Warn
  2223. }
  2224. logFn(msg, "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  2225. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  2226. blockReorgAddMeter.Mark(int64(len(newChain)))
  2227. blockReorgDropMeter.Mark(int64(len(oldChain)))
  2228. blockReorgMeter.Mark(1)
  2229. } else {
  2230. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  2231. }
  2232. // Insert the new chain(except the head block(reverse order)),
  2233. // taking care of the proper incremental order.
  2234. for i := len(newChain) - 1; i >= 1; i-- {
  2235. // Insert the block in the canonical way, re-writing history
  2236. bc.writeHeadBlock(newChain[i])
  2237. // Collect reborn logs due to chain reorg
  2238. collectLogs(newChain[i].Hash(), false)
  2239. // Collect the new added transactions.
  2240. addedTxs = append(addedTxs, newChain[i].Transactions()...)
  2241. }
  2242. // Delete useless indexes right now which includes the non-canonical
  2243. // transaction indexes, canonical chain indexes which above the head.
  2244. indexesBatch := bc.db.NewBatch()
  2245. for _, tx := range types.TxDifference(deletedTxs, addedTxs) {
  2246. rawdb.DeleteTxLookupEntry(indexesBatch, tx.Hash())
  2247. }
  2248. // Delete any canonical number assignments above the new head
  2249. number := bc.CurrentBlock().NumberU64()
  2250. for i := number + 1; ; i++ {
  2251. hash := rawdb.ReadCanonicalHash(bc.db, i)
  2252. if hash == (common.Hash{}) {
  2253. break
  2254. }
  2255. rawdb.DeleteCanonicalHash(indexesBatch, i)
  2256. }
  2257. if err := indexesBatch.Write(); err != nil {
  2258. log.Crit("Failed to delete useless indexes", "err", err)
  2259. }
  2260. // If any logs need to be fired, do it now. In theory we could avoid creating
  2261. // this goroutine if there are no events to fire, but realistcally that only
  2262. // ever happens if we're reorging empty blocks, which will only happen on idle
  2263. // networks where performance is not an issue either way.
  2264. if len(deletedLogs) > 0 {
  2265. bc.rmLogsFeed.Send(RemovedLogsEvent{mergeLogs(deletedLogs, true)})
  2266. }
  2267. if len(rebirthLogs) > 0 {
  2268. bc.logsFeed.Send(mergeLogs(rebirthLogs, false))
  2269. }
  2270. if len(oldChain) > 0 {
  2271. for i := len(oldChain) - 1; i >= 0; i-- {
  2272. bc.chainSideFeed.Send(ChainSideEvent{Block: oldChain[i]})
  2273. }
  2274. }
  2275. return nil
  2276. }
  2277. func (bc *BlockChain) update() {
  2278. futureTimer := time.NewTicker(5 * time.Second)
  2279. defer futureTimer.Stop()
  2280. for {
  2281. select {
  2282. case <-futureTimer.C:
  2283. bc.procFutureBlocks()
  2284. case <-bc.quit:
  2285. return
  2286. }
  2287. }
  2288. }
  2289. func (bc *BlockChain) trustedDiffLayerLoop() {
  2290. recheck := time.NewTicker(diffLayerFreezerRecheckInterval)
  2291. bc.wg.Add(1)
  2292. defer func() {
  2293. bc.wg.Done()
  2294. recheck.Stop()
  2295. }()
  2296. for {
  2297. select {
  2298. case diff := <-bc.diffQueueBuffer:
  2299. bc.diffQueue.Push(diff, -(int64(diff.Number)))
  2300. case <-bc.quit:
  2301. // Persist all diffLayers when shutdown, it will introduce redundant storage, but it is acceptable.
  2302. // If the client been ungracefully shutdown, it will missing all cached diff layers, it is acceptable as well.
  2303. var batch ethdb.Batch
  2304. for !bc.diffQueue.Empty() {
  2305. diff, _ := bc.diffQueue.Pop()
  2306. diffLayer := diff.(*types.DiffLayer)
  2307. if batch == nil {
  2308. batch = bc.db.DiffStore().NewBatch()
  2309. }
  2310. rawdb.WriteDiffLayer(batch, diffLayer.BlockHash, diffLayer)
  2311. if batch.ValueSize() > ethdb.IdealBatchSize {
  2312. if err := batch.Write(); err != nil {
  2313. log.Error("Failed to write diff layer", "err", err)
  2314. return
  2315. }
  2316. batch.Reset()
  2317. }
  2318. }
  2319. if batch != nil {
  2320. // flush data
  2321. if err := batch.Write(); err != nil {
  2322. log.Error("Failed to write diff layer", "err", err)
  2323. return
  2324. }
  2325. batch.Reset()
  2326. }
  2327. return
  2328. case <-recheck.C:
  2329. currentHeight := bc.CurrentBlock().NumberU64()
  2330. var batch ethdb.Batch
  2331. for !bc.diffQueue.Empty() {
  2332. diff, prio := bc.diffQueue.Pop()
  2333. diffLayer := diff.(*types.DiffLayer)
  2334. // if the block not old enough
  2335. if int64(currentHeight)+prio < int64(bc.triesInMemory) {
  2336. bc.diffQueue.Push(diffLayer, prio)
  2337. break
  2338. }
  2339. canonicalHash := bc.GetCanonicalHash(uint64(-prio))
  2340. // on the canonical chain
  2341. if canonicalHash == diffLayer.BlockHash {
  2342. if batch == nil {
  2343. batch = bc.db.DiffStore().NewBatch()
  2344. }
  2345. rawdb.WriteDiffLayer(batch, diffLayer.BlockHash, diffLayer)
  2346. staleHash := bc.GetCanonicalHash(uint64(-prio) - bc.diffLayerFreezerBlockLimit)
  2347. rawdb.DeleteDiffLayer(batch, staleHash)
  2348. }
  2349. if batch != nil && batch.ValueSize() > ethdb.IdealBatchSize {
  2350. if err := batch.Write(); err != nil {
  2351. panic(fmt.Sprintf("Failed to write diff layer, error %v", err))
  2352. }
  2353. batch.Reset()
  2354. }
  2355. }
  2356. if batch != nil {
  2357. if err := batch.Write(); err != nil {
  2358. panic(fmt.Sprintf("Failed to write diff layer, error %v", err))
  2359. }
  2360. batch.Reset()
  2361. }
  2362. }
  2363. }
  2364. }
  2365. func (bc *BlockChain) GetUnTrustedDiffLayer(blockHash common.Hash, pid string) *types.DiffLayer {
  2366. bc.diffMux.RLock()
  2367. defer bc.diffMux.RUnlock()
  2368. if diffs, exist := bc.blockHashToDiffLayers[blockHash]; exist && len(diffs) != 0 {
  2369. if len(diffs) == 1 {
  2370. // return the only one diff layer
  2371. for _, diff := range diffs {
  2372. return diff
  2373. }
  2374. }
  2375. // pick the one from exact same peer if we know where the block comes from
  2376. if pid != "" {
  2377. if diffHashes, exist := bc.diffPeersToDiffHashes[pid]; exist {
  2378. for diff := range diffs {
  2379. if _, overlap := diffHashes[diff]; overlap {
  2380. return bc.blockHashToDiffLayers[blockHash][diff]
  2381. }
  2382. }
  2383. }
  2384. }
  2385. // Do not find overlap, do random pick
  2386. for _, diff := range diffs {
  2387. return diff
  2388. }
  2389. }
  2390. return nil
  2391. }
  2392. func (bc *BlockChain) removeDiffLayers(diffHash common.Hash) {
  2393. bc.diffMux.Lock()
  2394. defer bc.diffMux.Unlock()
  2395. // Untrusted peers
  2396. pids := bc.diffHashToPeers[diffHash]
  2397. invalidDiffHashes := make(map[common.Hash]struct{})
  2398. for pid := range pids {
  2399. invaliDiffHashesPeer := bc.diffPeersToDiffHashes[pid]
  2400. for invaliDiffHash := range invaliDiffHashesPeer {
  2401. invalidDiffHashes[invaliDiffHash] = struct{}{}
  2402. }
  2403. delete(bc.diffPeersToDiffHashes, pid)
  2404. }
  2405. for invalidDiffHash := range invalidDiffHashes {
  2406. delete(bc.diffHashToPeers, invalidDiffHash)
  2407. affectedBlockHash := bc.diffHashToBlockHash[invalidDiffHash]
  2408. if diffs, exist := bc.blockHashToDiffLayers[affectedBlockHash]; exist {
  2409. delete(diffs, invalidDiffHash)
  2410. if len(diffs) == 0 {
  2411. delete(bc.blockHashToDiffLayers, affectedBlockHash)
  2412. }
  2413. }
  2414. delete(bc.diffHashToBlockHash, invalidDiffHash)
  2415. }
  2416. }
  2417. func (bc *BlockChain) untrustedDiffLayerPruneLoop() {
  2418. recheck := time.NewTicker(diffLayerPruneRecheckInterval)
  2419. bc.wg.Add(1)
  2420. defer func() {
  2421. bc.wg.Done()
  2422. recheck.Stop()
  2423. }()
  2424. for {
  2425. select {
  2426. case <-bc.quit:
  2427. return
  2428. case <-recheck.C:
  2429. bc.pruneDiffLayer()
  2430. }
  2431. }
  2432. }
  2433. func (bc *BlockChain) pruneDiffLayer() {
  2434. currentHeight := bc.CurrentBlock().NumberU64()
  2435. bc.diffMux.Lock()
  2436. defer bc.diffMux.Unlock()
  2437. sortNumbers := make([]uint64, 0, len(bc.diffNumToBlockHashes))
  2438. for number := range bc.diffNumToBlockHashes {
  2439. sortNumbers = append(sortNumbers, number)
  2440. }
  2441. sort.Slice(sortNumbers, func(i, j int) bool {
  2442. return sortNumbers[i] <= sortNumbers[j]
  2443. })
  2444. staleBlockHashes := make(map[common.Hash]struct{})
  2445. for _, number := range sortNumbers {
  2446. if number >= currentHeight-maxDiffForkDist {
  2447. break
  2448. }
  2449. affectedHashes := bc.diffNumToBlockHashes[number]
  2450. if affectedHashes != nil {
  2451. for affectedHash := range affectedHashes {
  2452. staleBlockHashes[affectedHash] = struct{}{}
  2453. }
  2454. delete(bc.diffNumToBlockHashes, number)
  2455. }
  2456. }
  2457. staleDiffHashes := make(map[common.Hash]struct{})
  2458. for blockHash := range staleBlockHashes {
  2459. if diffHashes, exist := bc.blockHashToDiffLayers[blockHash]; exist {
  2460. for diffHash := range diffHashes {
  2461. staleDiffHashes[diffHash] = struct{}{}
  2462. delete(bc.diffHashToBlockHash, diffHash)
  2463. delete(bc.diffHashToPeers, diffHash)
  2464. }
  2465. }
  2466. delete(bc.blockHashToDiffLayers, blockHash)
  2467. }
  2468. for diffHash := range staleDiffHashes {
  2469. for p, diffHashes := range bc.diffPeersToDiffHashes {
  2470. delete(diffHashes, diffHash)
  2471. if len(diffHashes) == 0 {
  2472. delete(bc.diffPeersToDiffHashes, p)
  2473. }
  2474. }
  2475. }
  2476. }
  2477. // Process received diff layers
  2478. func (bc *BlockChain) HandleDiffLayer(diffLayer *types.DiffLayer, pid string, fulfilled bool) error {
  2479. // Basic check
  2480. currentHeight := bc.CurrentBlock().NumberU64()
  2481. if diffLayer.Number > currentHeight && diffLayer.Number-currentHeight > maxDiffQueueDist {
  2482. log.Debug("diff layers too new from current", "pid", pid)
  2483. return nil
  2484. }
  2485. if diffLayer.Number < currentHeight && currentHeight-diffLayer.Number > maxDiffForkDist {
  2486. log.Debug("diff layers too old from current", "pid", pid)
  2487. return nil
  2488. }
  2489. bc.diffMux.Lock()
  2490. defer bc.diffMux.Unlock()
  2491. if blockHash, exist := bc.diffHashToBlockHash[diffLayer.DiffHash]; exist && blockHash == diffLayer.BlockHash {
  2492. return nil
  2493. }
  2494. if !fulfilled && len(bc.diffPeersToDiffHashes[pid]) > maxDiffLimitForBroadcast {
  2495. log.Debug("too many accumulated diffLayers", "pid", pid)
  2496. return nil
  2497. }
  2498. if len(bc.diffPeersToDiffHashes[pid]) > maxDiffLimit {
  2499. log.Debug("too many accumulated diffLayers", "pid", pid)
  2500. return nil
  2501. }
  2502. if _, exist := bc.diffPeersToDiffHashes[pid]; exist {
  2503. if _, alreadyHas := bc.diffPeersToDiffHashes[pid][diffLayer.DiffHash]; alreadyHas {
  2504. return nil
  2505. }
  2506. } else {
  2507. bc.diffPeersToDiffHashes[pid] = make(map[common.Hash]struct{})
  2508. }
  2509. bc.diffPeersToDiffHashes[pid][diffLayer.DiffHash] = struct{}{}
  2510. if _, exist := bc.diffNumToBlockHashes[diffLayer.Number]; !exist {
  2511. bc.diffNumToBlockHashes[diffLayer.Number] = make(map[common.Hash]struct{})
  2512. }
  2513. bc.diffNumToBlockHashes[diffLayer.Number][diffLayer.BlockHash] = struct{}{}
  2514. if _, exist := bc.diffHashToPeers[diffLayer.DiffHash]; !exist {
  2515. bc.diffHashToPeers[diffLayer.DiffHash] = make(map[string]struct{})
  2516. }
  2517. bc.diffHashToPeers[diffLayer.DiffHash][pid] = struct{}{}
  2518. if _, exist := bc.blockHashToDiffLayers[diffLayer.BlockHash]; !exist {
  2519. bc.blockHashToDiffLayers[diffLayer.BlockHash] = make(map[common.Hash]*types.DiffLayer)
  2520. }
  2521. bc.blockHashToDiffLayers[diffLayer.BlockHash][diffLayer.DiffHash] = diffLayer
  2522. bc.diffHashToBlockHash[diffLayer.DiffHash] = diffLayer.BlockHash
  2523. return nil
  2524. }
  2525. // maintainTxIndex is responsible for the construction and deletion of the
  2526. // transaction index.
  2527. //
  2528. // User can use flag `txlookuplimit` to specify a "recentness" block, below
  2529. // which ancient tx indices get deleted. If `txlookuplimit` is 0, it means
  2530. // all tx indices will be reserved.
  2531. //
  2532. // The user can adjust the txlookuplimit value for each launch after fast
  2533. // sync, Geth will automatically construct the missing indices and delete
  2534. // the extra indices.
  2535. func (bc *BlockChain) maintainTxIndex(ancients uint64) {
  2536. defer bc.wg.Done()
  2537. // Before starting the actual maintenance, we need to handle a special case,
  2538. // where user might init Geth with an external ancient database. If so, we
  2539. // need to reindex all necessary transactions before starting to process any
  2540. // pruning requests.
  2541. if ancients > 0 {
  2542. var from = uint64(0)
  2543. if bc.txLookupLimit != 0 && ancients > bc.txLookupLimit {
  2544. from = ancients - bc.txLookupLimit
  2545. }
  2546. rawdb.IndexTransactions(bc.db, from, ancients, bc.quit)
  2547. }
  2548. // indexBlocks reindexes or unindexes transactions depending on user configuration
  2549. indexBlocks := func(tail *uint64, head uint64, done chan struct{}) {
  2550. defer func() { done <- struct{}{} }()
  2551. // If the user just upgraded Geth to a new version which supports transaction
  2552. // index pruning, write the new tail and remove anything older.
  2553. if tail == nil {
  2554. if bc.txLookupLimit == 0 || head < bc.txLookupLimit {
  2555. // Nothing to delete, write the tail and return
  2556. rawdb.WriteTxIndexTail(bc.db, 0)
  2557. } else {
  2558. // Prune all stale tx indices and record the tx index tail
  2559. rawdb.UnindexTransactions(bc.db, 0, head-bc.txLookupLimit+1, bc.quit)
  2560. }
  2561. return
  2562. }
  2563. // If a previous indexing existed, make sure that we fill in any missing entries
  2564. if bc.txLookupLimit == 0 || head < bc.txLookupLimit {
  2565. if *tail > 0 {
  2566. rawdb.IndexTransactions(bc.db, 0, *tail, bc.quit)
  2567. }
  2568. return
  2569. }
  2570. // Update the transaction index to the new chain state
  2571. if head-bc.txLookupLimit+1 < *tail {
  2572. // Reindex a part of missing indices and rewind index tail to HEAD-limit
  2573. rawdb.IndexTransactions(bc.db, head-bc.txLookupLimit+1, *tail, bc.quit)
  2574. } else {
  2575. // Unindex a part of stale indices and forward index tail to HEAD-limit
  2576. rawdb.UnindexTransactions(bc.db, *tail, head-bc.txLookupLimit+1, bc.quit)
  2577. }
  2578. }
  2579. // Any reindexing done, start listening to chain events and moving the index window
  2580. var (
  2581. done chan struct{} // Non-nil if background unindexing or reindexing routine is active.
  2582. headCh = make(chan ChainHeadEvent, 1) // Buffered to avoid locking up the event feed
  2583. )
  2584. sub := bc.SubscribeChainHeadEvent(headCh)
  2585. if sub == nil {
  2586. return
  2587. }
  2588. defer sub.Unsubscribe()
  2589. for {
  2590. select {
  2591. case head := <-headCh:
  2592. if done == nil {
  2593. done = make(chan struct{})
  2594. go indexBlocks(rawdb.ReadTxIndexTail(bc.db), head.Block.NumberU64(), done)
  2595. }
  2596. case <-done:
  2597. done = nil
  2598. case <-bc.quit:
  2599. if done != nil {
  2600. log.Info("Waiting background transaction indexer to exit")
  2601. <-done
  2602. }
  2603. return
  2604. }
  2605. }
  2606. }
  2607. // reportBlock logs a bad block error.
  2608. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  2609. rawdb.WriteBadBlock(bc.db, block)
  2610. var receiptString string
  2611. for i, receipt := range receipts {
  2612. receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  2613. i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  2614. receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  2615. }
  2616. log.Error(fmt.Sprintf(`
  2617. ########## BAD BLOCK #########
  2618. Chain config: %v
  2619. Number: %v
  2620. Hash: 0x%x
  2621. %v
  2622. Error: %v
  2623. ##############################
  2624. `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  2625. }
  2626. // InsertHeaderChain attempts to insert the given header chain in to the local
  2627. // chain, possibly creating a reorg. If an error is returned, it will return the
  2628. // index number of the failing header as well an error describing what went wrong.
  2629. //
  2630. // The verify parameter can be used to fine tune whether nonce verification
  2631. // should be done or not. The reason behind the optional check is because some
  2632. // of the header retrieval mechanisms already need to verify nonces, as well as
  2633. // because nonces can be verified sparsely, not needing to check each.
  2634. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  2635. start := time.Now()
  2636. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  2637. return i, err
  2638. }
  2639. // Make sure only one thread manipulates the chain at once
  2640. bc.chainmu.Lock()
  2641. defer bc.chainmu.Unlock()
  2642. bc.wg.Add(1)
  2643. defer bc.wg.Done()
  2644. _, err := bc.hc.InsertHeaderChain(chain, start)
  2645. return 0, err
  2646. }
  2647. // CurrentHeader retrieves the current head header of the canonical chain. The
  2648. // header is retrieved from the HeaderChain's internal cache.
  2649. func (bc *BlockChain) CurrentHeader() *types.Header {
  2650. return bc.hc.CurrentHeader()
  2651. }
  2652. // GetTd retrieves a block's total difficulty in the canonical chain from the
  2653. // database by hash and number, caching it if found.
  2654. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  2655. return bc.hc.GetTd(hash, number)
  2656. }
  2657. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  2658. // database by hash, caching it if found.
  2659. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  2660. return bc.hc.GetTdByHash(hash)
  2661. }
  2662. // GetHeader retrieves a block header from the database by hash and number,
  2663. // caching it if found.
  2664. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  2665. return bc.hc.GetHeader(hash, number)
  2666. }
  2667. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  2668. // found.
  2669. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  2670. return bc.hc.GetHeaderByHash(hash)
  2671. }
  2672. // HasHeader checks if a block header is present in the database or not, caching
  2673. // it if present.
  2674. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  2675. return bc.hc.HasHeader(hash, number)
  2676. }
  2677. // GetCanonicalHash returns the canonical hash for a given block number
  2678. func (bc *BlockChain) GetCanonicalHash(number uint64) common.Hash {
  2679. return bc.hc.GetCanonicalHash(number)
  2680. }
  2681. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  2682. // hash, fetching towards the genesis block.
  2683. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  2684. return bc.hc.GetBlockHashesFromHash(hash, max)
  2685. }
  2686. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  2687. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  2688. // number of blocks to be individually checked before we reach the canonical chain.
  2689. //
  2690. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  2691. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  2692. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  2693. }
  2694. // GetHeaderByNumber retrieves a block header from the database by number,
  2695. // caching it (associated with its hash) if found.
  2696. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  2697. return bc.hc.GetHeaderByNumber(number)
  2698. }
  2699. // GetTransactionLookup retrieves the lookup associate with the given transaction
  2700. // hash from the cache or database.
  2701. func (bc *BlockChain) GetTransactionLookup(hash common.Hash) *rawdb.LegacyTxLookupEntry {
  2702. // Short circuit if the txlookup already in the cache, retrieve otherwise
  2703. if lookup, exist := bc.txLookupCache.Get(hash); exist {
  2704. return lookup.(*rawdb.LegacyTxLookupEntry)
  2705. }
  2706. tx, blockHash, blockNumber, txIndex := rawdb.ReadTransaction(bc.db, hash)
  2707. if tx == nil {
  2708. return nil
  2709. }
  2710. lookup := &rawdb.LegacyTxLookupEntry{BlockHash: blockHash, BlockIndex: blockNumber, Index: txIndex}
  2711. bc.txLookupCache.Add(hash, lookup)
  2712. return lookup
  2713. }
  2714. func (bc *BlockChain) TriesInMemory() uint64 { return bc.triesInMemory }
  2715. // Config retrieves the chain's fork configuration.
  2716. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  2717. // Engine retrieves the blockchain's consensus engine.
  2718. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  2719. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  2720. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  2721. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  2722. }
  2723. // SubscribeChainEvent registers a subscription of ChainEvent.
  2724. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  2725. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  2726. }
  2727. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  2728. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  2729. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  2730. }
  2731. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  2732. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  2733. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  2734. }
  2735. // SubscribeLogsEvent registers a subscription of []*types.Log.
  2736. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  2737. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  2738. }
  2739. // SubscribeBlockProcessingEvent registers a subscription of bool where true means
  2740. // block processing has started while false means it has stopped.
  2741. func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription {
  2742. return bc.scope.Track(bc.blockProcFeed.Subscribe(ch))
  2743. }
  2744. // Options
  2745. func EnableLightProcessor(bc *BlockChain) *BlockChain {
  2746. bc.processor = NewLightStateProcessor(bc.Config(), bc, bc.engine)
  2747. return bc
  2748. }
  2749. func EnablePersistDiff(limit uint64) BlockChainOption {
  2750. return func(chain *BlockChain) *BlockChain {
  2751. chain.diffLayerFreezerBlockLimit = limit
  2752. return chain
  2753. }
  2754. }