github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/les/backend.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 les implements the Light Ethereum Subprotocol.
    18  package les
    19  
    20  import (
    21  	"fmt"
    22  	"sync"
    23  	"time"
    24  
    25  	"github.com/ethereum/go-ethereum/accounts"
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/hexutil"
    28  	"github.com/ethereum/go-ethereum/consensus"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/bloombits"
    31  	"github.com/ethereum/go-ethereum/core/rawdb"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/eth"
    34  	"github.com/ethereum/go-ethereum/eth/downloader"
    35  	"github.com/ethereum/go-ethereum/eth/filters"
    36  	"github.com/ethereum/go-ethereum/eth/gasprice"
    37  	"github.com/ethereum/go-ethereum/event"
    38  	"github.com/ethereum/go-ethereum/internal/ethapi"
    39  	"github.com/ethereum/go-ethereum/light"
    40  	"github.com/ethereum/go-ethereum/log"
    41  	"github.com/ethereum/go-ethereum/node"
    42  	"github.com/ethereum/go-ethereum/p2p"
    43  	"github.com/ethereum/go-ethereum/p2p/discv5"
    44  	"github.com/ethereum/go-ethereum/params"
    45  	rpc "github.com/ethereum/go-ethereum/rpc"
    46  )
    47  
    48  type LightEthereum struct {
    49  	lesCommons
    50  
    51  	odr         *LesOdr
    52  	relay       *LesTxRelay
    53  	chainConfig *params.ChainConfig
    54  	// Channel for shutting down the service
    55  	shutdownChan chan bool
    56  
    57  	// Handlers
    58  	peers      *peerSet
    59  	txPool     *light.TxPool
    60  	blockchain *light.LightChain
    61  	serverPool *serverPool
    62  	reqDist    *requestDistributor
    63  	retriever  *retrieveManager
    64  
    65  	bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
    66  	bloomIndexer  *core.ChainIndexer
    67  
    68  	ApiBackend *LesApiBackend
    69  
    70  	eventMux       *event.TypeMux
    71  	engine         consensus.Engine
    72  	accountManager *accounts.Manager
    73  
    74  	networkId     uint64
    75  	netRPCService *ethapi.PublicNetAPI
    76  
    77  	wg sync.WaitGroup
    78  }
    79  
    80  func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) {
    81  	chainDb, err := eth.CreateDB(ctx, config, "lightchaindata")
    82  	if err != nil {
    83  		return nil, err
    84  	}
    85  	chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
    86  	if _, isCompat := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !isCompat {
    87  		return nil, genesisErr
    88  	}
    89  	log.Info("Initialised chain configuration", "config", chainConfig)
    90  
    91  	peers := newPeerSet()
    92  	quitSync := make(chan struct{})
    93  
    94  	leth := &LightEthereum{
    95  		lesCommons: lesCommons{
    96  			chainDb: chainDb,
    97  			config:  config,
    98  			iConfig: light.DefaultClientIndexerConfig,
    99  		},
   100  		chainConfig:    chainConfig,
   101  		eventMux:       ctx.EventMux,
   102  		peers:          peers,
   103  		reqDist:        newRequestDistributor(peers, quitSync),
   104  		accountManager: ctx.AccountManager,
   105  		engine:         eth.CreateConsensusEngine(ctx, chainConfig, &config.Ethash, nil, false, chainDb),
   106  		shutdownChan:   make(chan bool),
   107  		networkId:      config.NetworkId,
   108  		bloomRequests:  make(chan chan *bloombits.Retrieval),
   109  		bloomIndexer:   eth.NewBloomIndexer(chainDb, params.BloomBitsBlocksClient, params.HelperTrieConfirmations),
   110  	}
   111  
   112  	leth.relay = NewLesTxRelay(peers, leth.reqDist)
   113  	leth.serverPool = newServerPool(chainDb, quitSync, &leth.wg)
   114  	leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool)
   115  
   116  	leth.odr = NewLesOdr(chainDb, light.DefaultClientIndexerConfig, leth.retriever)
   117  	leth.chtIndexer = light.NewChtIndexer(chainDb, leth.odr, params.CHTFrequencyClient, params.HelperTrieConfirmations)
   118  	leth.bloomTrieIndexer = light.NewBloomTrieIndexer(chainDb, leth.odr, params.BloomBitsBlocksClient, params.BloomTrieFrequency)
   119  	leth.odr.SetIndexers(leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer)
   120  
   121  	// Note: NewLightChain adds the trusted checkpoint so it needs an ODR with
   122  	// indexers already set but not started yet
   123  	if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine); err != nil {
   124  		return nil, err
   125  	}
   126  	// Note: AddChildIndexer starts the update process for the child
   127  	leth.bloomIndexer.AddChildIndexer(leth.bloomTrieIndexer)
   128  	leth.chtIndexer.Start(leth.blockchain)
   129  	leth.bloomIndexer.Start(leth.blockchain)
   130  
   131  	// Rewind the chain in case of an incompatible config upgrade.
   132  	if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
   133  		log.Warn("Rewinding chain to upgrade configuration", "err", compat)
   134  		leth.blockchain.SetHead(compat.RewindTo)
   135  		rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
   136  	}
   137  
   138  	leth.txPool = light.NewTxPool(leth.chainConfig, leth.blockchain, leth.relay)
   139  	if leth.protocolManager, err = NewProtocolManager(leth.chainConfig, light.DefaultClientIndexerConfig, true, config.NetworkId, leth.eventMux, leth.engine, leth.peers, leth.blockchain, nil, chainDb, leth.odr, leth.relay, leth.serverPool, quitSync, &leth.wg); err != nil {
   140  		return nil, err
   141  	}
   142  	leth.ApiBackend = &LesApiBackend{leth, nil}
   143  	gpoParams := config.GPO
   144  	if gpoParams.Default == nil {
   145  		gpoParams.Default = config.MinerGasPrice
   146  	}
   147  	leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams)
   148  	return leth, nil
   149  }
   150  
   151  func lesTopic(genesisHash common.Hash, protocolVersion uint) discv5.Topic {
   152  	var name string
   153  	switch protocolVersion {
   154  	case lpv1:
   155  		name = "LES"
   156  	case lpv2:
   157  		name = "LES2"
   158  	default:
   159  		panic(nil)
   160  	}
   161  	return discv5.Topic(name + "@" + common.Bytes2Hex(genesisHash.Bytes()[0:8]))
   162  }
   163  
   164  type LightDummyAPI struct{}
   165  
   166  // Etherbase is the address that mining rewards will be send to
   167  func (s *LightDummyAPI) Etherbase() (common.Address, error) {
   168  	return common.Address{}, fmt.Errorf("not supported")
   169  }
   170  
   171  // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
   172  func (s *LightDummyAPI) Coinbase() (common.Address, error) {
   173  	return common.Address{}, fmt.Errorf("not supported")
   174  }
   175  
   176  // Hashrate returns the POW hashrate
   177  func (s *LightDummyAPI) Hashrate() hexutil.Uint {
   178  	return 0
   179  }
   180  
   181  // Mining returns an indication if this node is currently mining.
   182  func (s *LightDummyAPI) Mining() bool {
   183  	return false
   184  }
   185  
   186  // APIs returns the collection of RPC services the ethereum package offers.
   187  // NOTE, some of these services probably need to be moved to somewhere else.
   188  func (s *LightEthereum) APIs() []rpc.API {
   189  	return append(ethapi.GetAPIs(s.ApiBackend), []rpc.API{
   190  		{
   191  			Namespace: "eth",
   192  			Version:   "1.0",
   193  			Service:   &LightDummyAPI{},
   194  			Public:    true,
   195  		}, {
   196  			Namespace: "eth",
   197  			Version:   "1.0",
   198  			Service:   downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
   199  			Public:    true,
   200  		}, {
   201  			Namespace: "eth",
   202  			Version:   "1.0",
   203  			Service:   filters.NewPublicFilterAPI(s.ApiBackend, true),
   204  			Public:    true,
   205  		}, {
   206  			Namespace: "net",
   207  			Version:   "1.0",
   208  			Service:   s.netRPCService,
   209  			Public:    true,
   210  		},
   211  	}...)
   212  }
   213  
   214  func (s *LightEthereum) ResetWithGenesisBlock(gb *types.Block) {
   215  	s.blockchain.ResetWithGenesisBlock(gb)
   216  }
   217  
   218  func (s *LightEthereum) BlockChain() *light.LightChain      { return s.blockchain }
   219  func (s *LightEthereum) TxPool() *light.TxPool              { return s.txPool }
   220  func (s *LightEthereum) Engine() consensus.Engine           { return s.engine }
   221  func (s *LightEthereum) LesVersion() int                    { return int(ClientProtocolVersions[0]) }
   222  func (s *LightEthereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
   223  func (s *LightEthereum) EventMux() *event.TypeMux           { return s.eventMux }
   224  
   225  // Protocols implements node.Service, returning all the currently configured
   226  // network protocols to start.
   227  func (s *LightEthereum) Protocols() []p2p.Protocol {
   228  	return s.makeProtocols(ClientProtocolVersions)
   229  }
   230  
   231  // Start implements node.Service, starting all internal goroutines needed by the
   232  // Ethereum protocol implementation.
   233  func (s *LightEthereum) Start(srvr *p2p.Server) error {
   234  	log.Warn("Light client mode is an experimental feature")
   235  	s.startBloomHandlers(params.BloomBitsBlocksClient)
   236  	s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.networkId)
   237  	// clients are searching for the first advertised protocol in the list
   238  	protocolVersion := AdvertiseProtocolVersions[0]
   239  	s.serverPool.start(srvr, lesTopic(s.blockchain.Genesis().Hash(), protocolVersion))
   240  	s.protocolManager.Start(s.config.LightPeers)
   241  	return nil
   242  }
   243  
   244  // Stop implements node.Service, terminating all internal goroutines used by the
   245  // Ethereum protocol.
   246  func (s *LightEthereum) Stop() error {
   247  	s.odr.Stop()
   248  	s.bloomIndexer.Close()
   249  	s.chtIndexer.Close()
   250  	s.blockchain.Stop()
   251  	s.protocolManager.Stop()
   252  	s.txPool.Stop()
   253  	s.engine.Close()
   254  
   255  	s.eventMux.Stop()
   256  
   257  	time.Sleep(time.Millisecond * 200)
   258  	s.chainDb.Close()
   259  	close(s.shutdownChan)
   260  
   261  	return nil
   262  }