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