github.com/chapsuk/go-ethereum@v1.8.12-0.20180615081455-574378edb50c/eth/backend.go (about)

     1  // Copyright 2014 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 eth implements the Ethereum protocol.
    18  package eth
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  	"runtime"
    25  	"sync"
    26  	"sync/atomic"
    27  
    28  	"github.com/ethereum/go-ethereum/accounts"
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/common/hexutil"
    31  	"github.com/ethereum/go-ethereum/consensus"
    32  	"github.com/ethereum/go-ethereum/consensus/clique"
    33  	"github.com/ethereum/go-ethereum/consensus/ethash"
    34  	"github.com/ethereum/go-ethereum/core"
    35  	"github.com/ethereum/go-ethereum/core/bloombits"
    36  	"github.com/ethereum/go-ethereum/core/rawdb"
    37  	"github.com/ethereum/go-ethereum/core/types"
    38  	"github.com/ethereum/go-ethereum/core/vm"
    39  	"github.com/ethereum/go-ethereum/eth/downloader"
    40  	"github.com/ethereum/go-ethereum/eth/filters"
    41  	"github.com/ethereum/go-ethereum/eth/gasprice"
    42  	"github.com/ethereum/go-ethereum/ethdb"
    43  	"github.com/ethereum/go-ethereum/event"
    44  	"github.com/ethereum/go-ethereum/internal/ethapi"
    45  	"github.com/ethereum/go-ethereum/log"
    46  	"github.com/ethereum/go-ethereum/miner"
    47  	"github.com/ethereum/go-ethereum/node"
    48  	"github.com/ethereum/go-ethereum/p2p"
    49  	"github.com/ethereum/go-ethereum/params"
    50  	"github.com/ethereum/go-ethereum/rlp"
    51  	"github.com/ethereum/go-ethereum/rpc"
    52  )
    53  
    54  type LesServer interface {
    55  	Start(srvr *p2p.Server)
    56  	Stop()
    57  	Protocols() []p2p.Protocol
    58  	SetBloomBitsIndexer(bbIndexer *core.ChainIndexer)
    59  }
    60  
    61  // Ethereum implements the Ethereum full node service.
    62  type Ethereum struct {
    63  	config      *Config
    64  	chainConfig *params.ChainConfig
    65  
    66  	// Channel for shutting down the service
    67  	shutdownChan chan bool // Channel for shutting down the Ethereum
    68  
    69  	// Handlers
    70  	txPool          *core.TxPool
    71  	blockchain      *core.BlockChain
    72  	protocolManager *ProtocolManager
    73  	lesServer       LesServer
    74  
    75  	// DB interfaces
    76  	chainDb ethdb.Database // Block chain database
    77  
    78  	eventMux       *event.TypeMux
    79  	engine         consensus.Engine
    80  	accountManager *accounts.Manager
    81  
    82  	bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
    83  	bloomIndexer  *core.ChainIndexer             // Bloom indexer operating during block imports
    84  
    85  	APIBackend *EthAPIBackend
    86  
    87  	miner     *miner.Miner
    88  	gasPrice  *big.Int
    89  	etherbase common.Address
    90  
    91  	networkID     uint64
    92  	netRPCService *ethapi.PublicNetAPI
    93  
    94  	lock sync.RWMutex // Protects the variadic fields (e.g. gas price and etherbase)
    95  }
    96  
    97  func (s *Ethereum) AddLesServer(ls LesServer) {
    98  	s.lesServer = ls
    99  	ls.SetBloomBitsIndexer(s.bloomIndexer)
   100  }
   101  
   102  // New creates a new Ethereum object (including the
   103  // initialisation of the common Ethereum object)
   104  func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
   105  	if config.SyncMode == downloader.LightSync {
   106  		return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum")
   107  	}
   108  	if !config.SyncMode.IsValid() {
   109  		return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode)
   110  	}
   111  	chainDb, err := CreateDB(ctx, config, "chaindata")
   112  	if err != nil {
   113  		return nil, err
   114  	}
   115  	chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
   116  	if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
   117  		return nil, genesisErr
   118  	}
   119  	log.Info("Initialised chain configuration", "config", chainConfig)
   120  
   121  	eth := &Ethereum{
   122  		config:         config,
   123  		chainDb:        chainDb,
   124  		chainConfig:    chainConfig,
   125  		eventMux:       ctx.EventMux,
   126  		accountManager: ctx.AccountManager,
   127  		engine:         CreateConsensusEngine(ctx, &config.Ethash, chainConfig, chainDb),
   128  		shutdownChan:   make(chan bool),
   129  		networkID:      config.NetworkId,
   130  		gasPrice:       config.GasPrice,
   131  		etherbase:      config.Etherbase,
   132  		bloomRequests:  make(chan chan *bloombits.Retrieval),
   133  		bloomIndexer:   NewBloomIndexer(chainDb, params.BloomBitsBlocks),
   134  	}
   135  
   136  	log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)
   137  
   138  	if !config.SkipBcVersionCheck {
   139  		bcVersion := rawdb.ReadDatabaseVersion(chainDb)
   140  		if bcVersion != core.BlockChainVersion && bcVersion != 0 {
   141  			return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion)
   142  		}
   143  		rawdb.WriteDatabaseVersion(chainDb, core.BlockChainVersion)
   144  	}
   145  	var (
   146  		vmConfig    = vm.Config{EnablePreimageRecording: config.EnablePreimageRecording}
   147  		cacheConfig = &core.CacheConfig{Disabled: config.NoPruning, TrieNodeLimit: config.TrieCache, TrieTimeLimit: config.TrieTimeout}
   148  	)
   149  	eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, eth.chainConfig, eth.engine, vmConfig)
   150  	if err != nil {
   151  		return nil, err
   152  	}
   153  	// Rewind the chain in case of an incompatible config upgrade.
   154  	if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
   155  		log.Warn("Rewinding chain to upgrade configuration", "err", compat)
   156  		eth.blockchain.SetHead(compat.RewindTo)
   157  		rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
   158  	}
   159  	eth.bloomIndexer.Start(eth.blockchain)
   160  
   161  	if config.TxPool.Journal != "" {
   162  		config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal)
   163  	}
   164  	eth.txPool = core.NewTxPool(config.TxPool, eth.chainConfig, eth.blockchain)
   165  
   166  	if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb); err != nil {
   167  		return nil, err
   168  	}
   169  	eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.engine)
   170  	eth.miner.SetExtra(makeExtraData(config.ExtraData))
   171  
   172  	eth.APIBackend = &EthAPIBackend{eth, nil}
   173  	gpoParams := config.GPO
   174  	if gpoParams.Default == nil {
   175  		gpoParams.Default = config.GasPrice
   176  	}
   177  	eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams)
   178  
   179  	return eth, nil
   180  }
   181  
   182  func makeExtraData(extra []byte) []byte {
   183  	if len(extra) == 0 {
   184  		// create default extradata
   185  		extra, _ = rlp.EncodeToBytes([]interface{}{
   186  			uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch),
   187  			"geth",
   188  			runtime.Version(),
   189  			runtime.GOOS,
   190  		})
   191  	}
   192  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   193  		log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize)
   194  		extra = nil
   195  	}
   196  	return extra
   197  }
   198  
   199  // CreateDB creates the chain database.
   200  func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) {
   201  	db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles)
   202  	if err != nil {
   203  		return nil, err
   204  	}
   205  	if db, ok := db.(*ethdb.LDBDatabase); ok {
   206  		db.Meter("eth/db/chaindata/")
   207  	}
   208  	return db, nil
   209  }
   210  
   211  // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
   212  func CreateConsensusEngine(ctx *node.ServiceContext, config *ethash.Config, chainConfig *params.ChainConfig, db ethdb.Database) consensus.Engine {
   213  	// If proof-of-authority is requested, set it up
   214  	if chainConfig.Clique != nil {
   215  		return clique.New(chainConfig.Clique, db)
   216  	}
   217  	// Otherwise assume proof-of-work
   218  	switch config.PowMode {
   219  	case ethash.ModeFake:
   220  		log.Warn("Ethash used in fake mode")
   221  		return ethash.NewFaker()
   222  	case ethash.ModeTest:
   223  		log.Warn("Ethash used in test mode")
   224  		return ethash.NewTester()
   225  	case ethash.ModeShared:
   226  		log.Warn("Ethash used in shared mode")
   227  		return ethash.NewShared()
   228  	default:
   229  		engine := ethash.New(ethash.Config{
   230  			CacheDir:       ctx.ResolvePath(config.CacheDir),
   231  			CachesInMem:    config.CachesInMem,
   232  			CachesOnDisk:   config.CachesOnDisk,
   233  			DatasetDir:     config.DatasetDir,
   234  			DatasetsInMem:  config.DatasetsInMem,
   235  			DatasetsOnDisk: config.DatasetsOnDisk,
   236  		})
   237  		engine.SetThreads(-1) // Disable CPU mining
   238  		return engine
   239  	}
   240  }
   241  
   242  // APIs return the collection of RPC services the ethereum package offers.
   243  // NOTE, some of these services probably need to be moved to somewhere else.
   244  func (s *Ethereum) APIs() []rpc.API {
   245  	apis := ethapi.GetAPIs(s.APIBackend)
   246  
   247  	// Append any APIs exposed explicitly by the consensus engine
   248  	apis = append(apis, s.engine.APIs(s.BlockChain())...)
   249  
   250  	// Append all the local APIs and return
   251  	return append(apis, []rpc.API{
   252  		{
   253  			Namespace: "eth",
   254  			Version:   "1.0",
   255  			Service:   NewPublicEthereumAPI(s),
   256  			Public:    true,
   257  		}, {
   258  			Namespace: "eth",
   259  			Version:   "1.0",
   260  			Service:   NewPublicMinerAPI(s),
   261  			Public:    true,
   262  		}, {
   263  			Namespace: "eth",
   264  			Version:   "1.0",
   265  			Service:   downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
   266  			Public:    true,
   267  		}, {
   268  			Namespace: "miner",
   269  			Version:   "1.0",
   270  			Service:   NewPrivateMinerAPI(s),
   271  			Public:    false,
   272  		}, {
   273  			Namespace: "eth",
   274  			Version:   "1.0",
   275  			Service:   filters.NewPublicFilterAPI(s.APIBackend, false),
   276  			Public:    true,
   277  		}, {
   278  			Namespace: "admin",
   279  			Version:   "1.0",
   280  			Service:   NewPrivateAdminAPI(s),
   281  		}, {
   282  			Namespace: "debug",
   283  			Version:   "1.0",
   284  			Service:   NewPublicDebugAPI(s),
   285  			Public:    true,
   286  		}, {
   287  			Namespace: "debug",
   288  			Version:   "1.0",
   289  			Service:   NewPrivateDebugAPI(s.chainConfig, s),
   290  		}, {
   291  			Namespace: "net",
   292  			Version:   "1.0",
   293  			Service:   s.netRPCService,
   294  			Public:    true,
   295  		},
   296  	}...)
   297  }
   298  
   299  func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
   300  	s.blockchain.ResetWithGenesisBlock(gb)
   301  }
   302  
   303  func (s *Ethereum) Etherbase() (eb common.Address, err error) {
   304  	s.lock.RLock()
   305  	etherbase := s.etherbase
   306  	s.lock.RUnlock()
   307  
   308  	if etherbase != (common.Address{}) {
   309  		return etherbase, nil
   310  	}
   311  	if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
   312  		if accounts := wallets[0].Accounts(); len(accounts) > 0 {
   313  			etherbase := accounts[0].Address
   314  
   315  			s.lock.Lock()
   316  			s.etherbase = etherbase
   317  			s.lock.Unlock()
   318  
   319  			log.Info("Etherbase automatically configured", "address", etherbase)
   320  			return etherbase, nil
   321  		}
   322  	}
   323  	return common.Address{}, fmt.Errorf("etherbase must be explicitly specified")
   324  }
   325  
   326  // SetEtherbase sets the mining reward address.
   327  func (s *Ethereum) SetEtherbase(etherbase common.Address) {
   328  	s.lock.Lock()
   329  	s.etherbase = etherbase
   330  	s.lock.Unlock()
   331  
   332  	s.miner.SetEtherbase(etherbase)
   333  }
   334  
   335  func (s *Ethereum) StartMining(local bool) error {
   336  	eb, err := s.Etherbase()
   337  	if err != nil {
   338  		log.Error("Cannot start mining without etherbase", "err", err)
   339  		return fmt.Errorf("etherbase missing: %v", err)
   340  	}
   341  	if clique, ok := s.engine.(*clique.Clique); ok {
   342  		wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
   343  		if wallet == nil || err != nil {
   344  			log.Error("Etherbase account unavailable locally", "err", err)
   345  			return fmt.Errorf("signer missing: %v", err)
   346  		}
   347  		clique.Authorize(eb, wallet.SignHash)
   348  	}
   349  	if local {
   350  		// If local (CPU) mining is started, we can disable the transaction rejection
   351  		// mechanism introduced to speed sync times. CPU mining on mainnet is ludicrous
   352  		// so none will ever hit this path, whereas marking sync done on CPU mining
   353  		// will ensure that private networks work in single miner mode too.
   354  		atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
   355  	}
   356  	go s.miner.Start(eb)
   357  	return nil
   358  }
   359  
   360  func (s *Ethereum) StopMining()         { s.miner.Stop() }
   361  func (s *Ethereum) IsMining() bool      { return s.miner.Mining() }
   362  func (s *Ethereum) Miner() *miner.Miner { return s.miner }
   363  
   364  func (s *Ethereum) AccountManager() *accounts.Manager  { return s.accountManager }
   365  func (s *Ethereum) BlockChain() *core.BlockChain       { return s.blockchain }
   366  func (s *Ethereum) TxPool() *core.TxPool               { return s.txPool }
   367  func (s *Ethereum) EventMux() *event.TypeMux           { return s.eventMux }
   368  func (s *Ethereum) Engine() consensus.Engine           { return s.engine }
   369  func (s *Ethereum) ChainDb() ethdb.Database            { return s.chainDb }
   370  func (s *Ethereum) IsListening() bool                  { return true } // Always listening
   371  func (s *Ethereum) EthVersion() int                    { return int(s.protocolManager.SubProtocols[0].Version) }
   372  func (s *Ethereum) NetVersion() uint64                 { return s.networkID }
   373  func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
   374  
   375  // Protocols implements node.Service, returning all the currently configured
   376  // network protocols to start.
   377  func (s *Ethereum) Protocols() []p2p.Protocol {
   378  	if s.lesServer == nil {
   379  		return s.protocolManager.SubProtocols
   380  	}
   381  	return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
   382  }
   383  
   384  // Start implements node.Service, starting all internal goroutines needed by the
   385  // Ethereum protocol implementation.
   386  func (s *Ethereum) Start(srvr *p2p.Server) error {
   387  	// Start the bloom bits servicing goroutines
   388  	s.startBloomHandlers()
   389  
   390  	// Start the RPC service
   391  	s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
   392  
   393  	// Figure out a max peers count based on the server limits
   394  	maxPeers := srvr.MaxPeers
   395  	if s.config.LightServ > 0 {
   396  		if s.config.LightPeers >= srvr.MaxPeers {
   397  			return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, srvr.MaxPeers)
   398  		}
   399  		maxPeers -= s.config.LightPeers
   400  	}
   401  	// Start the networking layer and the light server if requested
   402  	s.protocolManager.Start(maxPeers)
   403  	if s.lesServer != nil {
   404  		s.lesServer.Start(srvr)
   405  	}
   406  	return nil
   407  }
   408  
   409  // Stop implements node.Service, terminating all internal goroutines used by the
   410  // Ethereum protocol.
   411  func (s *Ethereum) Stop() error {
   412  	s.bloomIndexer.Close()
   413  	s.blockchain.Stop()
   414  	s.protocolManager.Stop()
   415  	if s.lesServer != nil {
   416  		s.lesServer.Stop()
   417  	}
   418  	s.txPool.Stop()
   419  	s.miner.Stop()
   420  	s.eventMux.Stop()
   421  
   422  	s.chainDb.Close()
   423  	close(s.shutdownChan)
   424  
   425  	return nil
   426  }