blockchain.go 55 KB

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