blockchain.go 54 KB

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