blockchain.go 86 KB

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