headerchain.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. // Copyright 2015 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
  17. import (
  18. crand "crypto/rand"
  19. "errors"
  20. "fmt"
  21. "math"
  22. "math/big"
  23. mrand "math/rand"
  24. "sync/atomic"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/consensus"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/log"
  32. "github.com/ethereum/go-ethereum/params"
  33. lru "github.com/hashicorp/golang-lru"
  34. )
  35. const (
  36. headerCacheLimit = 512
  37. tdCacheLimit = 1024
  38. numberCacheLimit = 2048
  39. )
  40. // HeaderChain implements the basic block header chain logic that is shared by
  41. // core.BlockChain and light.LightChain. It is not usable in itself, only as
  42. // a part of either structure.
  43. // It is not thread safe either, the encapsulating chain structures should do
  44. // the necessary mutex locking/unlocking.
  45. type HeaderChain struct {
  46. config *params.ChainConfig
  47. chainDb ethdb.Database
  48. genesisHeader *types.Header
  49. currentHeader atomic.Value // Current head of the header chain (may be above the block chain!)
  50. currentHeaderHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time)
  51. headerCache *lru.Cache // Cache for the most recent block headers
  52. tdCache *lru.Cache // Cache for the most recent block total difficulties
  53. numberCache *lru.Cache // Cache for the most recent block numbers
  54. procInterrupt func() bool
  55. rand *mrand.Rand
  56. engine consensus.Engine
  57. }
  58. // NewHeaderChain creates a new HeaderChain structure.
  59. // getValidator should return the parent's validator
  60. // procInterrupt points to the parent's interrupt semaphore
  61. // wg points to the parent's shutdown wait group
  62. func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
  63. headerCache, _ := lru.New(headerCacheLimit)
  64. tdCache, _ := lru.New(tdCacheLimit)
  65. numberCache, _ := lru.New(numberCacheLimit)
  66. // Seed a fast but crypto originating random generator
  67. seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
  68. if err != nil {
  69. return nil, err
  70. }
  71. hc := &HeaderChain{
  72. config: config,
  73. chainDb: chainDb,
  74. headerCache: headerCache,
  75. tdCache: tdCache,
  76. numberCache: numberCache,
  77. procInterrupt: procInterrupt,
  78. rand: mrand.New(mrand.NewSource(seed.Int64())),
  79. engine: engine,
  80. }
  81. hc.genesisHeader = hc.GetHeaderByNumber(0)
  82. if hc.genesisHeader == nil {
  83. return nil, ErrNoGenesis
  84. }
  85. hc.currentHeader.Store(hc.genesisHeader)
  86. if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) {
  87. if chead := hc.GetHeaderByHash(head); chead != nil {
  88. hc.currentHeader.Store(chead)
  89. }
  90. }
  91. hc.currentHeaderHash = hc.CurrentHeader().Hash()
  92. headHeaderGauge.Update(hc.CurrentHeader().Number.Int64())
  93. return hc, nil
  94. }
  95. // GetBlockNumber retrieves the block number belonging to the given hash
  96. // from the cache or database
  97. func (hc *HeaderChain) GetBlockNumber(hash common.Hash) *uint64 {
  98. if cached, ok := hc.numberCache.Get(hash); ok {
  99. number := cached.(uint64)
  100. return &number
  101. }
  102. number := rawdb.ReadHeaderNumber(hc.chainDb, hash)
  103. if number != nil {
  104. hc.numberCache.Add(hash, *number)
  105. }
  106. return number
  107. }
  108. // WriteHeader writes a header into the local chain, given that its parent is
  109. // already known. If the total difficulty of the newly inserted header becomes
  110. // greater than the current known TD, the canonical chain is re-routed.
  111. //
  112. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  113. // into the chain, as side effects caused by reorganisations cannot be emulated
  114. // without the real blocks. Hence, writing headers directly should only be done
  115. // in two scenarios: pure-header mode of operation (light clients), or properly
  116. // separated header/block phases (non-archive clients).
  117. func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) {
  118. // Cache some values to prevent constant recalculation
  119. var (
  120. hash = header.Hash()
  121. number = header.Number.Uint64()
  122. )
  123. // Calculate the total difficulty of the header
  124. ptd := hc.GetTd(header.ParentHash, number-1)
  125. if ptd == nil {
  126. return NonStatTy, consensus.ErrUnknownAncestor
  127. }
  128. localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64())
  129. externTd := new(big.Int).Add(header.Difficulty, ptd)
  130. // Irrelevant of the canonical status, write the td and header to the database
  131. if err := hc.WriteTd(hash, number, externTd); err != nil {
  132. log.Crit("Failed to write header total difficulty", "err", err)
  133. }
  134. rawdb.WriteHeader(hc.chainDb, header)
  135. // If the total difficulty is higher than our known, add it to the canonical chain
  136. // Second clause in the if statement reduces the vulnerability to selfish mining.
  137. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  138. if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
  139. // Delete any canonical number assignments above the new head
  140. batch := hc.chainDb.NewBatch()
  141. for i := number + 1; ; i++ {
  142. hash := rawdb.ReadCanonicalHash(hc.chainDb, i)
  143. if hash == (common.Hash{}) {
  144. break
  145. }
  146. rawdb.DeleteCanonicalHash(batch, i)
  147. }
  148. batch.Write()
  149. // Overwrite any stale canonical number assignments
  150. var (
  151. headHash = header.ParentHash
  152. headNumber = header.Number.Uint64() - 1
  153. headHeader = hc.GetHeader(headHash, headNumber)
  154. )
  155. for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash {
  156. rawdb.WriteCanonicalHash(hc.chainDb, headHash, headNumber)
  157. headHash = headHeader.ParentHash
  158. headNumber = headHeader.Number.Uint64() - 1
  159. headHeader = hc.GetHeader(headHash, headNumber)
  160. }
  161. // Extend the canonical chain with the new header
  162. rawdb.WriteCanonicalHash(hc.chainDb, hash, number)
  163. rawdb.WriteHeadHeaderHash(hc.chainDb, hash)
  164. hc.currentHeaderHash = hash
  165. hc.currentHeader.Store(types.CopyHeader(header))
  166. headHeaderGauge.Update(header.Number.Int64())
  167. status = CanonStatTy
  168. } else {
  169. status = SideStatTy
  170. }
  171. hc.headerCache.Add(hash, header)
  172. hc.numberCache.Add(hash, number)
  173. return
  174. }
  175. // WhCallback is a callback function for inserting individual headers.
  176. // A callback is used for two reasons: first, in a LightChain, status should be
  177. // processed and light chain events sent, while in a BlockChain this is not
  178. // necessary since chain events are sent after inserting blocks. Second, the
  179. // header writes should be protected by the parent chain mutex individually.
  180. type WhCallback func(*types.Header) error
  181. func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  182. // Do a sanity check that the provided chain is actually ordered and linked
  183. for i := 1; i < len(chain); i++ {
  184. if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
  185. // Chain broke ancestry, log a message (programming error) and skip insertion
  186. log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
  187. "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())
  188. return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].Number,
  189. chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
  190. }
  191. }
  192. // Generate the list of seal verification requests, and start the parallel verifier
  193. seals := make([]bool, len(chain))
  194. if checkFreq != 0 {
  195. // In case of checkFreq == 0 all seals are left false.
  196. for i := 0; i < len(seals)/checkFreq; i++ {
  197. index := i*checkFreq + hc.rand.Intn(checkFreq)
  198. if index >= len(seals) {
  199. index = len(seals) - 1
  200. }
  201. seals[index] = true
  202. }
  203. // Last should always be verified to avoid junk.
  204. seals[len(seals)-1] = true
  205. }
  206. abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
  207. defer close(abort)
  208. // Iterate over the headers and ensure they all check out
  209. for i, header := range chain {
  210. // If the chain is terminating, stop processing blocks
  211. if hc.procInterrupt() {
  212. log.Debug("Premature abort during headers verification")
  213. return 0, errors.New("aborted")
  214. }
  215. // If the header is a banned one, straight out abort
  216. if BadHashes[header.Hash()] {
  217. return i, ErrBlacklistedHash
  218. }
  219. // Otherwise wait for headers checks and ensure they pass
  220. if err := <-results; err != nil {
  221. return i, err
  222. }
  223. }
  224. return 0, nil
  225. }
  226. // InsertHeaderChain attempts to insert the given header chain in to the local
  227. // chain, possibly creating a reorg. If an error is returned, it will return the
  228. // index number of the failing header as well an error describing what went wrong.
  229. //
  230. // The verify parameter can be used to fine tune whether nonce verification
  231. // should be done or not. The reason behind the optional check is because some
  232. // of the header retrieval mechanisms already need to verfy nonces, as well as
  233. // because nonces can be verified sparsely, not needing to check each.
  234. func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
  235. // Collect some import statistics to report on
  236. stats := struct{ processed, ignored int }{}
  237. // All headers passed verification, import them into the database
  238. for i, header := range chain {
  239. // Short circuit insertion if shutting down
  240. if hc.procInterrupt() {
  241. log.Debug("Premature abort during headers import")
  242. return i, errors.New("aborted")
  243. }
  244. // If the header's already known, skip it, otherwise store
  245. hash := header.Hash()
  246. if hc.HasHeader(hash, header.Number.Uint64()) {
  247. externTd := hc.GetTd(hash, header.Number.Uint64())
  248. localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64())
  249. if externTd == nil || externTd.Cmp(localTd) <= 0 {
  250. stats.ignored++
  251. continue
  252. }
  253. }
  254. if err := writeHeader(header); err != nil {
  255. return i, err
  256. }
  257. stats.processed++
  258. }
  259. // Report some public statistics so the user has a clue what's going on
  260. last := chain[len(chain)-1]
  261. context := []interface{}{
  262. "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
  263. "number", last.Number, "hash", last.Hash(),
  264. }
  265. if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute {
  266. context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...)
  267. }
  268. if stats.ignored > 0 {
  269. context = append(context, []interface{}{"ignored", stats.ignored}...)
  270. }
  271. log.Info("Imported new block headers", context...)
  272. return 0, nil
  273. }
  274. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  275. // hash, fetching towards the genesis block.
  276. func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  277. // Get the origin header from which to fetch
  278. header := hc.GetHeaderByHash(hash)
  279. if header == nil {
  280. return nil
  281. }
  282. // Iterate the headers until enough is collected or the genesis reached
  283. chain := make([]common.Hash, 0, max)
  284. for i := uint64(0); i < max; i++ {
  285. next := header.ParentHash
  286. if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
  287. break
  288. }
  289. chain = append(chain, next)
  290. if header.Number.Sign() == 0 {
  291. break
  292. }
  293. }
  294. return chain
  295. }
  296. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  297. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  298. // number of blocks to be individually checked before we reach the canonical chain.
  299. //
  300. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  301. func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  302. if ancestor > number {
  303. return common.Hash{}, 0
  304. }
  305. if ancestor == 1 {
  306. // in this case it is cheaper to just read the header
  307. if header := hc.GetHeader(hash, number); header != nil {
  308. return header.ParentHash, number - 1
  309. } else {
  310. return common.Hash{}, 0
  311. }
  312. }
  313. for ancestor != 0 {
  314. if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
  315. ancestorHash := rawdb.ReadCanonicalHash(hc.chainDb, number-ancestor)
  316. if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
  317. number -= ancestor
  318. return ancestorHash, number
  319. }
  320. }
  321. if *maxNonCanonical == 0 {
  322. return common.Hash{}, 0
  323. }
  324. *maxNonCanonical--
  325. ancestor--
  326. header := hc.GetHeader(hash, number)
  327. if header == nil {
  328. return common.Hash{}, 0
  329. }
  330. hash = header.ParentHash
  331. number--
  332. }
  333. return hash, number
  334. }
  335. // GetTd retrieves a block's total difficulty in the canonical chain from the
  336. // database by hash and number, caching it if found.
  337. func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
  338. // Short circuit if the td's already in the cache, retrieve otherwise
  339. if cached, ok := hc.tdCache.Get(hash); ok {
  340. return cached.(*big.Int)
  341. }
  342. td := rawdb.ReadTd(hc.chainDb, hash, number)
  343. if td == nil {
  344. return nil
  345. }
  346. // Cache the found body for next time and return
  347. hc.tdCache.Add(hash, td)
  348. return td
  349. }
  350. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  351. // database by hash, caching it if found.
  352. func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
  353. number := hc.GetBlockNumber(hash)
  354. if number == nil {
  355. return nil
  356. }
  357. return hc.GetTd(hash, *number)
  358. }
  359. // WriteTd stores a block's total difficulty into the database, also caching it
  360. // along the way.
  361. func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
  362. rawdb.WriteTd(hc.chainDb, hash, number, td)
  363. hc.tdCache.Add(hash, new(big.Int).Set(td))
  364. return nil
  365. }
  366. // GetHeader retrieves a block header from the database by hash and number,
  367. // caching it if found.
  368. func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  369. // Short circuit if the header's already in the cache, retrieve otherwise
  370. if header, ok := hc.headerCache.Get(hash); ok {
  371. return header.(*types.Header)
  372. }
  373. header := rawdb.ReadHeader(hc.chainDb, hash, number)
  374. if header == nil {
  375. return nil
  376. }
  377. // Cache the found header for next time and return
  378. hc.headerCache.Add(hash, header)
  379. return header
  380. }
  381. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  382. // found.
  383. func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
  384. number := hc.GetBlockNumber(hash)
  385. if number == nil {
  386. return nil
  387. }
  388. return hc.GetHeader(hash, *number)
  389. }
  390. // HasHeader checks if a block header is present in the database or not.
  391. func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
  392. if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
  393. return true
  394. }
  395. return rawdb.HasHeader(hc.chainDb, hash, number)
  396. }
  397. // GetHeaderByNumber retrieves a block header from the database by number,
  398. // caching it (associated with its hash) if found.
  399. func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
  400. hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
  401. if hash == (common.Hash{}) {
  402. return nil
  403. }
  404. return hc.GetHeader(hash, number)
  405. }
  406. func (hc *HeaderChain) GetCanonicalHash(number uint64) common.Hash {
  407. return rawdb.ReadCanonicalHash(hc.chainDb, number)
  408. }
  409. // CurrentHeader retrieves the current head header of the canonical chain. The
  410. // header is retrieved from the HeaderChain's internal cache.
  411. func (hc *HeaderChain) CurrentHeader() *types.Header {
  412. return hc.currentHeader.Load().(*types.Header)
  413. }
  414. // SetCurrentHeader sets the current head header of the canonical chain.
  415. func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
  416. rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash())
  417. hc.currentHeader.Store(head)
  418. hc.currentHeaderHash = head.Hash()
  419. headHeaderGauge.Update(head.Number.Int64())
  420. }
  421. type (
  422. // UpdateHeadBlocksCallback is a callback function that is called by SetHead
  423. // before head header is updated.
  424. UpdateHeadBlocksCallback func(ethdb.KeyValueWriter, *types.Header)
  425. // DeleteBlockContentCallback is a callback function that is called by SetHead
  426. // before each header is deleted.
  427. DeleteBlockContentCallback func(ethdb.KeyValueWriter, common.Hash, uint64)
  428. )
  429. // SetHead rewinds the local chain to a new head. Everything above the new head
  430. // will be deleted and the new one set.
  431. func (hc *HeaderChain) SetHead(head uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) {
  432. var (
  433. parentHash common.Hash
  434. batch = hc.chainDb.NewBatch()
  435. )
  436. for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() {
  437. hash, num := hdr.Hash(), hdr.Number.Uint64()
  438. // Rewind block chain to new head.
  439. parent := hc.GetHeader(hdr.ParentHash, num-1)
  440. if parent == nil {
  441. parent = hc.genesisHeader
  442. }
  443. parentHash = hdr.ParentHash
  444. // Notably, since geth has the possibility for setting the head to a low
  445. // height which is even lower than ancient head.
  446. // In order to ensure that the head is always no higher than the data in
  447. // the database(ancient store or active store), we need to update head
  448. // first then remove the relative data from the database.
  449. //
  450. // Update head first(head fast block, head full block) before deleting the data.
  451. if updateFn != nil {
  452. updateFn(hc.chainDb, parent)
  453. }
  454. // Update head header then.
  455. rawdb.WriteHeadHeaderHash(hc.chainDb, parentHash)
  456. // Remove the relative data from the database.
  457. if delFn != nil {
  458. delFn(batch, hash, num)
  459. }
  460. // Rewind header chain to new head.
  461. rawdb.DeleteHeader(batch, hash, num)
  462. rawdb.DeleteTd(batch, hash, num)
  463. rawdb.DeleteCanonicalHash(batch, num)
  464. hc.currentHeader.Store(parent)
  465. hc.currentHeaderHash = parentHash
  466. headHeaderGauge.Update(parent.Number.Int64())
  467. }
  468. batch.Write()
  469. // Clear out any stale content from the caches
  470. hc.headerCache.Purge()
  471. hc.tdCache.Purge()
  472. hc.numberCache.Purge()
  473. }
  474. // SetGenesis sets a new genesis block header for the chain
  475. func (hc *HeaderChain) SetGenesis(head *types.Header) {
  476. hc.genesisHeader = head
  477. }
  478. // Config retrieves the header chain's chain configuration.
  479. func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
  480. // Engine retrieves the header chain's consensus engine.
  481. func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
  482. // GetBlock implements consensus.ChainReader, and returns nil for every input as
  483. // a header chain does not have blocks available for retrieval.
  484. func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  485. return nil
  486. }