blockchain.go 49 KB

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