blockchain.go 40 KB

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