backend.go 13.8 KB
Newer Older
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 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
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 13 14
// GNU Lesser General Public License for more details.
//
// 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 19 20
package eth

import (
21
	"errors"
obscuren's avatar
obscuren committed
22
	"fmt"
23
	"math/big"
24
	"runtime"
25
	"sync"
26
	"sync/atomic"
27

28
	"github.com/ethereum/go-ethereum/accounts"
obscuren's avatar
obscuren committed
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/types"
37
	"github.com/ethereum/go-ethereum/core/vm"
38
	"github.com/ethereum/go-ethereum/eth/downloader"
39
	"github.com/ethereum/go-ethereum/eth/filters"
40
	"github.com/ethereum/go-ethereum/eth/gasprice"
obscuren's avatar
obscuren committed
41
	"github.com/ethereum/go-ethereum/ethdb"
42
	"github.com/ethereum/go-ethereum/event"
43
	"github.com/ethereum/go-ethereum/internal/ethapi"
44
	"github.com/ethereum/go-ethereum/log"
45
	"github.com/ethereum/go-ethereum/miner"
46
	"github.com/ethereum/go-ethereum/node"
47
	"github.com/ethereum/go-ethereum/p2p"
48
	"github.com/ethereum/go-ethereum/params"
49
	"github.com/ethereum/go-ethereum/rlp"
50
	"github.com/ethereum/go-ethereum/rpc"
51 52
)

53
type LesServer interface {
54
	Start(srvr *p2p.Server)
55 56
	Stop()
	Protocols() []p2p.Protocol
57
	SetBloomBitsIndexer(bbIndexer *core.ChainIndexer)
58 59
}

60 61
// Ethereum implements the Ethereum full node service.
type Ethereum struct {
62
	config      *Config
63
	chainConfig *params.ChainConfig
64

65
	// Channel for shutting down the service
66 67
	shutdownChan  chan bool    // Channel for shutting down the ethereum
	stopDbUpgrade func() error // stop chain db sequential key upgrade
68

69
	// Handlers
70
	txPool          *core.TxPool
71
	blockchain      *core.BlockChain
72
	protocolManager *ProtocolManager
73
	lesServer       LesServer
74

75 76
	// DB interfaces
	chainDb ethdb.Database // Block chain database
77

78
	eventMux       *event.TypeMux
79
	engine         consensus.Engine
80
	accountManager *accounts.Manager
zsfelfoldi's avatar
zsfelfoldi committed
81

82 83
	bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
	bloomIndexer  *core.ChainIndexer             // Bloom indexer operating during block imports
84

85
	ApiBackend *EthApiBackend
zelig's avatar
zelig committed
86

87 88 89
	miner     *miner.Miner
	gasPrice  *big.Int
	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 98
func (s *Ethereum) AddLesServer(ls LesServer) {
	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 106 107 108 109 110
	if config.SyncMode == downloader.LightSync {
		return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum")
	}
	if !config.SyncMode.IsValid() {
		return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode)
	}
111
	chainDb, err := CreateDB(ctx, config, "chaindata")
obscuren's avatar
obscuren committed
112
	if err != nil {
113
		return nil, err
obscuren's avatar
obscuren committed
114
	}
115
	stopDbUpgrade := upgradeDeduplicateData(chainDb)
116 117 118
	chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
	if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
		return nil, genesisErr
119
	}
120 121
	log.Info("Initialised chain configuration", "config", chainConfig)

122
	eth := &Ethereum{
123
		config:         config,
124
		chainDb:        chainDb,
125
		chainConfig:    chainConfig,
126
		eventMux:       ctx.EventMux,
127
		accountManager: ctx.AccountManager,
128
		engine:         CreateConsensusEngine(ctx, &config.Ethash, chainConfig, chainDb),
129 130
		shutdownChan:   make(chan bool),
		stopDbUpgrade:  stopDbUpgrade,
131
		networkId:      config.NetworkId,
132
		gasPrice:       config.GasPrice,
133
		etherbase:      config.Etherbase,
134 135
		bloomRequests:  make(chan chan *bloombits.Retrieval),
		bloomIndexer:   NewBloomIndexer(chainDb, params.BloomBitsBlocks),
136
	}
137

138
	log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)
139

140
	if !config.SkipBcVersionCheck {
141
		bcVersion := core.GetBlockChainVersion(chainDb)
142 143
		if bcVersion != core.BlockChainVersion && bcVersion != 0 {
			return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion)
144
		}
145
		core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
146
	}
147

148
	vmConfig := vm.Config{EnablePreimageRecording: config.EnablePreimageRecording}
