blockchain.go 82 KB

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