blockchain.go 42 KB

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