github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.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
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"math/big"
    23  	"sync"
    24  	"sync/atomic"
    25  	"time"
    26  
    27  	"github.com/hashicorp/golang-lru"
    28  	"github.com/vntchain/go-vnt/common"
    29  	"github.com/vntchain/go-vnt/consensus"
    30  	"github.com/vntchain/go-vnt/core"
    31  	"github.com/vntchain/go-vnt/core/rawdb"
    32  	"github.com/vntchain/go-vnt/core/state"
    33  	"github.com/vntchain/go-vnt/core/types"
    34  	"github.com/vntchain/go-vnt/event"
    35  	"github.com/vntchain/go-vnt/log"
    36  	"github.com/vntchain/go-vnt/params"
    37  	"github.com/vntchain/go-vnt/rlp"
    38  	"github.com/vntchain/go-vnt/vntdb"
    39  )
    40  
    41  var (
    42  	bodyCacheLimit  = 256
    43  	blockCacheLimit = 256
    44  )
    45  
    46  // LightChain represents a canonical chain that by default only handles block
    47  // headers, downloading block bodies and receipts on demand through an ODR
    48  // interface. It only does header validation during chain insertion.
    49  type LightChain struct {
    50  	hc            *core.HeaderChain
    51  	chainDb       vntdb.Database
    52  	odr           OdrBackend
    53  	chainFeed     event.Feed
    54  	chainSideFeed event.Feed
    55  	chainHeadFeed event.Feed
    56  	scope         event.SubscriptionScope
    57  	genesisBlock  *types.Block
    58  
    59  	mu      sync.RWMutex
    60  	chainmu sync.RWMutex
    61  
    62  	bodyCache    *lru.Cache // Cache for the most recent block bodies
    63  	bodyRLPCache *lru.Cache // Cache for the most recent block bodies in RLP encoded format
    64  	blockCache   *lru.Cache // Cache for the most recent entire blocks
    65  
    66  	quit    chan struct{}
    67  	running int32 // running must be called automically
    68  	// procInterrupt must be atomically called
    69  	procInterrupt int32 // interrupt signaler for block processing
    70  	wg            sync.WaitGroup
    71  
    72  	engine consensus.Engine
    73  }
    74  
    75  // NewLightChain returns a fully initialised light chain using information
    76  // available in the database. It initialises the default VNT header
    77  // validator.
    78  func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.Engine) (*LightChain, error) {
    79  	bodyCache, _ := lru.New(bodyCacheLimit)
    80  	bodyRLPCache, _ := lru.New(bodyCacheLimit)
    81  	blockCache, _ := lru.New(blockCacheLimit)
    82  
    83  	bc := &LightChain{
    84  		chainDb:      odr.Database(),
    85  		odr:          odr,
    86  		quit:         make(chan struct{}),
    87  		bodyCache:    bodyCache,
    88  		bodyRLPCache: bodyRLPCache,
    89  		blockCache:   blockCache,
    90  		engine:       engine,
    91  	}
    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 cp, ok := trustedCheckpoints[bc.genesisBlock.Hash()]; ok {
   102  		bc.addTrustedCheckpoint(cp)
   103  	}
   104  	if err := bc.loadLastState(); err != nil {
   105  		return nil, err
   106  	}
   107  	// Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
   108  	for hash := range core.BadHashes {
   109  		if header := bc.GetHeaderByHash(hash); header != nil {
   110  			log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
   111  			bc.SetHead(header.Number.Uint64() - 1)
   112  			log.Error("Chain rewind was successful, resuming normal operation")
   113  		}
   114  	}
   115  	return bc, nil
   116  }
   117  
   118  // addTrustedCheckpoint adds a trusted checkpoint to the blockchain
   119  func (self *LightChain) addTrustedCheckpoint(cp trustedCheckpoint) {
   120  	if self.odr.ChtIndexer() != nil {
   121  		StoreChtRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.chtRoot)
   122  		self.odr.ChtIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
   123  	}
   124  	if self.odr.BloomTrieIndexer() != nil {
   125  		StoreBloomTrieRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.bloomTrieRoot)
   126  		self.odr.BloomTrieIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
   127  	}
   128  	if self.odr.BloomIndexer() != nil {
   129  		self.odr.BloomIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
   130  	}
   131  	log.Info("Added trusted checkpoint", "chain", cp.name, "block", (cp.sectionIdx+1)*CHTFrequencyClient-1, "hash", cp.sectionHead)
   132  }
   133  
   134  func (self *LightChain) getProcInterrupt() bool {
   135  	return atomic.LoadInt32(&self.procInterrupt) == 1
   136  }
   137  
   138  // Odr returns the ODR backend of the chain
   139  func (self *LightChain) Odr() OdrBackend {
   140  	return self.odr
   141  }
   142  
   143  // loadLastState loads the last known chain state from the database. This method
   144  // assumes that the chain manager mutex is held.
   145  func (self *LightChain) loadLastState() error {
   146  	if head := rawdb.ReadHeadHeaderHash(self.chainDb); head == (common.Hash{}) {
   147  		// Corrupt or empty database, init from scratch
   148  		self.Reset()
   149  	} else {
   150  		if header := self.GetHeaderByHash(head); header != nil {
   151  			self.hc.SetCurrentHeader(header)
   152  		}
   153  	}
   154  
   155  	// Issue a status log and return
   156  	header := self.hc.CurrentHeader()
   157  	headerTd := self.GetTd(header.Hash(), header.Number.Uint64())
   158  	log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd)
   159  
   160  	return nil
   161  }
   162  
   163  // SetHead rewinds the local chain to a new head. Everything above the new
   164  // head will be deleted and the new one set.
   165  func (bc *LightChain) SetHead(head uint64) {
   166  	bc.mu.Lock()
   167  	defer bc.mu.Unlock()
   168  
   169  	bc.hc.SetHead(head, nil)
   170  	bc.loadLastState()
   171  }
   172  
   173  // GasLimit returns the gas limit of the current HEAD block.
   174  func (self *LightChain) GasLimit() uint64 {
   175  	return self.hc.CurrentHeader().GasLimit
   176  }
   177  
   178  // Reset purges the entire blockchain, restoring it to its genesis state.
   179  func (bc *LightChain) Reset() {
   180  	bc.ResetWithGenesisBlock(bc.genesisBlock)
   181  }
   182  
   183  // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
   184  // specified genesis state.
   185  func (bc *LightChain) ResetWithGenesisBlock(genesis *types.Block) {
   186  	// Dump the entire block chain and purge the caches
   187  	bc.SetHead(0)
   188  
   189  	bc.mu.Lock()
   190  	defer bc.mu.Unlock()
   191  
   192  	// Prepare the genesis block and reinitialise the chain
   193  	rawdb.WriteTd(bc.chainDb, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty())
   194  	rawdb.WriteBlock(bc.chainDb, genesis)
   195  
   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) 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(chain []*types.Header, checkFreq int) (int, error) {
   356  	start := time.Now()
   357  	if i, err := self.hc.ValidateHeaderChain(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 (self *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   500  	return self.scope.Track(self.chainFeed.Subscribe(ch))
   501  }
   502  
   503  // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
   504  func (self *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
   505  	return self.scope.Track(self.chainHeadFeed.Subscribe(ch))
   506  }
   507  
   508  // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
   509  func (self *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
   510  	return self.scope.Track(self.chainSideFeed.Subscribe(ch))
   511  }
   512  
   513  // SubscribeLogsEvent implements the interface of filters.Backend
   514  // LightChain does not send logs events, so return an empty subscription.
   515  func (self *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   516  	return self.scope.Track(new(event.Feed).Subscribe(ch))
   517  }
   518  
   519  // SubscribeRemovedLogsEvent implements the interface of filters.Backend
   520  // LightChain does not send core.RemovedLogsEvent, so return an empty subscription.
   521  func (self *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   522  	return self.scope.Track(new(event.Feed).Subscribe(ch))
   523  }