github.com/m3shine/gochain@v2.2.26+incompatible/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
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"math/big"
    23  	"sync"
    24  	"sync/atomic"
    25  	"time"
    26  
    27  	"github.com/gochain-io/gochain/common"
    28  	"github.com/gochain-io/gochain/consensus"
    29  	"github.com/gochain-io/gochain/core"
    30  	"github.com/gochain-io/gochain/core/rawdb"
    31  	"github.com/gochain-io/gochain/core/state"
    32  	"github.com/gochain-io/gochain/core/types"
    33  	"github.com/gochain-io/gochain/log"
    34  	"github.com/gochain-io/gochain/params"
    35  	"github.com/gochain-io/gochain/rlp"
    36  	"github.com/hashicorp/golang-lru"
    37  )
    38  
    39  var (
    40  	bodyCacheLimit  = 256
    41  	blockCacheLimit = 256
    42  )
    43  
    44  // LightChain represents a canonical chain that by default only handles block
    45  // headers, downloading block bodies and receipts on demand through an ODR
    46  // interface. It only does header validation during chain insertion.
    47  type LightChain struct {
    48  	hc      *core.HeaderChain
    49  	chainDb common.Database
    50  	odr     OdrBackend
    51  
    52  	chainFeed     core.ChainFeed
    53  	chainHeadFeed core.ChainHeadFeed
    54  	chainSideFeed core.ChainSideFeed
    55  
    56  	genesisBlock *types.Block
    57  
    58  	mu      sync.RWMutex
    59  	chainmu sync.RWMutex
    60  
    61  	bodyCache    *lru.Cache // Cache for the most recent block bodies
    62  	bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
    63  	blockCache   *lru.Cache // Cache for the most recent entire blocks
    64  
    65  	quit    chan struct{}
    66  	running int32 // running must be called automically
    67  	// procInterrupt must be atomically called
    68  	procInterrupt int32 // interrupt signaler for block processing
    69  	wg            sync.WaitGroup
    70  
    71  	engine consensus.Engine
    72  }
    73  
    74  // NewLightChain returns a fully initialised light chain using information
    75  // available in the database. It initialises the default Ethereum header
    76  // validator.
    77  func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.Engine) (*LightChain, error) {
    78  	bodyCache, _ := lru.New(bodyCacheLimit)
    79  	bodyRLPCache, _ := lru.New(bodyCacheLimit)
    80  	blockCache, _ := lru.New(blockCacheLimit)
    81  
    82  	bc := &LightChain{
    83  		chainDb:      odr.Database(),
    84  		odr:          odr,
    85  		quit:         make(chan struct{}),
    86  		bodyCache:    bodyCache,
    87  		bodyRLPCache: bodyRLPCache,
    88  		blockCache:   blockCache,
    89  		engine:       engine,
    90  	}
    91  	var err error
    92  	bc.hc, err = core.NewHeaderChain(odr.Database(), config, bc.engine, bc.getProcInterrupt)
    93  	if err != nil {
    94  		return nil, err
    95  	}
    96  	bc.genesisBlock, _ = bc.GetBlockByNumber(NoOdr, 0)
    97  	if bc.genesisBlock == nil {
    98  		return nil, core.ErrNoGenesis
    99  	}
   100  	if cp, ok := trustedCheckpoints[bc.genesisBlock.Hash()]; ok {
   101  		bc.addTrustedCheckpoint(cp)
   102  	}
   103  	if err := bc.loadLastState(); err != nil {
   104  		return nil, err
   105  	}
   106  	// Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
   107  	for hash := range core.BadHashes {
   108  		if header := bc.GetHeaderByHash(hash); header != nil {
   109  			log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
   110  			bc.SetHead(header.Number.Uint64() - 1)
   111  			log.Error("Chain rewind was successful, resuming normal operation")
   112  		}
   113  	}
   114  	return bc, nil
   115  }
   116  
   117  // addTrustedCheckpoint adds a trusted checkpoint to the blockchain
   118  func (self *LightChain) addTrustedCheckpoint(cp trustedCheckpoint) {
   119  	if self.odr.ChtIndexer() != nil {
   120  		StoreChtRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.chtRoot)
   121  		self.odr.ChtIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
   122  	}
   123  	if self.odr.BloomTrieIndexer() != nil {
   124  		StoreBloomTrieRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.bloomTrieRoot)
   125  		self.odr.BloomTrieIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
   126  	}
   127  	if self.odr.BloomIndexer() != nil {
   128  		self.odr.BloomIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
   129  	}
   130  	log.Info("Added trusted checkpoint", "chain", cp.name, "block", (cp.sectionIdx+1)*CHTFrequencyClient-1, "hash", cp.sectionHead)
   131  }
   132  
   133  func (self *LightChain) getProcInterrupt() bool {
   134  	return atomic.LoadInt32(&self.procInterrupt) == 1
   135  }
   136  
   137  // Odr returns the ODR backend of the chain
   138  func (self *LightChain) Odr() OdrBackend {
   139  	return self.odr
   140  }
   141  
   142  // loadLastState loads the last known chain state from the database. This method
   143  // assumes that the chain manager mutex is held.
   144  func (self *LightChain) loadLastState() error {
   145  	if head := rawdb.ReadHeadHeaderHash(self.chainDb.GlobalTable()); head == (common.Hash{}) {
   146  		// Corrupt or empty database, init from scratch
   147  		self.Reset()
   148  	} else {
   149  		if header := self.GetHeaderByHash(head); header != nil {
   150  			self.hc.SetCurrentHeader(header)
   151  		}
   152  	}
   153  
   154  	// Issue a status log and return
   155  	header := self.hc.CurrentHeader()
   156  	headerTd := self.GetTd(header.Hash(), header.Number.Uint64())
   157  	log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd)
   158  
   159  	return nil
   160  }
   161  
   162  // SetHead rewinds the local chain to a new head. Everything above the new
   163  // head will be deleted and the new one set.
   164  func (bc *LightChain) SetHead(head uint64) {
   165  	bc.mu.Lock()
   166  	defer bc.mu.Unlock()
   167  
   168  	bc.hc.SetHead(head, nil)
   169  	if err := bc.loadLastState(); err != nil {
   170  		log.Error("Cannot load last state while setting head", "err", err)
   171  	}
   172  }
   173  
   174  // GasLimit returns the gas limit of the current HEAD block.
   175  func (self *LightChain) GasLimit() uint64 {
   176  	return self.hc.CurrentHeader().GasLimit
   177  }
   178  
   179  // Reset purges the entire blockchain, restoring it to its genesis state.
   180  func (bc *LightChain) Reset() {
   181  	bc.ResetWithGenesisBlock(bc.genesisBlock)
   182  }
   183  
   184  // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
   185  // specified genesis state.
   186  func (bc *LightChain) ResetWithGenesisBlock(genesis *types.Block) {
   187  	// Dump the entire block chain and purge the caches
   188  	bc.SetHead(0)
   189  
   190  	bc.mu.Lock()
   191  	defer bc.mu.Unlock()
   192  
   193  	// Prepare the genesis block and reinitialise the chain
   194  	rawdb.WriteTd(bc.chainDb.GlobalTable(), genesis.Hash(), genesis.NumberU64(), genesis.Difficulty())
   195  	rawdb.WriteBlock(bc.chainDb, genesis)
   196  	bc.genesisBlock = genesis
   197  	bc.hc.SetGenesis(bc.genesisBlock.Header())
   198  	bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
   199  }
   200  
   201  // Accessors
   202  
   203  // Engine retrieves the light chain's consensus engine.
   204  func (bc *LightChain) Engine() consensus.Engine { return bc.engine }
   205  
   206  // Genesis returns the genesis block
   207  func (bc *LightChain) Genesis() *types.Block {
   208  	return bc.genesisBlock
   209  }
   210  
   211  // State returns a new mutable state based on the current HEAD block.
   212  func (bc *LightChain) State() (*state.StateDB, error) {
   213  	return nil, errors.New("not implemented, needs client/server interface split")
   214  }
   215  
   216  // GetBody retrieves a block body (transactions and uncles) from the database
   217  // or ODR service by hash, caching it if found.
   218  func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) {
   219  	// Short circuit if the body's already in the cache, retrieve otherwise
   220  	if cached, ok := self.bodyCache.Get(hash); ok {
   221  		body := cached.(*types.Body)
   222  		return body, nil
   223  	}
   224  	number := self.hc.GetBlockNumber(hash)
   225  	if number == nil {
   226  		return nil, errors.New("unknown block")
   227  	}
   228  	body, err := GetBody(ctx, self.odr, hash, *number)
   229  	if err != nil {
   230  		return nil, err
   231  	}
   232  	// Cache the found body for next time and return
   233  	self.bodyCache.Add(hash, body)
   234  	return body, nil
   235  }
   236  
   237  // GetBodyRLP retrieves a block body in RLP encoding from the database or
   238  // ODR service by hash, caching it if found.
   239  func (self *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) {
   240  	// Short circuit if the body's already in the cache, retrieve otherwise
   241  	if cached, ok := self.bodyRLPCache.Get(hash); ok {
   242  		return cached.(rlp.RawValue), nil
   243  	}
   244  	number := self.hc.GetBlockNumber(hash)
   245  	if number == nil {
   246  		return nil, errors.New("unknown block")
   247  	}
   248  	body, err := GetBodyRLP(ctx, self.odr, hash, *number)
   249  	if err != nil {
   250  		return nil, err
   251  	}
   252  	// Cache the found body for next time and return
   253  	self.bodyRLPCache.Add(hash, body)
   254  	return body, nil
   255  }
   256  
   257  // HasBlock checks if a block is fully present in the database or not, caching
   258  // it if present.
   259  func (bc *LightChain) HasBlock(hash common.Hash, number uint64) bool {
   260  	blk, _ := bc.GetBlock(NoOdr, hash, number)
   261  	return blk != nil
   262  }
   263  
   264  // GetBlock retrieves a block from the database or ODR service by hash and number,
   265  // caching it if found.
   266  func (self *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) {
   267  	// Short circuit if the block's already in the cache, retrieve otherwise
   268  	if block, ok := self.blockCache.Get(hash); ok {
   269  		return block.(*types.Block), nil
   270  	}
   271  	block, err := GetBlock(ctx, self.odr, hash, number)
   272  	if err != nil {
   273  		return nil, err
   274  	}
   275  	// Cache the found block for next time and return
   276  	self.blockCache.Add(block.Hash(), block)
   277  	return block, nil
   278  }
   279  
   280  // GetBlockByHash retrieves a block from the database or ODR service by hash,
   281  // caching it if found.
   282  func (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   283  	number := self.hc.GetBlockNumber(hash)
   284  	if number == nil {
   285  		return nil, errors.New("unknown block")
   286  	}
   287  	return self.GetBlock(ctx, hash, *number)
   288  }
   289  
   290  // GetBlockByNumber retrieves a block from the database or ODR service by
   291  // number, caching it (associated with its hash) if found.
   292  func (self *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) {
   293  	hash, err := GetCanonicalHash(ctx, self.odr, number)
   294  	if hash == (common.Hash{}) || err != nil {
   295  		return nil, err
   296  	}
   297  	return self.GetBlock(ctx, hash, number)
   298  }
   299  
   300  // Stop stops the blockchain service. If any imports are currently in progress
   301  // it will abort them using the procInterrupt.
   302  func (bc *LightChain) Stop() {
   303  	if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
   304  		return
   305  	}
   306  	close(bc.quit)
   307  	atomic.StoreInt32(&bc.procInterrupt, 1)
   308  
   309  	bc.wg.Wait()
   310  	log.Info("Blockchain manager stopped")
   311  }
   312  
   313  // Rollback is designed to remove a chain of links from the database that aren't
   314  // certain enough to be valid.
   315  func (self *LightChain) Rollback(chain []common.Hash) {
   316  	self.mu.Lock()
   317  	defer self.mu.Unlock()
   318  
   319  	for i := len(chain) - 1; i >= 0; i-- {
   320  		hash := chain[i]
   321  
   322  		if head := self.hc.CurrentHeader(); head.Hash() == hash {
   323  			self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1))
   324  		}
   325  	}
   326  }
   327  
   328  // postChainEvents iterates over the events generated by a chain insertion and
   329  // posts them into the event feed.
   330  func (self *LightChain) postChainEvents(events []interface{}) {
   331  	for _, event := range events {
   332  		switch ev := event.(type) {
   333  		case core.ChainEvent:
   334  			if self.CurrentHeader().Hash() == ev.Hash {
   335  				self.chainHeadFeed.Send(core.ChainHeadEvent{Block: ev.Block})
   336  			}
   337  			self.chainFeed.Send(ev)
   338  		case core.ChainSideEvent:
   339  			self.chainSideFeed.Send(ev)
   340  		}
   341  	}
   342  }
   343  
   344  // InsertHeaderChain attempts to insert the given header chain in to the local
   345  // chain, possibly creating a reorg. If an error is returned, it will return the
   346  // index number of the failing header as well an error describing what went wrong.
   347  //
   348  // The verify parameter can be used to fine tune whether nonce verification
   349  // should be done or not. The reason behind the optional check is because some
   350  // of the header retrieval mechanisms already need to verfy nonces, as well as
   351  // because nonces can be verified sparsely, not needing to check each.
   352  //
   353  // In the case of a light chain, InsertHeaderChain also creates and posts light
   354  // chain events when necessary.
   355  func (self *LightChain) InsertHeaderChain(ctx context.Context, chain []*types.Header, checkFreq int) (int, error) {
   356  	start := time.Now()
   357  	if i, err := self.hc.ValidateHeaderChain(ctx, chain, checkFreq); err != nil {
   358  		return i, err
   359  	}
   360  
   361  	// Make sure only one thread manipulates the chain at once
   362  	self.chainmu.Lock()
   363  	defer func() {
   364  		self.chainmu.Unlock()
   365  		time.Sleep(time.Millisecond * 10) // ugly hack; do not hog chain lock in case syncing is CPU-limited by validation
   366  	}()
   367  
   368  	self.wg.Add(1)
   369  	defer self.wg.Done()
   370  
   371  	var events []interface{}
   372  	whFunc := func(header *types.Header) error {
   373  		self.mu.Lock()
   374  		defer self.mu.Unlock()
   375  
   376  		status, err := self.hc.WriteHeader(header)
   377  
   378  		switch status {
   379  		case core.CanonStatTy:
   380  			log.Debug("Inserted new header", "number", header.Number, "hash", header.Hash())
   381  			events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()})
   382  
   383  		case core.SideStatTy:
   384  			log.Debug("Inserted forked header", "number", header.Number, "hash", header.Hash())
   385  			events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)})
   386  		}
   387  		return err
   388  	}
   389  	i, err := self.hc.InsertHeaderChain(chain, whFunc, start)
   390  	self.postChainEvents(events)
   391  	return i, err
   392  }
   393  
   394  // CurrentHeader retrieves the current head header of the canonical chain. The
   395  // header is retrieved from the HeaderChain's internal cache.
   396  func (self *LightChain) CurrentHeader() *types.Header {
   397  	return self.hc.CurrentHeader()
   398  }
   399  
   400  // GetTd retrieves a block's total difficulty in the canonical chain from the
   401  // database by hash and number, caching it if found.
   402  func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int {
   403  	return self.hc.GetTd(hash, number)
   404  }
   405  
   406  // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
   407  // database by hash, caching it if found.
   408  func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int {
   409  	return self.hc.GetTdByHash(hash)
   410  }
   411  
   412  // GetHeader retrieves a block header from the database by hash and number,
   413  // caching it if found.
   414  func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header {
   415  	return self.hc.GetHeader(hash, number)
   416  }
   417  
   418  // GetHeaderByHash retrieves a block header from the database by hash, caching it if
   419  // found.
   420  func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header {
   421  	return self.hc.GetHeaderByHash(hash)
   422  }
   423  
   424  // HasHeader checks if a block header is present in the database or not, caching
   425  // it if present.
   426  func (bc *LightChain) HasHeader(hash common.Hash, number uint64) bool {
   427  	return bc.hc.HasHeader(hash, number)
   428  }
   429  
   430  // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
   431  // hash, fetching towards the genesis block.
   432  func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
   433  	return self.hc.GetBlockHashesFromHash(hash, max)
   434  }
   435  
   436  // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
   437  // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
   438  // number of blocks to be individually checked before we reach the canonical chain.
   439  //
   440  // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
   441  func (bc *LightChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
   442  	bc.chainmu.Lock()
   443  	defer bc.chainmu.Unlock()
   444  
   445  	return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
   446  }
   447  
   448  // GetHeaderByNumber retrieves a block header from the database by number,
   449  // caching it (associated with its hash) if found.
   450  func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header {
   451  	return self.hc.GetHeaderByNumber(number)
   452  }
   453  
   454  // GetHeaderByNumberOdr retrieves a block header from the database or network
   455  // by number, caching it (associated with its hash) if found.
   456  func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) {
   457  	if header := self.hc.GetHeaderByNumber(number); header != nil {
   458  		return header, nil
   459  	}
   460  	return GetHeaderByNumber(ctx, self.odr, number)
   461  }
   462  
   463  // Config retrieves the header chain's chain configuration.
   464  func (self *LightChain) Config() *params.ChainConfig { return self.hc.Config() }
   465  
   466  func (self *LightChain) SyncCht(ctx context.Context) bool {
   467  	if self.odr.ChtIndexer() == nil {
   468  		return false
   469  	}
   470  	headNum := self.CurrentHeader().Number.Uint64()
   471  	chtCount, _, _ := self.odr.ChtIndexer().Sections()
   472  	if headNum+1 < chtCount*CHTFrequencyClient {
   473  		num := chtCount*CHTFrequencyClient - 1
   474  		header, err := GetHeaderByNumber(ctx, self.odr, num)
   475  		if header != nil && err == nil {
   476  			self.mu.Lock()
   477  			if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
   478  				self.hc.SetCurrentHeader(header)
   479  			}
   480  			self.mu.Unlock()
   481  			return true
   482  		}
   483  	}
   484  	return false
   485  }
   486  
   487  // LockChain locks the chain mutex for reading so that multiple canonical hashes can be
   488  // retrieved while it is guaranteed that they belong to the same version of the chain
   489  func (self *LightChain) LockChain() {
   490  	self.chainmu.RLock()
   491  }
   492  
   493  // UnlockChain unlocks the chain mutex
   494  func (self *LightChain) UnlockChain() {
   495  	self.chainmu.RUnlock()
   496  }
   497  
   498  // SubscribeChainEvent registers a subscription of ChainEvent.
   499  func (lc *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent, name string) {
   500  	lc.chainFeed.Subscribe(ch, name)
   501  }
   502  
   503  func (lc *LightChain) UnsubscribeChainEvent(ch chan<- core.ChainEvent) {
   504  	lc.chainFeed.Unsubscribe(ch)
   505  }
   506  
   507  // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
   508  func (lc *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent, name string) {
   509  	lc.chainHeadFeed.Subscribe(ch, name)
   510  }
   511  
   512  func (lc *LightChain) UnsubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) {
   513  	lc.chainHeadFeed.Unsubscribe(ch)
   514  }
   515  
   516  // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
   517  func (lc *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent, name string) {
   518  	lc.chainSideFeed.Subscribe(ch, name)
   519  }
   520  
   521  func (lc *LightChain) UnsubscribeChainSideEvent(ch chan<- core.ChainSideEvent) {
   522  	lc.chainSideFeed.Unsubscribe(ch)
   523  }