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