blockchain.go 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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/consensus"
  30. "github.com/ethereum/go-ethereum/core/state"
  31. "github.com/ethereum/go-ethereum/core/types"
  32. "github.com/ethereum/go-ethereum/core/vm"
  33. "github.com/ethereum/go-ethereum/crypto"
  34. "github.com/ethereum/go-ethereum/ethdb"
  35. "github.com/ethereum/go-ethereum/event"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/metrics"
  38. "github.com/ethereum/go-ethereum/params"
  39. "github.com/ethereum/go-ethereum/rlp"
  40. "github.com/ethereum/go-ethereum/trie"
  41. "github.com/hashicorp/golang-lru"
  42. )
  43. var (
  44. blockInsertTimer = metrics.NewTimer("chain/inserts")
  45. ErrNoGenesis = errors.New("Genesis not found in chain")
  46. )
  47. const (
  48. bodyCacheLimit = 256
  49. blockCacheLimit = 256
  50. maxFutureBlocks = 256
  51. maxTimeFutureBlocks = 30
  52. badBlockLimit = 10
  53. // BlockChainVersion ensures that an incompatible database forces a resync from scratch.
  54. BlockChainVersion = 3
  55. )
  56. // BlockChain represents the canonical chain given a database with a genesis
  57. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
  58. //
  59. // Importing blocks in to the block chain happens according to the set of rules
  60. // defined by the two stage Validator. Processing of blocks is done using the
  61. // Processor which processes the included transaction. The validation of the state
  62. // is done in the second part of the Validator. Failing results in aborting of
  63. // the import.
  64. //
  65. // The BlockChain also helps in returning blocks from **any** chain included
  66. // in the database as well as blocks that represents the canonical chain. It's
  67. // important to note that GetBlock can return any block and does not need to be
  68. // included in the canonical one where as GetBlockByNumber always represents the
  69. // canonical chain.
  70. type BlockChain struct {
  71. config *params.ChainConfig // chain & network configuration
  72. hc *HeaderChain
  73. chainDb ethdb.Database
  74. rmLogsFeed event.Feed
  75. chainFeed event.Feed
  76. chainSideFeed event.Feed
  77. chainHeadFeed event.Feed
  78. logsFeed event.Feed
  79. scope event.SubscriptionScope
  80. genesisBlock *types.Block
  81. mu sync.RWMutex // global mutex for locking chain operations
  82. chainmu sync.RWMutex // blockchain insertion lock
  83. procmu sync.RWMutex // block processor lock
  84. checkpoint int // checkpoint counts towards the new checkpoint
  85. currentBlock *types.Block // Current head of the block chain
  86. currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!)
  87. stateCache state.Database // State database to reuse between imports (contains state cache)
  88. bodyCache *lru.Cache // Cache for the most recent block bodies
  89. bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
  90. blockCache *lru.Cache // Cache for the most recent entire blocks
  91. futureBlocks *lru.Cache // future blocks are blocks added for later processing
  92. quit chan struct{} // blockchain quit channel
  93. running int32 // running must be called atomically
  94. // procInterrupt must be atomically called
  95. procInterrupt int32 // interrupt signaler for block processing
  96. wg sync.WaitGroup // chain processing wait group for shutting down
  97. engine consensus.Engine
  98. processor Processor // block processor interface
  99. validator Validator // block and state validator interface
  100. vmConfig vm.Config
  101. badBlocks *lru.Cache // Bad block cache
  102. }
  103. // NewBlockChain returns a fully initialised block chain using information
  104. // available in the database. It initialises the default Ethereum Validator and
  105. // Processor.
  106. func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config) (*BlockChain, error) {
  107. bodyCache, _ := lru.New(bodyCacheLimit)
  108. bodyRLPCache, _ := lru.New(bodyCacheLimit)
  109. blockCache, _ := lru.New(blockCacheLimit)
  110. futureBlocks, _ := lru.New(maxFutureBlocks)
  111. badBlocks, _ := lru.New(badBlockLimit)
  112. bc := &BlockChain{
  113. config: config,
  114. chainDb: chainDb,
  115. stateCache: state.NewDatabase(chainDb),
  116. quit: make(chan struct{}),
  117. bodyCache: bodyCache,
  118. bodyRLPCache: bodyRLPCache,
  119. blockCache: blockCache,
  120. futureBlocks: futureBlocks,
  121. engine: engine,
  122. vmConfig: vmConfig,
  123. badBlocks: badBlocks,
  124. }
  125. bc.SetValidator(NewBlockValidator(config, bc, engine))
  126. bc.SetProcessor(NewStateProcessor(config, bc, engine))
  127. var err error
  128. bc.hc, err = NewHeaderChain(chainDb, config, engine, bc.getProcInterrupt)
  129. if err != nil {
  130. return nil, err
  131. }
  132. bc.genesisBlock = bc.GetBlockByNumber(0)
  133. if bc.genesisBlock == nil {
  134. return nil, ErrNoGenesis
  135. }
  136. if err := bc.loadLastState(); err != nil {
  137. return nil, err
  138. }
  139. // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
  140. for hash := range BadHashes {
  141. if header := bc.GetHeaderByHash(hash); header != nil {
  142. // get the canonical block corresponding to the offending header's number
  143. headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
  144. // make sure the headerByNumber (if present) is in our current canonical chain
  145. if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
  146. log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
  147. bc.SetHead(header.Number.Uint64() - 1)
  148. log.Error("Chain rewind was successful, resuming normal operation")
  149. }
  150. }
  151. }
  152. // Take ownership of this particular state
  153. go bc.update()
  154. return bc, nil
  155. }
  156. func (bc *BlockChain) getProcInterrupt() bool {
  157. return atomic.LoadInt32(&bc.procInterrupt) == 1
  158. }
  159. // loadLastState loads the last known chain state from the database. This method
  160. // assumes that the chain manager mutex is held.
  161. func (bc *BlockChain) loadLastState() error {
  162. // Restore the last known head block
  163. head := GetHeadBlockHash(bc.chainDb)
  164. if head == (common.Hash{}) {
  165. // Corrupt or empty database, init from scratch
  166. log.Warn("Empty database, resetting chain")
  167. return bc.Reset()
  168. }
  169. // Make sure the entire head block is available
  170. currentBlock := bc.GetBlockByHash(head)
  171. if currentBlock == nil {
  172. // Corrupt or empty database, init from scratch
  173. log.Warn("Head block missing, resetting chain", "hash", head)
  174. return bc.Reset()
  175. }
  176. // Make sure the state associated with the block is available
  177. if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
  178. // Dangling block without a state associated, init from scratch
  179. log.Warn("Head state missing, resetting chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
  180. return bc.Reset()
  181. }
  182. // Everything seems to be fine, set as the head block
  183. bc.currentBlock = currentBlock
  184. // Restore the last known head header
  185. currentHeader := bc.currentBlock.Header()
  186. if head := GetHeadHeaderHash(bc.chainDb); head != (common.Hash{}) {
  187. if header := bc.GetHeaderByHash(head); header != nil {
  188. currentHeader = header
  189. }
  190. }
  191. bc.hc.SetCurrentHeader(currentHeader)
  192. // Restore the last known head fast block
  193. bc.currentFastBlock = bc.currentBlock
  194. if head := GetHeadFastBlockHash(bc.chainDb); head != (common.Hash{}) {
  195. if block := bc.GetBlockByHash(head); block != nil {
  196. bc.currentFastBlock = block
  197. }
  198. }
  199. // Issue a status log for the user
  200. headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
  201. blockTd := bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64())
  202. fastTd := bc.GetTd(bc.currentFastBlock.Hash(), bc.currentFastBlock.NumberU64())
  203. log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd)
  204. log.Info("Loaded most recent local full block", "number", bc.currentBlock.Number(), "hash", bc.currentBlock.Hash(), "td", blockTd)
  205. log.Info("Loaded most recent local fast block", "number", bc.currentFastBlock.Number(), "hash", bc.currentFastBlock.Hash(), "td", fastTd)
  206. return nil
  207. }
  208. // SetHead rewinds the local chain to a new head. In the case of headers, everything
  209. // above the new head will be deleted and the new one set. In the case of blocks
  210. // though, the head may be further rewound if block bodies are missing (non-archive
  211. // nodes after a fast sync).
  212. func (bc *BlockChain) SetHead(head uint64) error {
  213. log.Warn("Rewinding blockchain", "target", head)
  214. bc.mu.Lock()
  215. defer bc.mu.Unlock()
  216. // Rewind the header chain, deleting all block bodies until then
  217. delFn := func(hash common.Hash, num uint64) {
  218. DeleteBody(bc.chainDb, hash, num)
  219. }
  220. bc.hc.SetHead(head, delFn)
  221. currentHeader := bc.hc.CurrentHeader()
  222. // Clear out any stale content from the caches
  223. bc.bodyCache.Purge()
  224. bc.bodyRLPCache.Purge()
  225. bc.blockCache.Purge()
  226. bc.futureBlocks.Purge()
  227. // Rewind the block chain, ensuring we don't end up with a stateless head block
  228. if bc.currentBlock != nil && currentHeader.Number.Uint64() < bc.currentBlock.NumberU64() {
  229. bc.currentBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64())
  230. }
  231. if bc.currentBlock != nil {
  232. if _, err := state.New(bc.currentBlock.Root(), bc.stateCache); err != nil {
  233. // Rewound state missing, rolled back to before pivot, reset to genesis
  234. bc.currentBlock = nil
  235. }
  236. }
  237. // Rewind the fast block in a simpleton way to the target head
  238. if bc.currentFastBlock != nil && currentHeader.Number.Uint64() < bc.currentFastBlock.NumberU64() {
  239. bc.currentFastBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64())
  240. }
  241. // If either blocks reached nil, reset to the genesis state
  242. if bc.currentBlock == nil {
  243. bc.currentBlock = bc.genesisBlock
  244. }
  245. if bc.currentFastBlock == nil {
  246. bc.currentFastBlock = bc.genesisBlock
  247. }
  248. if err := WriteHeadBlockHash(bc.chainDb, bc.currentBlock.Hash()); err != nil {
  249. log.Crit("Failed to reset head full block", "err", err)
  250. }
  251. if err := WriteHeadFastBlockHash(bc.chainDb, bc.currentFastBlock.Hash()); err != nil {
  252. log.Crit("Failed to reset head fast block", "err", err)
  253. }
  254. return bc.loadLastState()
  255. }
  256. // FastSyncCommitHead sets the current head block to the one defined by the hash
  257. // irrelevant what the chain contents were prior.
  258. func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
  259. // Make sure that both the block as well at its state trie exists
  260. block := bc.GetBlockByHash(hash)
  261. if block == nil {
  262. return fmt.Errorf("non existent block [%x…]", hash[:4])
  263. }
  264. if _, err := trie.NewSecure(block.Root(), bc.chainDb, 0); err != nil {
  265. return err
  266. }
  267. // If all checks out, manually set the head block
  268. bc.mu.Lock()
  269. bc.currentBlock = block
  270. bc.mu.Unlock()
  271. log.Info("Committed new head block", "number", block.Number(), "hash", hash)
  272. return nil
  273. }
  274. // GasLimit returns the gas limit of the current HEAD block.
  275. func (bc *BlockChain) GasLimit() uint64 {
  276. bc.mu.RLock()
  277. defer bc.mu.RUnlock()
  278. return bc.currentBlock.GasLimit()
  279. }
  280. // LastBlockHash return the hash of the HEAD block.
  281. func (bc *BlockChain) LastBlockHash() common.Hash {
  282. bc.mu.RLock()
  283. defer bc.mu.RUnlock()
  284. return bc.currentBlock.Hash()
  285. }
  286. // CurrentBlock retrieves the current head block of the canonical chain. The
  287. // block is retrieved from the blockchain's internal cache.
  288. func (bc *BlockChain) CurrentBlock() *types.Block {
  289. bc.mu.RLock()
  290. defer bc.mu.RUnlock()
  291. return bc.currentBlock
  292. }
  293. // CurrentFastBlock retrieves the current fast-sync head block of the canonical
  294. // chain. The block is retrieved from the blockchain's internal cache.
  295. func (bc *BlockChain) CurrentFastBlock() *types.Block {
  296. bc.mu.RLock()
  297. defer bc.mu.RUnlock()
  298. return bc.currentFastBlock
  299. }
  300. // Status returns status information about the current chain such as the HEAD Td,
  301. // the HEAD hash and the hash of the genesis block.
  302. func (bc *BlockChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
  303. bc.mu.RLock()
  304. defer bc.mu.RUnlock()
  305. return bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64()), bc.currentBlock.Hash(), bc.genesisBlock.Hash()
  306. }
  307. // SetProcessor sets the processor required for making state modifications.
  308. func (bc *BlockChain) SetProcessor(processor Processor) {
  309. bc.procmu.Lock()
  310. defer bc.procmu.Unlock()
  311. bc.processor = processor
  312. }
  313. // SetValidator sets the validator which is used to validate incoming blocks.
  314. func (bc *BlockChain) SetValidator(validator Validator) {
  315. bc.procmu.Lock()
  316. defer bc.procmu.Unlock()
  317. bc.validator = validator
  318. }
  319. // Validator returns the current validator.
  320. func (bc *BlockChain) Validator() Validator {
  321. bc.procmu.RLock()
  322. defer bc.procmu.RUnlock()
  323. return bc.validator
  324. }
  325. // Processor returns the current processor.
  326. func (bc *BlockChain) Processor() Processor {
  327. bc.procmu.RLock()
  328. defer bc.procmu.RUnlock()
  329. return bc.processor
  330. }
  331. // State returns a new mutable state based on the current HEAD block.
  332. func (bc *BlockChain) State() (*state.StateDB, error) {
  333. return bc.StateAt(bc.CurrentBlock().Root())
  334. }
  335. // StateAt returns a new mutable state based on a particular point in time.
  336. func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
  337. return state.New(root, bc.stateCache)
  338. }
  339. // Reset purges the entire blockchain, restoring it to its genesis state.
  340. func (bc *BlockChain) Reset() error {
  341. return bc.ResetWithGenesisBlock(bc.genesisBlock)
  342. }
  343. // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
  344. // specified genesis state.
  345. func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
  346. // Dump the entire block chain and purge the caches
  347. if err := bc.SetHead(0); err != nil {
  348. return err
  349. }
  350. bc.mu.Lock()
  351. defer bc.mu.Unlock()
  352. // Prepare the genesis block and reinitialise the chain
  353. if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
  354. log.Crit("Failed to write genesis block TD", "err", err)
  355. }
  356. if err := WriteBlock(bc.chainDb, genesis); err != nil {
  357. log.Crit("Failed to write genesis block", "err", err)
  358. }
  359. bc.genesisBlock = genesis
  360. bc.insert(bc.genesisBlock)
  361. bc.currentBlock = bc.genesisBlock
  362. bc.hc.SetGenesis(bc.genesisBlock.Header())
  363. bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
  364. bc.currentFastBlock = bc.genesisBlock
  365. return nil
  366. }
  367. // Export writes the active chain to the given writer.
  368. func (bc *BlockChain) Export(w io.Writer) error {
  369. return bc.ExportN(w, uint64(0), bc.currentBlock.NumberU64())
  370. }
  371. // ExportN writes a subset of the active chain to the given writer.
  372. func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
  373. bc.mu.RLock()
  374. defer bc.mu.RUnlock()
  375. if first > last {
  376. return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
  377. }
  378. log.Info("Exporting batch of blocks", "count", last-first+1)
  379. for nr := first; nr <= last; nr++ {
  380. block := bc.GetBlockByNumber(nr)
  381. if block == nil {
  382. return fmt.Errorf("export failed on #%d: not found", nr)
  383. }
  384. if err := block.EncodeRLP(w); err != nil {
  385. return err
  386. }
  387. }
  388. return nil
  389. }
  390. // insert injects a new head block into the current block chain. This method
  391. // assumes that the block is indeed a true head. It will also reset the head
  392. // header and the head fast sync block to this very same block if they are older
  393. // or if they are on a different side chain.
  394. //
  395. // Note, this function assumes that the `mu` mutex is held!
  396. func (bc *BlockChain) insert(block *types.Block) {
  397. // If the block is on a side chain or an unknown one, force other heads onto it too
  398. updateHeads := GetCanonicalHash(bc.chainDb, block.NumberU64()) != block.Hash()
  399. // Add the block to the canonical chain number scheme and mark as the head
  400. if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
  401. log.Crit("Failed to insert block number", "err", err)
  402. }
  403. if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
  404. log.Crit("Failed to insert head block hash", "err", err)
  405. }
  406. bc.currentBlock = block
  407. // If the block is better than out head or is on a different chain, force update heads
  408. if updateHeads {
  409. bc.hc.SetCurrentHeader(block.Header())
  410. if err := WriteHeadFastBlockHash(bc.chainDb, block.Hash()); err != nil {
  411. log.Crit("Failed to insert head fast block hash", "err", err)
  412. }
  413. bc.currentFastBlock = block
  414. }
  415. }
  416. // Genesis retrieves the chain's genesis block.
  417. func (bc *BlockChain) Genesis() *types.Block {
  418. return bc.genesisBlock
  419. }
  420. // GetBody retrieves a block body (transactions and uncles) from the database by
  421. // hash, caching it if found.
  422. func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
  423. // Short circuit if the body's already in the cache, retrieve otherwise
  424. if cached, ok := bc.bodyCache.Get(hash); ok {
  425. body := cached.(*types.Body)
  426. return body
  427. }
  428. body := GetBody(bc.chainDb, hash, bc.hc.GetBlockNumber(hash))
  429. if body == nil {
  430. return nil
  431. }
  432. // Cache the found body for next time and return
  433. bc.bodyCache.Add(hash, body)
  434. return body
  435. }
  436. // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
  437. // caching it if found.
  438. func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
  439. // Short circuit if the body's already in the cache, retrieve otherwise
  440. if cached, ok := bc.bodyRLPCache.Get(hash); ok {
  441. return cached.(rlp.RawValue)
  442. }
  443. body := GetBodyRLP(bc.chainDb, hash, bc.hc.GetBlockNumber(hash))
  444. if len(body) == 0 {
  445. return nil
  446. }
  447. // Cache the found body for next time and return
  448. bc.bodyRLPCache.Add(hash, body)
  449. return body
  450. }
  451. // HasBlock checks if a block is fully present in the database or not.
  452. func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
  453. if bc.blockCache.Contains(hash) {
  454. return true
  455. }
  456. ok, _ := bc.chainDb.Has(blockBodyKey(hash, number))
  457. return ok
  458. }
  459. // HasBlockAndState checks if a block and associated state trie is fully present
  460. // in the database or not, caching it if present.
  461. func (bc *BlockChain) HasBlockAndState(hash common.Hash) bool {
  462. // Check first that the block itself is known
  463. block := bc.GetBlockByHash(hash)
  464. if block == nil {
  465. return false
  466. }
  467. // Ensure the associated state is also present
  468. _, err := bc.stateCache.OpenTrie(block.Root())
  469. return err == nil
  470. }
  471. // GetBlock retrieves a block from the database by hash and number,
  472. // caching it if found.
  473. func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  474. // Short circuit if the block's already in the cache, retrieve otherwise
  475. if block, ok := bc.blockCache.Get(hash); ok {
  476. return block.(*types.Block)
  477. }
  478. block := GetBlock(bc.chainDb, hash, number)
  479. if block == nil {
  480. return nil
  481. }
  482. // Cache the found block for next time and return
  483. bc.blockCache.Add(block.Hash(), block)
  484. return block
  485. }
  486. // GetBlockByHash retrieves a block from the database by hash, caching it if found.
  487. func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
  488. return bc.GetBlock(hash, bc.hc.GetBlockNumber(hash))
  489. }
  490. // GetBlockByNumber retrieves a block from the database by number, caching it
  491. // (associated with its hash) if found.
  492. func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
  493. hash := GetCanonicalHash(bc.chainDb, number)
  494. if hash == (common.Hash{}) {
  495. return nil
  496. }
  497. return bc.GetBlock(hash, number)
  498. }
  499. // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
  500. // [deprecated by eth/62]
  501. func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
  502. number := bc.hc.GetBlockNumber(hash)
  503. for i := 0; i < n; i++ {
  504. block := bc.GetBlock(hash, number)
  505. if block == nil {
  506. break
  507. }
  508. blocks = append(blocks, block)
  509. hash = block.ParentHash()
  510. number--
  511. }
  512. return
  513. }
  514. // GetUnclesInChain retrieves all the uncles from a given block backwards until
  515. // a specific distance is reached.
  516. func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
  517. uncles := []*types.Header{}
  518. for i := 0; block != nil && i < length; i++ {
  519. uncles = append(uncles, block.Uncles()...)
  520. block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  521. }
  522. return uncles
  523. }
  524. // Stop stops the blockchain service. If any imports are currently in progress
  525. // it will abort them using the procInterrupt.
  526. func (bc *BlockChain) Stop() {
  527. if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
  528. return
  529. }
  530. // Unsubscribe all subscriptions registered from blockchain
  531. bc.scope.Close()
  532. close(bc.quit)
  533. atomic.StoreInt32(&bc.procInterrupt, 1)
  534. bc.wg.Wait()
  535. log.Info("Blockchain manager stopped")
  536. }
  537. func (bc *BlockChain) procFutureBlocks() {
  538. blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
  539. for _, hash := range bc.futureBlocks.Keys() {
  540. if block, exist := bc.futureBlocks.Peek(hash); exist {
  541. blocks = append(blocks, block.(*types.Block))
  542. }
  543. }
  544. if len(blocks) > 0 {
  545. types.BlockBy(types.Number).Sort(blocks)
  546. // Insert one by one as chain insertion needs contiguous ancestry between blocks
  547. for i := range blocks {
  548. bc.InsertChain(blocks[i : i+1])
  549. }
  550. }
  551. }
  552. // WriteStatus status of write
  553. type WriteStatus byte
  554. const (
  555. NonStatTy WriteStatus = iota
  556. CanonStatTy
  557. SideStatTy
  558. )
  559. // Rollback is designed to remove a chain of links from the database that aren't
  560. // certain enough to be valid.
  561. func (bc *BlockChain) Rollback(chain []common.Hash) {
  562. bc.mu.Lock()
  563. defer bc.mu.Unlock()
  564. for i := len(chain) - 1; i >= 0; i-- {
  565. hash := chain[i]
  566. currentHeader := bc.hc.CurrentHeader()
  567. if currentHeader.Hash() == hash {
  568. bc.hc.SetCurrentHeader(bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
  569. }
  570. if bc.currentFastBlock.Hash() == hash {
  571. bc.currentFastBlock = bc.GetBlock(bc.currentFastBlock.ParentHash(), bc.currentFastBlock.NumberU64()-1)
  572. WriteHeadFastBlockHash(bc.chainDb, bc.currentFastBlock.Hash())
  573. }
  574. if bc.currentBlock.Hash() == hash {
  575. bc.currentBlock = bc.GetBlock(bc.currentBlock.ParentHash(), bc.currentBlock.NumberU64()-1)
  576. WriteHeadBlockHash(bc.chainDb, bc.currentBlock.Hash())
  577. }
  578. }
  579. }
  580. // SetReceiptsData computes all the non-consensus fields of the receipts
  581. func SetReceiptsData(config *params.ChainConfig, block *types.Block, receipts types.Receipts) {
  582. signer := types.MakeSigner(config, block.Number())
  583. transactions, logIndex := block.Transactions(), uint(0)
  584. for j := 0; j < len(receipts); j++ {
  585. // The transaction hash can be retrieved from the transaction itself
  586. receipts[j].TxHash = transactions[j].Hash()
  587. // The contract address can be derived from the transaction itself
  588. if transactions[j].To() == nil {
  589. // Deriving the signer is expensive, only do if it's actually needed
  590. from, _ := types.Sender(signer, transactions[j])
  591. receipts[j].ContractAddress = crypto.CreateAddress(from, transactions[j].Nonce())
  592. }
  593. // The used gas can be calculated based on previous receipts
  594. if j == 0 {
  595. receipts[j].GasUsed = receipts[j].CumulativeGasUsed
  596. } else {
  597. receipts[j].GasUsed = receipts[j].CumulativeGasUsed - receipts[j-1].CumulativeGasUsed
  598. }
  599. // The derived log fields can simply be set from the block and transaction
  600. for k := 0; k < len(receipts[j].Logs); k++ {
  601. receipts[j].Logs[k].BlockNumber = block.NumberU64()
  602. receipts[j].Logs[k].BlockHash = block.Hash()
  603. receipts[j].Logs[k].TxHash = receipts[j].TxHash
  604. receipts[j].Logs[k].TxIndex = uint(j)
  605. receipts[j].Logs[k].Index = logIndex
  606. logIndex++
  607. }
  608. }
  609. }
  610. // InsertReceiptChain attempts to complete an already existing header chain with
  611. // transaction and receipt data.
  612. func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
  613. bc.wg.Add(1)
  614. defer bc.wg.Done()
  615. // Do a sanity check that the provided chain is actually ordered and linked
  616. for i := 1; i < len(blockChain); i++ {
  617. if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
  618. log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
  619. "prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
  620. 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(),
  621. blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
  622. }
  623. }
  624. var (
  625. stats = struct{ processed, ignored int32 }{}
  626. start = time.Now()
  627. bytes = 0
  628. batch = bc.chainDb.NewBatch()
  629. )
  630. for i, block := range blockChain {
  631. receipts := receiptChain[i]
  632. // Short circuit insertion if shutting down or processing failed
  633. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  634. return 0, nil
  635. }
  636. // Short circuit if the owner header is unknown
  637. if !bc.HasHeader(block.Hash(), block.NumberU64()) {
  638. return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
  639. }
  640. // Skip if the entire data is already known
  641. if bc.HasBlock(block.Hash(), block.NumberU64()) {
  642. stats.ignored++
  643. continue
  644. }
  645. // Compute all the non-consensus fields of the receipts
  646. SetReceiptsData(bc.config, block, receipts)
  647. // Write all the data out into the database
  648. if err := WriteBody(batch, block.Hash(), block.NumberU64(), block.Body()); err != nil {
  649. return i, fmt.Errorf("failed to write block body: %v", err)
  650. }
  651. if err := WriteBlockReceipts(batch, block.Hash(), block.NumberU64(), receipts); err != nil {
  652. return i, fmt.Errorf("failed to write block receipts: %v", err)
  653. }
  654. if err := WriteTxLookupEntries(batch, block); err != nil {
  655. return i, fmt.Errorf("failed to write lookup metadata: %v", err)
  656. }
  657. stats.processed++
  658. if batch.ValueSize() >= ethdb.IdealBatchSize {
  659. if err := batch.Write(); err != nil {
  660. return 0, err
  661. }
  662. bytes += batch.ValueSize()
  663. batch = bc.chainDb.NewBatch()
  664. }
  665. }
  666. if batch.ValueSize() > 0 {
  667. bytes += batch.ValueSize()
  668. if err := batch.Write(); err != nil {
  669. return 0, err
  670. }
  671. }
  672. // Update the head fast sync block if better
  673. bc.mu.Lock()
  674. head := blockChain[len(blockChain)-1]
  675. if td := bc.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case
  676. if bc.GetTd(bc.currentFastBlock.Hash(), bc.currentFastBlock.NumberU64()).Cmp(td) < 0 {
  677. if err := WriteHeadFastBlockHash(bc.chainDb, head.Hash()); err != nil {
  678. log.Crit("Failed to update head fast block hash", "err", err)
  679. }
  680. bc.currentFastBlock = head
  681. }
  682. }
  683. bc.mu.Unlock()
  684. log.Info("Imported new block receipts",
  685. "count", stats.processed,
  686. "elapsed", common.PrettyDuration(time.Since(start)),
  687. "bytes", bytes,
  688. "number", head.Number(),
  689. "hash", head.Hash(),
  690. "ignored", stats.ignored)
  691. return 0, nil
  692. }
  693. // WriteBlock writes the block to the chain.
  694. func (bc *BlockChain) WriteBlockAndState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
  695. bc.wg.Add(1)
  696. defer bc.wg.Done()
  697. // Calculate the total difficulty of the block
  698. ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  699. if ptd == nil {
  700. return NonStatTy, consensus.ErrUnknownAncestor
  701. }
  702. // Make sure no inconsistent state is leaked during insertion
  703. bc.mu.Lock()
  704. defer bc.mu.Unlock()
  705. localTd := bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64())
  706. externTd := new(big.Int).Add(block.Difficulty(), ptd)
  707. // Irrelevant of the canonical status, write the block itself to the database
  708. if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
  709. return NonStatTy, err
  710. }
  711. // Write other block data using a batch.
  712. batch := bc.chainDb.NewBatch()
  713. if err := WriteBlock(batch, block); err != nil {
  714. return NonStatTy, err
  715. }
  716. if _, err := state.CommitTo(batch, bc.config.IsEIP158(block.Number())); err != nil {
  717. return NonStatTy, err
  718. }
  719. if err := WriteBlockReceipts(batch, block.Hash(), block.NumberU64(), receipts); err != nil {
  720. return NonStatTy, err
  721. }
  722. // If the total difficulty is higher than our known, add it to the canonical chain
  723. // Second clause in the if statement reduces the vulnerability to selfish mining.
  724. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  725. reorg := externTd.Cmp(localTd) > 0
  726. if !reorg && externTd.Cmp(localTd) == 0 {
  727. // Split same-difficulty blocks by number, then at random
  728. reorg = block.NumberU64() < bc.currentBlock.NumberU64() || (block.NumberU64() == bc.currentBlock.NumberU64() && mrand.Float64() < 0.5)
  729. }
  730. if reorg {
  731. // Reorganise the chain if the parent is not the head block
  732. if block.ParentHash() != bc.currentBlock.Hash() {
  733. if err := bc.reorg(bc.currentBlock, block); err != nil {
  734. return NonStatTy, err
  735. }
  736. }
  737. // Write the positional metadata for transaction and receipt lookups
  738. if err := WriteTxLookupEntries(batch, block); err != nil {
  739. return NonStatTy, err
  740. }
  741. // Write hash preimages
  742. if err := WritePreimages(bc.chainDb, block.NumberU64(), state.Preimages()); err != nil {
  743. return NonStatTy, err
  744. }
  745. status = CanonStatTy
  746. } else {
  747. status = SideStatTy
  748. }
  749. if err := batch.Write(); err != nil {
  750. return NonStatTy, err
  751. }
  752. // Set new head.
  753. if status == CanonStatTy {
  754. bc.insert(block)
  755. }
  756. bc.futureBlocks.Remove(block.Hash())
  757. return status, nil
  758. }
  759. // InsertChain attempts to insert the given batch of blocks in to the canonical
  760. // chain or, otherwise, create a fork. If an error is returned it will return
  761. // the index number of the failing block as well an error describing what went
  762. // wrong.
  763. //
  764. // After insertion is done, all accumulated events will be fired.
  765. func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  766. n, events, logs, err := bc.insertChain(chain)
  767. bc.PostChainEvents(events, logs)
  768. return n, err
  769. }
  770. // insertChain will execute the actual chain insertion and event aggregation. The
  771. // only reason this method exists as a separate one is to make locking cleaner
  772. // with deferred statements.
  773. func (bc *BlockChain) insertChain(chain types.Blocks) (int, []interface{}, []*types.Log, error) {
  774. // Do a sanity check that the provided chain is actually ordered and linked
  775. for i := 1; i < len(chain); i++ {
  776. if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
  777. // Chain broke ancestry, log a messge (programming error) and skip insertion
  778. log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(),
  779. "parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash())
  780. return 0, nil, nil, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(),
  781. chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
  782. }
  783. }
  784. // Pre-checks passed, start the full block imports
  785. bc.wg.Add(1)
  786. defer bc.wg.Done()
  787. bc.chainmu.Lock()
  788. defer bc.chainmu.Unlock()
  789. // A queued approach to delivering events. This is generally
  790. // faster than direct delivery and requires much less mutex
  791. // acquiring.
  792. var (
  793. stats = insertStats{startTime: mclock.Now()}
  794. events = make([]interface{}, 0, len(chain))
  795. lastCanon *types.Block
  796. coalescedLogs []*types.Log
  797. )
  798. // Start the parallel header verifier
  799. headers := make([]*types.Header, len(chain))
  800. seals := make([]bool, len(chain))
  801. for i, block := range chain {
  802. headers[i] = block.Header()
  803. seals[i] = true
  804. }
  805. abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  806. defer close(abort)
  807. // Iterate over the blocks and insert when the verifier permits
  808. for i, block := range chain {
  809. // If the chain is terminating, stop processing blocks
  810. if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  811. log.Debug("Premature abort during blocks processing")
  812. break
  813. }
  814. // If the header is a banned one, straight out abort
  815. if BadHashes[block.Hash()] {
  816. bc.reportBlock(block, nil, ErrBlacklistedHash)
  817. return i, events, coalescedLogs, ErrBlacklistedHash
  818. }
  819. // Wait for the block's verification to complete
  820. bstart := time.Now()
  821. err := <-results
  822. if err == nil {
  823. err = bc.Validator().ValidateBody(block)
  824. }
  825. if err != nil {
  826. if err == ErrKnownBlock {
  827. stats.ignored++
  828. continue
  829. }
  830. if err == consensus.ErrFutureBlock {
  831. // Allow up to MaxFuture second in the future blocks. If this limit
  832. // is exceeded the chain is discarded and processed at a later time
  833. // if given.
  834. max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
  835. if block.Time().Cmp(max) > 0 {
  836. return i, events, coalescedLogs, fmt.Errorf("future block: %v > %v", block.Time(), max)
  837. }
  838. bc.futureBlocks.Add(block.Hash(), block)
  839. stats.queued++
  840. continue
  841. }
  842. if err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(block.ParentHash()) {
  843. bc.futureBlocks.Add(block.Hash(), block)
  844. stats.queued++
  845. continue
  846. }
  847. bc.reportBlock(block, nil, err)
  848. return i, events, coalescedLogs, err
  849. }
  850. // Create a new statedb using the parent block and report an
  851. // error if it fails.
  852. var parent *types.Block
  853. if i == 0 {
  854. parent = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  855. } else {
  856. parent = chain[i-1]
  857. }
  858. state, err := state.New(parent.Root(), bc.stateCache)
  859. if err != nil {
  860. return i, events, coalescedLogs, err
  861. }
  862. // Process block using the parent state as reference point.
  863. receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
  864. if err != nil {
  865. bc.reportBlock(block, receipts, err)
  866. return i, events, coalescedLogs, err
  867. }
  868. // Validate the state using the default validator
  869. err = bc.Validator().ValidateState(block, parent, state, receipts, usedGas)
  870. if err != nil {
  871. bc.reportBlock(block, receipts, err)
  872. return i, events, coalescedLogs, err
  873. }
  874. // Write the block to the chain and get the status.
  875. status, err := bc.WriteBlockAndState(block, receipts, state)
  876. if err != nil {
  877. return i, events, coalescedLogs, err
  878. }
  879. switch status {
  880. case CanonStatTy:
  881. log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(), "uncles", len(block.Uncles()),
  882. "txs", len(block.Transactions()), "gas", block.GasUsed(), "elapsed", common.PrettyDuration(time.Since(bstart)))
  883. coalescedLogs = append(coalescedLogs, logs...)
  884. blockInsertTimer.UpdateSince(bstart)
  885. events = append(events, ChainEvent{block, block.Hash(), logs})
  886. lastCanon = block
  887. case SideStatTy:
  888. log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(), "diff", block.Difficulty(), "elapsed",
  889. common.PrettyDuration(time.Since(bstart)), "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()))
  890. blockInsertTimer.UpdateSince(bstart)
  891. events = append(events, ChainSideEvent{block})
  892. }
  893. stats.processed++
  894. stats.usedGas += usedGas
  895. stats.report(chain, i)
  896. }
  897. // Append a single chain head event if we've progressed the chain
  898. if lastCanon != nil && bc.LastBlockHash() == lastCanon.Hash() {
  899. events = append(events, ChainHeadEvent{lastCanon})
  900. }
  901. return 0, events, coalescedLogs, nil
  902. }
  903. // insertStats tracks and reports on block insertion.
  904. type insertStats struct {
  905. queued, processed, ignored int
  906. usedGas uint64
  907. lastIndex int
  908. startTime mclock.AbsTime
  909. }
  910. // statsReportLimit is the time limit during import after which we always print
  911. // out progress. This avoids the user wondering what's going on.
  912. const statsReportLimit = 8 * time.Second
  913. // report prints statistics if some number of blocks have been processed
  914. // or more than a few seconds have passed since the last message.
  915. func (st *insertStats) report(chain []*types.Block, index int) {
  916. // Fetch the timings for the batch
  917. var (
  918. now = mclock.Now()
  919. elapsed = time.Duration(now) - time.Duration(st.startTime)
  920. )
  921. // If we're at the last block of the batch or report period reached, log
  922. if index == len(chain)-1 || elapsed >= statsReportLimit {
  923. var (
  924. end = chain[index]
  925. txs = countTransactions(chain[st.lastIndex : index+1])
  926. )
  927. context := []interface{}{
  928. "blocks", st.processed, "txs", txs, "mgas", float64(st.usedGas) / 1000000,
  929. "elapsed", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed),
  930. "number", end.Number(), "hash", end.Hash(),
  931. }
  932. if st.queued > 0 {
  933. context = append(context, []interface{}{"queued", st.queued}...)
  934. }
  935. if st.ignored > 0 {
  936. context = append(context, []interface{}{"ignored", st.ignored}...)
  937. }
  938. log.Info("Imported new chain segment", context...)
  939. *st = insertStats{startTime: now, lastIndex: index + 1}
  940. }
  941. }
  942. func countTransactions(chain []*types.Block) (c int) {
  943. for _, b := range chain {
  944. c += len(b.Transactions())
  945. }
  946. return c
  947. }
  948. // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  949. // to be part of the new canonical chain and accumulates potential missing transactions and post an
  950. // event about them
  951. func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  952. var (
  953. newChain types.Blocks
  954. oldChain types.Blocks
  955. commonBlock *types.Block
  956. deletedTxs types.Transactions
  957. deletedLogs []*types.Log
  958. // collectLogs collects the logs that were generated during the
  959. // processing of the block that corresponds with the given hash.
  960. // These logs are later announced as deleted.
  961. collectLogs = func(h common.Hash) {
  962. // Coalesce logs and set 'Removed'.
  963. receipts := GetBlockReceipts(bc.chainDb, h, bc.hc.GetBlockNumber(h))
  964. for _, receipt := range receipts {
  965. for _, log := range receipt.Logs {
  966. del := *log
  967. del.Removed = true
  968. deletedLogs = append(deletedLogs, &del)
  969. }
  970. }
  971. }
  972. )
  973. // first reduce whoever is higher bound
  974. if oldBlock.NumberU64() > newBlock.NumberU64() {
  975. // reduce old chain
  976. for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  977. oldChain = append(oldChain, oldBlock)
  978. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  979. collectLogs(oldBlock.Hash())
  980. }
  981. } else {
  982. // reduce new chain and append new chain blocks for inserting later on
  983. for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  984. newChain = append(newChain, newBlock)
  985. }
  986. }
  987. if oldBlock == nil {
  988. return fmt.Errorf("Invalid old chain")
  989. }
  990. if newBlock == nil {
  991. return fmt.Errorf("Invalid new chain")
  992. }
  993. for {
  994. if oldBlock.Hash() == newBlock.Hash() {
  995. commonBlock = oldBlock
  996. break
  997. }
  998. oldChain = append(oldChain, oldBlock)
  999. newChain = append(newChain, newBlock)
  1000. deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1001. collectLogs(oldBlock.Hash())
  1002. oldBlock, newBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1003. if oldBlock == nil {
  1004. return fmt.Errorf("Invalid old chain")
  1005. }
  1006. if newBlock == nil {
  1007. return fmt.Errorf("Invalid new chain")
  1008. }
  1009. }
  1010. // Ensure the user sees large reorgs
  1011. if len(oldChain) > 0 && len(newChain) > 0 {
  1012. logFn := log.Debug
  1013. if len(oldChain) > 63 {
  1014. logFn = log.Warn
  1015. }
  1016. logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1017. "drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1018. } else {
  1019. log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1020. }
  1021. var addedTxs types.Transactions
  1022. // insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
  1023. for _, block := range newChain {
  1024. // insert the block in the canonical way, re-writing history
  1025. bc.insert(block)
  1026. // write lookup entries for hash based transaction/receipt searches
  1027. if err := WriteTxLookupEntries(bc.chainDb, block); err != nil {
  1028. return err
  1029. }
  1030. addedTxs = append(addedTxs, block.Transactions()...)
  1031. }
  1032. // calculate the difference between deleted and added transactions
  1033. diff := types.TxDifference(deletedTxs, addedTxs)
  1034. // When transactions get deleted from the database that means the
  1035. // receipts that were created in the fork must also be deleted
  1036. for _, tx := range diff {
  1037. DeleteTxLookupEntry(bc.chainDb, tx.Hash())
  1038. }
  1039. if len(deletedLogs) > 0 {
  1040. go bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs})
  1041. }
  1042. if len(oldChain) > 0 {
  1043. go func() {
  1044. for _, block := range oldChain {
  1045. bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1046. }
  1047. }()
  1048. }
  1049. return nil
  1050. }
  1051. // PostChainEvents iterates over the events generated by a chain insertion and
  1052. // posts them into the event feed.
  1053. // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.
  1054. func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) {
  1055. // post event logs for further processing
  1056. if logs != nil {
  1057. bc.logsFeed.Send(logs)
  1058. }
  1059. for _, event := range events {
  1060. switch ev := event.(type) {
  1061. case ChainEvent:
  1062. bc.chainFeed.Send(ev)
  1063. case ChainHeadEvent:
  1064. bc.chainHeadFeed.Send(ev)
  1065. case ChainSideEvent:
  1066. bc.chainSideFeed.Send(ev)
  1067. }
  1068. }
  1069. }
  1070. func (bc *BlockChain) update() {
  1071. futureTimer := time.NewTicker(5 * time.Second)
  1072. defer futureTimer.Stop()
  1073. for {
  1074. select {
  1075. case <-futureTimer.C:
  1076. bc.procFutureBlocks()
  1077. case <-bc.quit:
  1078. return
  1079. }
  1080. }
  1081. }
  1082. // BadBlockArgs represents the entries in the list returned when bad blocks are queried.
  1083. type BadBlockArgs struct {
  1084. Hash common.Hash `json:"hash"`
  1085. Header *types.Header `json:"header"`
  1086. }
  1087. // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1088. func (bc *BlockChain) BadBlocks() ([]BadBlockArgs, error) {
  1089. headers := make([]BadBlockArgs, 0, bc.badBlocks.Len())
  1090. for _, hash := range bc.badBlocks.Keys() {
  1091. if hdr, exist := bc.badBlocks.Peek(hash); exist {
  1092. header := hdr.(*types.Header)
  1093. headers = append(headers, BadBlockArgs{header.Hash(), header})
  1094. }
  1095. }
  1096. return headers, nil
  1097. }
  1098. // addBadBlock adds a bad block to the bad-block LRU cache
  1099. func (bc *BlockChain) addBadBlock(block *types.Block) {
  1100. bc.badBlocks.Add(block.Header().Hash(), block.Header())
  1101. }
  1102. // reportBlock logs a bad block error.
  1103. func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1104. bc.addBadBlock(block)
  1105. var receiptString string
  1106. for _, receipt := range receipts {
  1107. receiptString += fmt.Sprintf("\t%v\n", receipt)
  1108. }
  1109. log.Error(fmt.Sprintf(`
  1110. ########## BAD BLOCK #########
  1111. Chain config: %v
  1112. Number: %v
  1113. Hash: 0x%x
  1114. %v
  1115. Error: %v
  1116. ##############################
  1117. `, bc.config, block.Number(), block.Hash(), receiptString, err))
  1118. }
  1119. // InsertHeaderChain attempts to insert the given header chain in to the local
  1120. // chain, possibly creating a reorg. If an error is returned, it will return the
  1121. // index number of the failing header as well an error describing what went wrong.
  1122. //
  1123. // The verify parameter can be used to fine tune whether nonce verification
  1124. // should be done or not. The reason behind the optional check is because some
  1125. // of the header retrieval mechanisms already need to verify nonces, as well as
  1126. // because nonces can be verified sparsely, not needing to check each.
  1127. func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1128. start := time.Now()
  1129. if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1130. return i, err
  1131. }
  1132. // Make sure only one thread manipulates the chain at once
  1133. bc.chainmu.Lock()
  1134. defer bc.chainmu.Unlock()
  1135. bc.wg.Add(1)
  1136. defer bc.wg.Done()
  1137. whFunc := func(header *types.Header) error {
  1138. bc.mu.Lock()
  1139. defer bc.mu.Unlock()
  1140. _, err := bc.hc.WriteHeader(header)
  1141. return err
  1142. }
  1143. return bc.hc.InsertHeaderChain(chain, whFunc, start)
  1144. }
  1145. // writeHeader writes a header into the local chain, given that its parent is
  1146. // already known. If the total difficulty of the newly inserted header becomes
  1147. // greater than the current known TD, the canonical chain is re-routed.
  1148. //
  1149. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  1150. // into the chain, as side effects caused by reorganisations cannot be emulated
  1151. // without the real blocks. Hence, writing headers directly should only be done
  1152. // in two scenarios: pure-header mode of operation (light clients), or properly
  1153. // separated header/block phases (non-archive clients).
  1154. func (bc *BlockChain) writeHeader(header *types.Header) error {
  1155. bc.wg.Add(1)
  1156. defer bc.wg.Done()
  1157. bc.mu.Lock()
  1158. defer bc.mu.Unlock()
  1159. _, err := bc.hc.WriteHeader(header)
  1160. return err
  1161. }
  1162. // CurrentHeader retrieves the current head header of the canonical chain. The
  1163. // header is retrieved from the HeaderChain's internal cache.
  1164. func (bc *BlockChain) CurrentHeader() *types.Header {
  1165. bc.mu.RLock()
  1166. defer bc.mu.RUnlock()
  1167. return bc.hc.CurrentHeader()
  1168. }
  1169. // GetTd retrieves a block's total difficulty in the canonical chain from the
  1170. // database by hash and number, caching it if found.
  1171. func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1172. return bc.hc.GetTd(hash, number)
  1173. }
  1174. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1175. // database by hash, caching it if found.
  1176. func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1177. return bc.hc.GetTdByHash(hash)
  1178. }
  1179. // GetHeader retrieves a block header from the database by hash and number,
  1180. // caching it if found.
  1181. func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1182. return bc.hc.GetHeader(hash, number)
  1183. }
  1184. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1185. // found.
  1186. func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1187. return bc.hc.GetHeaderByHash(hash)
  1188. }
  1189. // HasHeader checks if a block header is present in the database or not, caching
  1190. // it if present.
  1191. func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  1192. return bc.hc.HasHeader(hash, number)
  1193. }
  1194. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1195. // hash, fetching towards the genesis block.
  1196. func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1197. return bc.hc.GetBlockHashesFromHash(hash, max)
  1198. }
  1199. // GetHeaderByNumber retrieves a block header from the database by number,
  1200. // caching it (associated with its hash) if found.
  1201. func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1202. return bc.hc.GetHeaderByNumber(number)
  1203. }
  1204. // Config retrieves the blockchain's chain configuration.
  1205. func (bc *BlockChain) Config() *params.ChainConfig { return bc.config }
  1206. // Engine retrieves the blockchain's consensus engine.
  1207. func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  1208. // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  1209. func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  1210. return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  1211. }
  1212. // SubscribeChainEvent registers a subscription of ChainEvent.
  1213. func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  1214. return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  1215. }
  1216. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  1217. func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  1218. return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  1219. }
  1220. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  1221. func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  1222. return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  1223. }
  1224. // SubscribeLogsEvent registers a subscription of []*types.Log.
  1225. func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  1226. return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  1227. }