blockchain.go 82 KB

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