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