headerchain.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. //
  44. // HeaderChain is responsible for maintaining the header chain including the
  45. // header query and updating.
  46. //
  47. // The components maintained by headerchain includes: (1) total difficult
  48. // (2) header (3) block hash -> number mapping (4) canonical number -> hash mapping
  49. // and (5) head header flag.
  50. //
  51. // It is not thread safe either, the encapsulating chain structures should do
  52. // the necessary mutex locking/unlocking.
  53. type HeaderChain struct {
  54. config *params.ChainConfig
  55. chainDb ethdb.Database
  56. genesisHeader *types.Header
  57. currentHeader atomic.Value // Current head of the header chain (may be above the block chain!)
  58. currentHeaderHash common.Hash // Hash of the current head of the header chain (prevent recomputing all the time)
  59. headerCache *lru.Cache // Cache for the most recent block headers
  60. tdCache *lru.Cache // Cache for the most recent block total difficulties
  61. numberCache *lru.Cache // Cache for the most recent block numbers
  62. procInterrupt func() bool
  63. rand *mrand.Rand
  64. engine consensus.Engine
  65. }
  66. // NewHeaderChain creates a new HeaderChain structure. ProcInterrupt points
  67. // to the parent's interrupt semaphore.
  68. func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
  69. headerCache, _ := lru.New(headerCacheLimit)
  70. tdCache, _ := lru.New(tdCacheLimit)
  71. numberCache, _ := lru.New(numberCacheLimit)
  72. // Seed a fast but crypto originating random generator
  73. seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
  74. if err != nil {
  75. return nil, err
  76. }
  77. hc := &HeaderChain{
  78. config: config,
  79. chainDb: chainDb,
  80. headerCache: headerCache,
  81. tdCache: tdCache,
  82. numberCache: numberCache,
  83. procInterrupt: procInterrupt,
  84. rand: mrand.New(mrand.NewSource(seed.Int64())),
  85. engine: engine,
  86. }
  87. hc.genesisHeader = hc.GetHeaderByNumber(0)
  88. if hc.genesisHeader == nil {
  89. return nil, ErrNoGenesis
  90. }
  91. hc.currentHeader.Store(hc.genesisHeader)
  92. if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) {
  93. if chead := hc.GetHeaderByHash(head); chead != nil {
  94. hc.currentHeader.Store(chead)
  95. }
  96. }
  97. hc.currentHeaderHash = hc.CurrentHeader().Hash()
  98. headHeaderGauge.Update(hc.CurrentHeader().Number.Int64())
  99. return hc, nil
  100. }
  101. // GetBlockNumber retrieves the block number belonging to the given hash
  102. // from the cache or database
  103. func (hc *HeaderChain) GetBlockNumber(hash common.Hash) *uint64 {
  104. if cached, ok := hc.numberCache.Get(hash); ok {
  105. number := cached.(uint64)
  106. return &number
  107. }
  108. number := rawdb.ReadHeaderNumber(hc.chainDb, hash)
  109. if number != nil {
  110. hc.numberCache.Add(hash, *number)
  111. }
  112. return number
  113. }
  114. type headerWriteResult struct {
  115. status WriteStatus
  116. ignored int
  117. imported int
  118. lastHash common.Hash
  119. lastHeader *types.Header
  120. }
  121. // WriteHeaders writes a chain of headers into the local chain, given that the parents
  122. // are already known. If the total difficulty of the newly inserted chain becomes
  123. // greater than the current known TD, the canonical chain is reorged.
  124. //
  125. // Note: This method is not concurrent-safe with inserting blocks simultaneously
  126. // into the chain, as side effects caused by reorganisations cannot be emulated
  127. // without the real blocks. Hence, writing headers directly should only be done
  128. // in two scenarios: pure-header mode of operation (light clients), or properly
  129. // separated header/block phases (non-archive clients).
  130. func (hc *HeaderChain) writeHeaders(headers []*types.Header) (result *headerWriteResult, err error) {
  131. if len(headers) == 0 {
  132. return &headerWriteResult{}, nil
  133. }
  134. ptd := hc.GetTd(headers[0].ParentHash, headers[0].Number.Uint64()-1)
  135. if ptd == nil {
  136. return &headerWriteResult{}, consensus.ErrUnknownAncestor
  137. }
  138. var (
  139. lastNumber = headers[0].Number.Uint64() - 1 // Last successfully imported number
  140. lastHash = headers[0].ParentHash // Last imported header hash
  141. newTD = new(big.Int).Set(ptd) // Total difficulty of inserted chain
  142. lastHeader *types.Header
  143. inserted []numberHash // Ephemeral lookup of number/hash for the chain
  144. firstInserted = -1 // Index of the first non-ignored header
  145. )
  146. batch := hc.chainDb.NewBatch()
  147. for i, header := range headers {
  148. var hash common.Hash
  149. // The headers have already been validated at this point, so we already
  150. // know that it's a contiguous chain, where
  151. // headers[i].Hash() == headers[i+1].ParentHash
  152. if i < len(headers)-1 {
  153. hash = headers[i+1].ParentHash
  154. } else {
  155. hash = header.Hash()
  156. }
  157. number := header.Number.Uint64()
  158. newTD.Add(newTD, header.Difficulty)
  159. // If the header is already known, skip it, otherwise store
  160. if !hc.HasHeader(hash, number) {
  161. // Irrelevant of the canonical status, write the TD and header to the database.
  162. rawdb.WriteTd(batch, hash, number, newTD)
  163. hc.tdCache.Add(hash, new(big.Int).Set(newTD))
  164. rawdb.WriteHeader(batch, header)
  165. inserted = append(inserted, numberHash{number, hash})
  166. hc.headerCache.Add(hash, header)
  167. hc.numberCache.Add(hash, number)
  168. if firstInserted < 0 {
  169. firstInserted = i
  170. }
  171. }
  172. lastHeader, lastHash, lastNumber = header, hash, number
  173. }
  174. // Skip the slow disk write of all headers if interrupted.
  175. if hc.procInterrupt() {
  176. log.Debug("Premature abort during headers import")
  177. return &headerWriteResult{}, errors.New("aborted")
  178. }
  179. // Commit to disk!
  180. if err := batch.Write(); err != nil {
  181. log.Crit("Failed to write headers", "error", err)
  182. }
  183. batch.Reset()
  184. var (
  185. head = hc.CurrentHeader().Number.Uint64()
  186. localTD = hc.GetTd(hc.currentHeaderHash, head)
  187. status = SideStatTy
  188. )
  189. // If the total difficulty is higher than our known, add it to the canonical chain
  190. // Second clause in the if statement reduces the vulnerability to selfish mining.
  191. // Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  192. reorg := newTD.Cmp(localTD) > 0
  193. if !reorg && newTD.Cmp(localTD) == 0 {
  194. if lastNumber < head {
  195. reorg = true
  196. } else if lastNumber == head {
  197. reorg = mrand.Float64() < 0.5
  198. }
  199. }
  200. // If the parent of the (first) block is already the canon header,
  201. // we don't have to go backwards to delete canon blocks, but
  202. // simply pile them onto the existing chain
  203. chainAlreadyCanon := headers[0].ParentHash == hc.currentHeaderHash
  204. if reorg {
  205. // If the header can be added into canonical chain, adjust the
  206. // header chain markers(canonical indexes and head header flag).
  207. //
  208. // Note all markers should be written atomically.
  209. markerBatch := batch // we can reuse the batch to keep allocs down
  210. if !chainAlreadyCanon {
  211. // Delete any canonical number assignments above the new head
  212. for i := lastNumber + 1; ; i++ {
  213. hash := rawdb.ReadCanonicalHash(hc.chainDb, i)
  214. if hash == (common.Hash{}) {
  215. break
  216. }
  217. rawdb.DeleteCanonicalHash(markerBatch, i)
  218. }
  219. // Overwrite any stale canonical number assignments, going
  220. // backwards from the first header in this import
  221. var (
  222. headHash = headers[0].ParentHash // inserted[0].parent?
  223. headNumber = headers[0].Number.Uint64() - 1 // inserted[0].num-1 ?
  224. headHeader = hc.GetHeader(headHash, headNumber)
  225. )
  226. for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash {
  227. rawdb.WriteCanonicalHash(markerBatch, headHash, headNumber)
  228. headHash = headHeader.ParentHash
  229. headNumber = headHeader.Number.Uint64() - 1
  230. headHeader = hc.GetHeader(headHash, headNumber)
  231. }
  232. // If some of the older headers were already known, but obtained canon-status
  233. // during this import batch, then we need to write that now
  234. // Further down, we continue writing the staus for the ones that
  235. // were not already known
  236. for i := 0; i < firstInserted; i++ {
  237. hash := headers[i].Hash()
  238. num := headers[i].Number.Uint64()
  239. rawdb.WriteCanonicalHash(markerBatch, hash, num)
  240. rawdb.WriteHeadHeaderHash(markerBatch, hash)
  241. }
  242. }
  243. // Extend the canonical chain with the new headers
  244. for _, hn := range inserted {
  245. rawdb.WriteCanonicalHash(markerBatch, hn.hash, hn.number)
  246. rawdb.WriteHeadHeaderHash(markerBatch, hn.hash)
  247. }
  248. if err := markerBatch.Write(); err != nil {
  249. log.Crit("Failed to write header markers into disk", "err", err)
  250. }
  251. markerBatch.Reset()
  252. // Last step update all in-memory head header markers
  253. hc.currentHeaderHash = lastHash
  254. hc.currentHeader.Store(types.CopyHeader(lastHeader))
  255. headHeaderGauge.Update(lastHeader.Number.Int64())
  256. // Chain status is canonical since this insert was a reorg.
  257. // Note that all inserts which have higher TD than existing are 'reorg'.
  258. status = CanonStatTy
  259. }
  260. if len(inserted) == 0 {
  261. status = NonStatTy
  262. }
  263. return &headerWriteResult{
  264. status: status,
  265. ignored: len(headers) - len(inserted),
  266. imported: len(inserted),
  267. lastHash: lastHash,
  268. lastHeader: lastHeader,
  269. }, nil
  270. }
  271. func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  272. // Do a sanity check that the provided chain is actually ordered and linked
  273. for i := 1; i < len(chain); i++ {
  274. if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 {
  275. hash := chain[i].Hash()
  276. parentHash := chain[i-1].Hash()
  277. // Chain broke ancestry, log a message (programming error) and skip insertion
  278. log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", hash,
  279. "parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", parentHash)
  280. 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,
  281. parentHash.Bytes()[:4], i, chain[i].Number, hash.Bytes()[:4], chain[i].ParentHash[:4])
  282. }
  283. // If the header is a banned one, straight out abort
  284. if BadHashes[chain[i].ParentHash] {
  285. return i - 1, ErrBlacklistedHash
  286. }
  287. // If it's the last header in the cunk, we need to check it too
  288. if i == len(chain)-1 && BadHashes[chain[i].Hash()] {
  289. return i, ErrBlacklistedHash
  290. }
  291. }
  292. // Generate the list of seal verification requests, and start the parallel verifier
  293. seals := make([]bool, len(chain))
  294. if checkFreq != 0 {
  295. // In case of checkFreq == 0 all seals are left false.
  296. for i := 0; i <= len(seals)/checkFreq; i++ {
  297. index := i*checkFreq + hc.rand.Intn(checkFreq)
  298. if index >= len(seals) {
  299. index = len(seals) - 1
  300. }
  301. seals[index] = true
  302. }
  303. // Last should always be verified to avoid junk.
  304. seals[len(seals)-1] = true
  305. }
  306. abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
  307. defer close(abort)
  308. // Iterate over the headers and ensure they all check out
  309. for i := range chain {
  310. // If the chain is terminating, stop processing blocks
  311. if hc.procInterrupt() {
  312. log.Debug("Premature abort during headers verification")
  313. return 0, errors.New("aborted")
  314. }
  315. // Otherwise wait for headers checks and ensure they pass
  316. if err := <-results; err != nil {
  317. return i, err
  318. }
  319. }
  320. return 0, nil
  321. }
  322. // InsertHeaderChain inserts the given headers.
  323. //
  324. // The validity of the headers is NOT CHECKED by this method, i.e. they need to be
  325. // validated by ValidateHeaderChain before calling InsertHeaderChain.
  326. //
  327. // This insert is all-or-nothing. If this returns an error, no headers were written,
  328. // otherwise they were all processed successfully.
  329. //
  330. // The returned 'write status' says if the inserted headers are part of the canonical chain
  331. // or a side chain.
  332. func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, start time.Time) (WriteStatus, error) {
  333. if hc.procInterrupt() {
  334. return 0, errors.New("aborted")
  335. }
  336. res, err := hc.writeHeaders(chain)
  337. // Report some public statistics so the user has a clue what's going on
  338. context := []interface{}{
  339. "count", res.imported,
  340. "elapsed", common.PrettyDuration(time.Since(start)),
  341. }
  342. if err != nil {
  343. context = append(context, "err", err)
  344. }
  345. if last := res.lastHeader; last != nil {
  346. context = append(context, "number", last.Number, "hash", res.lastHash)
  347. if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute {
  348. context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...)
  349. }
  350. }
  351. if res.ignored > 0 {
  352. context = append(context, []interface{}{"ignored", res.ignored}...)
  353. }
  354. log.Info("Imported new block headers", context...)
  355. return res.status, err
  356. }
  357. // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  358. // hash, fetching towards the genesis block.
  359. func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  360. // Get the origin header from which to fetch
  361. header := hc.GetHeaderByHash(hash)
  362. if header == nil {
  363. return nil
  364. }
  365. // Iterate the headers until enough is collected or the genesis reached
  366. chain := make([]common.Hash, 0, max)
  367. for i := uint64(0); i < max; i++ {
  368. next := header.ParentHash
  369. if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
  370. break
  371. }
  372. chain = append(chain, next)
  373. if header.Number.Sign() == 0 {
  374. break
  375. }
  376. }
  377. return chain
  378. }
  379. // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  380. // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  381. // number of blocks to be individually checked before we reach the canonical chain.
  382. //
  383. // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  384. func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  385. if ancestor > number {
  386. return common.Hash{}, 0
  387. }
  388. if ancestor == 1 {
  389. // in this case it is cheaper to just read the header
  390. if header := hc.GetHeader(hash, number); header != nil {
  391. return header.ParentHash, number - 1
  392. }
  393. return common.Hash{}, 0
  394. }
  395. for ancestor != 0 {
  396. if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
  397. ancestorHash := rawdb.ReadCanonicalHash(hc.chainDb, number-ancestor)
  398. if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
  399. number -= ancestor
  400. return ancestorHash, number
  401. }
  402. }
  403. if *maxNonCanonical == 0 {
  404. return common.Hash{}, 0
  405. }
  406. *maxNonCanonical--
  407. ancestor--
  408. header := hc.GetHeader(hash, number)
  409. if header == nil {
  410. return common.Hash{}, 0
  411. }
  412. hash = header.ParentHash
  413. number--
  414. }
  415. return hash, number
  416. }
  417. // GetTd retrieves a block's total difficulty in the canonical chain from the
  418. // database by hash and number, caching it if found.
  419. func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
  420. // Short circuit if the td's already in the cache, retrieve otherwise
  421. if cached, ok := hc.tdCache.Get(hash); ok {
  422. return cached.(*big.Int)
  423. }
  424. td := rawdb.ReadTd(hc.chainDb, hash, number)
  425. if td == nil {
  426. return nil
  427. }
  428. // Cache the found body for next time and return
  429. hc.tdCache.Add(hash, td)
  430. return td
  431. }
  432. // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  433. // database by hash, caching it if found.
  434. func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
  435. number := hc.GetBlockNumber(hash)
  436. if number == nil {
  437. return nil
  438. }
  439. return hc.GetTd(hash, *number)
  440. }
  441. // GetHeader retrieves a block header from the database by hash and number,
  442. // caching it if found.
  443. func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  444. // Short circuit if the header's already in the cache, retrieve otherwise
  445. if header, ok := hc.headerCache.Get(hash); ok {
  446. return header.(*types.Header)
  447. }
  448. header := rawdb.ReadHeader(hc.chainDb, hash, number)
  449. if header == nil {
  450. return nil
  451. }
  452. // Cache the found header for next time and return
  453. hc.headerCache.Add(hash, header)
  454. return header
  455. }
  456. // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  457. // found.
  458. func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
  459. number := hc.GetBlockNumber(hash)
  460. if number == nil {
  461. return nil
  462. }
  463. return hc.GetHeader(hash, *number)
  464. }
  465. // HasHeader checks if a block header is present in the database or not.
  466. // In theory, if header is present in the database, all relative components
  467. // like td and hash->number should be present too.
  468. func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
  469. if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
  470. return true
  471. }
  472. return rawdb.HasHeader(hc.chainDb, hash, number)
  473. }
  474. // GetHeaderByNumber retrieves a block header from the database by number,
  475. // caching it (associated with its hash) if found.
  476. func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
  477. hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
  478. if hash == (common.Hash{}) {
  479. return nil
  480. }
  481. return hc.GetHeader(hash, number)
  482. }
  483. func (hc *HeaderChain) GetCanonicalHash(number uint64) common.Hash {
  484. return rawdb.ReadCanonicalHash(hc.chainDb, number)
  485. }
  486. // CurrentHeader retrieves the current head header of the canonical chain. The
  487. // header is retrieved from the HeaderChain's internal cache.
  488. func (hc *HeaderChain) CurrentHeader() *types.Header {
  489. return hc.currentHeader.Load().(*types.Header)
  490. }
  491. // SetCurrentHeader sets the in-memory head header marker of the canonical chan
  492. // as the given header.
  493. func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
  494. hc.currentHeader.Store(head)
  495. hc.currentHeaderHash = head.Hash()
  496. headHeaderGauge.Update(head.Number.Int64())
  497. }
  498. type (
  499. // UpdateHeadBlocksCallback is a callback function that is called by SetHead
  500. // before head header is updated. The method will return the actual block it
  501. // updated the head to (missing state) and a flag if setHead should continue
  502. // rewinding till that forcefully (exceeded ancient limits)
  503. UpdateHeadBlocksCallback func(ethdb.KeyValueWriter, *types.Header) (uint64, bool)
  504. // DeleteBlockContentCallback is a callback function that is called by SetHead
  505. // before each header is deleted.
  506. DeleteBlockContentCallback func(ethdb.KeyValueWriter, common.Hash, uint64)
  507. )
  508. // SetHead rewinds the local chain to a new head. Everything above the new head
  509. // will be deleted and the new one set.
  510. func (hc *HeaderChain) SetHead(head uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) {
  511. var (
  512. parentHash common.Hash
  513. batch = hc.chainDb.NewBatch()
  514. origin = true
  515. )
  516. for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() {
  517. num := hdr.Number.Uint64()
  518. // Rewind block chain to new head.
  519. parent := hc.GetHeader(hdr.ParentHash, num-1)
  520. if parent == nil {
  521. parent = hc.genesisHeader
  522. }
  523. parentHash = hdr.ParentHash
  524. // Notably, since geth has the possibility for setting the head to a low
  525. // height which is even lower than ancient head.
  526. // In order to ensure that the head is always no higher than the data in
  527. // the database (ancient store or active store), we need to update head
  528. // first then remove the relative data from the database.
  529. //
  530. // Update head first(head fast block, head full block) before deleting the data.
  531. markerBatch := hc.chainDb.NewBatch()
  532. if updateFn != nil {
  533. newHead, force := updateFn(markerBatch, parent)
  534. if force && newHead < head {
  535. log.Warn("Force rewinding till ancient limit", "head", newHead)
  536. head = newHead
  537. }
  538. }
  539. // Update head header then.
  540. rawdb.WriteHeadHeaderHash(markerBatch, parentHash)
  541. if err := markerBatch.Write(); err != nil {
  542. log.Crit("Failed to update chain markers", "error", err)
  543. }
  544. hc.currentHeader.Store(parent)
  545. hc.currentHeaderHash = parentHash
  546. headHeaderGauge.Update(parent.Number.Int64())
  547. // If this is the first iteration, wipe any leftover data upwards too so
  548. // we don't end up with dangling daps in the database
  549. var nums []uint64
  550. if origin {
  551. for n := num + 1; len(rawdb.ReadAllHashes(hc.chainDb, n)) > 0; n++ {
  552. nums = append([]uint64{n}, nums...) // suboptimal, but we don't really expect this path
  553. }
  554. origin = false
  555. }
  556. nums = append(nums, num)
  557. // Remove the related data from the database on all sidechains
  558. for _, num := range nums {
  559. // Gather all the side fork hashes
  560. hashes := rawdb.ReadAllHashes(hc.chainDb, num)
  561. if len(hashes) == 0 {
  562. // No hashes in the database whatsoever, probably frozen already
  563. hashes = append(hashes, hdr.Hash())
  564. }
  565. for _, hash := range hashes {
  566. if delFn != nil {
  567. delFn(batch, hash, num)
  568. }
  569. rawdb.DeleteHeader(batch, hash, num)
  570. rawdb.DeleteTd(batch, hash, num)
  571. }
  572. rawdb.DeleteCanonicalHash(batch, num)
  573. }
  574. }
  575. // Flush all accumulated deletions.
  576. if err := batch.Write(); err != nil {
  577. log.Crit("Failed to rewind block", "error", err)
  578. }
  579. // Clear out any stale content from the caches
  580. hc.headerCache.Purge()
  581. hc.tdCache.Purge()
  582. hc.numberCache.Purge()
  583. }
  584. // SetGenesis sets a new genesis block header for the chain
  585. func (hc *HeaderChain) SetGenesis(head *types.Header) {
  586. hc.genesisHeader = head
  587. }
  588. // Config retrieves the header chain's chain configuration.
  589. func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
  590. // Engine retrieves the header chain's consensus engine.
  591. func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
  592. // GetBlock implements consensus.ChainReader, and returns nil for every input as
  593. // a header chain does not have blocks available for retrieval.
  594. func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
  595. return nil
  596. }