blockchain.go 81 KB

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