blockchain.go 62 KB

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