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