blockchain.go 111 KB

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