149
	eth.blockchain, err = core.NewBlockChain(chainDb, eth.chainConfig, eth.engine, vmConfig)
150 151 152
	if err != nil {
		return nil, err
	}
153 154 155 156 157 158
	// Rewind the chain in case of an incompatible config upgrade.
	if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
		log.Warn("Rewinding chain to upgrade configuration", "err", compat)
		eth.blockchain.SetHead(compat.RewindTo)
		core.WriteChainConfig(chainDb, genesisHash, chainConfig)
	}
159
	eth.bloomIndexer.Start(eth.blockchain)
160

161 162 163
	if config.TxPool.Journal != "" {
		config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal)
	}
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 168
		return nil, err
	}
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 174 175
	gpoParams := config.GPO
	if gpoParams.Default == nil {
		gpoParams.Default = config.GasPrice
176
	}
177
	eth.ApiBackend.gpo = gasprice.NewOracle(eth.ApiBackend, gpoParams)
178

179 180 181
	return eth, nil
}

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
func makeExtraData(extra []byte) []byte {
	if len(extra) == 0 {
		// create default extradata
		extra, _ = rlp.EncodeToBytes([]interface{}{
			uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch),
			"geth",
			runtime.Version(),
			runtime.GOOS,
		})
	}
	if uint64(len(extra)) > params.MaximumExtraDataSize {
		log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize)
		extra = nil
	}
	return extra
}

199 200 201
// CreateDB creates the chain database.
func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) {
	db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles)
202 203 204
	if err != nil {
		return nil, err
	}
205
	if db, ok := db.(*ethdb.LDBDatabase); ok {
206 207
		db.Meter("eth/db/chaindata/")
	}
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 214 215 216 217
	// If proof-of-authority is requested, set it up
	if chainConfig.Clique != nil {
		return clique.New(chainConfig.Clique, db)
	}
	// Otherwise assume proof-of-work
218
	switch {
219
	case config.PowMode == ethash.ModeFake:
220
		log.Warn("Ethash used in fake mode")
221
		return ethash.NewFaker()
222
	case config.PowMode == ethash.ModeTest:
223
		log.Warn("Ethash used in test mode")
224
		return ethash.NewTester()
225
	case config.PowMode == ethash.ModeShared:
226
		log.Warn("Ethash used in shared mode")
227
		return ethash.NewShared()
228
	default:
229 230 231 232 233 234 235 236
		engine := ethash.New(ethash.Config{
			CacheDir:       ctx.ResolvePath(config.CacheDir),
			CachesInMem:    config.CachesInMem,
			CachesOnDisk:   config.CachesOnDisk,
			DatasetDir:     config.DatasetDir,
			DatasetsInMem:  config.DatasetsInMem,
			DatasetsOnDisk: config.DatasetsOnDisk,
		})
237 238
		engine.SetThreads(-1) // Disable CPU mining
		return engine
239 240 241
	}
}

