github.com/memikequinn/go-ethereum@v1.6.6-0.20170621145815-58a1e13e6dd7/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 } 92 93 // New creates a new Ethereum object (including the 94 // initialisation of the common Ethereum object) 95 func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { 96 if config.SyncMode == downloader.LightSync { 97 return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum") 98 } 99 if !config.SyncMode.IsValid() { 100 return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode) 101 } 102 103 chainDb, err := CreateDB(ctx, config, "chaindata") 104 if err != nil { 105 return nil, err 106 } 107 stopDbUpgrade := upgradeSequentialKeys(chainDb) 108 chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis) 109 if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok { 110 return nil, genesisErr 111 } 112 log.Info("Initialised chain configuration", "config", chainConfig) 113 114 eth := &Ethereum{ 115 chainDb: chainDb, 116 chainConfig: chainConfig, 117 eventMux: ctx.EventMux, 118 accountManager: ctx.AccountManager, 119 engine: CreateConsensusEngine(ctx, config, chainConfig, chainDb), 120 shutdownChan: make(chan bool), 121 stopDbUpgrade: stopDbUpgrade, 122 networkId: config.NetworkId, 123 gasPrice: config.GasPrice, 124 etherbase: config.Etherbase, 125 } 126 127 if err := addMipmapBloomBins(chainDb); err != nil { 128 return nil, err 129 } 130 log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId) 131 132 if !config.SkipBcVersionCheck { 133 bcVersion := core.GetBlockChainVersion(chainDb) 134 if bcVersion != core.BlockChainVersion && bcVersion != 0 { 135 return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion) 136 } 137 core.WriteBlockChainVersion(chainDb, core.BlockChainVersion) 138 } 139 140 vmConfig := vm.Config{EnablePreimageRecording: config.EnablePreimageRecording} 141 eth.blockchain, err = core.NewBlockChain(chainDb, eth.chainConfig, eth.engine, eth.eventMux, vmConfig) 142 if err != nil { 143 return nil, err 144 } 145 // Rewind the chain in case of an incompatible config upgrade. 146 if compat, ok := genesisErr.(*params.ConfigCompatError); ok { 147 log.Warn("Rewinding chain to upgrade configuration", "err", compat) 148 eth.blockchain.SetHead(compat.RewindTo) 149 core.WriteChainConfig(chainDb, genesisHash, chainConfig) 150 } 151 152 newPool := core.NewTxPool(config.TxPool, eth.chainConfig, eth.EventMux(), eth.blockchain.State, eth.blockchain.GasLimit) 153 eth.txPool = newPool 154 155 maxPeers := config.MaxPeers 156 if config.LightServ > 0 { 157 // if we are running a light server, limit the number of ETH peers so that we reserve some space for incoming LES connections 158 // temporary solution until the new peer connectivity API is finished 159 halfPeers := maxPeers / 2 160 maxPeers -= config.LightPeers 161 if maxPeers < halfPeers { 162 maxPeers = halfPeers 163 } 164 } 165 166 if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.SyncMode, config.NetworkId, maxPeers, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb); err != nil { 167 return nil, err 168 } 169 170 eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.engine) 171 eth.miner.SetExtra(makeExtraData(config.ExtraData)) 172 173 eth.ApiBackend = &EthApiBackend{eth, nil} 174 gpoParams := config.GPO 175 if gpoParams.Default == nil { 176 gpoParams.Default = config.GasPrice 177 } 178 eth.ApiBackend.gpo = gasprice.NewOracle(eth.ApiBackend, gpoParams) 179 180 return eth, nil 181 } 182 183 func makeExtraData(extra []byte) []byte { 184 if len(extra) == 0 { 185 // create default extradata 186 extra, _ = rlp.EncodeToBytes([]interface{}{ 187 uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch), 188 "geth", 189 runtime.Version(), 190 runtime.GOOS, 191 }) 192 } 193 if uint64(len(extra)) > params.MaximumExtraDataSize { 194 log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize) 195 extra = nil 196 } 197 return extra 198 } 199 200 // CreateDB creates the chain database. 201 func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) { 202 db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles) 203 if db, ok := db.(*ethdb.LDBDatabase); ok { 204 db.Meter("eth/db/chaindata/") 205 } 206 return db, err 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("singer 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 } else { 366 return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...) 367 } 368 } 369 370 // Start implements node.Service, starting all internal goroutines needed by the 371 // Ethereum protocol implementation. 372 func (s *Ethereum) Start(srvr *p2p.Server) error { 373 s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion()) 374 375 s.protocolManager.Start() 376 if s.lesServer != nil { 377 s.lesServer.Start(srvr) 378 } 379 return nil 380 } 381 382 // Stop implements node.Service, terminating all internal goroutines used by the 383 // Ethereum protocol. 384 func (s *Ethereum) Stop() error { 385 if s.stopDbUpgrade != nil { 386 s.stopDbUpgrade() 387 } 388 s.blockchain.Stop() 389 s.protocolManager.Stop() 390 if s.lesServer != nil { 391 s.lesServer.Stop() 392 } 393 s.txPool.Stop() 394 s.miner.Stop() 395 s.eventMux.Stop() 396 397 s.chainDb.Close() 398 close(s.shutdownChan) 399 400 return nil 401 }