blockchain.go 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313
  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. blockReorgAddMeter = metrics.NewRegisteredMeter("chain/reorg/drop", nil)
  66. blockReorgDropMeter = metrics.NewRegisteredMeter("chain/reorg/add", nil)
  67. blockPrefetchExecuteTimer = metrics.NewRegisteredTimer("chain/prefetch/executes", nil)
  68. blockPrefetchInterruptMeter = metrics.NewRegisteredMeter("chain/prefetch/interrupts", nil)
  69. errInsertionInterrupted = errors.New("insertion is interrupted")
  70. )
  71. const (
  72. bodyCacheLimit = 256
  73. blockCacheLimit = 256
  74. receiptsCacheLimit = 10000
  75. txLookupCacheLimit = 1024
  76. maxFutureBlocks = 256
  77. maxTimeFutureBlocks = 30
  78. badBlockLimit = 10
  79. TriesInMemory = 1024
  80. // BlockChainVersion ensures that an incompatible database forces a resync from scratch.
  81. //
  82. // Changelog:
  83. //
  84. // - Version 4
  85. // The following incompatible database changes were added:
  86. // * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted
  87. // * the `Bloom` field of receipt is deleted
  88. // * the `BlockIndex` and `TxIndex` fields of txlookup are deleted
  89. // - Version 5
  90. // The following incompatible database changes were added:
  91. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are no longer stored for a receipt
  92. // * the `TxHash`, `GasCost`, and `ContractAddress` fields are computed by looking up the
  93. // receipts' corresponding block
  94. // - Version 6
  95. // The following incompatible database changes were added:
  96. // * Transaction lookup information stores the corresponding block number instead of block hash
  97. // - Version 7
  98. // The following incompatible database changes were added:
  99. // * Use freezer as the ancient database to maintain all ancient data
  100. BlockChainVersion uint64 = 7
  101. )
  102. // CacheConfig contains the configuration values for the trie caching/pruning
  103. // that's resident in a blockchain.
  104. type CacheConfig struct {
  105. TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
  106. TrieCleanNoPrefetch bool // Whether to disable heuristic state prefetching for followup blocks
  107. TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk
  108. TrieDirtyDisabled bool // Whether to disable trie write caching and GC altogether (archive node)
  109. TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
  110. SnapshotLimit int // Memory allowance (MB) to use for caching snapshot entries in memory
  111. SnapshotWait bool // Wait for snapshot construction on startup. TODO(karalabe): This is a dirty hack for testing, nuke it
  112. }
  113. // BlockChain represents the canonical chain given a database with a genesis
  114. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  115. //
  116. // Importing blocks in to the block chain happens according to the set of rules
  117. // defined by the two stage Validator. Processing of blocks is done using the
  118. // Processor which processes the included transaction. The validation of the state
  119. // is done in the second part of the Validator. Failing results in aborting of
  120. // the import.
  121. //
  122. // The BlockChain also helps in returning blocks from **any** chain included
  123. // in the database as well as blocks that represents the canonical chain. It's
  124. // important to note that GetBlock can return any block and does not need to be
  125. // included in the canonical one where as GetBlockByNumber always represents the
  126. // canonical chain.
  127. type BlockChain struct {
  128. chainConfig *params.ChainConfig // Chain & network configuration
  129. cacheConfig *CacheConfig // Cache configuration for pruning
  130. db ethdb.Database // Low level persistent database to store final content in
  131. snaps *snapshot.Tree // Snapshot tree for fast trie leaf access
  132. triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
  133. gcproc time.Duration // Accumulates canonical block processing for trie dumping
  134. hc *HeaderChain
  135. rmLogsFeed event.Feed
  136. chainFeed event.Feed
  137. chainSideFeed event.Feed
  138. chainHeadFeed event.Feed
  139. logsFeed event.Feed
  140. blockProcFeed event.Feed
  141. scope event.SubscriptionScope
  142. genesisBlock *types.Block
  143. chainmu sync.RWMutex // blockchain insertion lock
  144. currentBlock atomic.Value // Current head of the block chain
  145. currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
  146. stateCache state.Database // State database to reuse between imports (contains state cache)
  147. bodyCache *lru.Cache // Cache for the most recent block bodies
  148. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  149. receiptsCache *lru.Cache // Cache for the most recent receipts per block
  150. blockCache *lru.Cache // Cache for the most recent entire blocks
  151. txLookupCache *lru.Cache // Cache for the most recent transaction lookup data.
  152. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  153. quit chan struct{} // blockchain quit channel
  154. running int32 // running must be called atomically
  155. // procInterrupt must be atomically called
  156. procInterrupt int32 // interrupt signaler for block processing
  157. wg sync.WaitGroup // chain processing wait group for shutting down
  158. engine consensus.Engine
  159. validator Validator // Block and state validator interface
  160. prefetcher Prefetcher // Block state prefetcher interface
  161. processor Processor // Block transaction processor interface
  162. vmConfig vm.Config
  163. badBlocks *lru.Cache // Bad block cache
  164. shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
  165. terminateInsert func(common.Hash, uint64) bool // Testing hook used to terminate ancient receipt chain insertion.
  166. }
  167. // NewBlockChain returns a fully initialised block chain using information
  168. // available in the database. It initialises the default Ethereum Validator and
  169. // Processor.
  170. func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool) (*BlockChain, error) {
  171. if cacheConfig == nil {
  172. cacheConfig = &CacheConfig{
  173. TrieCleanLimit: 256,
  174. TrieDirtyLimit: 256,
  175. TrieTimeLimit: 5 * time.Minute,
  176. SnapshotLimit: 256,
  177. SnapshotWait: true,
  178. }
  179. }
  180. bodyCache, _ := lru.New(bodyCacheLimit)
  181. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  182. receiptsCache, _ := lru.New(receiptsCacheLimit)
  183. blockCache, _ := lru.New(blockCacheLimit)
  184. txLookupCache, _ := lru.New(txLookupCacheLimit)
  185. futureBlocks, _ := lru.New(maxFutureBlocks)
  186. badBlocks, _ := lru.New(badBlockLimit)
  187. bc := &BlockChain{
  188. chainConfig: chainConfig,
  189. cacheConfig: cacheConfig,
  190. db: db,
  191. triegc: prque.New(nil),
  192. stateCache: state.NewDatabaseWithCache(db, cacheConfig.TrieCleanLimit),
  193. quit: make(chan struct{}),
  194. shouldPreserve: shouldPreserve,
  195. bodyCache: bodyCache,
  196. bodyRLPCache: bodyRLPCache,
  197. receiptsCache: receiptsCache,
  198. blockCache: blockCache,
  199. txLookupCache: txLookupCache,
  200. futureBlocks: futureBlocks,
  201. engine: engine,
  202. vmConfig: vmConfig,
  203. badBlocks: badBlocks,
  204. }
  205. bc.validator = NewBlockValidator(chainConfig, bc, engine)
  206. bc.prefetcher = newStatePrefetcher(chainConfig, bc, engine)
  207. bc.processor = NewStateProcessor(chainConfig, bc, engine)
  208. var err error
  209. bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.getProcInterrupt)
  210. if err != nil {
  211. return nil, err
  212. }
  213. bc.genesisBlock = bc.GetBlockByNumber(0)
  214. if bc.genesisBlock == nil {
  215. return nil, ErrNoGenesis
  216. }
  217. var nilBlock *types.Block
  218. bc.currentBlock.Store(nilBlock)
  219. bc.currentFastBlock.Store(nilBlock)
  220. // Initialize the chain with ancient data if it isn't empty.
  221. if bc.empty() {
  222. rawdb.InitDatabaseFromFreezer(bc.db)
  223. }
  224. if err := bc.loadLastState(); err != nil {
  225. return nil, err
  226. }
  227. // The first thing the node will do is reconstruct the verification data for
  228. // the head block (ethash cache or clique voting snapshot). Might as well do
  229. // it in advance.
  230. bc.engine.VerifyHeader(bc, bc.CurrentHeader(), true)
  231. if frozen, err := bc.db.Ancients(); err == nil && frozen > 0 {
  232. var (
  233. needRewind bool
  234. low uint64
  235. )
  236. // The head full block may be rolled back to a very low height due to
  237. // blockchain repair. If the head full block is even lower than the ancient
  238. // chain, truncate the ancient store.
  239. fullBlock := bc.CurrentBlock()
  240. if fullBlock != nil && fullBlock != bc.genesisBlock && fullBlock.NumberU64() < frozen-1 {
  241. needRewind = true
  242. low = fullBlock.NumberU64()
  243. }
  244. // In fast sync, it may happen that ancient data has been written to the
  245. // ancient store, but the LastFastBlock has not been updated, truncate the
  246. // extra data here.
  247. fastBlock := bc.CurrentFastBlock()
  248. if fastBlock != nil && fastBlock.NumberU64() < frozen-1 {
  249. needRewind = true
  250. if fastBlock.NumberU64() < low || low == 0 {
  251. low = fastBlock.NumberU64()
  252. }
  253. }
  254. if needRewind {
  255. var hashes []common.Hash
  256. previous := bc.CurrentHeader().Number.Uint64()
  257. for i := low + 1; i <= bc.CurrentHeader().Number.Uint64(); i++ {
  258. hashes = append(hashes, rawdb.ReadCanonicalHash(bc.db, i))
  259. }
  260. bc.Rollback(hashes)
  261. log.Warn("Truncate ancient chain", "from", previous, "to", low)
  262. }
  263. }
  264. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  265. for hash := range BadHashes {
  266. if header := bc.GetHeaderByHash(hash); header != nil {
  267. // get the canonical block corresponding to the offending header's number
  268. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  269. // make sure the headerByNumber (if present) is in our current canonical chain
  270. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  271. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  272. bc.SetHead(header.Number.Uint64() - 1)
  273. log.Error("Chain rewind was successful, resuming normal operation")
  274. }
  275. }
  276. }
  277. // Load any existing snapshot, regenerating it if loading failed
  278. if bc.cacheConfig.SnapshotLimit > 0 {
  279. bc.snaps = snapshot.New(bc.db, bc.stateCache.TrieDB(), bc.cacheConfig.SnapshotLimit, bc.CurrentBlock().Root(), !bc.cacheConfig.SnapshotWait)
  280. }
  281. // Take ownership of this particular state
  282. go bc.update()
  283. return bc, nil
  284. }
  285. func (bc *BlockChain) getProcInterrupt() bool {
  286. return atomic.LoadInt32(&bc.procInterrupt) == 1
  287. }
  288. // GetVMConfig returns the block chain VM config.
  289. func (bc *BlockChain) GetVMConfig() *vm.Config {
  290. return &bc.vmConfig
  291. }
  292. func (bc *BlockChain) CacheReceipts(hash common.Hash, receipts types.Receipts) {
  293. bc.receiptsCache.Add(hash, receipts)
  294. }
  295. // empty returns an indicator whether the blockchain is empty.
  296. // Note, it's a special case that we connect a non-empty ancient
  297. // database with an empty node, so that we can plugin the ancient
  298. // into node seamlessly.
  299. func (bc *BlockChain) empty() bool {
  300. genesis := bc.genesisBlock.Hash()
  301. for _, hash := range []common.Hash{rawdb.ReadHeadBlockHash(bc.db), rawdb.ReadHeadHeaderHash(bc.db), rawdb.ReadHeadFastBlockHash(bc.db)} {
  302. if hash != genesis {
  303. return false
  304. }
  305. }
  306. return true
  307. }
  308. // loadLastState loads the last known chain state from the database. This method
  309. // assumes that the chain manager mutex is held.
  310. func (bc *BlockChain) loadLastState() error {
  311. // Restore the last known head block
  312. head := rawdb.ReadHeadBlockHash(bc.db)
  313. if head == (common.Hash{}) {
  314. // Corrupt or empty database, init from scratch
  315. log.Warn("Empty database, resetting chain")
  316. return bc.Reset()
  317. }
  318. // Make sure the entire head block is available
  319. currentBlock := bc.GetBlockByHash(head)
  320. if currentBlock == nil {
  321. // Corrupt or empty database, init from scratch
  322. log.Warn("Head block missing, resetting chain", "hash", head)
  323. return bc.Reset()
  324. }
  325. // Make sure the state associated with the block is available
  326. if _, err := state.New(currentBlock.Root(), bc.stateCache, bc.snaps); err != nil {
  327. // Dangling block without a state associated, init from scratch
  328. log.Warn("Head state missing, repairing chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
  329. if err := bc.repair(&currentBlock); err != nil {
  330. return err
  331. }
  332. rawdb.WriteHeadBlockHash(bc.db, currentBlock.Hash())
  333. }
  334. // Everything seems to be fine, set as the head block
  335. bc.currentBlock.Store(currentBlock)
  336. headBlockGauge.Update(int64(currentBlock.NumberU64()))
  337. // Restore the last known head header
  338. currentHeader := currentBlock.Header()
  339. if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
  340. if header := bc.GetHeaderByHash(head); header != nil {
  341. currentHeader = header
  342. }
  343. }
  344. bc.hc.SetCurrentHeader(currentHeader)
  345. // Restore the last known head fast block
  346. bc.currentFastBlock.Store(currentBlock)
  347. headFastBlockGauge.Update(int64(currentBlock.NumberU64()))
  348. if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
  349. if block := bc.GetBlockByHash(head); block != nil {
  350. bc.currentFastBlock.Store(block)
  351. headFastBlockGauge.Update(int64(block.NumberU64()))
  352. }
  353. }
  354. // Issue a status log for the user
  355. currentFastBlock := bc.CurrentFastBlock()
  356. headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  357. blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  358. fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
  359. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time), 0)))
  360. 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)))
  361. 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)))
  362. return nil
  363. }
  364. // SetHead rewinds the local chain to a new head. In the case of headers, everything
  365. // above the new head will be deleted and the new one set. In the case of blocks
  366. // though, the head may be further rewound if block bodies are missing (non-archive
  367. // nodes after a fast sync).
  368. func (bc *BlockChain) SetHead(head uint64) error {
  369. log.Warn("Rewinding blockchain", "target", head)
  370. bc.chainmu.Lock()
  371. defer bc.chainmu.Unlock()
  372. updateFn := func(db ethdb.KeyValueWriter, header *types.Header) {
  373. // Rewind the block chain, ensuring we don't end up with a stateless head block
  374. if currentBlock := bc.CurrentBlock(); currentBlock != nil && header.Number.Uint64() < currentBlock.NumberU64() {
  375. newHeadBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  376. if newHeadBlock == nil {
  377. newHeadBlock = bc.genesisBlock
  378. } else {
  379. if _, err := state.New(newHeadBlock.Root(), bc.stateCache, bc.snaps); err != nil {
  380. // Rewound state missing, rolled back to before pivot, reset to genesis
  381. newHeadBlock = bc.genesisBlock
  382. }
  383. }
  384. rawdb.WriteHeadBlockHash(db, newHeadBlock.Hash())
  385. // Degrade the chain markers if they are explicitly reverted.
  386. // In theory we should update all in-memory markers in the
  387. // last step, however the direction of SetHead is from high
  388. // to low, so it's safe the update in-memory markers directly.
  389. bc.currentBlock.Store(newHeadBlock)
  390. headBlockGauge.Update(int64(newHeadBlock.NumberU64()))
  391. }
  392. // Rewind the fast block in a simpleton way to the target head
  393. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && header.Number.Uint64() < currentFastBlock.NumberU64() {
  394. newHeadFastBlock := bc.GetBlock(header.Hash(), header.Number.Uint64())
  395. // If either blocks reached nil, reset to the genesis state
  396. if newHeadFastBlock == nil {
  397. newHeadFastBlock = bc.genesisBlock
  398. }
  399. rawdb.WriteHeadFastBlockHash(db, newHeadFastBlock.Hash())
  400. // Degrade the chain markers if they are explicitly reverted.
  401. // In theory we should update all in-memory markers in the
  402. // last step, however the direction of SetHead is from high
  403. // to low, so it's safe the update in-memory markers directly.
  404. bc.currentFastBlock.Store(newHeadFastBlock)
  405. headFastBlockGauge.Update(int64(newHeadFastBlock.NumberU64()))
  406. }
  407. }
  408. // Rewind the header chain, deleting all block bodies until then
  409. delFn := func(db ethdb.KeyValueWriter, hash common.Hash, num uint64) {
  410. // Ignore the error here since light client won't hit this path
  411. frozen, _ := bc.db.Ancients()
  412. if num+1 <= frozen {
  413. // Truncate all relative data(header, total difficulty, body, receipt
  414. // and canonical hash) from ancient store.
  415. if err := bc.db.TruncateAncients(num + 1); err != nil {
  416. log.Crit("Failed to truncate ancient data", "number", num, "err", err)
  417. }
  418. // Remove the hash <-> number mapping from the active store.
  419. rawdb.DeleteHeaderNumber(db, hash)
  420. } else {
  421. // Remove relative body and receipts from the active store.
  422. // The header, total difficulty and canonical hash will be
  423. // removed in the hc.SetHead function.
  424. rawdb.DeleteBody(db, hash, num)
  425. rawdb.DeleteReceipts(db, hash, num)
  426. }
  427. // Todo(rjl493456442) txlookup, bloombits, etc
  428. }
  429. bc.hc.SetHead(head, updateFn, delFn)
  430. // Clear out any stale content from the caches
  431. bc.bodyCache.Purge()
  432. bc.bodyRLPCache.Purge()
  433. bc.receiptsCache.Purge()
  434. bc.blockCache.Purge()
  435. bc.txLookupCache.Purge()
  436. bc.futureBlocks.Purge()
  437. return bc.loadLastState()
  438. }
  439. // FastSyncCommitHead sets the current head block to the one defined by the hash
  440. // irrelevant what the chain contents were prior.
  441. func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  442. // Make sure that both the block as well at its state trie exists
  443. block := bc.GetBlockByHash(hash)
  444. if block == nil {
  445. return fmt.Errorf("non existent block [%x…]", hash[:4])
  446. }
  447. if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB()); err != nil {
  448. return err
  449. }
  450. // If all checks out, manually set the head block
  451. bc.chainmu.Lock()
  452. bc.currentBlock.Store(block)
  453. headBlockGauge.Update(int64(block.NumberU64()))
  454. bc.chainmu.Unlock()
  455. // Destroy any existing state snapshot and regenerate it in the background
  456. if bc.snaps != nil {
  457. bc.snaps.Rebuild(block.Root())
  458. }
  459. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  460. return nil
  461. }
  462. // GasLimit returns the gas limit of the current HEAD block.
  463. func (bc *BlockChain) GasLimit() uint64 {
  464. return bc.CurrentBlock().GasLimit()
  465. }
  466. // CurrentBlock retrieves the current head block of the canonical chain. The
  467. // block is retrieved from the blockchain's internal cache.
  468. func (bc *BlockChain) CurrentBlock() *types.Block {
  469. return bc.currentBlock.Load().(*types.Block)
  470. }
  471. // Snapshot returns the blockchain snapshot tree. This method is mainly used for
  472. // testing, to make it possible to verify the snapshot after execution.
  473. //
  474. // Warning: There are no guarantees about the safety of using the returned 'snap' if the
  475. // blockchain is simultaneously importing blocks, so take care.
  476. func (bc *BlockChain) Snapshot() *snapshot.Tree {
  477. return bc.snaps
  478. }
  479. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  480. // chain. The block is retrieved from the blockchain's internal cache.
  481. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  482. return bc.currentFastBlock.Load().(*types.Block)
  483. }
  484. // Validator returns the current validator.
  485. func (bc *BlockChain) Validator() Validator {
  486. return bc.validator
  487. }
  488. // Processor returns the current processor.
  489. func (bc *BlockChain) Processor() Processor {
  490. return bc.processor
  491. }
  492. // State returns a new mutable state based on the current HEAD block.
  493. func (bc *BlockChain) State() (*state.StateDB, error) {
  494. return bc.StateAt(bc.CurrentBlock().Root())
  495. }
  496. // StateAt returns a new mutable state based on a particular point in time.
  497. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  498. return state.New(root, bc.stateCache, bc.snaps)
  499. }
  500. // StateCache returns the caching database underpinning the blockchain instance.
  501. func (bc *BlockChain) StateCache() state.Database {
  502. return bc.stateCache
  503. }
  504. // Reset purges the entire blockchain, restoring it to its genesis state.
  505. func (bc *BlockChain) Reset() error {
  506. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  507. }
  508. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  509. // specified genesis state.
  510. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  511. // Dump the entire block chain and purge the caches
  512. if err := bc.SetHead(0); err != nil {
  513. return err
  514. }
  515. bc.chainmu.Lock()
  516. defer bc.chainmu.Unlock()
  517. // Prepare the genesis block and reinitialise the chain
  518. batch := bc.db.NewBatch()
  519. rawdb.WriteTd(batch, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty())
  520. rawdb.WriteBlock(batch, genesis)
  521. if err := batch.Write(); err != nil {
  522. log.Crit("Failed to write genesis block", "err", err)
  523. }
  524. bc.writeHeadBlock(genesis)
  525. // Last update all in-memory chain markers
  526. bc.genesisBlock = genesis
  527. bc.currentBlock.Store(bc.genesisBlock)
  528. headBlockGauge.Update(int64(bc.genesisBlock.NumberU64()))
  529. bc.hc.SetGenesis(bc.genesisBlock.Header())
  530. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  531. bc.currentFastBlock.Store(bc.genesisBlock)
  532. headFastBlockGauge.Update(int64(bc.genesisBlock.NumberU64()))
  533. return nil
  534. }
  535. // repair tries to repair the current blockchain by rolling back the current block
  536. // until one with associated state is found. This is needed to fix incomplete db
  537. // writes caused either by crashes/power outages, or simply non-committed tries.
  538. //
  539. // This method only rolls back the current block. The current header and current
  540. // fast block are left intact.
  541. func (bc *BlockChain) repair(head **types.Block) error {
  542. for {
  543. // Abort if we've rewound to a head block that does have associated state
  544. if _, err := state.New((*head).Root(), bc.stateCache, bc.snaps); err == nil {
  545. log.Info("Rewound blockchain to past state", "number", (*head).Number(), "hash", (*head).Hash())
  546. return nil
  547. }
  548. // Otherwise rewind one block and recheck state availability there
  549. block := bc.GetBlock((*head).ParentHash(), (*head).NumberU64()-1)
  550. if block == nil {
  551. return fmt.Errorf("missing block %d [%x]", (*head).NumberU64()-1, (*head).ParentHash())
  552. }
  553. *head = block
  554. }
  555. }
  556. // Export writes the active chain to the given writer.
  557. func (bc *BlockChain) Export(w io.Writer) error {
  558. return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64())
  559. }
  560. // ExportN writes a subset of the active chain to the given writer.
  561. func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  562. bc.chainmu.RLock()
  563. defer bc.chainmu.RUnlock()
  564. if first > last {
  565. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  566. }
  567. log.Info("Exporting batch of blocks", "count", last-first+1)
  568. start, reported := time.Now(), time.Now()
  569. for nr := first; nr <= last; nr++ {
  570. block := bc.GetBlockByNumber(nr)
  571. if block == nil {
  572. return fmt.Errorf("export failed on #%d: not found", nr)
  573. }
  574. if err := block.EncodeRLP(w); err != nil {
  575. return err
  576. }
  577. if time.Since(reported) >= statsReportLimit {
  578. log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
  579. reported = time.Now()
  580. }
  581. }
  582. return nil
  583. }
  584. // writeHeadBlock injects a new head block into the current block chain. This method
  585. // assumes that the block is indeed a true head. It will also reset the head
  586. // header and the head fast sync block to this very same block if they are older
  587. // or if they are on a different side chain.
  588. //
  589. // Note, this function assumes that the `mu` mutex is held!
  590. func (bc *BlockChain) writeHeadBlock(block *types.Block) {
  591. // If the block is on a side chain or an unknown one, force other heads onto it too
  592. updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()
  593. // Add the block to the canonical chain number scheme and mark as the head
  594. batch := bc.db.NewBatch()
  595. rawdb.WriteCanonicalHash(batch, block.Hash(), block.NumberU64())
  596. rawdb.WriteTxLookupEntries(batch, block)
  597. rawdb.WriteHeadBlockHash(batch, block.Hash())
  598. // If the block is better than our head or is on a different chain, force update heads
  599. if updateHeads {
  600. rawdb.WriteHeadHeaderHash(batch, block.Hash())
  601. rawdb.WriteHeadFastBlockHash(batch, block.Hash())
  602. }
  603. // Flush the whole batch into the disk, exit the node if failed
  604. if err := batch.Write(); err != nil {
  605. log.Crit("Failed to update chain indexes and markers", "err", err)
  606. }
  607. // Update all in-memory chain markers in the last step
  608. if updateHeads {
  609. bc.hc.SetCurrentHeader(block.Header())
  610. bc.currentFastBlock.Store(block)
  611. headFastBlockGauge.Update(int64(block.NumberU64()))
  612. }
  613. bc.currentBlock.Store(block)
  614. headBlockGauge.Update(int64(block.NumberU64()))
  615. }
  616. // Genesis retrieves the chain's genesis block.
  617. func (bc *BlockChain) Genesis() *types.Block {
  618. return bc.genesisBlock
  619. }
  620. // GetBody retrieves a block body (transactions and uncles) from the database by
  621. // hash, caching it if found.
  622. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  623. // Short circuit if the body's already in the cache, retrieve otherwise
  624. if cached, ok := bc.bodyCache.Get(hash); ok {
  625. body := cached.(*types.Body)
  626. return body
  627. }
  628. number := bc.hc.GetBlockNumber(hash)
  629. if number == nil {
  630. return nil
  631. }
  632. body := rawdb.ReadBody(bc.db, hash, *number)
  633. if body == nil {
  634. return nil
  635. }
  636. // Cache the found body for next time and return
  637. bc.bodyCache.Add(hash, body)
  638. return body
  639. }
  640. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  641. // caching it if found.
  642. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  643. // Short circuit if the body's already in the cache, retrieve otherwise
  644. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  645. return cached.(rlp.RawValue)
  646. }
  647. number := bc.hc.GetBlockNumber(hash)
  648. if number == nil {
  649. return nil
  650. }
  651. body := rawdb.ReadBodyRLP(bc.db, hash, *number)
  652. if len(body) == 0 {
  653. return nil
  654. }
  655. // Cache the found body for next time and return
  656. bc.bodyRLPCache.Add(hash, body)
  657. return body
  658. }
  659. // HasBlock checks if a block is fully present in the database or not.
  660. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  661. if bc.blockCache.Contains(hash) {
  662. return true
  663. }
  664. return rawdb.HasBody(bc.db, hash, number)
  665. }
  666. // HasFastBlock checks if a fast block is fully present in the database or not.
  667. func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool {
  668. if !bc.HasBlock(hash, number) {
  669. return false
  670. }
  671. if bc.receiptsCache.Contains(hash) {
  672. return true
  673. }
  674. return rawdb.HasReceipts(bc.db, hash, number)
  675. }
  676. // HasState checks if state trie is fully present in the database or not.
  677. func (bc *BlockChain) HasState(hash common.Hash) bool {
  678. _, err := bc.stateCache.OpenTrie(hash)
  679. return err == nil
  680. }
  681. // HasBlockAndState checks if a block and associated state trie is fully present
  682. // in the database or not, caching it if present.
  683. func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
  684. // Check first that the block itself is known
  685. block := bc.GetBlock(hash, number)
  686. if block == nil {
  687. return false
  688. }
  689. return bc.HasState(block.Root())
  690. }
  691. // GetBlock retrieves a block from the database by hash and number,
  692. // caching it if found.
  693. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  694. // Short circuit if the block's already in the cache, retrieve otherwise
  695. if block, ok := bc.blockCache.Get(hash); ok {
  696. return block.(*types.Block)
  697. }
  698. block := rawdb.ReadBlock(bc.db, hash, number)
  699. if block == nil {
  700. return nil
  701. }
  702. // Cache the found block for next time and return
  703. bc.blockCache.Add(block.Hash(), block)
  704. return block
  705. }
  706. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  707. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  708. number := bc.hc.GetBlockNumber(hash)
  709. if number == nil {
  710. return nil
  711. }
  712. return bc.GetBlock(hash, *number)
  713. }
  714. // GetBlockByNumber retrieves a block from the database by number, caching it
  715. // (associated with its hash) if found.
  716. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  717. hash := rawdb.ReadCanonicalHash(bc.db, number)
  718. if hash == (common.Hash{}) {
  719. return nil
  720. }
  721. return bc.GetBlock(hash, number)
  722. }
  723. // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
  724. func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
  725. if receipts, ok := bc.receiptsCache.Get(hash); ok {
  726. return receipts.(types.Receipts)
  727. }
  728. number := rawdb.ReadHeaderNumber(bc.db, hash)
  729. if number == nil {
  730. return nil
  731. }
  732. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  733. if receipts == nil {
  734. return nil
  735. }
  736. bc.receiptsCache.Add(hash, receipts)
  737. return receipts
  738. }
  739. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  740. // [deprecated by eth/62]
  741. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  742. number := bc.hc.GetBlockNumber(hash)
  743. if number == nil {
  744. return nil
  745. }
  746. for i := 0; i < n; i++ {
  747. block := bc.GetBlock(hash, *number)
  748. if block == nil {
  749. break
  750. }
  751. blocks = append(blocks, block)
  752. hash = block.ParentHash()
  753. *number--
  754. }
  755. return
  756. }
  757. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  758. // a specific distance is reached.
  759. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  760. uncles := []*types.Header{}
  761. for i := 0; block != nil && i < length; i++ {
  762. uncles = append(uncles, block.Uncles()...)
  763. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  764. }
  765. return uncles
  766. }
  767. // TrieNode retrieves a blob of data associated with a trie node (or code hash)
  768. // either from ephemeral in-memory cache, or from persistent storage.
  769. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  770. return bc.stateCache.TrieDB().Node(hash)
  771. }
  772. // Stop stops the blockchain service. If any imports are currently in progress
  773. // it will abort them using the procInterrupt.
  774. func (bc *BlockChain) Stop() {
  775. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  776. return
  777. }
  778. // Unsubscribe all subscriptions registered from blockchain
  779. bc.scope.Close()
  780. close(bc.quit)
  781. atomic.StoreInt32(&bc.procInterrupt, 1)
  782. bc.wg.Wait()
  783. // Ensure that the entirety of the state snapshot is journalled to disk.
  784. var snapBase common.Hash
  785. if bc.snaps != nil {
  786. var err error
  787. if snapBase, err = bc.snaps.Journal(bc.CurrentBlock().Root()); err != nil {
  788. log.Error("Failed to journal state snapshot", "err", err)
  789. }
  790. }
  791. // Ensure the state of a recent block is also stored to disk before exiting.
  792. // We're writing three different states to catch different restart scenarios:
  793. // - HEAD: So we don't need to reprocess any blocks in the general case
  794. // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle
  795. // - HEAD-127: So we have a hard limit on the number of blocks reexecuted
  796. if !bc.cacheConfig.TrieDirtyDisabled {
  797. triedb := bc.stateCache.TrieDB()
  798. for _, offset := range []uint64{0, 1, TriesInMemory - 1} {
  799. if number := bc.CurrentBlock().NumberU64(); number > offset {
  800. recent := bc.GetBlockByNumber(number - offset)
  801. log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
  802. if err := triedb.Commit(recent.Root(), true); err != nil {
  803. log.Error("Failed to commit recent state trie", "err", err)
  804. }
  805. }
  806. }
  807. if snapBase != (common.Hash{}) {
  808. log.Info("Writing snapshot state to disk", "root", snapBase)
  809. if err := triedb.Commit(snapBase, true); err != nil {
  810. log.Error("Failed to commit recent state trie", "err", err)
  811. }
  812. }
  813. for !bc.triegc.Empty() {
  814. triedb.Dereference(bc.triegc.PopItem().(common.Hash))
  815. }
  816. if size, _ := triedb.Size(); size != 0 {
  817. log.Error("Dangling trie nodes after full cleanup")
  818. }
  819. }
  820. log.Info("Blockchain stopped")
  821. }
  822. func (bc *BlockChain) procFutureBlocks() {
  823. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  824. for _, hash := range bc.futureBlocks.Keys() {
  825. if block, exist := bc.futureBlocks.Peek(hash); exist {
  826. blocks = append(blocks, block.(*types.Block))
  827. }
  828. }
  829. if len(blocks) > 0 {
  830. sort.Slice(blocks, func(i, j int) bool {
  831. return blocks[i].NumberU64() < blocks[j].NumberU64()
  832. })
  833. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  834. for i := range blocks {
  835. bc.InsertChain(blocks[i : i+1])
  836. }
  837. }
  838. }
  839. // WriteStatus status of write
  840. type WriteStatus byte
  841. const (
  842. NonStatTy WriteStatus = iota
  843. CanonStatTy
  844. SideStatTy
  845. )
  846. // Rollback is designed to remove a chain of links from the database that aren't
  847. // certain enough to be valid.
  848. func (bc *BlockChain) Rollback(chain []common.Hash) {
  849. bc.chainmu.Lock()
  850. defer bc.chainmu.Unlock()
  851. batch := bc.db.NewBatch()
  852. for i := len(chain) - 1; i >= 0; i-- {
  853. hash := chain[i]
  854. // Degrade the chain markers if they are explicitly reverted.
  855. // In theory we should update all in-memory markers in the
  856. // last step, however the direction of rollback is from high
  857. // to low, so it's safe the update in-memory markers directly.
  858. currentHeader := bc.hc.CurrentHeader()
  859. if currentHeader.Hash() == hash {
  860. newHeadHeader := bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1)
  861. rawdb.WriteHeadHeaderHash(batch, currentHeader.ParentHash)
  862. bc.hc.SetCurrentHeader(newHeadHeader)
  863. }
  864. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock.Hash() == hash {
  865. newFastBlock := bc.GetBlock(currentFastBlock.ParentHash(), currentFastBlock.NumberU64()-1)
  866. rawdb.WriteHeadFastBlockHash(batch, currentFastBlock.ParentHash())
  867. bc.currentFastBlock.Store(newFastBlock)
  868. headFastBlockGauge.Update(int64(newFastBlock.NumberU64()))
  869. }
  870. if currentBlock := bc.CurrentBlock(); currentBlock.Hash() == hash {
  871. newBlock := bc.GetBlock(currentBlock.ParentHash(), currentBlock.NumberU64()-1)
  872. rawdb.WriteHeadBlockHash(batch, currentBlock.ParentHash())
  873. bc.currentBlock.Store(newBlock)
  874. headBlockGauge.Update(int64(newBlock.NumberU64()))
  875. }
  876. }
  877. if err := batch.Write(); err != nil {
  878. log.Crit("Failed to rollback chain markers", "err", err)
  879. }
  880. // Truncate ancient data which exceeds the current header.
  881. //
  882. // Notably, it can happen that system crashes without truncating the ancient data
  883. // but the head indicator has been updated in the active store. Regarding this issue,
  884. // system will self recovery by truncating the extra data during the setup phase.
  885. if err := bc.truncateAncient(bc.hc.CurrentHeader().Number.Uint64()); err != nil {
  886. log.Crit("Truncate ancient store failed", "err", err)
  887. }
  888. }
  889. // truncateAncient rewinds the blockchain to the specified header and deletes all
  890. // data in the ancient store that exceeds the specified header.
  891. func (bc *BlockChain) truncateAncient(head uint64) error {
  892. frozen, err := bc.db.Ancients()
  893. if err != nil {
  894. return err
  895. }
  896. // Short circuit if there is no data to truncate in ancient store.
  897. if frozen <= head+1 {
  898. return nil
  899. }
  900. // Truncate all the data in the freezer beyond the specified head
  901. if err := bc.db.TruncateAncients(head + 1); err != nil {
  902. return err
  903. }
  904. // Clear out any stale content from the caches
  905. bc.hc.headerCache.Purge()
  906. bc.hc.tdCache.Purge()
  907. bc.hc.numberCache.Purge()
  908. // Clear out any stale content from the caches
  909. bc.bodyCache.Purge()
  910. bc.bodyRLPCache.Purge()
  911. bc.receiptsCache.Purge()
  912. bc.blockCache.Purge()
  913. bc.txLookupCache.Purge()
  914. bc.futureBlocks.Purge()
  915. log.Info("Rewind ancient data", "number", head)
  916. return nil
  917. }
  918. // numberHash is just a container for a number and a hash, to represent a block
  919. type numberHash struct {
  920. number uint64
  921. hash common.Hash
  922. }
  923. // InsertReceiptChain attempts to complete an already existing header chain with
  924. // transaction and receipt data.
  925. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts, ancientLimit uint64) (int, error) {
  926. // We don't require the chainMu here since we want to maximize the
  927. // concurrency of header insertion and receipt insertion.
  928. bc.wg.Add(1)
  929. defer bc.wg.Done()
  930. var (
  931. ancientBlocks, liveBlocks types.Blocks
  932. ancientReceipts, liveReceipts []types.Receipts
  933. )
  934. // Do a sanity check that the provided chain is actually ordered and linked
  935. for i := 0; i < len(blockChain); i++ {
  936. if i != 0 {
  937. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  938. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  939. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  940. 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(),
  941. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  942. }
  943. }
  944. if blockChain[i].NumberU64() <= ancientLimit {
  945. ancientBlocks, ancientReceipts = append(ancientBlocks, blockChain[i]), append(ancientReceipts, receiptChain[i])
  946. } else {
  947. liveBlocks, liveReceipts = append(liveBlocks, blockChain[i]), append(liveReceipts, receiptChain[i])
  948. }
  949. }
  950. var (
  951. stats = struct{ processed, ignored int32 }{}
  952. start = time.Now()
  953. size = 0
  954. )
  955. // updateHead updates the head fast sync block if the inserted blocks are better
  956. // and returns a indicator whether the inserted blocks are canonical.
  957. updateHead := func(head *types.Block) bool {
  958. bc.chainmu.Lock()
  959. // Rewind may have occurred, skip in that case.
  960. if bc.CurrentHeader().Number.Cmp(head.Number()) >= 0 {
  961. currentFastBlock, td := bc.CurrentFastBlock(), bc.GetTd(head.Hash(), head.NumberU64())
  962. if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
  963. rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
  964. bc.currentFastBlock.Store(head)
  965. headFastBlockGauge.Update(int64(head.NumberU64()))
  966. bc.chainmu.Unlock()
  967. return true
  968. }
  969. }
  970. bc.chainmu.Unlock()
  971. return false
  972. }
  973. // writeAncient writes blockchain and corresponding receipt chain into ancient store.
  974. //
  975. // this function only accepts canonical chain data. All side chain will be reverted
  976. // eventually.
  977. writeAncient := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  978. var (
  979. previous = bc.CurrentFastBlock()
  980. batch = bc.db.NewBatch()
  981. )
  982. // If any error occurs before updating the head or we are inserting a side chain,
  983. // all the data written this time wll be rolled back.
  984. defer func() {
  985. if previous != nil {
  986. if err := bc.truncateAncient(previous.NumberU64()); err != nil {
  987. log.Crit("Truncate ancient store failed", "err", err)
  988. }
  989. }
  990. }()
  991. var deleted []*numberHash
  992. for i, block := range blockChain {
  993. // Short circuit insertion if shutting down or processing failed
  994. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  995. return 0, errInsertionInterrupted
  996. }
  997. // Short circuit insertion if it is required(used in testing only)
  998. if bc.terminateInsert != nil && bc.terminateInsert(block.Hash(), block.NumberU64()) {
  999. return i, errors.New("insertion is terminated for testing purpose")
  1000. }
  1001. // Short circuit if the owner header is unknown
  1002. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  1003. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  1004. }
  1005. var (
  1006. start = time.Now()
  1007. logged = time.Now()
  1008. count int
  1009. )
  1010. // Migrate all ancient blocks. This can happen if someone upgrades from Geth
  1011. // 1.8.x to 1.9.x mid-fast-sync. Perhaps we can get rid of this path in the
  1012. // long term.
  1013. for {
  1014. // We can ignore the error here since light client won't hit this code path.
  1015. frozen, _ := bc.db.Ancients()
  1016. if frozen >= block.NumberU64() {
  1017. break
  1018. }
  1019. h := rawdb.ReadCanonicalHash(bc.db, frozen)
  1020. b := rawdb.ReadBlock(bc.db, h, frozen)
  1021. size += rawdb.WriteAncientBlock(bc.db, b, rawdb.ReadReceipts(bc.db, h, frozen, bc.chainConfig), rawdb.ReadTd(bc.db, h, frozen))
  1022. count += 1
  1023. // Always keep genesis block in active database.
  1024. if b.NumberU64() != 0 {
  1025. deleted = append(deleted, &numberHash{b.NumberU64(), b.Hash()})
  1026. }
  1027. if time.Since(logged) > 8*time.Second {
  1028. log.Info("Migrating ancient blocks", "count", count, "elapsed", common.PrettyDuration(time.Since(start)))
  1029. logged = time.Now()
  1030. }
  1031. // Don't collect too much in-memory, write it out every 100K blocks
  1032. if len(deleted) > 100000 {
  1033. // Sync the ancient store explicitly to ensure all data has been flushed to disk.
  1034. if err := bc.db.Sync(); err != nil {
  1035. return 0, err
  1036. }
  1037. // Wipe out canonical block data.
  1038. for _, nh := range deleted {
  1039. rawdb.DeleteBlockWithoutNumber(batch, nh.hash, nh.number)
  1040. rawdb.DeleteCanonicalHash(batch, nh.number)
  1041. }
  1042. if err := batch.Write(); err != nil {
  1043. return 0, err
  1044. }
  1045. batch.Reset()
  1046. // Wipe out side chain too.
  1047. for _, nh := range deleted {
  1048. for _, hash := range rawdb.ReadAllHashes(bc.db, nh.number) {
  1049. rawdb.DeleteBlock(batch, hash, nh.number)
  1050. }
  1051. }
  1052. if err := batch.Write(); err != nil {
  1053. return 0, err
  1054. }
  1055. batch.Reset()
  1056. deleted = deleted[0:]
  1057. }
  1058. }
  1059. if count > 0 {
  1060. log.Info("Migrated ancient blocks", "count", count, "elapsed", common.PrettyDuration(time.Since(start)))
  1061. }
  1062. // Flush data into ancient database.
  1063. size += rawdb.WriteAncientBlock(bc.db, block, receiptChain[i], bc.GetTd(block.Hash(), block.NumberU64()))
  1064. rawdb.WriteTxLookupEntries(batch, block)
  1065. stats.processed++
  1066. }
  1067. // Flush all tx-lookup index data.
  1068. size += batch.ValueSize()
  1069. if err := batch.Write(); err != nil {
  1070. return 0, err
  1071. }
  1072. batch.Reset()
  1073. // Sync the ancient store explicitly to ensure all data has been flushed to disk.
  1074. if err := bc.db.Sync(); err != nil {
  1075. return 0, err
  1076. }
  1077. if !updateHead(blockChain[len(blockChain)-1]) {
  1078. return 0, errors.New("side blocks can't be accepted as the ancient chain data")
  1079. }
  1080. previous = nil // disable rollback explicitly
  1081. // Wipe out canonical block data.
  1082. for _, nh := range deleted {
  1083. rawdb.DeleteBlockWithoutNumber(batch, nh.hash, nh.number)
  1084. rawdb.DeleteCanonicalHash(batch, nh.number)
  1085. }
  1086. for _, block := range blockChain {
  1087. // Always keep genesis block in active database.
  1088. if block.NumberU64() != 0 {
  1089. rawdb.DeleteBlockWithoutNumber(batch, block.Hash(), block.NumberU64())
  1090. rawdb.DeleteCanonicalHash(batch, block.NumberU64())
  1091. }
  1092. }
  1093. if err := batch.Write(); err != nil {
  1094. return 0, err
  1095. }
  1096. batch.Reset()
  1097. // Wipe out side chain too.
  1098. for _, nh := range deleted {
  1099. for _, hash := range rawdb.ReadAllHashes(bc.db, nh.number) {
  1100. rawdb.DeleteBlock(batch, hash, nh.number)
  1101. }
  1102. }
  1103. for _, block := range blockChain {
  1104. // Always keep genesis block in active database.
  1105. if block.NumberU64() != 0 {
  1106. for _, hash := range rawdb.ReadAllHashes(bc.db, block.NumberU64()) {
  1107. rawdb.DeleteBlock(batch, hash, block.NumberU64())
  1108. }
  1109. }
  1110. }
  1111. if err := batch.Write(); err != nil {
  1112. return 0, err
  1113. }
  1114. return 0, nil
  1115. }
  1116. // writeLive writes blockchain and corresponding receipt chain into active store.
  1117. writeLive := func(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  1118. batch := bc.db.NewBatch()
  1119. for i, block := range blockChain {
  1120. // Short circuit insertion if shutting down or processing failed
  1121. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1122. return 0, errInsertionInterrupted
  1123. }
  1124. // Short circuit if the owner header is unknown
  1125. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  1126. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  1127. }
  1128. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  1129. stats.ignored++
  1130. continue
  1131. }
  1132. // Write all the data out into the database
  1133. rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
  1134. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receiptChain[i])
  1135. rawdb.WriteTxLookupEntries(batch, block)
  1136. // Write everything belongs to the blocks into the database. So that
  1137. // we can ensure all components of body is completed(body, receipts,
  1138. // tx indexes)
  1139. if batch.ValueSize() >= ethdb.IdealBatchSize {
  1140. if err := batch.Write(); err != nil {
  1141. return 0, err
  1142. }
  1143. size += batch.ValueSize()
  1144. batch.Reset()
  1145. }
  1146. stats.processed++
  1147. }
  1148. // Write everything belongs to the blocks into the database. So that
  1149. // we can ensure all components of body is completed(body, receipts,
  1150. // tx indexes)
  1151. if batch.ValueSize() > 0 {
  1152. size += batch.ValueSize()
  1153. if err := batch.Write(); err != nil {
  1154. return 0, err
  1155. }
  1156. }
  1157. updateHead(blockChain[len(blockChain)-1])
  1158. return 0, nil
  1159. }
  1160. // Write downloaded chain data and corresponding receipt chain data.
  1161. if len(ancientBlocks) > 0 {
  1162. if n, err := writeAncient(ancientBlocks, ancientReceipts); err != nil {
  1163. if err == errInsertionInterrupted {
  1164. return 0, nil
  1165. }
  1166. return n, err
  1167. }
  1168. }
  1169. if len(liveBlocks) > 0 {
  1170. if n, err := writeLive(liveBlocks, liveReceipts); err != nil {
  1171. if err == errInsertionInterrupted {
  1172. return 0, nil
  1173. }
  1174. return n, err
  1175. }
  1176. }
  1177. head := blockChain[len(blockChain)-1]
  1178. context := []interface{}{
  1179. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  1180. "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(int64(head.Time()), 0)),
  1181. "size", common.StorageSize(size),
  1182. }
  1183. if stats.ignored > 0 {
  1184. context = append(context, []interface{}{"ignored", stats.ignored}...)
  1185. }
  1186. log.Info("Imported new block receipts", context...)
  1187. return 0, nil
  1188. }
  1189. var lastWrite uint64
  1190. // writeBlockWithoutState writes only the block and its metadata to the database,
  1191. // but does not write any state. This is used to construct competing side forks
  1192. // up to the point where they exceed the canonical total difficulty.
  1193. func (bc *BlockChain) writeBlockWithoutState(block *types.Block, td *big.Int) (err error) {
  1194. bc.wg.Add(1)
  1195. defer bc.wg.Done()
  1196. batch := bc.db.NewBatch()
  1197. rawdb.WriteTd(batch, block.Hash(), block.NumberU64(), td)
  1198. rawdb.WriteBlock(batch, block)
  1199. if err := batch.Write(); err != nil {
  1200. log.Crit("Failed to write block into disk", "err", err)
  1201. }
  1202. return nil
  1203. }
  1204. // writeKnownBlock updates the head block flag with a known block
  1205. // and introduces chain reorg if necessary.
  1206. func (bc *BlockChain) writeKnownBlock(block *types.Block) error {
  1207. bc.wg.Add(1)
  1208. defer bc.wg.Done()
  1209. current := bc.CurrentBlock()
  1210. if block.ParentHash() != current.Hash() {
  1211. if err := bc.reorg(current, block); err != nil {
  1212. return err
  1213. }
  1214. }
  1215. bc.writeHeadBlock(block)
  1216. return nil
  1217. }
  1218. // WriteBlockWithState writes the block and all associated state to the database.
  1219. func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, emitHeadEvent bool) (status WriteStatus, err error) {
  1220. bc.chainmu.Lock()
  1221. defer bc.chainmu.Unlock()
  1222. return bc.writeBlockWithState(block, receipts, logs, state, emitHeadEvent)
  1223. }
  1224. // writeBlockWithState writes the block and all associated state to the database,
  1225. // but is expects the chain mutex to be held.
  1226. func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, logs []*types.Log, state *state.StateDB, emitHeadEvent bool) (status WriteStatus, err error) {
  1227. bc.wg.Add(1)
  1228. defer bc.wg.Done()
  1229. // Calculate the total difficulty of the block
  1230. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1231. if ptd == nil {
  1232. return NonStatTy, consensus.ErrUnknownAncestor
  1233. }
  1234. // Make sure no inconsistent state is leaked during insertion
  1235. currentBlock := bc.CurrentBlock()
  1236. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  1237. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  1238. // Irrelevant of the canonical status, write the block itself to the database.
  1239. //
  1240. // Note all the components of block(td, hash->number map, header, body, receipts)
  1241. // should be written atomically. BlockBatch is used for containing all components.
  1242. blockBatch := bc.db.NewBatch()
  1243. rawdb.WriteTd(blockBatch, block.Hash(), block.NumberU64(), externTd)
  1244. rawdb.WriteBlock(blockBatch, block)
  1245. rawdb.WriteReceipts(blockBatch, block.Hash(), block.NumberU64(), receipts)
  1246. rawdb.WritePreimages(blockBatch, state.Preimages())
  1247. if err := blockBatch.Write(); err != nil {
  1248. log.Crit("Failed to write block into disk", "err", err)
  1249. }
  1250. // Commit all cached state changes into underlying memory database.
  1251. root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
  1252. if err != nil {
  1253. return NonStatTy, err
  1254. }
  1255. triedb := bc.stateCache.TrieDB()
  1256. // If we're running an archive node, always flush
  1257. if bc.cacheConfig.TrieDirtyDisabled {
  1258. if err := triedb.Commit(root, false); err != nil {
  1259. return NonStatTy, err
  1260. }
  1261. } else {
  1262. // Full but not archive node, do proper garbage collection
  1263. triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
  1264. bc.triegc.Push(root, -int64(block.NumberU64()))
  1265. if current := block.NumberU64(); current > TriesInMemory {
  1266. // If we exceeded our memory allowance, flush matured singleton nodes to disk
  1267. var (
  1268. nodes, imgs = triedb.Size()
  1269. limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
  1270. )
  1271. if nodes > limit || imgs > 4*1024*1024 {
  1272. triedb.Cap(limit - ethdb.IdealBatchSize)
  1273. }
  1274. // Find the next state trie we need to commit
  1275. chosen := current - TriesInMemory
  1276. // If we exceeded out time allowance, flush an entire trie to disk
  1277. if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
  1278. canWrite := true
  1279. if posa, ok := bc.engine.(consensus.PoSA); ok {
  1280. if !posa.EnoughDistance(bc, block.Header()) {
  1281. canWrite = false
  1282. }
  1283. }
  1284. if canWrite {
  1285. // If the header is missing (canonical chain behind), we're reorging a low
  1286. // diff sidechain. Suspend committing until this operation is completed.
  1287. header := bc.GetHeaderByNumber(chosen)
  1288. if header == nil {
  1289. log.Warn("Reorg in progress, trie commit postponed", "number", chosen)
  1290. } else {
  1291. // If we're exceeding limits but haven't reached a large enough memory gap,
  1292. // warn the user that the system is becoming unstable.
  1293. if chosen < lastWrite+TriesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
  1294. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/TriesInMemory)
  1295. }
  1296. // Flush an entire trie and restart the counters
  1297. triedb.Commit(header.Root, true)
  1298. lastWrite = chosen
  1299. bc.gcproc = 0
  1300. }
  1301. }
  1302. }
  1303. // Garbage collect anything below our required write retention
  1304. for !bc.triegc.Empty() {
  1305. root, number := bc.triegc.Pop()
  1306. if uint64(-number) > chosen {
  1307. bc.triegc.Push(root, number)
  1308. break
  1309. }
  1310. triedb.Dereference(root.(common.Hash))
  1311. }
  1312. }
  1313. }
  1314. // If the total difficulty is higher than our known, add it to the canonical chain
  1315. // Second clause in the if statement reduces the vulnerability to selfish mining.
  1316. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  1317. reorg := externTd.Cmp(localTd) > 0
  1318. currentBlock = bc.CurrentBlock()
  1319. if !reorg && externTd.Cmp(localTd) == 0 {
  1320. // Split same-difficulty blocks by number, then preferentially select
  1321. // the block generated by the local miner as the canonical block.
  1322. if block.NumberU64() < currentBlock.NumberU64() {
  1323. reorg = true
  1324. } else if block.NumberU64() == currentBlock.NumberU64() {
  1325. var currentPreserve, blockPreserve bool
  1326. if bc.shouldPreserve != nil {
  1327. currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  1328. }
  1329. reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  1330. }
  1331. }
  1332. if reorg {
  1333. // Reorganise the chain if the parent is not the head block
  1334. if block.ParentHash() != currentBlock.Hash() {
  1335. if err := bc.reorg(currentBlock, block); err != nil {
  1336. return NonStatTy, err
  1337. }
  1338. }
  1339. status = CanonStatTy
  1340. } else {
  1341. status = SideStatTy
  1342. }
  1343. // Set new head.
  1344. if status == CanonStatTy {
  1345. bc.writeHeadBlock(block)
  1346. }
  1347. bc.futureBlocks.Remove(block.Hash())
  1348. if status == CanonStatTy {
  1349. bc.chainFeed.Send(ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
  1350. if len(logs) > 0 {
  1351. bc.logsFeed.Send(logs)
  1352. }
  1353. // In theory we should fire a ChainHeadEvent when we inject
  1354. // a canonical block, but sometimes we can insert a batch of
  1355. // canonicial blocks. Avoid firing too much ChainHeadEvents,
  1356. // we will fire an accumulated ChainHeadEvent and disable fire
  1357. // event here.
  1358. if emitHeadEvent {
  1359. bc.chainHeadFeed.Send(ChainHeadEvent{Block: block})
  1360. }
  1361. } else {
  1362. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1363. }
  1364. return status, nil
  1365. }
  1366. // addFutureBlock checks if the block is within the max allowed window to get
  1367. // accepted for future processing, and returns an error if the block is too far
  1368. // ahead and was not added.
  1369. func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  1370. max := uint64(time.Now().Unix() + maxTimeFutureBlocks)
  1371. if block.Time() > max {
  1372. return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  1373. }
  1374. bc.futureBlocks.Add(block.Hash(), block)
  1375. return nil
  1376. }
  1377. // InsertChain attempts to insert the given batch of blocks in to the canonical
  1378. // chain or, otherwise, create a fork. If an error is returned it will return
  1379. // the index number of the failing block as well an error describing what went
  1380. // wrong.
  1381. //
  1382. // After insertion is done, all accumulated events will be fired.
  1383. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  1384. // Sanity check that we have something meaningful to import
  1385. if len(chain) == 0 {
  1386. return 0, nil
  1387. }
  1388. bc.blockProcFeed.Send(true)
  1389. defer bc.blockProcFeed.Send(false)
  1390. // Remove already known canon-blocks
  1391. var (
  1392. block, prev *types.Block
  1393. )
  1394. // Do a sanity check that the provided chain is actually ordered and linked
  1395. for i := 1; i < len(chain); i++ {
  1396. block = chain[i]
  1397. prev = chain[i-1]
  1398. if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() {
  1399. // Chain broke ancestry, log a message (programming error) and skip insertion
  1400. log.Error("Non contiguous block insert", "number", block.Number(), "hash", block.Hash(),
  1401. "parent", block.ParentHash(), "prevnumber", prev.Number(), "prevhash", prev.Hash())
  1402. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, prev.NumberU64(),
  1403. prev.Hash().Bytes()[:4], i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4])
  1404. }
  1405. }
  1406. // Pre-checks passed, start the full block imports
  1407. bc.wg.Add(1)
  1408. bc.chainmu.Lock()
  1409. n, err := bc.insertChain(chain, true)
  1410. bc.chainmu.Unlock()
  1411. bc.wg.Done()
  1412. return n, err
  1413. }
  1414. // insertChain is the internal implementation of InsertChain, which assumes that
  1415. // 1) chains are contiguous, and 2) The chain mutex is held.
  1416. //
  1417. // This method is split out so that import batches that require re-injecting
  1418. // historical blocks can do so without releasing the lock, which could lead to
  1419. // racey behaviour. If a sidechain import is in progress, and the historic state
  1420. // is imported, but then new canon-head is added before the actual sidechain
  1421. // completes, then the historic state could be pruned again
  1422. func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, error) {
  1423. // If the chain is terminating, don't even bother starting up
  1424. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1425. return 0, nil
  1426. }
  1427. // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  1428. senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  1429. var (
  1430. stats = insertStats{startTime: mclock.Now()}
  1431. lastCanon *types.Block
  1432. )
  1433. // Fire a single chain head event if we've progressed the chain
  1434. defer func() {
  1435. if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1436. bc.chainHeadFeed.Send(ChainHeadEvent{lastCanon})
  1437. }
  1438. }()
  1439. // Start the parallel header verifier
  1440. headers := make([]*types.Header, len(chain))
  1441. seals := make([]bool, len(chain))
  1442. for i, block := range chain {
  1443. headers[i] = block.Header()
  1444. seals[i] = verifySeals
  1445. }
  1446. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1447. defer close(abort)
  1448. // Peek the error for the first block to decide the directing import logic
  1449. it := newInsertIterator(chain, results, bc.validator)
  1450. block, err := it.next()
  1451. // Left-trim all the known blocks
  1452. if err == ErrKnownBlock {
  1453. // First block (and state) is known
  1454. // 1. We did a roll-back, and should now do a re-import
  1455. // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1456. // from the canonical chain, which has not been verified.
  1457. // Skip all known blocks that are behind us
  1458. var (
  1459. current = bc.CurrentBlock()
  1460. localTd = bc.GetTd(current.Hash(), current.NumberU64())
  1461. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1) // The first block can't be nil
  1462. )
  1463. for block != nil && err == ErrKnownBlock {
  1464. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1465. if localTd.Cmp(externTd) < 0 {
  1466. break
  1467. }
  1468. log.Debug("Ignoring already known block", "number", block.Number(), "hash", block.Hash())
  1469. stats.ignored++
  1470. block, err = it.next()
  1471. }
  1472. // The remaining blocks are still known blocks, the only scenario here is:
  1473. // During the fast sync, the pivot point is already submitted but rollback
  1474. // happens. Then node resets the head full block to a lower height via `rollback`
  1475. // and leaves a few known blocks in the database.
  1476. //
  1477. // When node runs a fast sync again, it can re-import a batch of known blocks via
  1478. // `insertChain` while a part of them have higher total difficulty than current
  1479. // head full block(new pivot point).
  1480. for block != nil && err == ErrKnownBlock {
  1481. log.Debug("Writing previously known block", "number", block.Number(), "hash", block.Hash())
  1482. if err := bc.writeKnownBlock(block); err != nil {
  1483. return it.index, err
  1484. }
  1485. lastCanon = block
  1486. block, err = it.next()
  1487. }
  1488. // Falls through to the block import
  1489. }
  1490. switch {
  1491. // First block is pruned, insert as sidechain and reorg only if TD grows enough
  1492. case err == consensus.ErrPrunedAncestor:
  1493. log.Debug("Pruned ancestor, inserting as sidechain", "number", block.Number(), "hash", block.Hash())
  1494. return bc.insertSideChain(block, it)
  1495. // First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1496. case err == consensus.ErrFutureBlock || (err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(it.first().ParentHash())):
  1497. for block != nil && (it.index == 0 || err == consensus.ErrUnknownAncestor) {
  1498. log.Debug("Future block, postponing import", "number", block.Number(), "hash", block.Hash())
  1499. if err := bc.addFutureBlock(block); err != nil {
  1500. return it.index, err
  1501. }
  1502. block, err = it.next()
  1503. }
  1504. stats.queued += it.processed()
  1505. stats.ignored += it.remaining()
  1506. // If there are any still remaining, mark as ignored
  1507. return it.index, err
  1508. // Some other error occurred, abort
  1509. case err != nil:
  1510. bc.futureBlocks.Remove(block.Hash())
  1511. stats.ignored += len(it.chain)
  1512. bc.reportBlock(block, nil, err)
  1513. return it.index, err
  1514. }
  1515. // No validation errors for the first block (or chain prefix skipped)
  1516. for ; block != nil && err == nil || err == ErrKnownBlock; block, err = it.next() {
  1517. // If the chain is terminating, stop processing blocks
  1518. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1519. log.Debug("Premature abort during blocks processing")
  1520. break
  1521. }
  1522. // If the header is a banned one, straight out abort
  1523. if BadHashes[block.Hash()] {
  1524. bc.reportBlock(block, nil, ErrBlacklistedHash)
  1525. return it.index, ErrBlacklistedHash
  1526. }
  1527. // If the block is known (in the middle of the chain), it's a special case for
  1528. // Clique blocks where they can share state among each other, so importing an
  1529. // older block might complete the state of the subsequent one. In this case,
  1530. // just skip the block (we already validated it once fully (and crashed), since
  1531. // its header and body was already in the database).
  1532. if err == ErrKnownBlock {
  1533. logger := log.Debug
  1534. if bc.chainConfig.Clique == nil {
  1535. logger = log.Warn
  1536. }
  1537. logger("Inserted known block", "number", block.Number(), "hash", block.Hash(),
  1538. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1539. "root", block.Root())
  1540. if err := bc.writeKnownBlock(block); err != nil {
  1541. return it.index, err
  1542. }
  1543. stats.processed++
  1544. // We can assume that logs are empty here, since the only way for consecutive
  1545. // Clique blocks to have the same state is if there are no transactions.
  1546. lastCanon = block
  1547. continue
  1548. }
  1549. // Retrieve the parent block and it's state to execute on top
  1550. start := time.Now()
  1551. parent := it.previous()
  1552. if parent == nil {
  1553. parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
  1554. }
  1555. statedb, err := state.New(parent.Root, bc.stateCache, bc.snaps)
  1556. if err != nil {
  1557. return it.index, err
  1558. }
  1559. // If we have a followup block, run that against the current state to pre-cache
  1560. // transactions and probabilistically some of the account/storage trie nodes.
  1561. var followupInterrupt uint32
  1562. if !bc.cacheConfig.TrieCleanNoPrefetch {
  1563. if followup, err := it.peek(); followup != nil && err == nil {
  1564. throwaway, _ := state.New(parent.Root, bc.stateCache, bc.snaps)
  1565. go func(start time.Time, followup *types.Block, throwaway *state.StateDB, interrupt *uint32) {
  1566. bc.prefetcher.Prefetch(followup, throwaway, bc.vmConfig, &followupInterrupt)
  1567. blockPrefetchExecuteTimer.Update(time.Since(start))
  1568. if atomic.LoadUint32(interrupt) == 1 {
  1569. blockPrefetchInterruptMeter.Mark(1)
  1570. }
  1571. }(time.Now(), followup, throwaway, &followupInterrupt)
  1572. }
  1573. }
  1574. // Process block using the parent state as reference point
  1575. substart := time.Now()
  1576. receipts, logs, usedGas, err := bc.processor.Process(block, statedb, bc.vmConfig)
  1577. if err != nil {
  1578. bc.reportBlock(block, receipts, err)
  1579. atomic.StoreUint32(&followupInterrupt, 1)
  1580. return it.index, err
  1581. }
  1582. bc.CacheReceipts(block.Hash(), receipts)
  1583. // Update the metrics touched during block processing
  1584. accountReadTimer.Update(statedb.AccountReads) // Account reads are complete, we can mark them
  1585. storageReadTimer.Update(statedb.StorageReads) // Storage reads are complete, we can mark them
  1586. accountUpdateTimer.Update(statedb.AccountUpdates) // Account updates are complete, we can mark them
  1587. storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them
  1588. snapshotAccountReadTimer.Update(statedb.SnapshotAccountReads) // Account reads are complete, we can mark them
  1589. snapshotStorageReadTimer.Update(statedb.SnapshotStorageReads) // Storage reads are complete, we can mark them
  1590. triehash := statedb.AccountHashes + statedb.StorageHashes // Save to not double count in validation
  1591. trieproc := statedb.SnapshotAccountReads + statedb.AccountReads + statedb.AccountUpdates
  1592. trieproc += statedb.SnapshotStorageReads + statedb.StorageReads + statedb.StorageUpdates
  1593. blockExecutionTimer.Update(time.Since(substart) - trieproc - triehash)
  1594. // Validate the state using the default validator
  1595. substart = time.Now()
  1596. if err := bc.validator.ValidateState(block, statedb, receipts, usedGas); err != nil {
  1597. bc.reportBlock(block, receipts, err)
  1598. atomic.StoreUint32(&followupInterrupt, 1)
  1599. return it.index, err
  1600. }
  1601. proctime := time.Since(start)
  1602. // Update the metrics touched during block validation
  1603. accountHashTimer.Update(statedb.AccountHashes) // Account hashes are complete, we can mark them
  1604. storageHashTimer.Update(statedb.StorageHashes) // Storage hashes are complete, we can mark them
  1605. blockValidationTimer.Update(time.Since(substart) - (statedb.AccountHashes + statedb.StorageHashes - triehash))
  1606. // Write the block to the chain and get the status.
  1607. substart = time.Now()
  1608. status, err := bc.writeBlockWithState(block, receipts, logs, statedb, false)
  1609. atomic.StoreUint32(&followupInterrupt, 1)
  1610. if err != nil {
  1611. return it.index, err
  1612. }
  1613. // Update the metrics touched during block commit
  1614. accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them
  1615. storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them
  1616. snapshotCommitTimer.Update(statedb.SnapshotCommits) // Snapshot commits are complete, we can mark them
  1617. blockWriteTimer.Update(time.Since(substart) - statedb.AccountCommits - statedb.StorageCommits - statedb.SnapshotCommits)
  1618. blockInsertTimer.UpdateSince(start)
  1619. switch status {
  1620. case CanonStatTy:
  1621. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1622. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1623. "elapsed", common.PrettyDuration(time.Since(start)),
  1624. "root", block.Root())
  1625. lastCanon = block
  1626. // Only count canonical blocks for GC processing time
  1627. bc.gcproc += proctime
  1628. case SideStatTy:
  1629. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1630. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1631. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1632. "root", block.Root())
  1633. default:
  1634. // This in theory is impossible, but lets be nice to our future selves and leave
  1635. // a log, instead of trying to track down blocks imports that don't emit logs.
  1636. log.Warn("Inserted block with unknown status", "number", block.Number(), "hash", block.Hash(),
  1637. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1638. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1639. "root", block.Root())
  1640. }
  1641. stats.processed++
  1642. stats.usedGas += usedGas
  1643. dirty, _ := bc.stateCache.TrieDB().Size()
  1644. stats.report(chain, it.index, dirty)
  1645. }
  1646. // Any blocks remaining here? The only ones we care about are the future ones
  1647. if block != nil && err == consensus.ErrFutureBlock {
  1648. if err := bc.addFutureBlock(block); err != nil {
  1649. return it.index, err
  1650. }
  1651. block, err = it.next()
  1652. for ; block != nil && err == consensus.ErrUnknownAncestor; block, err = it.next() {
  1653. if err := bc.addFutureBlock(block); err != nil {
  1654. return it.index, err
  1655. }
  1656. stats.queued++
  1657. }
  1658. }
  1659. stats.ignored += it.remaining()
  1660. return it.index, err
  1661. }
  1662. // insertSideChain is called when an import batch hits upon a pruned ancestor
  1663. // error, which happens when a sidechain with a sufficiently old fork-block is
  1664. // found.
  1665. //
  1666. // The method writes all (header-and-body-valid) blocks to disk, then tries to
  1667. // switch over to the new chain if the TD exceeded the current chain.
  1668. func (bc *BlockChain) insertSideChain(block *types.Block, it *insertIterator) (int, error) {
  1669. var (
  1670. externTd *big.Int
  1671. current = bc.CurrentBlock()
  1672. )
  1673. // The first sidechain block error is already verified to be ErrPrunedAncestor.
  1674. // Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  1675. // ones. Any other errors means that the block is invalid, and should not be written
  1676. // to disk.
  1677. err := consensus.ErrPrunedAncestor
  1678. for ; block != nil && (err == consensus.ErrPrunedAncestor); block, err = it.next() {
  1679. // Check the canonical state root for that number
  1680. if number := block.NumberU64(); current.NumberU64() >= number {
  1681. canonical := bc.GetBlockByNumber(number)
  1682. if canonical != nil && canonical.Hash() == block.Hash() {
  1683. // Not a sidechain block, this is a re-import of a canon block which has it's state pruned
  1684. // Collect the TD of the block. Since we know it's a canon one,
  1685. // we can get it directly, and not (like further below) use
  1686. // the parent and then add the block on top
  1687. externTd = bc.GetTd(block.Hash(), block.NumberU64())
  1688. continue
  1689. }
  1690. if canonical != nil && canonical.Root() == block.Root() {
  1691. // This is most likely a shadow-state attack. When a fork is imported into the
  1692. // database, and it eventually reaches a block height which is not pruned, we
  1693. // just found that the state already exist! This means that the sidechain block
  1694. // refers to a state which already exists in our canon chain.
  1695. //
  1696. // If left unchecked, we would now proceed importing the blocks, without actually
  1697. // having verified the state of the previous blocks.
  1698. log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  1699. // If someone legitimately side-mines blocks, they would still be imported as usual. However,
  1700. // we cannot risk writing unverified blocks to disk when they obviously target the pruning
  1701. // mechanism.
  1702. return it.index, errors.New("sidechain ghost-state attack")
  1703. }
  1704. }
  1705. if externTd == nil {
  1706. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1707. }
  1708. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1709. if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  1710. start := time.Now()
  1711. if err := bc.writeBlockWithoutState(block, externTd); err != nil {
  1712. return it.index, err
  1713. }
  1714. log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(),
  1715. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1716. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1717. "root", block.Root())
  1718. }
  1719. }
  1720. // At this point, we've written all sidechain blocks to database. Loop ended
  1721. // either on some other error or all were processed. If there was some other
  1722. // error, we can ignore the rest of those blocks.
  1723. //
  1724. // If the externTd was larger than our local TD, we now need to reimport the previous
  1725. // blocks to regenerate the required state
  1726. localTd := bc.GetTd(current.Hash(), current.NumberU64())
  1727. if localTd.Cmp(externTd) > 0 {
  1728. log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().Number, "sidetd", externTd, "localtd", localTd)
  1729. return it.index, err
  1730. }
  1731. // Gather all the sidechain hashes (full blocks may be memory heavy)
  1732. var (
  1733. hashes []common.Hash
  1734. numbers []uint64
  1735. )
  1736. parent := it.previous()
  1737. for parent != nil && !bc.HasState(parent.Root) {
  1738. hashes = append(hashes, parent.Hash())
  1739. numbers = append(numbers, parent.Number.Uint64())
  1740. parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  1741. }
  1742. if parent == nil {
  1743. return it.index, errors.New("missing parent")
  1744. }
  1745. // Import all the pruned blocks to make the state available
  1746. var (
  1747. blocks []*types.Block
  1748. memory common.StorageSize
  1749. )
  1750. for i := len(hashes) - 1; i >= 0; i-- {
  1751. // Append the next block to our batch
  1752. block := bc.GetBlock(hashes[i], numbers[i])
  1753. blocks = append(blocks, block)
  1754. memory += block.Size()
  1755. // If memory use grew too large, import and continue. Sadly we need to discard
  1756. // all raised events and logs from notifications since we're too heavy on the
  1757. // memory here.
  1758. if len(blocks) >= 2048 || memory > 64*1024*1024 {
  1759. log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  1760. if _, err := bc.insertChain(blocks, false); err != nil {
  1761. return 0, err
  1762. }
  1763. blocks, memory = blocks[:0], 0
  1764. // If the chain is terminating, stop processing blocks
  1765. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1766. log.Debug("Premature abort during blocks processing")
  1767. return 0, nil
  1768. }
  1769. }
  1770. }
  1771. if len(blocks) > 0 {
  1772. log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  1773. return bc.insertChain(blocks, false)
  1774. }
  1775. return 0, nil
  1776. }
  1777. // reorg takes two blocks, an old chain and a new chain and will reconstruct the
  1778. // blocks and inserts them to be part of the new canonical chain and accumulates
  1779. // potential missing transactions and post an event about them.
  1780. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1781. var (
  1782. newChain types.Blocks
  1783. oldChain types.Blocks
  1784. commonBlock *types.Block
  1785. deletedTxs types.Transactions
  1786. addedTxs types.Transactions
  1787. deletedLogs [][]*types.Log
  1788. rebirthLogs [][]*types.Log
  1789. // collectLogs collects the logs that were generated or removed during
  1790. // the processing of the block that corresponds with the given hash.
  1791. // These logs are later announced as deleted or reborn
  1792. collectLogs = func(hash common.Hash, removed bool) {
  1793. number := bc.hc.GetBlockNumber(hash)
  1794. if number == nil {
  1795. return
  1796. }
  1797. receipts := rawdb.ReadReceipts(bc.db, hash, *number, bc.chainConfig)
  1798. var logs []*types.Log
  1799. for _, receipt := range receipts {
  1800. for _, log := range receipt.Logs {
  1801. l := *log
  1802. if removed {
  1803. l.Removed = true
  1804. } else {
  1805. }
  1806. logs = append(logs, &l)
  1807. }
  1808. }
  1809. if len(logs) > 0 {
  1810. if removed {
  1811. deletedLogs = append(deletedLogs, logs)
  1812. } else {
  1813. rebirthLogs = append(rebirthLogs, logs)
  1814. }
  1815. }
  1816. }
  1817. // mergeLogs returns a merged log slice with specified sort order.
  1818. mergeLogs = func(logs [][]*types.Log, reverse bool) []*types.Log {
  1819. var ret []*types.Log
  1820. if reverse {
  1821. for i := len(logs) - 1; i >= 0; i-- {
  1822. ret = append(ret, logs[i]...)
  1823. }
  1824. } else {
  1825. for i := 0; i < len(logs); i++ {
  1826. ret = append(ret, logs[i]...)
  1827. }
  1828. }
  1829. return ret
  1830. }
  1831. )
  1832. // Reduce the longer chain to the same number as the shorter one
  1833. if oldBlock.NumberU64() > newBlock.NumberU64() {
  1834. // Old chain is longer, gather all transactions and logs as deleted ones
  1835. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  1836. oldChain = append(oldChain, oldBlock)
  1837. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1838. collectLogs(oldBlock.Hash(), true)
  1839. }
  1840. } else {
  1841. // New chain is longer, stash all blocks away for subsequent insertion
  1842. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1843. newChain = append(newChain, newBlock)
  1844. }
  1845. }
  1846. if oldBlock == nil {
  1847. return fmt.Errorf("invalid old chain")
  1848. }
  1849. if newBlock == nil {
  1850. return fmt.Errorf("invalid new chain")
  1851. }
  1852. // Both sides of the reorg are at the same number, reduce both until the common
  1853. // ancestor is found
  1854. for {
  1855. // If the common ancestor was found, bail out
  1856. if oldBlock.Hash() == newBlock.Hash() {
  1857. commonBlock = oldBlock
  1858. break
  1859. }
  1860. // Remove an old block as well as stash away a new block
  1861. oldChain = append(oldChain, oldBlock)
  1862. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1863. collectLogs(oldBlock.Hash(), true)
  1864. newChain = append(newChain, newBlock)
  1865. // Step back with both chains
  1866. oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1)
  1867. if oldBlock == nil {
  1868. return fmt.Errorf("invalid old chain")
  1869. }
  1870. newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1871. if newBlock == nil {
  1872. return fmt.Errorf("invalid new chain")
  1873. }
  1874. }
  1875. // Ensure the user sees large reorgs
  1876. if len(oldChain) > 0 && len(newChain) > 0 {
  1877. logFn := log.Info
  1878. msg := "Chain reorg detected"
  1879. if len(oldChain) > 63 {
  1880. msg = "Large chain reorg detected"
  1881. logFn = log.Warn
  1882. }
  1883. logFn(msg, "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1884. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1885. blockReorgAddMeter.Mark(int64(len(newChain)))
  1886. blockReorgDropMeter.Mark(int64(len(oldChain)))
  1887. } else {
  1888. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1889. }
  1890. // Insert the new chain(except the head block(reverse order)),
  1891. // taking care of the proper incremental order.
  1892. for i := len(newChain) - 1; i >= 1; i-- {
  1893. // Insert the block in the canonical way, re-writing history
  1894. bc.writeHeadBlock(newChain[i])
  1895. // Collect reborn logs due to chain reorg
  1896. collectLogs(newChain[i].Hash(), false)
  1897. // Collect the new added transactions.
  1898. addedTxs = append(addedTxs, newChain[i].Transactions()...)
  1899. }
  1900. // Delete useless indexes right now which includes the non-canonical
  1901. // transaction indexes, canonical chain indexes which above the head.
  1902. indexesBatch := bc.db.NewBatch()
  1903. for _, tx := range types.TxDifference(deletedTxs, addedTxs) {
  1904. rawdb.DeleteTxLookupEntry(indexesBatch, tx.Hash())
  1905. }
  1906. // Delete any canonical number assignments above the new head
  1907. number := bc.CurrentBlock().NumberU64()
  1908. for i := number + 1; ; i++ {
  1909. hash := rawdb.ReadCanonicalHash(bc.db, i)
  1910. if hash == (common.Hash{}) {
  1911. break
  1912. }
  1913. rawdb.DeleteCanonicalHash(indexesBatch, i)
  1914. }
  1915. if err := indexesBatch.Write(); err != nil {
  1916. log.Crit("Failed to delete useless indexes", "err", err)
  1917. }
  1918. // If any logs need to be fired, do it now. In theory we could avoid creating
  1919. // this goroutine if there are no events to fire, but realistcally that only
  1920. // ever happens if we're reorging empty blocks, which will only happen on idle
  1921. // networks where performance is not an issue either way.
  1922. if len(deletedLogs) > 0 {
  1923. bc.rmLogsFeed.Send(RemovedLogsEvent{mergeLogs(deletedLogs, true)})
  1924. }
  1925. if len(rebirthLogs) > 0 {
  1926. bc.logsFeed.Send(mergeLogs(rebirthLogs, false))
  1927. }
  1928. if len(oldChain) > 0 {
  1929. for i := len(oldChain) - 1; i >= 0; i-- {
  1930. bc.chainSideFeed.Send(ChainSideEvent{Block: oldChain[i]})
  1931. }
  1932. }
  1933. return nil
  1934. }
  1935. func (bc *BlockChain) update() {
  1936. futureTimer := time.NewTicker(5 * time.Second)
  1937. defer futureTimer.Stop()
  1938. for {
  1939. select {
  1940. case <-futureTimer.C:
  1941. bc.procFutureBlocks()
  1942. case <-bc.quit:
  1943. return
  1944. }
  1945. }
  1946. }
  1947. // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1948. func (bc *BlockChain) BadBlocks() []*types.Block {
  1949. blocks := make([]*types.Block, 0, bc.badBlocks.Len())
  1950. for _, hash := range bc.badBlocks.Keys() {
  1951. if blk, exist := bc.badBlocks.Peek(hash); exist {
  1952. block := blk.(*types.Block)
  1953. blocks = append(blocks, block)
  1954. }
  1955. }
  1956. return blocks
  1957. }
  1958. // addBadBlock adds a bad block to the bad-block LRU cache
  1959. func (bc *BlockChain) addBadBlock(block *types.Block) {
  1960. bc.badBlocks.Add(block.Hash(), block)
  1961. }
  1962. // reportBlock logs a bad block error.
  1963. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1964. bc.addBadBlock(block)
  1965. var receiptString string
  1966. for i, receipt := range receipts {
  1967. receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  1968. i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  1969. receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  1970. }
  1971. log.Error(fmt.Sprintf(`
  1972. ########## BAD BLOCK #########
  1973. Chain config: %v
  1974. Number: %v
  1975. Hash: 0x%x
  1976. %v
  1977. Error: %v
  1978. ##############################
  1979. `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  1980. }
  1981. // InsertHeaderChain attempts to insert the given header chain in to the local
  1982. // chain, possibly creating a reorg. If an error is returned, it will return the
  1983. // index number of the failing header as well an error describing what went wrong.
  1984. //
  1985. // The verify parameter can be used to fine tune whether nonce verification
  1986. // should be done or not. The reason behind the optional check is because some
  1987. // of the header retrieval mechanisms already need to verify nonces, as well as
  1988. // because nonces can be verified sparsely, not needing to check each.
  1989. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1990. start := time.Now()
  1991. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1992. return i, err
  1993. }
  1994. // Make sure only one thread manipulates the chain at once
  1995. bc.chainmu.Lock()
  1996. defer bc.chainmu.Unlock()
  1997. bc.wg.Add(1)
  1998. defer bc.wg.Done()
  1999. whFunc := func(header *types.Header) error {
  2000. _, err := bc.hc.WriteHeader(header)
  2001. return err
  2002. }
  2003. return bc.hc.InsertHeaderChain(chain, whFunc, start)
  2004. }
  2005. // CurrentHeader retrieves the current head header of the canonical chain. The
  2006. // header is retrieved from the HeaderChain's internal cache.
  2007. func (bc *BlockChain) CurrentHeader() *types.Header {
  2008. return bc.hc.CurrentHeader()
  2009. }
  2010. // GetTd retrieves a block's total difficulty in the canonical chain from the
  2011. // database by hash and number, caching it if found.
  2012. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  2013. return bc.hc.GetTd(hash, number)
  2014. }
  2015. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  2016. // database by hash, caching it if found.
  2017. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  2018. return bc.hc.GetTdByHash(hash)
  2019. }
  2020. // GetHeader retrieves a block header from the database by hash and number,
  2021. // caching it if found.
  2022. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  2023. return bc.hc.GetHeader(hash, number)
  2024. }
  2025. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  2026. // found.
  2027. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  2028. return bc.hc.GetHeaderByHash(hash)
  2029. }
  2030. // HasHeader checks if a block header is present in the database or not, caching
  2031. // it if present.
  2032. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  2033. return bc.hc.HasHeader(hash, number)
  2034. }
  2035. // GetCanonicalHash returns the canonical hash for a given block number
  2036. func (bc *BlockChain) GetCanonicalHash(number uint64) common.Hash {
  2037. return bc.hc.GetCanonicalHash(number)
  2038. }
  2039. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  2040. // hash, fetching towards the genesis block.
  2041. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  2042. return bc.hc.GetBlockHashesFromHash(hash, max)
  2043. }
  2044. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  2045. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  2046. // number of blocks to be individually checked before we reach the canonical chain.
  2047. //
  2048. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  2049. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  2050. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  2051. }
  2052. // GetHeaderByNumber retrieves a block header from the database by number,
  2053. // caching it (associated with its hash) if found.
  2054. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  2055. return bc.hc.GetHeaderByNumber(number)
  2056. }
  2057. // GetTransactionLookup retrieves the lookup associate with the given transaction
  2058. // hash from the cache or database.
  2059. func (bc *BlockChain) GetTransactionLookup(hash common.Hash) *rawdb.LegacyTxLookupEntry {
  2060. // Short circuit if the txlookup already in the cache, retrieve otherwise
  2061. if lookup, exist := bc.txLookupCache.Get(hash); exist {
  2062. return lookup.(*rawdb.LegacyTxLookupEntry)
  2063. }
  2064. tx, blockHash, blockNumber, txIndex := rawdb.ReadTransaction(bc.db, hash)
  2065. if tx == nil {
  2066. return nil
  2067. }
  2068. lookup := &rawdb.LegacyTxLookupEntry{BlockHash: blockHash, BlockIndex: blockNumber, Index: txIndex}
  2069. bc.txLookupCache.Add(hash, lookup)
  2070. return lookup
  2071. }
  2072. // Config retrieves the chain's fork configuration.
  2073. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  2074. // Engine retrieves the blockchain's consensus engine.
  2075. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  2076. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  2077. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  2078. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  2079. }
  2080. // SubscribeChainEvent registers a subscription of ChainEvent.
  2081. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  2082. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  2083. }
  2084. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  2085. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  2086. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  2087. }
  2088. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  2089. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  2090. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  2091. }
  2092. // SubscribeLogsEvent registers a subscription of []*types.Log.
  2093. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  2094. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  2095. }
  2096. // SubscribeBlockProcessingEvent registers a subscription of bool where true means
  2097. // block processing has started while false means it has stopped.
  2098. func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription {
  2099. return bc.scope.Track(bc.blockProcFeed.Subscribe(ch))
  2100. }