blockchain.go 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  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. bc.receiptsCache.Add(hash, receipts)
  574. return receipts
  575. }
  576. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  577. // [deprecated by eth/62]
  578. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  579. number := bc.hc.GetBlockNumber(hash)
  580. if number == nil {
  581. return nil
  582. }
  583. for i := 0; i < n; i++ {
  584. block := bc.GetBlock(hash, *number)
  585. if block == nil {
  586. break
  587. }
  588. blocks = append(blocks, block)
  589. hash = block.ParentHash()
  590. *number--
  591. }
  592. return
  593. }
  594. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  595. // a specific distance is reached.
  596. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  597. uncles := []*types.Header{}
  598. for i := 0; block != nil && i < length; i++ {
  599. uncles = append(uncles, block.Uncles()...)
  600. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  601. }
  602. return uncles
  603. }
  604. // TrieNode retrieves a blob of data associated with a trie node (or code hash)
  605. // either from ephemeral in-memory cache, or from persistent storage.
  606. func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
  607. return bc.stateCache.TrieDB().Node(hash)
  608. }
  609. // Stop stops the blockchain service. If any imports are currently in progress
  610. // it will abort them using the procInterrupt.
  611. func (bc *BlockChain) Stop() {
  612. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  613. return
  614. }
  615. // Unsubscribe all subscriptions registered from blockchain
  616. bc.scope.Close()
  617. close(bc.quit)
  618. atomic.StoreInt32(&bc.procInterrupt, 1)
  619. bc.wg.Wait()
  620. // Ensure the state of a recent block is also stored to disk before exiting.
  621. // We're writing three different states to catch different restart scenarios:
  622. // - HEAD: So we don't need to reprocess any blocks in the general case
  623. // - HEAD-1: So we don't do large reorgs if our HEAD becomes an uncle
  624. // - HEAD-127: So we have a hard limit on the number of blocks reexecuted
  625. if !bc.cacheConfig.Disabled {
  626. triedb := bc.stateCache.TrieDB()
  627. for _, offset := range []uint64{0, 1, triesInMemory - 1} {
  628. if number := bc.CurrentBlock().NumberU64(); number > offset {
  629. recent := bc.GetBlockByNumber(number - offset)
  630. log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
  631. if err := triedb.Commit(recent.Root(), true); err != nil {
  632. log.Error("Failed to commit recent state trie", "err", err)
  633. }
  634. }
  635. }
  636. for !bc.triegc.Empty() {
  637. triedb.Dereference(bc.triegc.PopItem().(common.Hash))
  638. }
  639. if size, _ := triedb.Size(); size != 0 {
  640. log.Error("Dangling trie nodes after full cleanup")
  641. }
  642. }
  643. log.Info("Blockchain manager stopped")
  644. }
  645. func (bc *BlockChain) procFutureBlocks() {
  646. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  647. for _, hash := range bc.futureBlocks.Keys() {
  648. if block, exist := bc.futureBlocks.Peek(hash); exist {
  649. blocks = append(blocks, block.(*types.Block))
  650. }
  651. }
  652. if len(blocks) > 0 {
  653. types.BlockBy(types.Number).Sort(blocks)
  654. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  655. for i := range blocks {
  656. bc.InsertChain(blocks[i : i+1])
  657. }
  658. }
  659. }
  660. // WriteStatus status of write
  661. type WriteStatus byte
  662. const (
  663. NonStatTy WriteStatus = iota
  664. CanonStatTy
  665. SideStatTy
  666. )
  667. // Rollback is designed to remove a chain of links from the database that aren't
  668. // certain enough to be valid.
  669. func (bc *BlockChain) Rollback(chain []common.Hash) {
  670. bc.chainmu.Lock()
  671. defer bc.chainmu.Unlock()
  672. for i := len(chain) - 1; i >= 0; i-- {
  673. hash := chain[i]
  674. currentHeader := bc.hc.CurrentHeader()
  675. if currentHeader.Hash() == hash {
  676. bc.hc.SetCurrentHeader(bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
  677. }
  678. if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock.Hash() == hash {
  679. newFastBlock := bc.GetBlock(currentFastBlock.ParentHash(), currentFastBlock.NumberU64()-1)
  680. bc.currentFastBlock.Store(newFastBlock)
  681. rawdb.WriteHeadFastBlockHash(bc.db, newFastBlock.Hash())
  682. }
  683. if currentBlock := bc.CurrentBlock(); currentBlock.Hash() == hash {
  684. newBlock := bc.GetBlock(currentBlock.ParentHash(), currentBlock.NumberU64()-1)
  685. bc.currentBlock.Store(newBlock)
  686. rawdb.WriteHeadBlockHash(bc.db, newBlock.Hash())
  687. }
  688. }
  689. }
  690. // SetReceiptsData computes all the non-consensus fields of the receipts
  691. func SetReceiptsData(config *params.ChainConfig, block *types.Block, receipts types.Receipts) error {
  692. signer := types.MakeSigner(config, block.Number())
  693. transactions, logIndex := block.Transactions(), uint(0)
  694. if len(transactions) != len(receipts) {
  695. return errors.New("transaction and receipt count mismatch")
  696. }
  697. for j := 0; j < len(receipts); j++ {
  698. // The transaction hash can be retrieved from the transaction itself
  699. receipts[j].TxHash = transactions[j].Hash()
  700. // The contract address can be derived from the transaction itself
  701. if transactions[j].To() == nil {
  702. // Deriving the signer is expensive, only do if it's actually needed
  703. from, _ := types.Sender(signer, transactions[j])
  704. receipts[j].ContractAddress = crypto.CreateAddress(from, transactions[j].Nonce())
  705. }
  706. // The used gas can be calculated based on previous receipts
  707. if j == 0 {
  708. receipts[j].GasUsed = receipts[j].CumulativeGasUsed
  709. } else {
  710. receipts[j].GasUsed = receipts[j].CumulativeGasUsed - receipts[j-1].CumulativeGasUsed
  711. }
  712. // The derived log fields can simply be set from the block and transaction
  713. for k := 0; k < len(receipts[j].Logs); k++ {
  714. receipts[j].Logs[k].BlockNumber = block.NumberU64()
  715. receipts[j].Logs[k].BlockHash = block.Hash()
  716. receipts[j].Logs[k].TxHash = receipts[j].TxHash
  717. receipts[j].Logs[k].TxIndex = uint(j)
  718. receipts[j].Logs[k].Index = logIndex
  719. logIndex++
  720. }
  721. }
  722. return nil
  723. }
  724. // InsertReceiptChain attempts to complete an already existing header chain with
  725. // transaction and receipt data.
  726. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  727. bc.wg.Add(1)
  728. defer bc.wg.Done()
  729. // Do a sanity check that the provided chain is actually ordered and linked
  730. for i := 1; i < len(blockChain); i++ {
  731. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  732. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  733. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  734. 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(),
  735. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  736. }
  737. }
  738. var (
  739. stats = struct{ processed, ignored int32 }{}
  740. start = time.Now()
  741. bytes = 0
  742. batch = bc.db.NewBatch()
  743. )
  744. for i, block := range blockChain {
  745. receipts := receiptChain[i]
  746. // Short circuit insertion if shutting down or processing failed
  747. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  748. return 0, nil
  749. }
  750. // Short circuit if the owner header is unknown
  751. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  752. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  753. }
  754. // Skip if the entire data is already known
  755. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  756. stats.ignored++
  757. continue
  758. }
  759. // Compute all the non-consensus fields of the receipts
  760. if err := SetReceiptsData(bc.chainConfig, block, receipts); err != nil {
  761. return i, fmt.Errorf("failed to set receipts data: %v", err)
  762. }
  763. // Write all the data out into the database
  764. rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
  765. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  766. rawdb.WriteTxLookupEntries(batch, block)
  767. stats.processed++
  768. if batch.ValueSize() >= ethdb.IdealBatchSize {
  769. if err := batch.Write(); err != nil {
  770. return 0, err
  771. }
  772. bytes += batch.ValueSize()
  773. batch.Reset()
  774. }
  775. }
  776. if batch.ValueSize() > 0 {
  777. bytes += batch.ValueSize()
  778. if err := batch.Write(); err != nil {
  779. return 0, err
  780. }
  781. }
  782. // Update the head fast sync block if better
  783. bc.chainmu.Lock()
  784. head := blockChain[len(blockChain)-1]
  785. if td := bc.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case
  786. currentFastBlock := bc.CurrentFastBlock()
  787. if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
  788. rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
  789. bc.currentFastBlock.Store(head)
  790. }
  791. }
  792. bc.chainmu.Unlock()
  793. context := []interface{}{
  794. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  795. "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(head.Time().Int64(), 0)),
  796. "size", common.StorageSize(bytes),
  797. }
  798. if stats.ignored > 0 {
  799. context = append(context, []interface{}{"ignored", stats.ignored}...)
  800. }
  801. log.Info("Imported new block receipts", context...)
  802. return 0, nil
  803. }
  804. var lastWrite uint64
  805. // WriteBlockWithoutState writes only the block and its metadata to the database,
  806. // but does not write any state. This is used to construct competing side forks
  807. // up to the point where they exceed the canonical total difficulty.
  808. func (bc *BlockChain) WriteBlockWithoutState(block *types.Block, td *big.Int) (err error) {
  809. bc.wg.Add(1)
  810. defer bc.wg.Done()
  811. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), td); err != nil {
  812. return err
  813. }
  814. rawdb.WriteBlock(bc.db, block)
  815. return nil
  816. }
  817. // WriteBlockWithState writes the block and all associated state to the database.
  818. func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  819. bc.chainmu.Lock()
  820. defer bc.chainmu.Unlock()
  821. return bc.writeBlockWithState(block, receipts, state)
  822. }
  823. // writeBlockWithState writes the block and all associated state to the database,
  824. // but is expects the chain mutex to be held.
  825. func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  826. bc.wg.Add(1)
  827. defer bc.wg.Done()
  828. // Calculate the total difficulty of the block
  829. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  830. if ptd == nil {
  831. return NonStatTy, consensus.ErrUnknownAncestor
  832. }
  833. // Make sure no inconsistent state is leaked during insertion
  834. currentBlock := bc.CurrentBlock()
  835. localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
  836. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  837. // Irrelevant of the canonical status, write the block itself to the database
  838. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
  839. return NonStatTy, err
  840. }
  841. rawdb.WriteBlock(bc.db, block)
  842. root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
  843. if err != nil {
  844. return NonStatTy, err
  845. }
  846. triedb := bc.stateCache.TrieDB()
  847. // If we're running an archive node, always flush
  848. if bc.cacheConfig.Disabled {
  849. if err := triedb.Commit(root, false); err != nil {
  850. return NonStatTy, err
  851. }
  852. } else {
  853. // Full but not archive node, do proper garbage collection
  854. triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
  855. bc.triegc.Push(root, -int64(block.NumberU64()))
  856. if current := block.NumberU64(); current > triesInMemory {
  857. // If we exceeded our memory allowance, flush matured singleton nodes to disk
  858. var (
  859. nodes, imgs = triedb.Size()
  860. limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
  861. )
  862. if nodes > limit || imgs > 4*1024*1024 {
  863. triedb.Cap(limit - ethdb.IdealBatchSize)
  864. }
  865. // Find the next state trie we need to commit
  866. header := bc.GetHeaderByNumber(current - triesInMemory)
  867. chosen := header.Number.Uint64()
  868. // If we exceeded out time allowance, flush an entire trie to disk
  869. if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
  870. // If we're exceeding limits but haven't reached a large enough memory gap,
  871. // warn the user that the system is becoming unstable.
  872. if chosen < lastWrite+triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
  873. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/triesInMemory)
  874. }
  875. // Flush an entire trie and restart the counters
  876. triedb.Commit(header.Root, true)
  877. lastWrite = chosen
  878. bc.gcproc = 0
  879. }
  880. // Garbage collect anything below our required write retention
  881. for !bc.triegc.Empty() {
  882. root, number := bc.triegc.Pop()
  883. if uint64(-number) > chosen {
  884. bc.triegc.Push(root, number)
  885. break
  886. }
  887. triedb.Dereference(root.(common.Hash))
  888. }
  889. }
  890. }
  891. // Write other block data using a batch.
  892. batch := bc.db.NewBatch()
  893. rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  894. // If the total difficulty is higher than our known, add it to the canonical chain
  895. // Second clause in the if statement reduces the vulnerability to selfish mining.
  896. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  897. reorg := externTd.Cmp(localTd) > 0
  898. currentBlock = bc.CurrentBlock()
  899. if !reorg && externTd.Cmp(localTd) == 0 {
  900. // Split same-difficulty blocks by number, then preferentially select
  901. // the block generated by the local miner as the canonical block.
  902. if block.NumberU64() < currentBlock.NumberU64() {
  903. reorg = true
  904. } else if block.NumberU64() == currentBlock.NumberU64() {
  905. var currentPreserve, blockPreserve bool
  906. if bc.shouldPreserve != nil {
  907. currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  908. }
  909. reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  910. }
  911. }
  912. if reorg {
  913. // Reorganise the chain if the parent is not the head block
  914. if block.ParentHash() != currentBlock.Hash() {
  915. if err := bc.reorg(currentBlock, block); err != nil {
  916. return NonStatTy, err
  917. }
  918. }
  919. // Write the positional metadata for transaction/receipt lookups and preimages
  920. rawdb.WriteTxLookupEntries(batch, block)
  921. rawdb.WritePreimages(batch, state.Preimages())
  922. status = CanonStatTy
  923. } else {
  924. status = SideStatTy
  925. }
  926. if err := batch.Write(); err != nil {
  927. return NonStatTy, err
  928. }
  929. // Set new head.
  930. if status == CanonStatTy {
  931. bc.insert(block)
  932. }
  933. bc.futureBlocks.Remove(block.Hash())
  934. return status, nil
  935. }
  936. // addFutureBlock checks if the block is within the max allowed window to get
  937. // accepted for future processing, and returns an error if the block is too far
  938. // ahead and was not added.
  939. func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  940. max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
  941. if block.Time().Cmp(max) > 0 {
  942. return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  943. }
  944. bc.futureBlocks.Add(block.Hash(), block)
  945. return nil
  946. }
  947. // InsertChain attempts to insert the given batch of blocks in to the canonical
  948. // chain or, otherwise, create a fork. If an error is returned it will return
  949. // the index number of the failing block as well an error describing what went
  950. // wrong.
  951. //
  952. // After insertion is done, all accumulated events will be fired.
  953. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  954. // Sanity check that we have something meaningful to import
  955. if len(chain) == 0 {
  956. return 0, nil
  957. }
  958. // Do a sanity check that the provided chain is actually ordered and linked
  959. for i := 1; i < len(chain); i++ {
  960. if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
  961. // Chain broke ancestry, log a message (programming error) and skip insertion
  962. log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(),
  963. "parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash())
  964. 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(),
  965. chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
  966. }
  967. }
  968. // Pre-checks passed, start the full block imports
  969. bc.wg.Add(1)
  970. bc.chainmu.Lock()
  971. n, events, logs, err := bc.insertChain(chain, true)
  972. bc.chainmu.Unlock()
  973. bc.wg.Done()
  974. bc.PostChainEvents(events, logs)
  975. return n, err
  976. }
  977. // insertChain is the internal implementation of insertChain, which assumes that
  978. // 1) chains are contiguous, and 2) The chain mutex is held.
  979. //
  980. // This method is split out so that import batches that require re-injecting
  981. // historical blocks can do so without releasing the lock, which could lead to
  982. // racey behaviour. If a sidechain import is in progress, and the historic state
  983. // is imported, but then new canon-head is added before the actual sidechain
  984. // completes, then the historic state could be pruned again
  985. func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []interface{}, []*types.Log, error) {
  986. // If the chain is terminating, don't even bother starting u
  987. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  988. return 0, nil, nil, nil
  989. }
  990. // Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  991. senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  992. // A queued approach to delivering events. This is generally
  993. // faster than direct delivery and requires much less mutex
  994. // acquiring.
  995. var (
  996. stats = insertStats{startTime: mclock.Now()}
  997. events = make([]interface{}, 0, len(chain))
  998. lastCanon *types.Block
  999. coalescedLogs []*types.Log
  1000. )
  1001. // Start the parallel header verifier
  1002. headers := make([]*types.Header, len(chain))
  1003. seals := make([]bool, len(chain))
  1004. for i, block := range chain {
  1005. headers[i] = block.Header()
  1006. seals[i] = verifySeals
  1007. }
  1008. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1009. defer close(abort)
  1010. // Peek the error for the first block to decide the directing import logic
  1011. it := newInsertIterator(chain, results, bc.Validator())
  1012. block, err := it.next()
  1013. switch {
  1014. // First block is pruned, insert as sidechain and reorg only if TD grows enough
  1015. case err == consensus.ErrPrunedAncestor:
  1016. return bc.insertSidechain(it)
  1017. // First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1018. case err == consensus.ErrFutureBlock || (err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(it.first().ParentHash())):
  1019. for block != nil && (it.index == 0 || err == consensus.ErrUnknownAncestor) {
  1020. if err := bc.addFutureBlock(block); err != nil {
  1021. return it.index, events, coalescedLogs, err
  1022. }
  1023. block, err = it.next()
  1024. }
  1025. stats.queued += it.processed()
  1026. stats.ignored += it.remaining()
  1027. // If there are any still remaining, mark as ignored
  1028. return it.index, events, coalescedLogs, err
  1029. // First block (and state) is known
  1030. // 1. We did a roll-back, and should now do a re-import
  1031. // 2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1032. // from the canonical chain, which has not been verified.
  1033. case err == ErrKnownBlock:
  1034. // Skip all known blocks that behind us
  1035. current := bc.CurrentBlock().NumberU64()
  1036. for block != nil && err == ErrKnownBlock && current >= block.NumberU64() {
  1037. stats.ignored++
  1038. block, err = it.next()
  1039. }
  1040. // Falls through to the block import
  1041. // Some other error occurred, abort
  1042. case err != nil:
  1043. stats.ignored += len(it.chain)
  1044. bc.reportBlock(block, nil, err)
  1045. return it.index, events, coalescedLogs, err
  1046. }
  1047. // No validation errors for the first block (or chain prefix skipped)
  1048. for ; block != nil && err == nil; block, err = it.next() {
  1049. // If the chain is terminating, stop processing blocks
  1050. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1051. log.Debug("Premature abort during blocks processing")
  1052. break
  1053. }
  1054. // If the header is a banned one, straight out abort
  1055. if BadHashes[block.Hash()] {
  1056. bc.reportBlock(block, nil, ErrBlacklistedHash)
  1057. return it.index, events, coalescedLogs, ErrBlacklistedHash
  1058. }
  1059. // Retrieve the parent block and it's state to execute on top
  1060. start := time.Now()
  1061. parent := it.previous()
  1062. if parent == nil {
  1063. parent = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  1064. }
  1065. state, err := state.New(parent.Root(), bc.stateCache)
  1066. if err != nil {
  1067. return it.index, events, coalescedLogs, err
  1068. }
  1069. // Process block using the parent state as reference point.
  1070. t0 := time.Now()
  1071. receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
  1072. t1 := time.Now()
  1073. if err != nil {
  1074. bc.reportBlock(block, receipts, err)
  1075. return it.index, events, coalescedLogs, err
  1076. }
  1077. // Validate the state using the default validator
  1078. if err := bc.Validator().ValidateState(block, parent, state, receipts, usedGas); err != nil {
  1079. bc.reportBlock(block, receipts, err)
  1080. return it.index, events, coalescedLogs, err
  1081. }
  1082. t2 := time.Now()
  1083. proctime := time.Since(start)
  1084. // Write the block to the chain and get the status.
  1085. status, err := bc.writeBlockWithState(block, receipts, state)
  1086. t3 := time.Now()
  1087. if err != nil {
  1088. return it.index, events, coalescedLogs, err
  1089. }
  1090. blockInsertTimer.UpdateSince(start)
  1091. blockExecutionTimer.Update(t1.Sub(t0))
  1092. blockValidationTimer.Update(t2.Sub(t1))
  1093. blockWriteTimer.Update(t3.Sub(t2))
  1094. switch status {
  1095. case CanonStatTy:
  1096. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1097. "uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1098. "elapsed", common.PrettyDuration(time.Since(start)),
  1099. "root", block.Root())
  1100. coalescedLogs = append(coalescedLogs, logs...)
  1101. events = append(events, ChainEvent{block, block.Hash(), logs})
  1102. lastCanon = block
  1103. // Only count canonical blocks for GC processing time
  1104. bc.gcproc += proctime
  1105. case SideStatTy:
  1106. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1107. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1108. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1109. "root", block.Root())
  1110. events = append(events, ChainSideEvent{block})
  1111. }
  1112. blockInsertTimer.UpdateSince(start)
  1113. stats.processed++
  1114. stats.usedGas += usedGas
  1115. cache, _ := bc.stateCache.TrieDB().Size()
  1116. stats.report(chain, it.index, cache)
  1117. }
  1118. // Any blocks remaining here? The only ones we care about are the future ones
  1119. if block != nil && err == consensus.ErrFutureBlock {
  1120. if err := bc.addFutureBlock(block); err != nil {
  1121. return it.index, events, coalescedLogs, err
  1122. }
  1123. block, err = it.next()
  1124. for ; block != nil && err == consensus.ErrUnknownAncestor; block, err = it.next() {
  1125. if err := bc.addFutureBlock(block); err != nil {
  1126. return it.index, events, coalescedLogs, err
  1127. }
  1128. stats.queued++
  1129. }
  1130. }
  1131. stats.ignored += it.remaining()
  1132. // Append a single chain head event if we've progressed the chain
  1133. if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1134. events = append(events, ChainHeadEvent{lastCanon})
  1135. }
  1136. return it.index, events, coalescedLogs, err
  1137. }
  1138. // insertSidechain is called when an import batch hits upon a pruned ancestor
  1139. // error, which happens when a sidechain with a sufficiently old fork-block is
  1140. // found.
  1141. //
  1142. // The method writes all (header-and-body-valid) blocks to disk, then tries to
  1143. // switch over to the new chain if the TD exceeded the current chain.
  1144. func (bc *BlockChain) insertSidechain(it *insertIterator) (int, []interface{}, []*types.Log, error) {
  1145. var (
  1146. externTd *big.Int
  1147. current = bc.CurrentBlock()
  1148. )
  1149. // The first sidechain block error is already verified to be ErrPrunedAncestor.
  1150. // Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  1151. // ones. Any other errors means that the block is invalid, and should not be written
  1152. // to disk.
  1153. block, err := it.current(), consensus.ErrPrunedAncestor
  1154. for ; block != nil && (err == consensus.ErrPrunedAncestor); block, err = it.next() {
  1155. // Check the canonical state root for that number
  1156. if number := block.NumberU64(); current.NumberU64() >= number {
  1157. if canonical := bc.GetBlockByNumber(number); canonical != nil && canonical.Root() == block.Root() {
  1158. // This is most likely a shadow-state attack. When a fork is imported into the
  1159. // database, and it eventually reaches a block height which is not pruned, we
  1160. // just found that the state already exist! This means that the sidechain block
  1161. // refers to a state which already exists in our canon chain.
  1162. //
  1163. // If left unchecked, we would now proceed importing the blocks, without actually
  1164. // having verified the state of the previous blocks.
  1165. log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  1166. // If someone legitimately side-mines blocks, they would still be imported as usual. However,
  1167. // we cannot risk writing unverified blocks to disk when they obviously target the pruning
  1168. // mechanism.
  1169. return it.index, nil, nil, errors.New("sidechain ghost-state attack")
  1170. }
  1171. }
  1172. if externTd == nil {
  1173. externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1174. }
  1175. externTd = new(big.Int).Add(externTd, block.Difficulty())
  1176. if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  1177. start := time.Now()
  1178. if err := bc.WriteBlockWithoutState(block, externTd); err != nil {
  1179. return it.index, nil, nil, err
  1180. }
  1181. log.Debug("Inserted sidechain block", "number", block.Number(), "hash", block.Hash(),
  1182. "diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1183. "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1184. "root", block.Root())
  1185. }
  1186. }
  1187. // At this point, we've written all sidechain blocks to database. Loop ended
  1188. // either on some other error or all were processed. If there was some other
  1189. // error, we can ignore the rest of those blocks.
  1190. //
  1191. // If the externTd was larger than our local TD, we now need to reimport the previous
  1192. // blocks to regenerate the required state
  1193. localTd := bc.GetTd(current.Hash(), current.NumberU64())
  1194. if localTd.Cmp(externTd) > 0 {
  1195. log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().NumberU64(), "sidetd", externTd, "localtd", localTd)
  1196. return it.index, nil, nil, err
  1197. }
  1198. // Gather all the sidechain hashes (full blocks may be memory heavy)
  1199. var (
  1200. hashes []common.Hash
  1201. numbers []uint64
  1202. )
  1203. parent := bc.GetHeader(it.previous().Hash(), it.previous().NumberU64())
  1204. for parent != nil && !bc.HasState(parent.Root) {
  1205. hashes = append(hashes, parent.Hash())
  1206. numbers = append(numbers, parent.Number.Uint64())
  1207. parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  1208. }
  1209. if parent == nil {
  1210. return it.index, nil, nil, errors.New("missing parent")
  1211. }
  1212. // Import all the pruned blocks to make the state available
  1213. var (
  1214. blocks []*types.Block
  1215. memory common.StorageSize
  1216. )
  1217. for i := len(hashes) - 1; i >= 0; i-- {
  1218. // Append the next block to our batch
  1219. block := bc.GetBlock(hashes[i], numbers[i])
  1220. blocks = append(blocks, block)
  1221. memory += block.Size()
  1222. // If memory use grew too large, import and continue. Sadly we need to discard
  1223. // all raised events and logs from notifications since we're too heavy on the
  1224. // memory here.
  1225. if len(blocks) >= 2048 || memory > 64*1024*1024 {
  1226. log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  1227. if _, _, _, err := bc.insertChain(blocks, false); err != nil {
  1228. return 0, nil, nil, err
  1229. }
  1230. blocks, memory = blocks[:0], 0
  1231. // If the chain is terminating, stop processing blocks
  1232. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1233. log.Debug("Premature abort during blocks processing")
  1234. return 0, nil, nil, nil
  1235. }
  1236. }
  1237. }
  1238. if len(blocks) > 0 {
  1239. log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  1240. return bc.insertChain(blocks, false)
  1241. }
  1242. return 0, nil, nil, nil
  1243. }
  1244. // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  1245. // to be part of the new canonical chain and accumulates potential missing transactions and post an
  1246. // event about them
  1247. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1248. var (
  1249. newChain types.Blocks
  1250. oldChain types.Blocks
  1251. commonBlock *types.Block
  1252. deletedTxs types.Transactions
  1253. deletedLogs []*types.Log
  1254. // collectLogs collects the logs that were generated during the
  1255. // processing of the block that corresponds with the given hash.
  1256. // These logs are later announced as deleted.
  1257. collectLogs = func(hash common.Hash) {
  1258. // Coalesce logs and set 'Removed'.
  1259. number := bc.hc.GetBlockNumber(hash)
  1260. if number == nil {
  1261. return
  1262. }
  1263. receipts := rawdb.ReadReceipts(bc.db, hash, *number)
  1264. for _, receipt := range receipts {
  1265. for _, log := range receipt.Logs {
  1266. del := *log
  1267. del.Removed = true
  1268. deletedLogs = append(deletedLogs, &del)
  1269. }
  1270. }
  1271. }
  1272. )
  1273. // first reduce whoever is higher bound
  1274. if oldBlock.NumberU64() > newBlock.NumberU64() {
  1275. // reduce old chain
  1276. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  1277. oldChain = append(oldChain, oldBlock)
  1278. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1279. collectLogs(oldBlock.Hash())
  1280. }
  1281. } else {
  1282. // reduce new chain and append new chain blocks for inserting later on
  1283. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1284. newChain = append(newChain, newBlock)
  1285. }
  1286. }
  1287. if oldBlock == nil {
  1288. return fmt.Errorf("Invalid old chain")
  1289. }
  1290. if newBlock == nil {
  1291. return fmt.Errorf("Invalid new chain")
  1292. }
  1293. for {
  1294. if oldBlock.Hash() == newBlock.Hash() {
  1295. commonBlock = oldBlock
  1296. break
  1297. }
  1298. oldChain = append(oldChain, oldBlock)
  1299. newChain = append(newChain, newBlock)
  1300. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1301. collectLogs(oldBlock.Hash())
  1302. oldBlock, newBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1303. if oldBlock == nil {
  1304. return fmt.Errorf("Invalid old chain")
  1305. }
  1306. if newBlock == nil {
  1307. return fmt.Errorf("Invalid new chain")
  1308. }
  1309. }
  1310. // Ensure the user sees large reorgs
  1311. if len(oldChain) > 0 && len(newChain) > 0 {
  1312. logFn := log.Debug
  1313. if len(oldChain) > 63 {
  1314. logFn = log.Warn
  1315. }
  1316. logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1317. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1318. } else {
  1319. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1320. }
  1321. // Insert the new chain, taking care of the proper incremental order
  1322. var addedTxs types.Transactions
  1323. for i := len(newChain) - 1; i >= 0; i-- {
  1324. // insert the block in the canonical way, re-writing history
  1325. bc.insert(newChain[i])
  1326. // write lookup entries for hash based transaction/receipt searches
  1327. rawdb.WriteTxLookupEntries(bc.db, newChain[i])
  1328. addedTxs = append(addedTxs, newChain[i].Transactions()...)
  1329. }
  1330. // calculate the difference between deleted and added transactions
  1331. diff := types.TxDifference(deletedTxs, addedTxs)
  1332. // When transactions get deleted from the database that means the
  1333. // receipts that were created in the fork must also be deleted
  1334. batch := bc.db.NewBatch()
  1335. for _, tx := range diff {
  1336. rawdb.DeleteTxLookupEntry(batch, tx.Hash())
  1337. }
  1338. batch.Write()
  1339. if len(deletedLogs) > 0 {
  1340. go bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs})
  1341. }
  1342. if len(oldChain) > 0 {
  1343. go func() {
  1344. for _, block := range oldChain {
  1345. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1346. }
  1347. }()
  1348. }
  1349. return nil
  1350. }
  1351. // PostChainEvents iterates over the events generated by a chain insertion and
  1352. // posts them into the event feed.
  1353. // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.
  1354. func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) {
  1355. // post event logs for further processing
  1356. if logs != nil {
  1357. bc.logsFeed.Send(logs)
  1358. }
  1359. for _, event := range events {
  1360. switch ev := event.(type) {
  1361. case ChainEvent:
  1362. bc.chainFeed.Send(ev)
  1363. case ChainHeadEvent:
  1364. bc.chainHeadFeed.Send(ev)
  1365. case ChainSideEvent:
  1366. bc.chainSideFeed.Send(ev)
  1367. }
  1368. }
  1369. }
  1370. func (bc *BlockChain) update() {
  1371. futureTimer := time.NewTicker(5 * time.Second)
  1372. defer futureTimer.Stop()
  1373. for {
  1374. select {
  1375. case <-futureTimer.C:
  1376. bc.procFutureBlocks()
  1377. case <-bc.quit:
  1378. return
  1379. }
  1380. }
  1381. }
  1382. // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1383. func (bc *BlockChain) BadBlocks() []*types.Block {
  1384. blocks := make([]*types.Block, 0, bc.badBlocks.Len())
  1385. for _, hash := range bc.badBlocks.Keys() {
  1386. if blk, exist := bc.badBlocks.Peek(hash); exist {
  1387. block := blk.(*types.Block)
  1388. blocks = append(blocks, block)
  1389. }
  1390. }
  1391. return blocks
  1392. }
  1393. // addBadBlock adds a bad block to the bad-block LRU cache
  1394. func (bc *BlockChain) addBadBlock(block *types.Block) {
  1395. bc.badBlocks.Add(block.Hash(), block)
  1396. }
  1397. // reportBlock logs a bad block error.
  1398. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1399. bc.addBadBlock(block)
  1400. var receiptString string
  1401. for i, receipt := range receipts {
  1402. receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  1403. i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  1404. receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  1405. }
  1406. log.Error(fmt.Sprintf(`
  1407. ########## BAD BLOCK #########
  1408. Chain config: %v
  1409. Number: %v
  1410. Hash: 0x%x
  1411. %v
  1412. Error: %v
  1413. ##############################
  1414. `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  1415. }
  1416. // InsertHeaderChain attempts to insert the given header chain in to the local
  1417. // chain, possibly creating a reorg. If an error is returned, it will return the
  1418. // index number of the failing header as well an error describing what went wrong.
  1419. //
  1420. // The verify parameter can be used to fine tune whether nonce verification
  1421. // should be done or not. The reason behind the optional check is because some
  1422. // of the header retrieval mechanisms already need to verify nonces, as well as
  1423. // because nonces can be verified sparsely, not needing to check each.
  1424. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1425. start := time.Now()
  1426. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1427. return i, err
  1428. }
  1429. // Make sure only one thread manipulates the chain at once
  1430. bc.chainmu.Lock()
  1431. defer bc.chainmu.Unlock()
  1432. bc.wg.Add(1)
  1433. defer bc.wg.Done()
  1434. whFunc := func(header *types.Header) error {
  1435. _, err := bc.hc.WriteHeader(header)
  1436. return err
  1437. }
  1438. return bc.hc.InsertHeaderChain(chain, whFunc, start)
  1439. }
  1440. // CurrentHeader retrieves the current head header of the canonical chain. The
  1441. // header is retrieved from the HeaderChain's internal cache.
  1442. func (bc *BlockChain) CurrentHeader() *types.Header {
  1443. return bc.hc.CurrentHeader()
  1444. }
  1445. // GetTd retrieves a block's total difficulty in the canonical chain from the
  1446. // database by hash and number, caching it if found.
  1447. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1448. return bc.hc.GetTd(hash, number)
  1449. }
  1450. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1451. // database by hash, caching it if found.
  1452. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1453. return bc.hc.GetTdByHash(hash)
  1454. }
  1455. // GetHeader retrieves a block header from the database by hash and number,
  1456. // caching it if found.
  1457. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1458. return bc.hc.GetHeader(hash, number)
  1459. }
  1460. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1461. // found.
  1462. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1463. return bc.hc.GetHeaderByHash(hash)
  1464. }
  1465. // HasHeader checks if a block header is present in the database or not, caching
  1466. // it if present.
  1467. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  1468. return bc.hc.HasHeader(hash, number)
  1469. }
  1470. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1471. // hash, fetching towards the genesis block.
  1472. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1473. return bc.hc.GetBlockHashesFromHash(hash, max)
  1474. }
  1475. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  1476. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  1477. // number of blocks to be individually checked before we reach the canonical chain.
  1478. //
  1479. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  1480. func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  1481. bc.chainmu.RLock()
  1482. defer bc.chainmu.RUnlock()
  1483. return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  1484. }
  1485. // GetHeaderByNumber retrieves a block header from the database by number,
  1486. // caching it (associated with its hash) if found.
  1487. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1488. return bc.hc.GetHeaderByNumber(number)
  1489. }
  1490. // Config retrieves the blockchain's chain configuration.
  1491. func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  1492. // Engine retrieves the blockchain's consensus engine.
  1493. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  1494. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  1495. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  1496. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  1497. }
  1498. // SubscribeChainEvent registers a subscription of ChainEvent.
  1499. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  1500. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  1501. }
  1502. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  1503. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  1504. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  1505. }
  1506. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  1507. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  1508. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  1509. }
  1510. // SubscribeLogsEvent registers a subscription of []*types.Log.
  1511. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  1512. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  1513. }