github.com/luckypickle/go-ethereum-vet@v1.14.2/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/luckypickle/go-ethereum-vet/accounts" 29 "github.com/luckypickle/go-ethereum-vet/common" 30 "github.com/luckypickle/go-ethereum-vet/common/hexutil" 31 "github.com/luckypickle/go-ethereum-vet/consensus" 32 "github.com/luckypickle/go-ethereum-vet/consensus/clique" 33 "github.com/luckypickle/go-ethereum-vet/consensus/ethash" 34 "github.com/luckypickle/go-ethereum-vet/core" 35 "github.com/luckypickle/go-ethereum-vet/core/bloombits" 36 "github.com/luckypickle/go-ethereum-vet/core/rawdb" 37 "github.com/luckypickle/go-ethereum-vet/core/types" 38 "github.com/luckypickle/go-ethereum-vet/core/vm" 39 "github.com/luckypickle/go-ethereum-vet/eth/downloader" 40 "github.com/luckypickle/go-ethereum-vet/eth/filters" 41 "github.com/luckypickle/go-ethereum-vet/eth/gasprice" 42 "github.com/luckypickle/go-ethereum-vet/ethdb" 43 "github.com/luckypickle/go-ethereum-vet/event" 44 "github.com/luckypickle/go-ethereum-vet/internal/ethapi" 45 "github.com/luckypickle/go-ethereum-vet/log" 46 "github.com/luckypickle/go-ethereum-vet/miner" 47 "github.com/luckypickle/go-ethereum-vet/node" 48 "github.com/luckypickle/go-ethereum-vet/p2p" 49 "github.com/luckypickle/go-ethereum-vet/params" 50 "github.com/luckypickle/go-ethereum-vet/rlp" 51 "github.com/luckypickle/go-ethereum-vet/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, chainConfig, &config.Ethash, config.MinerNotify, chainDb), 128 shutdownChan: make(chan bool), 129 networkID: config.NetworkId, 130 gasPrice: config.MinerGasPrice, 131 etherbase: config.Etherbase, 132 bloomRequests: make(chan chan *bloombits.Retrieval), 133 bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks, bloomConfirms), 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).\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 170 eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.engine, config.MinerRecommit) 171 eth.miner.SetExtra(makeExtraData(config.MinerExtraData)) 172 173 eth.APIBackend = &EthAPIBackend{eth, nil} 174 gpoParams := config.GPO 175 if gpoParams.Default == nil { 176 gpoParams.Default = config.MinerGasPrice 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 err != nil { 204 return nil, err 205 } 206 if db, ok := db.(*ethdb.LDBDatabase); ok { 207 db.Meter("eth/db/chaindata/") 208 } 209 return db, nil 210 } 211 212 // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service 213 func CreateConsensusEngine(ctx *node.ServiceContext, chainConfig *params.ChainConfig, config *ethash.Config, notify []string, db ethdb.Database) consensus.Engine { 214 // If proof-of-authority is requested, set it up 215 if chainConfig.Clique != nil { 216 return clique.New(chainConfig.Clique, db) 217 } 218 // Otherwise assume proof-of-work 219 switch config.PowMode { 220 case ethash.ModeFake: 221 log.Warn("Ethash used in fake mode") 222 return ethash.NewFaker() 223 case ethash.ModeTest: 224 log.Warn("Ethash used in test mode") 225 return ethash.NewTester(nil) 226 case ethash.ModeShared: 227 log.Warn("Ethash used in shared mode") 228 return ethash.NewShared() 229 default: 230 engine := ethash.New(ethash.Config{ 231 CacheDir: ctx.ResolvePath(config.CacheDir), 232 CachesInMem: config.CachesInMem, 233 CachesOnDisk: config.CachesOnDisk, 234 DatasetDir: config.DatasetDir, 235 DatasetsInMem: config.DatasetsInMem, 236 DatasetsOnDisk: config.DatasetsOnDisk, 237 }, notify) 238 engine.SetThreads(-1) // Disable CPU mining 239 return engine 240 } 241 } 242 243 // APIs return the collection of RPC services the ethereum package offers. 244 // NOTE, some of these services probably need to be moved to somewhere else. 245 func (s *Ethereum) APIs() []rpc.API { 246 apis := ethapi.GetAPIs(s.APIBackend) 247 248 // Append any APIs exposed explicitly by the consensus engine 249 apis = append(apis, s.engine.APIs(s.BlockChain())...) 250 251 // Append all the local APIs and return 252 return append(apis, []rpc.API{ 253 { 254 Namespace: "eth", 255 Version: "1.0", 256 Service: NewPublicEthereumAPI(s), 257 Public: true, 258 }, { 259 Namespace: "eth", 260 Version: "1.0", 261 Service: NewPublicMinerAPI(s), 262 Public: true, 263 }, { 264 Namespace: "eth", 265 Version: "1.0", 266 Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux), 267 Public: true, 268 }, { 269 Namespace: "miner", 270 Version: "1.0", 271 Service: NewPrivateMinerAPI(s), 272 Public: false, 273 }, { 274 Namespace: "eth", 275 Version: "1.0", 276 Service: filters.NewPublicFilterAPI(s.APIBackend, false), 277 Public: true, 278 }, { 279 Namespace: "admin", 280 Version: "1.0", 281 Service: NewPrivateAdminAPI(s), 282 }, { 283 Namespace: "debug", 284 Version: "1.0", 285 Service: NewPublicDebugAPI(s), 286 Public: true, 287 }, { 288 Namespace: "debug", 289 Version: "1.0", 290 Service: NewPrivateDebugAPI(s.chainConfig, s), 291 }, { 292 Namespace: "net", 293 Version: "1.0", 294 Service: s.netRPCService, 295 Public: true, 296 }, 297 }...) 298 } 299 300 func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) { 301 s.blockchain.ResetWithGenesisBlock(gb) 302 } 303 304 func (s *Ethereum) Etherbase() (eb common.Address, err error) { 305 s.lock.RLock() 306 etherbase := s.etherbase 307 s.lock.RUnlock() 308 309 if etherbase != (common.Address{}) { 310 return etherbase, nil 311 } 312 if wallets := s.AccountManager().Wallets(); len(wallets) > 0 { 313 if accounts := wallets[0].Accounts(); len(accounts) > 0 { 314 etherbase := accounts[0].Address 315 316 s.lock.Lock() 317 s.etherbase = etherbase 318 s.lock.Unlock() 319 320 log.Info("Etherbase automatically configured", "address", etherbase) 321 return etherbase, nil 322 } 323 } 324 return common.Address{}, fmt.Errorf("etherbase must be explicitly specified") 325 } 326 327 // SetEtherbase sets the mining reward address. 328 func (s *Ethereum) SetEtherbase(etherbase common.Address) { 329 s.lock.Lock() 330 s.etherbase = etherbase 331 s.lock.Unlock() 332 333 s.miner.SetEtherbase(etherbase) 334 } 335 336 func (s *Ethereum) StartMining(local bool) error { 337 eb, err := s.Etherbase() 338 if err != nil { 339 log.Error("Cannot start mining without etherbase", "err", err) 340 return fmt.Errorf("etherbase missing: %v", err) 341 } 342 if clique, ok := s.engine.(*clique.Clique); ok { 343 wallet, err := s.accountManager.Find(accounts.Account{Address: eb}) 344 if wallet == nil || err != nil { 345 log.Error("Etherbase account unavailable locally", "err", err) 346 return fmt.Errorf("signer missing: %v", err) 347 } 348 clique.Authorize(eb, wallet.SignHash) 349 } 350 if local { 351 // If local (CPU) mining is started, we can disable the transaction rejection 352 // mechanism introduced to speed sync times. CPU mining on mainnet is ludicrous 353 // so none will ever hit this path, whereas marking sync done on CPU mining 354 // will ensure that private networks work in single miner mode too. 355 atomic.StoreUint32(&s.protocolManager.acceptTxs, 1) 356 } 357 go s.miner.Start(eb) 358 return nil 359 } 360 361 func (s *Ethereum) StopMining() { s.miner.Stop() } 362 func (s *Ethereum) IsMining() bool { return s.miner.Mining() } 363 func (s *Ethereum) Miner() *miner.Miner { return s.miner } 364 365 func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager } 366 func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain } 367 func (s *Ethereum) TxPool() *core.TxPool { return s.txPool } 368 func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux } 369 func (s *Ethereum) Engine() consensus.Engine { return s.engine } 370 func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb } 371 func (s *Ethereum) IsListening() bool { return true } // Always listening 372 func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) } 373 func (s *Ethereum) NetVersion() uint64 { return s.networkID } 374 func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader } 375 376 // Protocols implements node.Service, returning all the currently configured 377 // network protocols to start. 378 func (s *Ethereum) Protocols() []p2p.Protocol { 379 if s.lesServer == nil { 380 return s.protocolManager.SubProtocols 381 } 382 return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...) 383 } 384 385 // Start implements node.Service, starting all internal goroutines needed by the 386 // Ethereum protocol implementation. 387 func (s *Ethereum) Start(srvr *p2p.Server) error { 388 // Start the bloom bits servicing goroutines 389 s.startBloomHandlers() 390 391 // Start the RPC service 392 s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion()) 393 394 // Figure out a max peers count based on the server limits 395 maxPeers := srvr.MaxPeers 396 if s.config.LightServ > 0 { 397 if s.config.LightPeers >= srvr.MaxPeers { 398 return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, srvr.MaxPeers) 399 } 400 maxPeers -= s.config.LightPeers 401 } 402 // Start the networking layer and the light server if requested 403 s.protocolManager.Start(maxPeers) 404 if s.lesServer != nil { 405 s.lesServer.Start(srvr) 406 } 407 return nil 408 } 409 410 // Stop implements node.Service, terminating all internal goroutines used by the 411 // Ethereum protocol. 412 func (s *Ethereum) Stop() error { 413 s.bloomIndexer.Close() 414 s.blockchain.Stop() 415 s.engine.Close() 416 s.protocolManager.Stop() 417 if s.lesServer != nil { 418 s.lesServer.Stop() 419 } 420 s.txPool.Stop() 421 s.miner.Stop() 422 s.eventMux.Stop() 423 424 s.chainDb.Close() 425 close(s.shutdownChan) 426 return nil 427 }