github.com/vantum/vantum@v0.0.0-20180815184342-fe37d5f7a990/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/vantum/vantum/common"
    28  	"github.com/vantum/vantum/consensus"
    29  	"github.com/vantum/vantum/core"
    30  	"github.com/vantum/vantum/core/state"
    31  	"github.com/vantum/vantum/core/types"
    32  	"github.com/vantum/vantum/ethdb"
    33  	"github.com/vantum/vantum/event"
    34  	"github.com/vantum/vantum/log"
    35  	"github.com/vantum/vantum/params"
    36  	"github.com/vantum/vantum/rlp"
    37  	"github.com/hashicorp/golang-lru"
    38  )
    39  
    40  var (
    41  	bodyCacheLimit  = 256
    42  	blockCacheLimit = 256
    43  )
    44  
    45  // LightChain represents a canonical chain that by default only handles block
    46  // headers, downloading block bodies and receipts on demand through an ODR
    47  // interface. It only does header validation during chain insertion.
    48  type LightChain struct {
    49  	hc            *core.HeaderChain
    50  	chainDb       ethdb.Database
    51  	odr           OdrBackend
    52  	chainFeed     event.Feed
    53  	chainSideFeed event.Feed
    54  	chainHeadFeed event.Feed
    55  	scope         event.SubscriptionScope
    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 := core.GetHeadHeaderHash(self.chainDb); 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  	bc.loadLastState()
   170  }
   171  
   172  // GasLimit returns the gas limit of the current HEAD block.
   173  func (self *LightChain) GasLimit() uint64 {
   174  	self.mu.RLock()
   175  	defer self.mu.RUnlock()
   176  
   177  	return self.hc.CurrentHeader().GasLimit
   178  }
   179  
   180  // Reset purges the entire blockchain, restoring it to its genesis state.
   181  func (bc *LightChain) Reset() {
   182  	bc.ResetWithGenesisBlock(bc.genesisBlock)
   183  }
   184  
   185  // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
   186  // specified genesis state.
   187  func (bc *LightChain) ResetWithGenesisBlock(genesis *types.Block) {
   188  	// Dump the entire block chain and purge the caches
   189  	bc.SetHead(0)
   190  
   191  	bc.mu.Lock()
   192  	defer bc.mu.Unlock()
   193  
   194  	// Prepare the genesis block and reinitialise the chain
   195  	if err := core.WriteTd(bc.chainDb, genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
   196  		log.Crit("Failed to write genesis block TD", "err", err)
   197  	}
   198  	if err := core.WriteBlock(bc.chainDb, genesis); err != nil {
   199  		log.Crit("Failed to write genesis block", "err", err)
   200  	}
   201  	bc.genesisBlock = genesis
   202  	bc.hc.SetGenesis(bc.genesisBlock.Header())
   203  	bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
   204  }
   205  
   206  // Accessors
   207  
   208  // Engine retrieves the light chain's consensus engine.
   209  func (bc *LightChain) Engine() consensus.Engine { return bc.engine }
   210  
   211  // Genesis returns the genesis block
   212  func (bc *LightChain) Genesis() *types.Block {
   213  	return bc.genesisBlock
   214  }
   215  
   216  // State returns a new mutable state based on the current HEAD block.
   217  func (bc *LightChain) State() (*state.StateDB, error) {
   218  	return nil, errors.New("not implemented, needs client/server interface split")
   219  }
   220  
   221  // GetBody retrieves a block body (transactions and uncles) from the database
   222  // or ODR service by hash, caching it if found.
   223  func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) {
   224  	// Short circuit if the body's already in the cache, retrieve otherwise
   225  	if cached, ok := self.bodyCache.Get(hash); ok {
   226  		body := cached.(*types.Body)
   227  		return body, nil
   228  	}
   229  	body, err := GetBody(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
   230  	if err != nil {
   231  		return nil, err
   232  	}
   233  	// Cache the found body for next time and return
   234  	self.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 (self *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 := self.bodyRLPCache.Get(hash); ok {
   243  		return cached.(rlp.RawValue), nil
   244  	}
   245  	body, err := GetBodyRLP(ctx, self.odr, hash, self.hc.GetBlockNumber(hash))
   246  	if err != nil {
   247  		return nil, err
   248  	}
   249  	// Cache the found body for next time and return
   250  	self.bodyRLPCache.Add(hash, body)
   251  	return body, nil
   252  }
   253  
   254  // HasBlock checks if a block is fully present in the database or not, caching
   255  // it if present.
   256  func (bc *LightChain) HasBlock(hash common.Hash, number uint64) bool {
   257  	blk, _ := bc.GetBlock(NoOdr, hash, number)
   258  	return blk != nil
   259  }
   260  
   261  // GetBlock retrieves a block from the database or ODR service by hash and number,
   262  // caching it if found.
   263  func (self *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) {
   264  	// Short circuit if the block's already in the cache, retrieve otherwise
   265  	if block, ok := self.blockCache.Get(hash); ok {
   266  		return block.(*types.Block), nil
   267  	}
   268  	block, err := GetBlock(ctx, self.odr, hash, number)
   269  	if err != nil {
   270  		return nil, err
   271  	}
   272  	// Cache the found block for next time and return
   273  	self.blockCache.Add(block.Hash(), block)
   274  	return block, nil
   275  }
   276  
   277  // GetBlockByHash retrieves a block from the database or ODR service by hash,
   278  // caching it if found.
   279  func (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   280  	return self.GetBlock(ctx, hash, self.hc.GetBlockNumber(hash))
   281  }
   282  
   283  // GetBlockByNumber retrieves a block from the database or ODR service by
   284  // number, caching it (associated with its hash) if found.
   285  func (self *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) {
   286  	hash, err := GetCanonicalHash(ctx, self.odr, number)
   287  	if hash == (common.Hash{}) || err != nil {
   288  		return nil, err
   289  	}
   290  	return self.GetBlock(ctx, hash, number)
   291  }
   292  
   293  // Stop stops the blockchain service. If any imports are currently in progress
   294  // it will abort them using the procInterrupt.
   295  func (bc *LightChain) Stop() {
   296  	if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
   297  		return
   298  	}
   299  	close(bc.quit)
   300  	atomic.StoreInt32(&bc.procInterrupt, 1)
   301  
   302  	bc.wg.Wait()
   303  	log.Info("Blockchain manager stopped")
   304  }
   305  
   306  // Rollback is designed to remove a chain of links from the database that aren't
   307  // certain enough to be valid.
   308  func (self *LightChain) Rollback(chain []common.Hash) {
   309  	self.mu.Lock()
   310  	defer self.mu.Unlock()
   311  
   312  	for i := len(chain) - 1; i >= 0; i-- {
   313  		hash := chain[i]
   314  
   315  		if head := self.hc.CurrentHeader(); head.Hash() == hash {
   316  			self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1))
   317  		}
   318  	}
   319  }
   320  
   321  // postChainEvents iterates over the events generated by a chain insertion and
   322  // posts them into the event feed.
   323  func (self *LightChain) postChainEvents(events []interface{}) {
   324  	for _, event := range events {
   325  		switch ev := event.(type) {
   326  		case core.ChainEvent:
   327  			if self.CurrentHeader().Hash() == ev.Hash {
   328  				self.chainHeadFeed.Send(core.ChainHeadEvent{Block: ev.Block})
   329  			}
   330  			self.chainFeed.Send(ev)
   331  		case core.ChainSideEvent:
   332  			self.chainSideFeed.Send(ev)
   333  		}
   334  	}
   335  }
   336  
   337  // InsertHeaderChain attempts to insert the given header chain in to the local
   338  // chain, possibly creating a reorg. If an error is returned, it will return the
   339  // index number of the failing header as well an error describing what went wrong.
   340  //
   341  // The verify parameter can be used to fine tune whether nonce verification
   342  // should be done or not. The reason behind the optional check is because some
   343  // of the header retrieval mechanisms already need to verfy nonces, as well as
   344  // because nonces can be verified sparsely, not needing to check each.
   345  //
   346  // In the case of a light chain, InsertHeaderChain also creates and posts light
   347  // chain events when necessary.
   348  func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
   349  	start := time.Now()
   350  	if i, err := self.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
   351  		return i, err
   352  	}
   353  
   354  	// Make sure only one thread manipulates the chain at once
   355  	self.chainmu.Lock()
   356  	defer func() {
   357  		self.chainmu.Unlock()
   358  		time.Sleep(time.Millisecond * 10) // ugly hack; do not hog chain lock in case syncing is CPU-limited by validation
   359  	}()
   360  
   361  	self.wg.Add(1)
   362  	defer self.wg.Done()
   363  
   364  	var events []interface{}
   365  	whFunc := func(header *types.Header) error {
   366  		self.mu.Lock()
   367  		defer self.mu.Unlock()
   368  
   369  		status, err := self.hc.WriteHeader(header)
   370  
   371  		switch status {
   372  		case core.CanonStatTy:
   373  			log.Debug("Inserted new header", "number", header.Number, "hash", header.Hash())
   374  			events = append(events, core.ChainEvent{Block: types.NewBlockWithHeader(header), Hash: header.Hash()})
   375  
   376  		case core.SideStatTy:
   377  			log.Debug("Inserted forked header", "number", header.Number, "hash", header.Hash())
   378  			events = append(events, core.ChainSideEvent{Block: types.NewBlockWithHeader(header)})
   379  		}
   380  		return err
   381  	}
   382  	i, err := self.hc.InsertHeaderChain(chain, whFunc, start)
   383  	self.postChainEvents(events)
   384  	return i, err
   385  }
   386  
   387  // CurrentHeader retrieves the current head header of the canonical chain. The
   388  // header is retrieved from the HeaderChain's internal cache.
   389  func (self *LightChain) CurrentHeader() *types.Header {
   390  	self.mu.RLock()
   391  	defer self.mu.RUnlock()
   392  
   393  	return self.hc.CurrentHeader()
   394  }
   395  
   396  // GetTd retrieves a block's total difficulty in the canonical chain from the
   397  // database by hash and number, caching it if found.
   398  func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int {
   399  	return self.hc.GetTd(hash, number)
   400  }
   401  
   402  // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
   403  // database by hash, caching it if found.
   404  func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int {
   405  	return self.hc.GetTdByHash(hash)
   406  }
   407  
   408  // GetHeader retrieves a block header from the database by hash and number,
   409  // caching it if found.
   410  func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header {
   411  	return self.hc.GetHeader(hash, number)
   412  }
   413  
   414  // GetHeaderByHash retrieves a block header from the database by hash, caching it if
   415  // found.
   416  func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header {
   417  	return self.hc.GetHeaderByHash(hash)
   418  }
   419  
   420  // HasHeader checks if a block header is present in the database or not, caching
   421  // it if present.
   422  func (bc *LightChain) HasHeader(hash common.Hash, number uint64) bool {
   423  	return bc.hc.HasHeader(hash, number)
   424  }
   425  
   426  // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
   427  // hash, fetching towards the genesis block.
   428  func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
   429  	return self.hc.GetBlockHashesFromHash(hash, max)
   430  }
   431  
   432  // GetHeaderByNumber retrieves a block header from the database by number,
   433  // caching it (associated with its hash) if found.
   434  func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header {
   435  	return self.hc.GetHeaderByNumber(number)
   436  }
   437  
   438  // GetHeaderByNumberOdr retrieves a block header from the database or network
   439  // by number, caching it (associated with its hash) if found.
   440  func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) {
   441  	if header := self.hc.GetHeaderByNumber(number); header != nil {
   442  		return header, nil
   443  	}
   444  	return GetHeaderByNumber(ctx, self.odr, number)
   445  }
   446  
   447  // Config retrieves the header chain's chain configuration.
   448  func (self *LightChain) Config() *params.ChainConfig { return self.hc.Config() }
   449  
   450  func (self *LightChain) SyncCht(ctx context.Context) bool {
   451  	if self.odr.ChtIndexer() == nil {
   452  		return false
   453  	}
   454  	headNum := self.CurrentHeader().Number.Uint64()
   455  	chtCount, _, _ := self.odr.ChtIndexer().Sections()
   456  	if headNum+1 < chtCount*CHTFrequencyClient {
   457  		num := chtCount*CHTFrequencyClient - 1
   458  		header, err := GetHeaderByNumber(ctx, self.odr, num)
   459  		if header != nil && err == nil {
   460  			self.mu.Lock()
   461  			if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
   462  				self.hc.SetCurrentHeader(header)
   463  			}
   464  			self.mu.Unlock()
   465  			return true
   466  		}
   467  	}
   468  	return false
   469  }
   470  
   471  // LockChain locks the chain mutex for reading so that multiple canonical hashes can be
   472  // retrieved while it is guaranteed that they belong to the same version of the chain
   473  func (self *LightChain) LockChain() {
   474  	self.chainmu.RLock()
   475  }
   476  
   477  // UnlockChain unlocks the chain mutex
   478  func (self *LightChain) UnlockChain() {
   479  	self.chainmu.RUnlock()
   480  }
   481  
   482  // SubscribeChainEvent registers a subscription of ChainEvent.
   483  func (self *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
   484  	return self.scope.Track(self.chainFeed.Subscribe(ch))
   485  }
   486  
   487  // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
   488  func (self *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
   489  	return self.scope.Track(self.chainHeadFeed.Subscribe(ch))
   490  }
   491  
   492  // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
   493  func (self *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
   494  	return self.scope.Track(self.chainSideFeed.Subscribe(ch))
   495  }
   496  
   497  // SubscribeLogsEvent implements the interface of filters.Backend
   498  // LightChain does not send logs events, so return an empty subscription.
   499  func (self *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
   500  	return self.scope.Track(new(event.Feed).Subscribe(ch))
   501  }
   502  
   503  // SubscribeRemovedLogsEvent implements the interface of filters.Backend
   504  // LightChain does not send core.RemovedLogsEvent, so return an empty subscription.
   505  func (self *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
   506  	return self.scope.Track(new(event.Feed).Subscribe(ch))
   507  }