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