blockchain.go 94 KB

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