blockchain.go 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package core implements the Ethereum consensus protocol.
  17. package core
  18. import (
  19. "errors"
  20. "fmt"
  21. "io"
  22. "math/big"
  23. mrand "math/rand"
  24. "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/mclock"
  29. "github.com/ethereum/go-ethereum/common/prque"
  30. "github.com/ethereum/go-ethereum/consensus"
  31. "github.com/ethereum/go-ethereum/core/rawdb"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/crypto"
  36. "github.com/ethereum/go-ethereum/ethdb"
  37. "github.com/ethereum/go-ethereum/event"
  38. "github.com/ethereum/go-ethereum/log"
  39. "github.com/ethereum/go-ethereum/metrics"
  40. "github.com/ethereum/go-ethereum/params"
  41. "github.com/ethereum/go-ethereum/rlp"
  42. "github.com/ethereum/go-ethereum/trie"
  43. lru "github.com/hashicorp/golang-lru"
  44. )
  45. var (
  46. blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil)
  47. blockValidationTimer = metrics.NewRegisteredTimer("chain/validation", nil)
  48. blockExecutionTimer = metrics.NewRegisteredTimer("chain/execution", nil)
  49. blockWriteTimer = metrics.NewRegisteredTimer("chain/write", nil)
  50. ErrNoGenesis = errors.New("Genesis not found in chain")
  51. )
  52. const (
  53. bodyCacheLimit = 256
  54. blockCacheLimit = 256
  55. receiptsCacheLimit = 32
  56. maxFutureBlocks = 256
  57. maxTimeFutureBlocks = 30
  58. badBlockLimit = 10
  59. triesInMemory = 128
  60. // BlockChainVersion ensures that an incompatible database forces a resync from scratch.
  61. //
  62. // During the process of upgrading the database version from 3 to 4,
  63. // the following incompatible database changes were added.
  64. // * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted
  65. // * the `Bloom` field of receipt is deleted
  66. // * the `BlockIndex` and `TxIndex` fields of txlookup are deleted
  67. BlockChainVersion uint64 = 4
  68. )
  69. // CacheConfig contains the configuration values for the trie caching/pruning
  70. // that's resident in a blockchain.
  71. type CacheConfig struct {
  72. Disabled bool // Whether to disable trie write caching (archive node)
  73. TrieCleanLimit int // Memory allowance (MB) to use for caching trie nodes in memory
  74. TrieDirtyLimit int // Memory limit (MB) at which to start flushing dirty trie nodes to disk
  75. TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
  76. }
  77. // BlockChain represents the canonical chain given a database with a genesis
  78. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  79. //
  80. // Importing blocks in to the block chain happens according to the set of rules
  81. // defined by the two stage Validator. Processing of blocks is done using the
  82. // Processor which processes the included transaction. The validation of the state
  83. // is done in the second part of the Validator. Failing results in aborting of
  84. // the import.
  85. //
  86. // The BlockChain also helps in returning blocks from **any** chain included
  87. // in the database as well as blocks that represents the canonical chain. It's
  88. // important to note that GetBlock can return any block and does not need to be
  89. // included in the canonical one where as GetBlockByNumber always represents the
  90. // canonical chain.
  91. type BlockChain struct {
  92. chainConfig *params.ChainConfig // Chain & network configuration
  93. cacheConfig *CacheConfig // Cache configuration for pruning
  94. db ethdb.Database // Low level persistent database to store final content in
  95. triegc *prque.Prque // Priority queue mapping block numbers to tries to gc
  96. gcproc time.Duration // Accumulates canonical block processing for trie dumping
  97. hc *HeaderChain
  98. rmLogsFeed event.Feed
  99. chainFeed event.Feed
  100. chainSideFeed event.Feed
  101. chainHeadFeed event.Feed
  102. logsFeed event.Feed
  103. blockProcFeed event.Feed
  104. scope event.SubscriptionScope
  105. genesisBlock *types.Block
  106. chainmu sync.RWMutex // blockchain insertion lock
  107. procmu sync.RWMutex // block processor lock
  108. checkpoint int // checkpoint counts towards the new checkpoint
  109. currentBlock atomic.Value // Current head of the block chain
  110. currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
  111. stateCache state.Database // State database to reuse between imports (contains state cache)
  112. bodyCache *lru.Cache // Cache for the most recent block bodies
  113. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  114. receiptsCache *lru.Cache // Cache for the most recent receipts per block
  115. blockCache *lru.Cache // Cache for the most recent entire blocks
  116. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  117. quit chan struct{} // blockchain quit channel
  118. running int32 // running must be called atomically
  119. // procInterrupt must be atomically called
  120. procInterrupt int32 // interrupt signaler for block processing
  121. wg sync.WaitGroup // chain processing wait group for shutting down
  122. engine consensus.Engine
  123. processor Processor // block processor interface
  124. validator Validator // block and state validator interface
  125. vmConfig vm.Config
  126. badBlocks *lru.Cache // Bad block cache
  127. shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
  128. }
  129. // NewBlockChain returns a fully initialised block chain using information
  130. // available in the database. It initialises the default Ethereum Validator and
  131. // Processor.
  132. func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool) (*BlockChain, error) {
  133. if cacheConfig == nil {
  134. cacheConfig = &CacheConfig{
  135. TrieCleanLimit: 256,
  136. TrieDirtyLimit: 256,
  137. TrieTimeLimit: 5 * time.Minute,
  138. }
  139. }
  140. bodyCache, _ := lru.New(bodyCacheLimit)
  141. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  142. receiptsCache, _ := lru.New(receiptsCacheLimit)
  143. blockCache, _ := lru.New(blockCacheLimit)
  144. futureBlocks, _ := lru.New(maxFutureBlocks)
  145. badBlocks, _ := lru.New(badBlockLimit)
  146. bc := &BlockChain{
  147. chainConfig: chainConfig,
  148. cacheConfig: cacheConfig,
  149. db: db,
  150. triegc: prque.New(nil),
  151. stateCache: state.NewDatabaseWithCache(db, cacheConfig.TrieCleanLimit),
  152. quit: make(chan struct{}),
  153. shouldPreserve: shouldPreserve,
  154. bodyCache: bodyCache,
  155. bodyRLPCache: bodyRLPCache,
  156. receiptsCache: receiptsCache,
  157. blockCache: blockCache,
  158. futureBlocks: futureBlocks,
  159. engine: engine,
  160. vmConfig: vmConfig,
  161. badBlocks: badBlocks,
  162. }
  163. bc.SetValidator(NewBlockValidator(chainConfig, bc, engine))
  164. bc.SetProcessor(NewStateProcessor(chainConfig, bc, engine))
  165. var err error
  166. bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.getProcInterrupt)
  167. if err != nil {
  168. return nil, err
  169. }
  170. bc.genesisBlock = bc.GetBlockByNumber(0)
  171. if bc.genesisBlock == nil {
  172. return nil, ErrNoGenesis
  173. }
  174. if err := bc.loadLastState(); err != nil {
  175. return nil, err
  176. }
  177. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  178. for hash := range BadHashes {
  179. if header := bc.GetHeaderByHash(hash); header != nil {
  180. // get the canonical block corresponding to the offending header's number
  181. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  182. // make sure the headerByNumber (if present) is in our current canonical chain
  183. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  184. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  185. bc.SetHead(header.Number.Uint64() - 1)
  186. log.Error("Chain rewind was successful, resuming normal operation")
  187. }
  188. }
  189. }
  190. // Take ownership of this particular state
  191. go bc.update()
  192. return bc, nil
  193. }
  194. func (bc *BlockChain) getProcInterrupt() bool {
  195. return atomic.LoadInt32(&bc.procInterrupt) == 1
  196. }
  197. // GetVMConfig returns the block chain VM config.
  198. func (bc *BlockChain) GetVMConfig() *vm.Config {
  199. return &bc.vmConfig
  200. }
  201. // loadLastState loads the last known chain state from the database. This method
  202. // assumes that the chain manager mutex is held.
  203. func (bc *BlockChain) loadLastState() error {
  204. // Restore the last known head block
  205. head := rawdb.ReadHeadBlockHash(bc.db)
  206. if head == (common.Hash{}) {
  207. // Corrupt or empty database, init from scratch
  208. log.Warn("Empty database, resetting chain")
  209. return bc.Reset()
  210. }
  211. // Make sure the entire head block is available
  212. currentBlock := bc.GetBlockByHash(head)
  213. if currentBlock == nil {
  214. // Corrupt or empty database, init from scratch
  215. log.Warn("Head block missing, resetting chain", "hash", head)
  216. return bc.Reset()
  217. }
  218. // Make sure the state associated with the block is available
  219. if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
  220. // Dangling block without a state associated, init from scratch
  221. log.Warn("Head state missing, repairing chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
  222. if err := bc.repair(&currentBlock); err != nil {
  223. return err
  224. }
  225. }
  226. // Everything seems to be fine, set as the head block
  227. bc.currentBlock.Store(currentBlock)
  228. // Restore the last known head header
  229. currentHeader := currentBlock.Header()
  230. if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
  231. if header := bc.GetHeaderByHash(head); header != nil {
  232. currentHeader = header
  233. }
  234. }
  235. bc.hc.SetCurrentHeader(currentHeader)
  236. // Restore the last known head fast block
  237. bc.currentFastBlock.Store(currentBlock)
  238. if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
  239. if block := bc.GetBlockByHash(head); block != nil {
  240. bc.currentFastBlock.Store(block)
  241. }
  242. }
  243. // Issue a status log for the user
  244. currentFastBlock := bc.CurrentFastBlock()
  245. headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  246. blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  247. fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
  248. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(currentHeader.Time.Int64(), 0)))
  249. log.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(currentBlock.Time().Int64(), 0)))
  250. log.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(currentFastBlock.Time().Int64(), 0)))
  251. return nil
  252. }
  253. // SetHead rewinds the local chain to a new head. In the case of headers, everything
  254. // above the new head will be deleted and the new one set. In the case of blocks
  255. // though, the head may be further rewound if block bodies are missing (non-archive
  256. // nodes after a fast sync).
  257. func (bc *BlockChain) SetHead(head uint64) error {
  258. log.Warn("Rewinding blockchain", "target", head)
  259. bc.chainmu.Lock()
  260. defer bc.chainmu.Unlock()
  261. // Rewind the header chain, deleting all block bodies until then
  262. delFn := func(db ethdb.Deleter, hash common.Hash, num uint64) {
  263. rawdb.DeleteBody(db, hash, num)
  264. }
  265. bc.hc.SetHead(head, delFn)
  266. currentHeader := bc.hc.CurrentHeader()
  267. // Clear out any stale content from the caches
  268. bc.bodyCache.Purge()
  269. bc.bodyRLPCache.Purge()
  270. bc.receiptsCache.Purge()
  271. bc.blockCache.Purge()
  272. bc.futureBlocks.Purge()
  273. // Rewind the block chain, ensuring we don't end up with a stateless head block
  274. if currentBlock := bc.CurrentBlock(); currentBlock != nil && currentHeader.Number.Uint64() < currentBlock.NumberU64() {
  275. bc.currentBlock.Store(bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()))
  276. }
  277. if currentBlock := bc.CurrentBlock(); currentBlock != nil {
  278. if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
  279. // Rewound state missing, rolled back to before pivot, reset to genesis
  280. bc.currentBlock.Store(bc.genesisBlock)
  281. }
  282. }
  283. // Rewind the fast block in a simpleton way to the target head
  284. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && currentHeader.Number.Uint64() < currentFastBlock.NumberU64() {
  285. bc.currentFastBlock.Store(bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()))
  286. }
  287. // If either blocks reached nil, reset to the genesis state
  288. if currentBlock := bc.CurrentBlock(); currentBlock == nil {
  289. bc.currentBlock.Store(bc.genesisBlock)
  290. }
  291. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock == nil {
  292. bc.currentFastBlock.Store(bc.genesisBlock)
  293. }
  294. currentBlock := bc.CurrentBlock()
  295. currentFastBlock := bc.CurrentFastBlock()
  296. rawdb.WriteHeadBlockHash(bc.db, currentBlock.Hash())
  297. rawdb.WriteHeadFastBlockHash(bc.db, currentFastBlock.Hash())
  298. return bc.loadLastState()
  299. }
  300. // FastSyncCommitHead sets the current head block to the one defined by the hash
  301. // irrelevant what the chain contents were prior.
  302. func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  303. // Make sure that both the block as well at its state trie exists
  304. block := bc.GetBlockByHash(hash)
  305. if block == nil {
  306. return fmt.Errorf("non existent block [%x…]", hash[:4])
  307. }
  308. if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB(), 0); err != nil {
  309. return err
  310. }
  311. // If all checks out, manually set the head block
  312. bc.chainmu.Lock()
  313. bc.currentBlock.Store(block)
  314. bc.chainmu.Unlock()
  315. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  316. return nil
  317. }
  318. // GasLimit returns the gas limit of the current HEAD block.
  319. func (bc *BlockChain) GasLimit() uint64 {
  320. return bc.CurrentBlock().GasLimit()
  321. }
  322. // CurrentBlock retrieves the current head block of the canonical chain. The
  323. // block is retrieved from the blockchain's internal cache.
  324. func (bc *BlockChain) CurrentBlock() *types.Block {
  325. return bc.currentBlock.Load().(*types.Block)
  326. }
  327. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  328. // chain. The block is retrieved from the blockchain's internal cache.
  329. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  330. return bc.currentFastBlock.Load().(*types.Block)
  331. }
  332. // SetProcessor sets the processor required for making state modifications.
  333. func (bc *BlockChain) SetProcessor(processor Processor) {
  334. bc.procmu.Lock()
  335. defer bc.procmu.Unlock()
  336. bc.processor = processor
  337. }
  338. // SetValidator sets the validator which is used to validate incoming blocks.
  339. func (bc *BlockChain) SetValidator(validator Validator) {
  340. bc.procmu.Lock()
  341. defer bc.procmu.Unlock()
  342. bc.validator = validator
  343. }
  344. // Validator returns the current validator.
  345. func (bc *BlockChain) Validator() Validator {
  346. bc.procmu.RLock()
  347. defer bc.procmu.RUnlock()
  348. return bc.validator
  349. }
  350. // Processor returns the current processor.
  351. func (bc *BlockChain) Processor() Processor {
  352. bc.procmu.RLock()
  353. defer bc.procmu.RUnlock()
  354. return bc.processor
  355. }
  356. // State returns a new mutable state based on the current HEAD block.
  357. func (bc *BlockChain) State() (*state.StateDB, error) {
  358. return bc.StateAt(bc.CurrentBlock().Root())
  359. }
  360. // StateAt returns a new mutable state based on a particular point in time.
  361. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  362. return state.New(root, bc.stateCache)
  363. }
  364. // StateCache returns the caching database underpinning the blockchain instance.
  365. func (bc *BlockChain) StateCache() state.Database {
  366. return bc.stateCache
  367. }
  368. // Reset purges the entire blockchain, restoring it to its genesis state.
  369. func (bc *BlockChain) Reset() error {
  370. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  371. }
  372. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  373. // specified genesis state.
  374. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  375. // Dump the entire block chain and purge the caches
  376. if err := bc.SetHead(0); err != nil {
  377. return err
  378. }
  379. bc.chainmu.Lock()
  380. defer bc.chainmu.Unlock()
  381. // Prepare the genesis block and reinitialise the chain
  382. if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  383. log.Crit("Failed to write genesis block TD", "err", err)
  384. }
  385. rawdb.WriteBlock(bc.db, genesis)
  386. bc.genesisBlock = genesis
  387. bc.insert(bc.genesisBlock)
  388. bc.currentBlock.Store(bc.genesisBlock)
  389. bc.hc.SetGenesis(bc.genesisBlock.Header())
  390. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  391. bc.currentFastBlock.Store(bc.genesisBlock)
  392. return nil
  393. }
  394. // repair tries to repair the current blockchain by rolling back the current block
  395. // until one with associated state is found. This is needed to fix incomplete db
  396. // writes caused either by crashes/power outages, or simply non-committed tries.
  397. //
  398. // This method only rolls back the current block. The current header and current
  399. // fast block are left intact.
  400. func (bc *BlockChain) repair(head **types.Block) error {
  401. for {
  402. // Abort if we've rewound to a head block that does have associated state
  403. if _, err := state.New((*head).Root(), bc.stateCache); err == nil {
  404. log.Info("Rewound blockchain to past state", "number", (*head).Number(), "hash", (*head).Hash())
  405. return nil
  406. }
  407. // Otherwise rewind one block and recheck state availability there
  408. block := bc.GetBlock((*head).ParentHash(), (*head).NumberU64()-1)
  409. if block == nil {
  410. return fmt.Errorf("missing block %d [%x]", (*head).NumberU64()-1, (*head).ParentHash())
  411. }
  412. *head = block
  413. }
  414. }
  415. // Export writes the active chain to the given writer.
  416. func (bc *BlockChain) Export(w io.Writer) error {
  417. return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64())
  418. }
  419. // ExportN writes a subset of the active chain to the given writer.
  420. func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  421. bc.chainmu.RLock()
  422. defer bc.chainmu.RUnlock()
  423. if first > last {
  424. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  425. }
  426. log.Info("Exporting batch of blocks", "count", last-first+1)
  427. start, reported := time.Now(), time.Now()
  428. for nr := first; nr <= last; nr++ {
  429. block := bc.GetBlockByNumber(nr)
  430. if block == nil {
  431. return fmt.Errorf("export failed on #%d: not found", nr)
  432. }
  433. if err := block.EncodeRLP(w); err != nil {
  434. return err
  435. }
  436. if time.Since(reported) >= statsReportLimit {
  437. log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
  438. reported = time.Now()
  439. }
  440. }
  441. return nil
  442. }
  443. // insert injects a new head block into the current block chain. This method
  444. // assumes that the block is indeed a true head. It will also reset the head
  445. // header and the head fast sync block to this very same block if they are older
  446. // or if they are on a different side chain.
  447. //
  448. // Note, this function assumes that the `mu` mutex is held!
  449. func (bc *BlockChain) insert(block *types.Block) {
  450. // If the block is on a side chain or an unknown one, force other heads onto it too
  451. updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()
  452. // Add the block to the canonical chain number scheme and mark as the head
  453. rawdb.WriteCanonicalHash(bc.db, block.Hash(), block.NumberU64())
  454. rawdb.WriteHeadBlockHash(bc.db, block.Hash())
  455. bc.currentBlock.Store(block)
  456. // If the block is better than our head or is on a different chain, force update heads
  457. if updateHeads {
  458. bc.hc.SetCurrentHeader(block.Header())
  459. rawdb.WriteHeadFastBlockHash(bc.db, block.Hash())
  460. bc.currentFastBlock.Store(block)
  461. }
  462. }
  463. // Genesis retrieves the chain's genesis block.
  464. func (bc *BlockChain) Genesis() *types.Block {
  465. return bc.genesisBlock
  466. }
  467. // GetBody retrieves a block body (transactions and uncles) from the database by
  468. // hash, caching it if found.
  469. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  470. // Short circuit if the body's already in the cache, retrieve otherwise
  471. if cached, ok := bc.bodyCache.Get(hash); ok {
  472. body := cached.(*types.Body)
  473. return body
  474. }
  475. number := bc.hc.GetBlockNumber(hash)
  476. if number == nil {
  477. return nil
  478. }
  479. body := rawdb.ReadBody(bc.db, hash, *number)
  480. if body == nil {
  481. return nil
  482. }
  483. // Cache the found body for next time and return
  484. bc.bodyCache.Add(hash, body)
  485. return body
  486. }
  487. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  488. // caching it if found.
  489. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  490. // Short circuit if the body's already in the cache, retrieve otherwise
  491. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  492. return cached.(rlp.RawValue)
  493. }
  494. number := bc.hc.GetBlockNumber(hash)
  495. if number == nil {
  496. return nil
  497. }
  498. body := rawdb.ReadBodyRLP(bc.db, hash, *number)
  499. if len(body) == 0 {
  500. return nil
  501. }
  502. // Cache the found body for next time and return
  503. bc.bodyRLPCache.Add(hash, body)
  504. return body
  505. }
  506. // HasBlock checks if a block is fully present in the database or not.
  507. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  508. if bc.blockCache.Contains(hash) {
  509. return true
  510. }
  511. return rawdb.HasBody(bc.db, hash, number)
  512. }
  513. // HasFastBlock checks if a fast block is fully present in the database or not.
  514. func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool {
  515. if !bc.HasBlock(hash, number) {
  516. return false
  517. }
  518. if bc.receiptsCache.Contains(hash) {
  519. return true
  520. }
  521. return rawdb.HasReceipts(bc.db, hash, number)
  522. }
  523. // HasState checks if state trie is fully present in the database or not.
  524. func (bc *BlockChain) HasState(hash common.Hash) bool {
  525. _, err := bc.stateCache.OpenTrie(hash)
  526. return err == nil
  527. }
  528. // HasBlockAndState checks if a block and associated state trie is fully present
  529. // in the database or not, caching it if present.
  530. func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
  531. // Check first that the block itself is known
  532. block := bc.GetBlock(hash, number)
  533. if block == nil {
  534. return false
  535. }
  536. return bc.HasState(block.Root())
  537. }
  538. // GetBlock retrieves a block from the database by hash and number,
  539. // caching it if found.
  540. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  541. // Short circuit if the block's already in the cache, retrieve otherwise
  542. if block, ok := bc.blockCache.Get(hash); ok {
  543. return block.(*types.Block)
  544. }
  545. block := rawdb.ReadBlock(bc.db, hash, number)
  546. if block == nil {
  547. return nil
  548. }
  549. // Cache the found block for next time and return
  550. bc.blockCache.Add(block.Hash(), block)
  551. return block
  552. }
  553. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  554. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  555. number := bc.hc.GetBlockNumber(hash)
  556. if number == nil {
  557. return nil
  558. }
  559. return bc.GetBlock(hash, *number)
  560. }
  561. // GetBlockByNumber retrieves a block from the database by number, caching it
  562. // (associated with its hash) if found.
  563. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  564. hash := rawdb.ReadCanonicalHash(bc.db, number)
  565. if hash == (common.Hash{}) {
  566. return nil
  567. }
  568. return bc.GetBlock(hash, number)
  569. }
  570. // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
  571. func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
  572. if receipts, ok := bc.receiptsCache.Get(hash); ok {
  573. return receipts.(types.Receipts)
  574. }
  575. number := rawdb.ReadHeaderNumber(bc.db, hash)
  576. if number == nil {
  577. return nil
  578. }
  579. receipts := rawdb.ReadReceipts(bc.db, hash, *number)
  580. if receipts == nil {
  581. return nil
  582. }
  583. bc.receiptsCache.Add(hash, receipts)
  584. return receipts
  585. }
  586. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  587. // [deprecated by eth/62]
  588. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  589. number := bc.hc.GetBlockNumber(hash)
  590. if number == nil {
  591. return nil
  592. }
  593. for i := 0; i < n; i++ {
  594. block := bc.GetBlock(hash, *number)
  595. if block == nil {
  596. break
  597. }
  598. blocks = append(blocks, block)
  599. hash = block.ParentHash()
  600. *number--
  601. }
  602. return
  603. }
  604. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  605. // a specific distance is reached.
  606. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  607. uncles := []*types.Header{}
  608. for i := 0; block != nil && i < length; i++ {
  609. uncles = append(uncles, block.Uncles()...)
  610. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  611. }
  612. return uncles
  613. }
  614. // TrieNode retrieves a blob of data associated with a trie node (or code hash)
  615. // either from ephemeral in-memory cache, or from persistent storage.
  616. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  617. return bc.stateCache.TrieDB().Node(hash)
  618. }
  619. // Stop stops the blockchain service. If any imports are currently in progress
  620. // it will abort them using the procInterrupt.
  621. func (bc *BlockChain) Stop() {
  622. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  623. return
  624. }
  625. // Unsubscribe all subscriptions registered from blockchain
  626. bc.scope.Close()
  627. close(bc.quit)
  628. atomic.StoreInt32(&bc.procInterrupt, 1)
  629. bc.wg.Wait()
  630. // Ensure the state of a recent block is also stored to disk before exiting.
  631. // We're writing three different states to catch different restart scenarios:
  632. // - HEAD: So we don't need to reprocess any blocks in the general case
  633. // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle
  634. // - HEAD-127: So we have a hard limit on the number of blocks reexecuted
  635. if !bc.cacheConfig.Disabled {
  636. triedb := bc.stateCache.TrieDB()
  637. for _, offset := range []uint64{0, 1, triesInMemory - 1} {
  638. if number := bc.CurrentBlock().NumberU64(); number > offset {
  639. recent := bc.GetBlockByNumber(number - offset)
  640. log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
  641. if err := triedb.Commit(recent.Root(), true); err != nil {
  642. log.Error("Failed to commit recent state trie", "err", err)
  643. }
  644. }
  645. }
  646. for !bc.triegc.Empty() {
  647. triedb.Dereference(bc.triegc.PopItem().(common.Hash))
  648. }
  649. if size, _ := triedb.Size(); size != 0 {
  650. log.Error("Dangling trie nodes after full cleanup")
  651. }
  652. }
  653. log.Info("Blockchain manager stopped")
  654. }
  655. func (bc *BlockChain) procFutureBlocks() {
  656. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  657. for _, hash := range bc.futureBlocks.Keys() {
  658. if block, exist := bc.futureBlocks.Peek(hash); exist {
  659. blocks = append(blocks, block.(*types.Block))
  660. }
  661. }
  662. if len(blocks) > 0 {
  663. types.BlockBy(types.Number).Sort(blocks)
  664. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  665. for i := range blocks {
  666. bc.InsertChain(blocks[i : i+1])
  667. }
  668. }
  669. }
  670. // WriteStatus status of write
  671. type WriteStatus byte
  672. const (
  673. NonStatTy WriteStatus = iota
  674. CanonStatTy
  675. SideStatTy
  676. )
  677. // Rollback is designed to remove a chain of links from the database that aren't
  678. // certain enough to be valid.
  679. func (bc *BlockChain) Rollback(chain []common.Hash) {
  680. bc.chainmu.Lock()
  681. defer bc.chainmu.Unlock()
  682. for i := len(chain) - 1; i >= 0; i-- {
  683. hash := chain[i]
  684. currentHeader := bc.hc.CurrentHeader()
  685. if currentHeader.Hash() == hash {
  686. bc.hc.SetCurrentHeader(bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
  687. }
  688. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock.Hash() == hash {
  689. newFastBlock := bc.GetBlock(currentFastBlock.ParentHash(), currentFastBlock.NumberU64()-1)
  690. bc.currentFastBlock.Store(newFastBlock)
  691. rawdb.WriteHeadFastBlockHash(bc.db, newFastBlock.Hash())
  692. }
  693. if currentBlock := bc.CurrentBlock(); currentBlock.Hash() == hash {
  694. newBlock := bc.GetBlock(currentBlock.ParentHash(), currentBlock.NumberU64()-1)
  695. bc.currentBlock.Store(newBlock)
  696. rawdb.WriteHeadBlockHash(bc.db, newBlock.Hash())
  697. }
  698. }
  699. }
  700. // SetReceiptsData computes all the non-consensus fields of the receipts
  701. func SetReceiptsData(config *params.ChainConfig, block *types.Block, receipts types.Receipts) error {
  702. signer := types.MakeSigner(config, block.Number())
  703. transactions, logIndex := block.Transactions(), uint(0)
  704. if len(transactions) != len(receipts) {
  705. return errors.New("transaction and receipt count mismatch")
  706. }
  707. for j := 0; j < len(receipts); j++ {
  708. // The transaction hash can be retrieved from the transaction itself
  709. receipts[j].TxHash = transactions[j].Hash()
  710. // The contract address can be derived from the transaction itself
  711. if transactions[j].To() == nil {
  712. // Deriving the signer is expensive, only do if it's actually needed
  713. from, _ := types.Sender(signer, transactions[j])
  714. receipts[j].ContractAddress = crypto.CreateAddress(from, transactions[j].Nonce())
  715. }
  716. // The used gas can be calculated based on previous receipts
  717. if j == 0 {
  718. receipts[j].GasUsed = receipts[j].CumulativeGasUsed
  719. } else {
  720. receipts[j].GasUsed = receipts[j].CumulativeGasUsed - receipts[j-1].CumulativeGasUsed
  721. }
  722. // The derived log fields can simply be set from the block and transaction
  723. for k := 0; k < len(receipts[j].Logs); k++ {
  724. receipts[j].Logs[k].BlockNumber = block.NumberU64()
  725. receipts[j].Logs[k].BlockHash = block.Hash()
  726. receipts[j].Logs[k].TxHash = receipts[j].TxHash
  727. receipts[j].Logs[k].TxIndex = uint(j)
  728. receipts[j].Logs[k].Index = logIndex
  729. logIndex++
  730. }
  731. }
  732. return nil
  733. }
  734. // InsertReceiptChain attempts to complete an already existing header chain with
  735. // transaction and receipt data.
  736. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  737. bc.wg.Add(1)
  738. defer bc.wg.Done()
  739. // Do a sanity check that the provided chain is actually ordered and linked
  740. for i := 1; i < len(blockChain); i++ {
  741. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  742. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  743. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  744. 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(),
  745. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  746. }
  747. }
  748. var (
  749. stats = struct{ processed, ignored int32 }{}
  750. start = time.Now()
  751. bytes = 0
  752. batch = bc.db.NewBatch()
  753. )
  754. for i, block := range blockChain {
  755. receipts := receiptChain[i]
  756. // Short circuit insertion if shutting down or processing failed
  757. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  758. return 0, nil
  759. }
  760. // Short circuit if the owner header is unknown
  761. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  762. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  763. }
  764. // Skip if the entire data is already known
  765. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  766. stats.ignored++
  767. continue
  768. }
  769. // Compute all the non-consensus fields of the receipts
  770. if err := SetReceiptsData(bc.chainConfig, block, receipts); err != nil {
  771. return i, fmt.Errorf("failed to set receipts data: %v", err)
  772. }
  773. // Write all the data out into the database
  774. rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
  775. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  776. rawdb.WriteTxLookupEntries(batch, block)
  777. stats.processed++
  778. if batch.ValueSize() >= ethdb.IdealBatchSize {
  779. if err := batch.Write(); err != nil {
  780. return 0, err
  781. }
  782. bytes += batch.ValueSize()
  783. batch.Reset()
  784. }
  785. }
  786. if batch.ValueSize() > 0 {
  787. bytes += batch.ValueSize()
  788. if err := batch.Write(); err != nil {
  789. return 0, err
  790. }
  791. }
  792. // Update the head fast sync block if better
  793. bc.chainmu.Lock()
  794. head := blockChain[len(blockChain)-1]
  795. if td := bc.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case
  796. currentFastBlock := bc.CurrentFastBlock()
  797. if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
  798. rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
  799. bc.currentFastBlock.Store(head)
  800. }
  801. }
  802. bc.chainmu.Unlock()
  803. context := []interface{}{
  804. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  805. "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(head.Time().Int64(), 0)),
  806. "size", common.StorageSize(bytes),
  807. }
  808. if stats.ignored > 0 {
  809. context = append(context, []interface{}{"ignored", stats.ignored}...)
  810. }
  811. log.Info("Imported new block receipts", context...)
  812. return 0, nil
  813. }
  814. var lastWrite uint64
  815. // WriteBlockWithoutState writes only the block and its metadata to the database,
  816. // but does not write any state. This is used to construct competing side forks
  817. // up to the point where they exceed the canonical total difficulty.
  818. func (bc *BlockChain) WriteBlockWithoutState(block *types.Block, td *big.Int) (err error) {
  819. bc.wg.Add(1)
  820. defer bc.wg.Done()
  821. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), td); err != nil {
  822. return err
  823. }
  824. rawdb.WriteBlock(bc.db, block)
  825. return nil
  826. }
  827. // WriteBlockWithState writes the block and all associated state to the database.
  828. func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  829. bc.chainmu.Lock()
  830. defer bc.chainmu.Unlock()
  831. return bc.writeBlockWithState(block, receipts, state)
  832. }
  833. // writeBlockWithState writes the block and all associated state to the database,
  834. // but is expects the chain mutex to be held.
  835. func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  836. bc.wg.Add(1)
  837. defer bc.wg.Done()
  838. // Calculate the total difficulty of the block
  839. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  840. if ptd == nil {
  841. return NonStatTy, consensus.ErrUnknownAncestor
  842. }
  843. // Make sure no inconsistent state is leaked during insertion
  844. currentBlock := bc.CurrentBlock()
  845. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  846. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  847. // Irrelevant of the canonical status, write the block itself to the database
  848. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
  849. return NonStatTy, err
  850. }
  851. rawdb.WriteBlock(bc.db, block)
  852. root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
  853. if err != nil {
  854. return NonStatTy, err
  855. }
  856. triedb := bc.stateCache.TrieDB()
  857. // If we're running an archive node, always flush
  858. if bc.cacheConfig.Disabled {
  859. if err := triedb.Commit(root, false); err != nil {
  860. return NonStatTy, err
  861. }
  862. } else {
  863. // Full but not archive node, do proper garbage collection
  864. triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
  865. bc.triegc.Push(root, -int64(block.NumberU64()))
  866. if current := block.NumberU64(); current > triesInMemory {
  867. // If we exceeded our memory allowance, flush matured singleton nodes to disk
  868. var (
  869. nodes, imgs = triedb.Size()
  870. limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
  871. )
  872. if nodes > limit || imgs > 4*1024*1024 {
  873. triedb.Cap(limit - ethdb.IdealBatchSize)
  874. }
  875. // Find the next state trie we need to commit
  876. chosen := current - triesInMemory
  877. // If we exceeded out time allowance, flush an entire trie to disk
  878. if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
  879. // If the header is missing (canonical chain behind), we're reorging a low
  880. // diff sidechain. Suspend committing until this operation is completed.
  881. header := bc.GetHeaderByNumber(chosen)
  882. if header == nil {
  883. log.Warn("Reorg in progress, trie commit postponed", "number", chosen)
  884. } else {
  885. // If we're exceeding limits but haven't reached a large enough memory gap,
  886. // warn the user that the system is becoming unstable.
  887. if chosen < lastWrite+triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
  888. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/triesInMemory)
  889. }
  890. // Flush an entire trie and restart the counters
  891. triedb.Commit(header.Root, true)
  892. lastWrite = chosen
  893. bc.gcproc = 0
  894. }
  895. }
  896. // Garbage collect anything below our required write retention
  897. for !bc.triegc.Empty() {
  898. root, number := bc.triegc.Pop()
  899. if uint64(-number) > chosen {
  900. bc.triegc.Push(root, number)
  901. break
  902. }
  903. triedb.Dereference(root.(common.Hash))
  904. }
  905. }
  906. }
  907. // Write other block data using a batch.
  908. batch := bc.db.NewBatch()
  909. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  910. // If the total difficulty is higher than our known, add it to the canonical chain
  911. // Second clause in the if statement reduces the vulnerability to selfish mining.
  912. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  913. reorg := externTd.Cmp(localTd) > 0
  914. currentBlock = bc.CurrentBlock()
  915. if !reorg && externTd.Cmp(localTd) == 0 {
  916. // Split same-difficulty blocks by number, then preferentially select
  917. // the block generated by the local miner as the canonical block.
  918. if block.NumberU64() < currentBlock.NumberU64() {
  919. reorg = true
  920. } else if block.NumberU64() == currentBlock.NumberU64() {
  921. var currentPreserve, blockPreserve bool
  922. if bc.shouldPreserve != nil {
  923. currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  924. }
  925. reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  926. }
  927. }
  928. if reorg {
  929. // Reorganise the chain if the parent is not the head block
  930. if block.ParentHash() != currentBlock.Hash() {
  931. if err := bc.reorg(currentBlock, block); err != nil {
  932. return NonStatTy, err
  933. }
  934. }
  935. // Write the positional metadata for transaction/receipt lookups and preimages
  936. rawdb.WriteTxLookupEntries(batch, block)
  937. rawdb.WritePreimages(batch, state.Preimages())
  938. status = CanonStatTy
  939. } else {
  940. status = SideStatTy
  941. }
  942. if err := batch.Write(); err != nil {
  943. return NonStatTy, err
  944. }
  945. // Set new head.
  946. if status == CanonStatTy {
  947. bc.insert(block)
  948. }
  949. bc.futureBlocks.Remove(block.Hash())
  950. return status, nil
  951. }
  952. // addFutureBlock checks if the block is within the max allowed window to get
  953. // accepted for future processing, and returns an error if the block is too far
  954. // ahead and was not added.
  955. func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  956. max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
  957. if block.Time().Cmp(max) > 0 {
  958. return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  959. }
  960. bc.futureBlocks.Add(block.Hash(), block)
  961. return nil
  962. }
  963. // InsertChain attempts to insert the given batch of blocks in to the canonical
  964. // chain or, otherwise, create a fork. If an error is returned it will return
  965. // the index number of the failing block as well an error describing what went
  966. // wrong.
  967. //
  968. // After insertion is done, all accumulated events will be fired.
  969. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  970. // Sanity check that we have something meaningful to import
  971. if len(chain) == 0 {
  972. return 0, nil
  973. }
  974. bc.blockProcFeed.Send(true)
  975. defer bc.blockProcFeed.Send(false)
  976. // Remove already known canon-blocks
  977. var (
  978. block, prev *types.Block
  979. )
  980. // Do a sanity check that the provided chain is actually ordered and linked
  981. for i := 1; i < len(chain); i++ {
  982. block = chain[i]
  983. prev = chain[i-1]
  984. if block.NumberU64() != prev.NumberU64()+1 || block.ParentHash() != prev.Hash() {
  985. // Chain broke ancestry, log a message (programming error) and skip insertion
  986. log.Error("Non contiguous block insert", "number", block.Number(), "hash", block.Hash(),
  987. "parent", block.ParentHash(), "prevnumber", prev.Number(), "prevhash", prev.Hash())
  988. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, prev.NumberU64(),
  989. prev.Hash().Bytes()[:4], i, block.NumberU64(), block.Hash().Bytes()[:4], block.ParentHash().Bytes()[:4])
  990. }
  991. }
  992. // Pre-checks passed, start the full block imports
  993. bc.wg.Add(1)
  994. bc.chainmu.Lock()
  995. n, events, logs, err := bc.insertChain(chain, true)
  996. bc.chainmu.Unlock()
  997. bc.wg.Done()
  998. bc.PostChainEvents(events, logs)
  999. return n, err
  1000. }
  1001. // insertChain is the internal implementation of insertChain, which assumes that
  1002. // 1) chains are contiguous, and 2) The chain mutex is held.
  1003. //
  1004. // This method is split out so that import batches that require re-injecting
  1005. // historical blocks can do so without releasing the lock, which could lead to
  1006. // racey behaviour. If a sidechain import is in progress, and the historic state
  1007. // is imported, but then new canon-head is added before the actual sidechain
  1008. // completes, then the historic state could be pruned again
  1009. func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []interface{}, []*types.Log, error) {
  1010. // If the chain is terminating, don't even bother starting u
  1011. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1012. return 0, nil, nil, nil
  1013. }
  1014. // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  1015. senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  1016. // A queued approach to delivering events. This is generally
  1017. // faster than direct delivery and requires much less mutex
  1018. // acquiring.
  1019. var (
  1020. stats = insertStats{startTime: mclock.Now()}
  1021. events = make([]interface{}, 0, len(chain))
  1022. lastCanon *types.Block
  1023. coalescedLogs []*types.Log
  1024. )
  1025. // Start the parallel header verifier
  1026. headers := make([]*types.Header, len(chain))
  1027. seals := make([]bool, len(chain))
  1028. for i, block := range chain {
  1029. headers[i] = block.Header()
  1030. seals[i] = verifySeals
  1031. }
  1032. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1033. defer close(abort)
  1034. // Peek the error for the first block to decide the directing import logic
  1035. it := newInsertIterator(chain, results, bc.Validator())
  1036. block, err := it.next()
  1037. // Left-trim all the known blocks
  1038. if err == ErrKnownBlock {
  1039. // First block (and state) is known
  1040. // 1. We did a roll-back, and should now do a re-import
  1041. // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1042. // from the canonical chain, which has not been verified.
  1043. // Skip all known blocks that are behind us
  1044. current := bc.CurrentBlock().NumberU64()
  1045. for block != nil && err == ErrKnownBlock && current >= block.NumberU64() {
  1046. stats.ignored++
  1047. block, err = it.next()
  1048. }
  1049. // Falls through to the block import
  1050. }
  1051. switch {
  1052. // First block is pruned, insert as sidechain and reorg only if TD grows enough
  1053. case err == consensus.ErrPrunedAncestor:
  1054. return bc.insertSidechain(block, it)
  1055. // First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1056. case err == consensus.ErrFutureBlock || (err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(it.first().ParentHash())):
  1057. for block != nil && (it.index == 0 || err == consensus.ErrUnknownAncestor) {
  1058. if err := bc.addFutureBlock(block); err != nil {
  1059. return it.index, events, coalescedLogs, err
  1060. }
  1061. block, err = it.next()
  1062. }
  1063. stats.queued += it.processed()
  1064. stats.ignored += it.remaining()
  1065. // If there are any still remaining, mark as ignored
  1066. return it.index, events, coalescedLogs, err
  1067. // Some other error occurred, abort
  1068. case err != nil:
  1069. stats.ignored += len(it.chain)
  1070. bc.reportBlock(block, nil, err)
  1071. return it.index, events, coalescedLogs, err
  1072. }
  1073. // No validation errors for the first block (or chain prefix skipped)
  1074. for ; block != nil && err == nil; block, err = it.next() {
  1075. // If the chain is terminating, stop processing blocks
  1076. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1077. log.Debug("Premature abort during blocks processing")
  1078. break
  1079. }
  1080. // If the header is a banned one, straight out abort
  1081. if BadHashes[block.Hash()] {
  1082. bc.reportBlock(block, nil, ErrBlacklistedHash)
  1083. return it.index, events, coalescedLogs, ErrBlacklistedHash
  1084. }
  1085. // Retrieve the parent block and it's state to execute on top
  1086. start := time.Now()
  1087. parent := it.previous()
  1088. if parent == nil {
  1089. parent = bc.GetHeader(block.ParentHash(), block.NumberU64()-1)
  1090. }
  1091. state, err := state.New(parent.Root, bc.stateCache)
  1092. if err != nil {
  1093. return it.index, events, coalescedLogs, err
  1094. }
  1095. // Process block using the parent state as reference point.
  1096. t0 := time.Now()
  1097. receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
  1098. t1 := time.Now()
  1099. if err != nil {
  1100. bc.reportBlock(block, receipts, err)
  1101. return it.index, events, coalescedLogs, err
  1102. }
  1103. // Validate the state using the default validator
  1104. if err := bc.Validator().ValidateState(block, state, receipts, usedGas); err != nil {
  1105. bc.reportBlock(block, receipts, err)
  1106. return it.index, events, coalescedLogs, err
  1107. }
  1108. t2 := time.Now()
  1109. proctime := time.Since(start)
  1110. // Write the block to the chain and get the status.
  1111. status, err := bc.writeBlockWithState(block, receipts, state)
  1112. t3 := time.Now()
  1113. if err != nil {
  1114. return it.index, events, coalescedLogs, err
  1115. }
  1116. blockInsertTimer.UpdateSince(start)
  1117. blockExecutionTimer.Update(t1.Sub(t0))
  1118. blockValidationTimer.Update(t2.Sub(t1))
  1119. blockWriteTimer.Update(t3.Sub(t2))
  1120. switch status {
  1121. case CanonStatTy:
  1122. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1123. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1124. "elapsed", common.PrettyDuration(time.Since(start)),
  1125. "root", block.Root())
  1126. coalescedLogs = append(coalescedLogs, logs...)
  1127. events = append(events, ChainEvent{block, block.Hash(), logs})
  1128. lastCanon = block
  1129. // Only count canonical blocks for GC processing time
  1130. bc.gcproc += proctime
  1131. case SideStatTy:
  1132. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1133. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1134. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1135. "root", block.Root())
  1136. events = append(events, ChainSideEvent{block})
  1137. }
  1138. blockInsertTimer.UpdateSince(start)
  1139. stats.processed++
  1140. stats.usedGas += usedGas
  1141. dirty, _ := bc.stateCache.TrieDB().Size()
  1142. stats.report(chain, it.index, dirty)
  1143. }
  1144. // Any blocks remaining here? The only ones we care about are the future ones
  1145. if block != nil && err == consensus.ErrFutureBlock {
  1146. if err := bc.addFutureBlock(block); err != nil {
  1147. return it.index, events, coalescedLogs, err
  1148. }
  1149. block, err = it.next()
  1150. for ; block != nil && err == consensus.ErrUnknownAncestor; block, err = it.next() {
  1151. if err := bc.addFutureBlock(block); err != nil {
  1152. return it.index, events, coalescedLogs, err
  1153. }
  1154. stats.queued++
  1155. }
  1156. }
  1157. stats.ignored += it.remaining()
  1158. // Append a single chain head event if we've progressed the chain
  1159. if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1160. events = append(events, ChainHeadEvent{lastCanon})
  1161. }
  1162. return it.index, events, coalescedLogs, err
  1163. }
  1164. // insertSidechain is called when an import batch hits upon a pruned ancestor
  1165. // error, which happens when a sidechain with a sufficiently old fork-block is
  1166. // found.
  1167. //
  1168. // The method writes all (header-and-body-valid) blocks to disk, then tries to
  1169. // switch over to the new chain if the TD exceeded the current chain.
  1170. func (bc *BlockChain) insertSidechain(block *types.Block, it *insertIterator) (int, []interface{}, []*types.Log, error) {
  1171. var (
  1172. externTd *big.Int
  1173. current = bc.CurrentBlock()
  1174. )
  1175. // The first sidechain block error is already verified to be ErrPrunedAncestor.
  1176. // Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  1177. // ones. Any other errors means that the block is invalid, and should not be written
  1178. // to disk.
  1179. err := consensus.ErrPrunedAncestor
  1180. for ; block != nil && (err == consensus.ErrPrunedAncestor); block, err = it.next() {
  1181. // Check the canonical state root for that number
  1182. if number := block.NumberU64(); current.NumberU64() >= number {
  1183. canonical := bc.GetBlockByNumber(number)
  1184. if canonical != nil && canonical.Hash() == block.Hash() {
  1185. // Not a sidechain block, this is a re-import of a canon block which has it's state pruned
  1186. continue
  1187. }
  1188. if canonical != nil && canonical.Root() == block.Root() {
  1189. // This is most likely a shadow-state attack. When a fork is imported into the
  1190. // database, and it eventually reaches a block height which is not pruned, we
  1191. // just found that the state already exist! This means that the sidechain block
  1192. // refers to a state which already exists in our canon chain.
  1193. //
  1194. // If left unchecked, we would now proceed importing the blocks, without actually
  1195. // having verified the state of the previous blocks.
  1196. log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  1197. // If someone legitimately side-mines blocks, they would still be imported as usual. However,
  1198. // we cannot risk writing unverified blocks to disk when they obviously target the pruning
  1199. // mechanism.
  1200. return it.index, nil, nil, errors.New("sidechain ghost-state attack")
  1201. }
  1202. }
  1203. if externTd == nil {
  1204. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1205. }
  1206. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1207. if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  1208. start := time.Now()
  1209. if err := bc.WriteBlockWithoutState(block, externTd); err != nil {
  1210. return it.index, nil, nil, err
  1211. }
  1212. log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(),
  1213. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1214. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1215. "root", block.Root())
  1216. }
  1217. }
  1218. // At this point, we've written all sidechain blocks to database. Loop ended
  1219. // either on some other error or all were processed. If there was some other
  1220. // error, we can ignore the rest of those blocks.
  1221. //
  1222. // If the externTd was larger than our local TD, we now need to reimport the previous
  1223. // blocks to regenerate the required state
  1224. localTd := bc.GetTd(current.Hash(), current.NumberU64())
  1225. if localTd.Cmp(externTd) > 0 {
  1226. log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().Number, "sidetd", externTd, "localtd", localTd)
  1227. return it.index, nil, nil, err
  1228. }
  1229. // Gather all the sidechain hashes (full blocks may be memory heavy)
  1230. var (
  1231. hashes []common.Hash
  1232. numbers []uint64
  1233. )
  1234. parent := it.previous()
  1235. for parent != nil && !bc.HasState(parent.Root) {
  1236. hashes = append(hashes, parent.Hash())
  1237. numbers = append(numbers, parent.Number.Uint64())
  1238. parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  1239. }
  1240. if parent == nil {
  1241. return it.index, nil, nil, errors.New("missing parent")
  1242. }
  1243. // Import all the pruned blocks to make the state available
  1244. var (
  1245. blocks []*types.Block
  1246. memory common.StorageSize
  1247. )
  1248. for i := len(hashes) - 1; i >= 0; i-- {
  1249. // Append the next block to our batch
  1250. block := bc.GetBlock(hashes[i], numbers[i])
  1251. blocks = append(blocks, block)
  1252. memory += block.Size()
  1253. // If memory use grew too large, import and continue. Sadly we need to discard
  1254. // all raised events and logs from notifications since we're too heavy on the
  1255. // memory here.
  1256. if len(blocks) >= 2048 || memory > 64*1024*1024 {
  1257. log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  1258. if _, _, _, err := bc.insertChain(blocks, false); err != nil {
  1259. return 0, nil, nil, err
  1260. }
  1261. blocks, memory = blocks[:0], 0
  1262. // If the chain is terminating, stop processing blocks
  1263. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1264. log.Debug("Premature abort during blocks processing")
  1265. return 0, nil, nil, nil
  1266. }
  1267. }
  1268. }
  1269. if len(blocks) > 0 {
  1270. log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  1271. return bc.insertChain(blocks, false)
  1272. }
  1273. return 0, nil, nil, nil
  1274. }
  1275. // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  1276. // to be part of the new canonical chain and accumulates potential missing transactions and post an
  1277. // event about them
  1278. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1279. var (
  1280. newChain types.Blocks
  1281. oldChain types.Blocks
  1282. commonBlock *types.Block
  1283. deletedTxs types.Transactions
  1284. deletedLogs []*types.Log
  1285. // collectLogs collects the logs that were generated during the
  1286. // processing of the block that corresponds with the given hash.
  1287. // These logs are later announced as deleted.
  1288. collectLogs = func(hash common.Hash) {
  1289. // Coalesce logs and set 'Removed'.
  1290. number := bc.hc.GetBlockNumber(hash)
  1291. if number == nil {
  1292. return
  1293. }
  1294. receipts := rawdb.ReadReceipts(bc.db, hash, *number)
  1295. for _, receipt := range receipts {
  1296. for _, log := range receipt.Logs {
  1297. del := *log
  1298. del.Removed = true
  1299. deletedLogs = append(deletedLogs, &del)
  1300. }
  1301. }
  1302. }
  1303. )
  1304. // first reduce whoever is higher bound
  1305. if oldBlock.NumberU64() > newBlock.NumberU64() {
  1306. // reduce old chain
  1307. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  1308. oldChain = append(oldChain, oldBlock)
  1309. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1310. collectLogs(oldBlock.Hash())
  1311. }
  1312. } else {
  1313. // reduce new chain and append new chain blocks for inserting later on
  1314. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1315. newChain = append(newChain, newBlock)
  1316. }
  1317. }
  1318. if oldBlock == nil {
  1319. return fmt.Errorf("Invalid old chain")
  1320. }
  1321. if newBlock == nil {
  1322. return fmt.Errorf("Invalid new chain")
  1323. }
  1324. for {
  1325. if oldBlock.Hash() == newBlock.Hash() {
  1326. commonBlock = oldBlock
  1327. break
  1328. }
  1329. oldChain = append(oldChain, oldBlock)
  1330. newChain = append(newChain, newBlock)
  1331. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1332. collectLogs(oldBlock.Hash())
  1333. oldBlock, newBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1334. if oldBlock == nil {
  1335. return fmt.Errorf("Invalid old chain")
  1336. }
  1337. if newBlock == nil {
  1338. return fmt.Errorf("Invalid new chain")
  1339. }
  1340. }
  1341. // Ensure the user sees large reorgs
  1342. if len(oldChain) > 0 && len(newChain) > 0 {
  1343. logFn := log.Debug
  1344. if len(oldChain) > 63 {
  1345. logFn = log.Warn
  1346. }
  1347. logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1348. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1349. } else {
  1350. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1351. }
  1352. // Insert the new chain, taking care of the proper incremental order
  1353. var addedTxs types.Transactions
  1354. for i := len(newChain) - 1; i >= 0; i-- {
  1355. // insert the block in the canonical way, re-writing history
  1356. bc.insert(newChain[i])
  1357. // write lookup entries for hash based transaction/receipt searches
  1358. rawdb.WriteTxLookupEntries(bc.db, newChain[i])
  1359. addedTxs = append(addedTxs, newChain[i].Transactions()...)
  1360. }
  1361. // calculate the difference between deleted and added transactions
  1362. diff := types.TxDifference(deletedTxs, addedTxs)
  1363. // When transactions get deleted from the database that means the
  1364. // receipts that were created in the fork must also be deleted
  1365. batch := bc.db.NewBatch()
  1366. for _, tx := range diff {
  1367. rawdb.DeleteTxLookupEntry(batch, tx.Hash())
  1368. }
  1369. batch.Write()
  1370. if len(deletedLogs) > 0 {
  1371. go bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs})
  1372. }
  1373. if len(oldChain) > 0 {
  1374. go func() {
  1375. for _, block := range oldChain {
  1376. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1377. }
  1378. }()
  1379. }
  1380. return nil
  1381. }
  1382. // PostChainEvents iterates over the events generated by a chain insertion and
  1383. // posts them into the event feed.
  1384. // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.
  1385. func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) {
  1386. // post event logs for further processing
  1387. if logs != nil {
  1388. bc.logsFeed.Send(logs)
  1389. }
  1390. for _, event := range events {
  1391. switch ev := event.(type) {
  1392. case ChainEvent:
  1393. bc.chainFeed.Send(ev)
  1394. case ChainHeadEvent:
  1395. bc.chainHeadFeed.Send(ev)
  1396. case ChainSideEvent:
  1397. bc.chainSideFeed.Send(ev)
  1398. }
  1399. }
  1400. }
  1401. func (bc *BlockChain) update() {
  1402. futureTimer := time.NewTicker(5 * time.Second)
  1403. defer futureTimer.Stop()
  1404. for {
  1405. select {
  1406. case <-futureTimer.C:
  1407. bc.procFutureBlocks()
  1408. case <-bc.quit:
  1409. return
  1410. }
  1411. }
  1412. }
  1413. // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1414. func (bc *BlockChain) BadBlocks() []*types.Block {
  1415. blocks := make([]*types.Block, 0, bc.badBlocks.Len())
  1416. for _, hash := range bc.badBlocks.Keys() {
  1417. if blk, exist := bc.badBlocks.Peek(hash); exist {
  1418. block := blk.(*types.Block)
  1419. blocks = append(blocks, block)
  1420. }
  1421. }
  1422. return blocks
  1423. }
  1424. // addBadBlock adds a bad block to the bad-block LRU cache
  1425. func (bc *BlockChain) addBadBlock(block *types.Block) {
  1426. bc.badBlocks.Add(block.Hash(), block)
  1427. }
  1428. // reportBlock logs a bad block error.
  1429. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1430. bc.addBadBlock(block)
  1431. var receiptString string
  1432. for i, receipt := range receipts {
  1433. receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  1434. i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  1435. receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  1436. }
  1437. log.Error(fmt.Sprintf(`
  1438. ########## BAD BLOCK #########
  1439. Chain config: %v
  1440. Number: %v
  1441. Hash: 0x%x
  1442. %v
  1443. Error: %v
  1444. ##############################
  1445. `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  1446. }
  1447. // InsertHeaderChain attempts to insert the given header chain in to the local
  1448. // chain, possibly creating a reorg. If an error is returned, it will return the
  1449. // index number of the failing header as well an error describing what went wrong.
  1450. //
  1451. // The verify parameter can be used to fine tune whether nonce verification
  1452. // should be done or not. The reason behind the optional check is because some
  1453. // of the header retrieval mechanisms already need to verify nonces, as well as
  1454. // because nonces can be verified sparsely, not needing to check each.
  1455. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1456. start := time.Now()
  1457. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1458. return i, err
  1459. }
  1460. // Make sure only one thread manipulates the chain at once
  1461. bc.chainmu.Lock()
  1462. defer bc.chainmu.Unlock()
  1463. bc.wg.Add(1)
  1464. defer bc.wg.Done()
  1465. whFunc := func(header *types.Header) error {
  1466. _, err := bc.hc.WriteHeader(header)
  1467. return err
  1468. }
  1469. return bc.hc.InsertHeaderChain(chain, whFunc, start)
  1470. }
  1471. // CurrentHeader retrieves the current head header of the canonical chain. The
  1472. // header is retrieved from the HeaderChain's internal cache.
  1473. func (bc *BlockChain) CurrentHeader() *types.Header {
  1474. return bc.hc.CurrentHeader()
  1475. }
  1476. // GetTd retrieves a block's total difficulty in the canonical chain from the
  1477. // database by hash and number, caching it if found.
  1478. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1479. return bc.hc.GetTd(hash, number)
  1480. }
  1481. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1482. // database by hash, caching it if found.
  1483. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1484. return bc.hc.GetTdByHash(hash)
  1485. }
  1486. // GetHeader retrieves a block header from the database by hash and number,
  1487. // caching it if found.
  1488. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1489. return bc.hc.GetHeader(hash, number)
  1490. }
  1491. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1492. // found.
  1493. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1494. return bc.hc.GetHeaderByHash(hash)
  1495. }
  1496. // HasHeader checks if a block header is present in the database or not, caching
  1497. // it if present.
  1498. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  1499. return bc.hc.HasHeader(hash, number)
  1500. }
  1501. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1502. // hash, fetching towards the genesis block.
  1503. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1504. return bc.hc.GetBlockHashesFromHash(hash, max)
  1505. }
  1506. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  1507. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  1508. // number of blocks to be individually checked before we reach the canonical chain.
  1509. //
  1510. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  1511. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  1512. bc.chainmu.RLock()
  1513. defer bc.chainmu.RUnlock()
  1514. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  1515. }
  1516. // GetHeaderByNumber retrieves a block header from the database by number,
  1517. // caching it (associated with its hash) if found.
  1518. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1519. return bc.hc.GetHeaderByNumber(number)
  1520. }
  1521. // Config retrieves the blockchain's chain configuration.
  1522. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  1523. // Engine retrieves the blockchain's consensus engine.
  1524. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  1525. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  1526. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  1527. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  1528. }
  1529. // SubscribeChainEvent registers a subscription of ChainEvent.
  1530. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  1531. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  1532. }
  1533. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  1534. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  1535. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  1536. }
  1537. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  1538. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  1539. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  1540. }
  1541. // SubscribeLogsEvent registers a subscription of []*types.Log.
  1542. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  1543. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  1544. }
  1545. // SubscribeBlockProcessingEvent registers a subscription of bool where true means
  1546. // block processing has started while false means it has stopped.
  1547. func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription {
  1548. return bc.scope.Track(bc.blockProcFeed.Subscribe(ch))
  1549. }