github.com/jimmyx0x/go-ethereum@v1.10.28/light/lightchain.go (about)

     1  // Copyright 2016 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  
    17  // Package light implements on-demand retrieval capable state and chain objects
    18  // for the Ethereum Light Client.
    19  package light
    20  
    21  import (
    22  	"context"
    23  	"errors"
    24  	"math/big"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/common/lru"
    31  	"github.com/ethereum/go-ethereum/consensus"
    32  	"github.com/ethereum/go-ethereum/core"
    33  	"github.com/ethereum/go-ethereum/core/rawdb"
    34  	"github.com/ethereum/go-ethereum/core/state"
    35  	"github.com/ethereum/go-ethereum/core/types"
    36  	"github.com/ethereum/go-ethereum/ethdb"
    37  	"github.com/ethereum/go-ethereum/event"
    38  	"github.com/ethereum/go-ethereum/log"
    39  	"github.com/ethereum/go-ethereum/params"
    40  	"github.com/ethereum/go-ethereum/rlp"
    41  )
    42  
    43  var (
    44  	bodyCacheLimit  = 256
    45  	blockCacheLimit = 256
    46  )
    47  
    48  // LightChain represents a canonical chain that by default only handles block
    49  // headers, downloading block bodies and receipts on demand through an ODR
    50  // interface. It only does header validation during chain insertion.
    51  type LightChain struct {
    52  	hc            *core.HeaderChain
    53  	indexerConfig *IndexerConfig
    54  	chainDb       ethdb.Database
    55  	engine        consensus.Engine
    56  	odr           OdrBackend
    57  	chainFeed     event.Feed
    58  	chainSideFeed event.Feed
    59  	chainHeadFeed event.Feed
    60  	scope         event.SubscriptionScope
    61  	genesisBlock  *types.Block
    62  	forker        *core.ForkChoice
    63  
    64  	bodyCache    *lru.Cache[common.Hash, *types.Body]
    65  	bodyRLPCache *lru.Cache[common.Hash, rlp.RawValue]
    66  	blockCache   *lru.Cache[common.Hash, *types.Block]
    67  
    68  	chainmu sync.RWMutex // protects header inserts
    69  	quit    chan struct{}
    70  	wg      sync.WaitGroup
    71  
    72  	// Atomic boolean switches:
    73  	running          int32 // whether LightChain is running or stopped
    74  	procInterrupt    int32 // interrupts chain insert
    75  	disableCheckFreq int32 // disables header verification
    76  }
    77  
    78  // NewLightChain returns a fully initialised light chain using information
    79  // available in the database. It initialises the default Ethereum header
    80  // validator.
    81  func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.Engine, checkpoint *params.TrustedCheckpoint) (*LightChain, error) {
    82  	bc := &LightChain{
    83  		chainDb:       odr.Database(),
    84  		indexerConfig: odr.IndexerConfig(),
    85  		odr:           odr,
    86  		quit:          make(chan struct{}),
    87  		bodyCache:     lru.NewCache[common.Hash, *types.Body](bodyCacheLimit),
    88  		bodyRLPCache:  lru.NewCache[common.Hash, rlp.RawValue](bodyCacheLimit),
    89  		blockCache:    lru.NewCache[common.Hash, *types.Block](blockCacheLimit),
    90  		engine:        engine,
    91  	}
    92  	bc.forker = core.NewForkChoice(bc, nil)
    93  	var err error
    94  	bc.hc, err = core.NewHeaderChain(odr.Database(), config, bc.engine, bc.getProcInterrupt)
    95  	if err != nil {
    96  		return nil, err
    97  	}
    98  	bc.genesisBlock, _ = bc.GetBlockByNumber(NoOdr, 0)
    99  	if bc.genesisBlock == nil {
   100  		return nil, core.ErrNoGenesis
   101  	}
   102  	if checkpoint != nil {
   103  		bc.AddTrustedCheckpoint(checkpoint)
   104  	}
   105  	if err := bc.loadLastState(); err != nil {
   106  		return nil, err
   107  	}
   108  	// Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
   109  	for hash := range core.BadHashes {
   110  		if header := bc.GetHeaderByHash(hash); header != nil {
   111  			log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
   112  			bc.SetHead(header.Number.Uint64() - 1)
   113  			log.Info("Chain rewind was successful, resuming normal operation")
   114  		}
   115  	}
   116  	return bc, nil
   117  }
   118  
   119  // AddTrustedCheckpoint adds a trusted checkpoint to the blockchain
   120  func (lc *LightChain) AddTrustedCheckpoint(cp *params.TrustedCheckpoint) {
   121  	if lc.odr.ChtIndexer() != nil {
   122  		StoreChtRoot(lc.chainDb, cp.SectionIndex, cp.SectionHead, cp.CHTRoot)
   123  		lc.odr.ChtIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead)
   124  	}
   125  	if lc.odr.BloomTrieIndexer() != nil {
   126  		StoreBloomTrieRoot(lc.chainDb, cp.SectionIndex, cp.SectionHead, cp.BloomRoot)
   127  		lc.odr.BloomTrieIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead)
   128  	}
   129  	if lc.odr.BloomIndexer() != nil {
   130  		lc.odr.BloomIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead)
   131  	}
   132  	log.Info("Added trusted checkpoint", "block", (cp.SectionIndex+1)*lc.indexerConfig.ChtSize-1, "hash", cp.SectionHead)
   133  }
   134  
   135  func (lc *LightChain) getProcInterrupt() bool {
   136  	return atomic.LoadInt32(&lc.procInterrupt) == 1
   137  }
   138  
   139  // Odr returns the ODR backend of the chain
   140  func (lc *LightChain) Odr() OdrBackend {
   141  	return lc.odr
   142  }
   143  
   144  // HeaderChain returns the underlying header chain.
   145  func (lc *LightChain) HeaderChain() *core.HeaderChain {
   146  	return lc.hc
   147  }
   148  
   149  // loadLastState loads the last known chain state from the database. This method
   150  // assumes that the chain manager mutex is held.
   151  func (lc *LightChain) loadLastState() error {
   152  	if head := rawdb.ReadHeadHeaderHash(lc.chainDb); head == (common.Hash{}) {
   153  		// Corrupt or empty database, init from scratch
   154  		lc.Reset()
   155  	} else {
   156  		header := lc.GetHeaderByHash(head)
   157  		if header == nil {
   158  			// Corrupt or empty database, init from scratch
   159  			lc.Reset()
   160  		} else {
   161  			lc.hc.SetCurrentHeader(header)
   162  		}
   163  	}
   164  	// Issue a status log and return
   165  	header := lc.hc.CurrentHeader()
   166  	headerTd := lc.GetTd(header.Hash(), header.Number.Uint64())
   167  	log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(header.Time), 0)))
   168  	return nil
   169  }
   170  
   171  // SetHead rewinds the local chain to a new head. Everything above the new
   172  // head will be deleted and the new one set.
   173  func (lc *LightChain) SetHead(head uint64) error {
   174  	lc.chainmu.Lock()
   175  	defer lc.chainmu.Unlock()
   176  
   177  	lc.hc.SetHead(head, nil, nil)
   178  	return lc.loadLastState()
   179  }
   180  
   181  // SetHeadWithTimestamp rewinds the local chain to a new head that has at max
   182  // the given timestamp. Everything above the new head will be deleted and the
   183  // new one set.
   184  func (lc *LightChain) SetHeadWithTimestamp(timestamp uint64) error {
   185  	lc.chainmu.Lock()
   186  	defer lc.chainmu.Unlock()
   187  
   188  	lc.hc.SetHeadWithTimestamp(timestamp, nil, nil)
   189  	return lc.loadLastState()
   190  }
   191  
   192  // GasLimit returns the gas limit of the current HEAD block.
   193  func (lc *LightChain) GasLimit() uint64 {
   194  	return lc.hc.CurrentHeader().GasLimit
   195  }
   196  
   197  // Reset purges the entire blockchain, restoring it to its genesis state.
   198  func (lc *LightChain) Reset() {
   199  	lc.ResetWithGenesisBlock(lc.genesisBlock)
   200  }
   201  
   202  // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
   203  // specified genesis state.
   204  func (lc *LightChain) ResetWithGenesisBlock(genesis *types.Block) {
   205  	// Dump the entire block chain and purge the caches
   206  	lc.SetHead(0)
   207  
   208  	lc.chainmu.Lock()
   209  	defer lc.chainmu.Unlock()
   210  
   211  	// Prepare the genesis block and reinitialise the chain
   212  	batch := lc.chainDb.NewBatch()
   213  	rawdb.WriteTd(batch, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty())
   214  	rawdb.WriteBlock(batch, genesis)
   215  	rawdb.WriteHeadHeaderHash(batch, genesis.Hash())
   216  	if err := batch.Write(); err != nil {
   217  		log.Crit("Failed to reset genesis block", "err", err)
   218  	}
   219  	lc.genesisBlock = genesis
   220  	lc.hc.SetGenesis(lc.genesisBlock.Header())
   221  	lc.hc.SetCurrentHeader(lc.genesisBlock.Header())
   222  }
   223  
   224  // Accessors
   225  
   226  // Engine retrieves the light chain's consensus engine.
   227  func (lc *LightChain) Engine() consensus.Engine { return lc.engine }
   228  
   229  // Genesis returns the genesis block
   230  func (lc *LightChain) Genesis() *types.Block {
   231  	return lc.genesisBlock
   232  }
   233  
   234  func (lc *LightChain) StateCache() state.Database {
   235  	panic("not implemented")
   236  }
   237  
   238  // GetBody retrieves a block body (transactions and uncles) from the database
   239  // or ODR service by hash, caching it if found.
   240  func (lc *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) {
   241  	// Short circuit if the body's already in the cache, retrieve otherwise
   242  	if cached, ok := lc.bodyCache.Get(hash); ok {
   243  		return cached, nil
   244  	}
   245  	number := lc.hc.GetBlockNumber(hash)
   246  	if number == nil {
   247  		return nil, errors.New("unknown block")
   248  	}
   249  	body, err := GetBody(ctx, lc.odr, hash, *number)
   250  	if err != nil {
   251  		return nil, err
   252  	}
   253  	// Cache the found body for next time and return
   254  	lc.bodyCache.Add(hash, body)
   255  	return body, nil
   256  }
   257  
   258  // GetBodyRLP retrieves a block body in RLP encoding from the database or
   259  // ODR service by hash, caching it if found.
   260  func (lc *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) {
   261  	// Short circuit if the body's already in the cache, retrieve otherwise
   262  	if cached, ok := lc.bodyRLPCache.Get(hash); ok {
   263  		return cached, nil
   264  	}
   265  	number := lc.hc.GetBlockNumber(hash)
   266  	if number == nil {
   267  		return nil, errors.New("unknown block")
   268  	}
   269  	body, err := GetBodyRLP(ctx, lc.odr, hash, *number)
   270  	if err != nil {
   271  		return nil, err
   272  	}
   273  	// Cache the found body for next time and return
   274  	lc.bodyRLPCache.Add(hash, body)
   275  	return body, nil
   276  }
   277  
   278  // HasBlock checks if a block is fully present in the database or not, caching
   279  // it if present.
   280  func (lc *LightChain) HasBlock(hash common.Hash, number uint64) bool {
   281  	blk, _ := lc.GetBlock(NoOdr, hash, number)
   282  	return blk != nil
   283  }
   284  
   285  // GetBlock retrieves a block from the database or ODR service by hash and number,
   286  // caching it if found.
   287  func (lc *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) {
   288  	// Short circuit if the block's already in the cache, retrieve otherwise
   289  	if block, ok := lc.blockCache.Get(hash); ok {
   290  		return block, nil
   291  	}
   292  	block, err := GetBlock(ctx, lc.odr, hash, number)
   293  	if err != nil {
   294  		return nil, err
   295  	}
   296  	// Cache the found block for next time and return
   297  	lc.blockCache.Add(block.Hash(), block)
   298  	return block, nil
   299  }
   300  
   301  // GetBlockByHash retrieves a block from the database or ODR service by hash,
   302  // caching it if found.
   303  func (lc *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   304  	number := lc.hc.GetBlockNumber(hash)
   305  	if number == nil {
   306  		return nil, errors.New("unknown block")
   307  	}
   308  	return lc.GetBlock(ctx, hash, *number)
   309  }
   310  
   311  // GetBlockByNumber retrieves a block from the database or ODR service by
   312  // number, caching it (associated with its hash) if found.
   313  func (lc *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) {
   314  	hash, err := GetCanonicalHash(ctx, lc.odr, number)
   315  	if hash == (common.Hash{}) || err != nil {
   316  		return nil, err
   317  	}
   318  	return lc.GetBlock(ctx, hash, number)
   319  }
   320  
   321  // Stop stops the blockchain service. If any imports are currently in progress
   322  // it will abort them using the procInterrupt.
   323  func (lc *LightChain) Stop() {
   324  	if !atomic.CompareAndSwapInt32(&lc.running, 0, 1) {
   325  		return
   326  	}
   327  	close(lc.quit)
   328  	lc.StopInsert()
   329  	lc.wg.Wait()
   330  	log.Info("Blockchain stopped")
   331  }
   332  
   333  // StopInsert interrupts all insertion methods, causing them to return
   334  // errInsertionInterrupted as soon as possible. Insertion is permanently disabled after
   335  // calling this method.
   336  func (lc *LightChain) StopInsert() {
   337  	atomic.StoreInt32(&lc.procInterrupt, 1)
   338  }
   339  
   340  // Rollback is designed to remove a chain of links from the database that aren't
   341  // certain enough to be valid.
   342  func (lc *LightChain) Rollback(chain []common.Hash) {
   343  	lc.chainmu.Lock()
   344  	defer lc.chainmu.Unlock()
   345  
   346  	batch := lc.chainDb.NewBatch()
   347  	for i := len(chain) - 1; i >= 0; i-- {
   348  		hash := chain[i]
   349  
   350  		// Degrade the chain markers if they are explicitly reverted.
   351  		// In theory we should update all in-memory markers in the
   352  		// last step, however the direction of rollback is from high
   353  		// to low, so it's safe the update in-memory markers directly.
   354  		if head := lc.hc.CurrentHeader(); head.Hash() == hash {
   355  			rawdb.WriteHeadHeaderHash(batch, head.ParentHash)
   356  			lc.hc.SetCurrentHeader(lc.GetHeader(head.ParentHash, head.Number.Uint64()-1))
   357  		}
   358  	}
   359  	if err := batch.Write(); err != nil {
   360  		log.Crit("Failed to rollback light chain", "error", err)
   361  	}
   362  }
   363  
   364  func (lc *LightChain) InsertHeader(header *types.Header) error {
   365  	// Verify the header first before obtaining the lock
   366  	headers := []*types.Header{header}
   367  	if _, err := lc.hc.ValidateHeaderChain(headers, 100); err != nil {
   368  		return err
   369  	}
   370  	// Make sure only one thread manipulates the chain at once
   371  	lc.chainmu.Lock()
   372  	defer lc.chainmu.Unlock()
   373  
   374  	lc.wg.Add(1)
   375  	defer lc.wg.Done()
   376  
   377  	_, err := lc.hc.WriteHeaders(headers)
   378  	log.Info("Inserted header", "number", header.Number, "hash", header.Hash())
   379  	return err
   380  }
   381  
   382  func (lc *LightChain) SetCanonical(header *types.Header) error {
   383  	lc.chainmu.Lock()
   384  	defer lc.chainmu.Unlock()
   385  
   386  	lc.wg.Add(1)
   387  	defer lc.wg.Done()
   388  
   389  	if err := lc.hc.Reorg([]*types.Header{header}); err != nil {
   390  		return err
   391  	}
   392  	// Emit events
   393  	block := types.NewBlockWithHeader(header)
   394  	lc.chainFeed.Send(core.ChainEvent{Block: block, Hash: block.Hash()})
   395  	lc.chainHeadFeed.Send(core.ChainHeadEvent{Block: block})
   396  	log.Info("Set the chain head", "number", block.Number(), "hash", block.Hash())
   397  	return nil
   398  }
   399  
   400  // InsertHeaderChain attempts to insert the given header chain in to the local
   401  // chain, possibly creating a reorg. If an error is returned, it will return the
   402  // index number of the failing header as well an error describing what went wrong.
   403  //
   404  // The verify parameter can be used to fine tune whether nonce verification
   405  // should be done or not. The reason behind the optional check is because some
   406  // of the header retrieval mechanisms already need to verify nonces, as well as
   407  // because nonces can be verified sparsely, not needing to check each.
   408  //
   409  // In the case of a light chain, InsertHeaderChain also creates and posts light
   410  // chain events when necessary.
   411  func (lc *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
   412  	if len(chain) == 0 {
   413  		return 0, nil
   414  	}
   415  	if atomic.LoadInt32(&lc.disableCheckFreq) == 1 {
   416  		checkFreq = 0
   417  	}
   418  	start := time.Now()
   419  	if i, err := lc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
   420  		return i, err
   421  	}
   422  
   423  	// Make sure only one thread manipulates the chain at once
   424  	lc.chainmu.Lock()
   425  	defer lc.chainmu.Unlock()
   426  
   427  	lc.wg.Add(1)
   428  	defer lc.wg.Done()
   429  
   430  	status, err := lc.hc.InsertHeaderChain(chain, start, lc.forker)
   431  	if err != nil || len(chain) == 0 {
   432  		return 0, err
   433  	}
   434  
   435  	// Create chain event for the new head block of this insertion.
   436  	var (
   437  		lastHeader = chain[len(chain)-1]
   438  		block      = types.NewBlockWithHeader(lastHeader)
   439  	)
   440  	switch status {
   441  	case core.CanonStatTy:
   442  		lc.chainFeed.Send(core.ChainEvent{Block: block, Hash: block.Hash()})
   443  		lc.chainHeadFeed.Send(core.ChainHeadEvent{Block: block})
   444  	case core.SideStatTy:
   445  		lc.chainSideFeed.Send(core.ChainSideEvent{Block: block})
   446  	}
   447  	return 0, err
   448  }
   449  
   450  // CurrentHeader retrieves the current head header of the canonical chain. The
   451  // header is retrieved from the HeaderChain's internal cache.
   452  func (lc *LightChain) CurrentHeader() *types.Header {
   453  	return lc.hc.CurrentHeader()
   454  }
   455  
   456  // GetTd retrieves a block's total difficulty in the canonical chain from the
   457  // database by hash and number, caching it if found.
   458  func (lc *LightChain) GetTd(hash common.Hash, number uint64) *big.Int {
   459  	return lc.hc.GetTd(hash, number)
   460  }
   461  
   462  // GetTdOdr retrieves the total difficult from the database or
   463  // network by hash and number, caching it (associated with its hash) if found.
   464  func (lc *LightChain) GetTdOdr(ctx context.Context, hash common.Hash, number uint64) *big.Int {
   465  	td := lc.GetTd(hash, number)
   466  	if td != nil {
   467  		return td
   468  	}
   469  	td, _ = GetTd(ctx, lc.odr, hash, number)
   470  	return td
   471  }
   472  
   473  // GetHeader retrieves a block header from the database by hash and number,
   474  // caching it if found.
   475  func (lc *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header {
   476  	return lc.hc.GetHeader(hash, number)
   477  }
   478  
   479  // GetHeaderByHash retrieves a block header from the database by hash, caching it if
   480  // found.
   481  func (lc *LightChain) GetHeaderByHash(hash common.Hash) *types.Header {
   482  	return lc.hc.GetHeaderByHash(hash)
   483  }
   484  
   485  // HasHeader checks if a block header is present in the database or not, caching
   486  // it if present.
   487  func (lc *LightChain) HasHeader(hash common.Hash, number uint64) bool {
   488  	return lc.hc.HasHeader(hash, number)
   489  }
   490  
   491  // GetCanonicalHash returns the canonical hash for a given block number
   492  func (bc *LightChain) GetCanonicalHash(number uint64) common.Hash {
   493  	return bc.hc.GetCanonicalHash(number)
   494  }
   495  
   496  // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
   497  // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
   498  // number of blocks to be individually checked before we reach the canonical chain.
   499  //
   500  // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
   501  func (lc *LightChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
   502  	return lc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
   503  }
   504  
   505  // GetHeaderByNumber retrieves a block header from the database by number,
   506  // caching it (associated with its hash) if found.
   507  func (lc *LightChain) GetHeaderByNumber(number uint64) *types.Header {
   508  	return lc.hc.GetHeaderByNumber(number)
   509  }
   510  
   511  // GetHeaderByNumberOdr retrieves a block header from the database or network
   512  // by number, caching it (associated with its hash) if found.
   513  func (lc *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) {
   514  	if header := lc.hc.GetHeaderByNumber(number); header != nil {
   515  		return header, nil
   516  	}
   517  	return GetHeaderByNumber(ctx, lc.odr, number)
   518  }
   519  
   520  // Config retrieves the header chain's chain configuration.
   521  func (lc *LightChain) Config() *params.ChainConfig { return lc.hc.Config() }
   522  
   523  // SyncCheckpoint fetches the checkpoint point block header according to
   524  // the checkpoint provided by the remote peer.
   525  //
   526  // Note if we are running the clique, fetches the last epoch snapshot header
   527  // which covered by checkpoint.
   528  func (lc *LightChain) SyncCheckpoint(ctx context.Context, checkpoint *params.TrustedCheckpoint) bool {
   529  	// Ensure the remote checkpoint head is ahead of us
   530  	head := lc.CurrentHeader().Number.Uint64()
   531  
   532  	latest := (checkpoint.SectionIndex+1)*lc.indexerConfig.ChtSize - 1
   533  	if clique := lc.hc.Config().Clique; clique != nil {
   534  		latest -= latest % clique.Epoch // epoch snapshot for clique
   535  	}
   536  	if head >= latest {
   537  		return true
   538  	}
   539  	// Retrieve the latest useful header and update to it
   540  	if header, err := GetHeaderByNumber(ctx, lc.odr, latest); header != nil && err == nil {
   541  		lc.chainmu.Lock()
   542  		defer lc.chainmu.Unlock()
   543  
   544  		// Ensure the chain didn't move past the latest block while retrieving it
   545  		if lc.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
   546  			log.Info("Updated latest header based on CHT", "number", header.Number, "hash", header.Hash(), "age", common.PrettyAge(time.Unix(int64(header.Time), 0)))
   547  			rawdb.WriteHeadHeaderHash(lc.chainDb, header.Hash())
   548  			lc.hc.SetCurrentHeader(header)
   549  		}
   550  		return true
   551  	}
   552  	return false
   553  }
   554  
   555  // LockChain locks the chain mutex for reading so that multiple canonical hashes can be
   556  // retrieved while it is guaranteed that they belong to the same version of the chain
   557  func (lc *LightChain) LockChain() {
   558  	lc.chainmu.RLock()
   559  }
   560  
   561  // UnlockChain unlocks the chain mutex
   562  func (lc *LightChain) UnlockChain() {
   563  	lc.chainmu.RUnlock()
   564  }
   565  
   566  // SubscribeChainEvent registers a subscription of ChainEvent.
   567  func (lc *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   568  	return lc.scope.Track(lc.chainFeed.Subscribe(ch))
   569  }
   570  
   571  // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
   572  func (lc *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
   573  	return lc.scope.Track(lc.chainHeadFeed.Subscribe(ch))
   574  }
   575  
   576  // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
   577  func (lc *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
   578  	return lc.scope.Track(lc.chainSideFeed.Subscribe(ch))
   579  }
   580  
   581  // SubscribeLogsEvent implements the interface of filters.Backend
   582  // LightChain does not send logs events, so return an empty subscription.
   583  func (lc *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   584  	return lc.scope.Track(new(event.Feed).Subscribe(ch))
   585  }
   586  
   587  // SubscribeRemovedLogsEvent implements the interface of filters.Backend
   588  // LightChain does not send core.RemovedLogsEvent, so return an empty subscription.
   589  func (lc *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   590  	return lc.scope.Track(new(event.Feed).Subscribe(ch))
   591  }
   592  
   593  // DisableCheckFreq disables header validation. This is used for ultralight mode.
   594  func (lc *LightChain) DisableCheckFreq() {
   595  	atomic.StoreInt32(&lc.disableCheckFreq, 1)
   596  }
   597  
   598  // EnableCheckFreq enables header validation.
   599  func (lc *LightChain) EnableCheckFreq() {
   600  	atomic.StoreInt32(&lc.disableCheckFreq, 0)
   601  }