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