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