blockchain.go 109 KB

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