242 243
// APIs returns the collection of RPC services the ethereum package offers.
// 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 248 249 250 251

	// Append any APIs exposed explicitly by the consensus engine
	apis = append(apis, s.engine.APIs(s.BlockChain())...)

	// Append all the local APIs and return
	return append(apis, []rpc.API{
252 253 254
		{
			Namespace: "eth",
			Version:   "1.0",
255
			Service:   NewPublicEthereumAPI(s),
256 257 258 259
			Public:    true,
		}, {
			Namespace: "eth",
			Version:   "1.0",
260
			Service:   NewPublicMinerAPI(s),
261 262 263 264
			Public:    true,
		}, {
			Namespace: "eth",
			Version:   "1.0",
265
			Service:   downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
266 267 268 269 270 271 272 273 274
			Public:    true,
		}, {
			Namespace: "miner",
			Version:   "1.0",
			Service:   NewPrivateMinerAPI(s),
			Public:    false,
		}, {
			Namespace: "eth",
			Version:   "1.0",
275
			Service:   filters.NewPublicFilterAPI(s.ApiBackend, false),
276
			Public:    true,
277 278 279
		}, {
			Namespace: "admin",
			Version:   "1.0",
280
			Service:   NewPrivateAdminAPI(s),
281 282 283
		}, {
			Namespace: "debug",
			Version:   "1.0",
284
			Service:   NewPublicDebugAPI(s),
285 286 287 288
			Public:    true,
		}, {
			Namespace: "debug",
			Version:   "1.0",
289
			Service:   NewPrivateDebugAPI(s.chainConfig, s),
290 291 292 293 294
		}, {
			Namespace: "net",
			Version:   "1.0",
			Service:   s.netRPCService,
			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 305 306 307 308 309
	s.lock.RLock()
	etherbase := s.etherbase
	s.lock.RUnlock()

	if etherbase != (common.Address{}) {
		return etherbase, nil
310
	}
311 312
	if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
		if accounts := wallets[0].Accounts(); len(accounts) > 0 {
313 314 315 316 317 318 319 320
			etherbase := accounts[0].Address

			s.lock.Lock()
			s.etherbase = etherbase
			s.lock.Unlock()

			log.Info("Etherbase automatically configured", "address", etherbase)
			return etherbase, nil
321
		}
zelig's avatar
zelig committed
322
	}
323
	return common.Address{}, fmt.Errorf("etherbase must be explicitly specified")
zelig's avatar
zelig committed
324 325
}

326
// set in js console via admin interface or wrapper from cli flags
327
func (self *Ethereum) SetEtherbase(etherbase common.Address) {
328
	self.lock.Lock()
329
	self.etherbase = etherbase
330 331
	self.lock.Unlock()

332
	self.miner.SetEtherbase(etherbase)
333 334
}

335
func (s *Ethereum) StartMining(local bool) error {
336 337
	eb, err := s.Etherbase()
	if err != nil {
338 339
		log.Error("Cannot start mining without etherbase", "err", err)
		return fmt.Errorf("etherbase missing: %v", err)
340
	}
341 342 343 344
	if clique, ok := s.engine.(*clique.Clique); ok {
		wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
		if wallet == nil || err != nil {
			log.Error("Etherbase account unavailable locally", "err", err)
Lio李欧's avatar
Lio李欧 committed
345
			return fmt.Errorf("signer missing: %v", err)
346 347 348
		}
		clique.Authorize(eb, wallet.SignHash)
	}
349 350 351 352 353 354 355
	if local {
		// If local (CPU) mining is started, we can disable the transaction rejection
		// mechanism introduced to speed sync times. CPU mining on mainnet is ludicrous
		// so noone will ever hit this path, whereas marking sync done on CPU mining
		// will ensure that private networks work in single miner mode too.
		atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
	}
356
	go s.miner.Start(eb)
357 358 359
	return nil
}

360 361 362 363 364 365 366 367
func (s *Ethereum) StopMining()         { s.miner.Stop() }
func (s *Ethereum) IsMining() bool      { return s.miner.Mining() }
func (s *Ethereum) Miner() *miner.Miner { return s.miner }

func (s *Ethereum) AccountManager() *accounts.Manager  { return s.accountManager }
func (s *Ethereum) BlockChain() *core.BlockChain       { return s.blockchain }
func (s *Ethereum) TxPool() *core.TxPool               { return s.txPool }
func (s *Ethereum) EventMux() *event.TypeMux           { return s.eventMux }
368
func (s *Ethereum) Engine() consensus.Engine           { return s.engine }
369 370 371
func (s *Ethereum) ChainDb() ethdb.Database            { return s.chainDb }
func (s *Ethereum) IsListening() bool                  { return true } // Always listening
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 }
obscuren's avatar
obscuren committed
374

375 376
// Protocols implements node.Service, returning all the currently configured
// network protocols to start.
377
func (s *Ethereum) Protocols() []p2p.Protocol {
378 379 380
	if s.lesServer == nil {
		return s.protocolManager.SubProtocols
	}
381
	return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
382
}
383

384
// Start implements node.Service, starting all internal goroutines needed by the
385 386
// Ethereum protocol implementation.
func (s *Ethereum) Start(srvr *p2p.Server) error {
387 388 389 390
	// Start the bloom bits servicing goroutines
	s.startBloomHandlers()

	// Start the RPC service
391
	s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
392

393 394 395 396 397 398 399 400
	// Figure out a max peers count based on the server limits
	maxPeers := srvr.MaxPeers
	if s.config.LightServ > 0 {
		maxPeers -= s.config.LightPeers
		if maxPeers < srvr.MaxPeers/2 {
			maxPeers = srvr.MaxPeers / 2
		}
	}
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 407 408
	return nil
}

409 410
// Stop implements node.Service, terminating all internal goroutines used by the
// Ethereum protocol.
411
func (s *Ethereum) Stop() error {
412 413 414
	if s.stopDbUpgrade != nil {
		s.stopDbUpgrade()
	}
415
	s.bloomIndexer.Close()
416
	s.blockchain.Stop()
417
	s.protocolManager.Stop()
418 419 420
	if s.lesServer != nil {
		s.lesServer.Stop()
	}
421
	s.txPool.Stop()
422
	s.miner.Stop()
423
	s.eventMux.Stop()
424

Felix Lange's avatar
Felix Lange committed
425
	s.chainDb.Close()
426
	close(s.shutdownChan)
427 428

	return nil
429
}