blockchain.go 47 KB

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