blockchain.go 82 KB

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