blockchain.go 111 KB

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