blockchain.go 46 KB

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