blockchain.go 114 KB

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