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