github.com/jimmyx0x/go-ethereum@v1.10.28/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/beacon" 33 "github.com/ethereum/go-ethereum/consensus/clique" 34 "github.com/ethereum/go-ethereum/core" 35 "github.com/ethereum/go-ethereum/core/bloombits" 36 "github.com/ethereum/go-ethereum/core/rawdb" 37 "github.com/ethereum/go-ethereum/core/state/pruner" 38 "github.com/ethereum/go-ethereum/core/txpool" 39 "github.com/ethereum/go-ethereum/core/types" 40 "github.com/ethereum/go-ethereum/core/vm" 41 "github.com/ethereum/go-ethereum/eth/downloader" 42 "github.com/ethereum/go-ethereum/eth/ethconfig" 43 "github.com/ethereum/go-ethereum/eth/gasprice" 44 "github.com/ethereum/go-ethereum/eth/protocols/eth" 45 "github.com/ethereum/go-ethereum/eth/protocols/snap" 46 "github.com/ethereum/go-ethereum/ethdb" 47 "github.com/ethereum/go-ethereum/event" 48 "github.com/ethereum/go-ethereum/internal/ethapi" 49 "github.com/ethereum/go-ethereum/internal/shutdowncheck" 50 "github.com/ethereum/go-ethereum/log" 51 "github.com/ethereum/go-ethereum/miner" 52 "github.com/ethereum/go-ethereum/node" 53 "github.com/ethereum/go-ethereum/p2p" 54 "github.com/ethereum/go-ethereum/p2p/dnsdisc" 55 "github.com/ethereum/go-ethereum/p2p/enode" 56 "github.com/ethereum/go-ethereum/params" 57 "github.com/ethereum/go-ethereum/rlp" 58 "github.com/ethereum/go-ethereum/rpc" 59 ) 60 61 // Config contains the configuration options of the ETH protocol. 62 // Deprecated: use ethconfig.Config instead. 63 type Config = ethconfig.Config 64 65 // Ethereum implements the Ethereum full node service. 66 type Ethereum struct { 67 config *ethconfig.Config 68 69 // Handlers 70 txPool *txpool.TxPool 71 blockchain *core.BlockChain 72 handler *handler 73 ethDialCandidates enode.Iterator 74 snapDialCandidates enode.Iterator 75 merger *consensus.Merger 76 77 // DB interfaces 78 chainDb ethdb.Database // Block chain database 79 80 eventMux *event.TypeMux 81 engine consensus.Engine 82 accountManager *accounts.Manager 83 84 bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests 85 bloomIndexer *core.ChainIndexer // Bloom indexer operating during block imports 86 closeBloomHandler chan struct{} 87 88 APIBackend *EthAPIBackend 89 90 miner *miner.Miner 91 gasPrice *big.Int 92 etherbase common.Address 93 94 networkID uint64 95 netRPCService *ethapi.NetAPI 96 97 p2pServer *p2p.Server 98 99 lock sync.RWMutex // Protects the variadic fields (e.g. gas price and etherbase) 100 101 shutdownTracker *shutdowncheck.ShutdownTracker // Tracks if and when the node has shutdown ungracefully 102 } 103 104 // New creates a new Ethereum object (including the 105 // initialisation of the common Ethereum object) 106 func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) { 107 // Ensure configuration values are compatible and sane 108 if config.SyncMode == downloader.LightSync { 109 return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum") 110 } 111 if !config.SyncMode.IsValid() { 112 return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode) 113 } 114 if config.Miner.GasPrice == nil || config.Miner.GasPrice.Cmp(common.Big0) <= 0 { 115 log.Warn("Sanitizing invalid miner gas price", "provided", config.Miner.GasPrice, "updated", ethconfig.Defaults.Miner.GasPrice) 116 config.Miner.GasPrice = new(big.Int).Set(ethconfig.Defaults.Miner.GasPrice) 117 } 118 if config.NoPruning && config.TrieDirtyCache > 0 { 119 if config.SnapshotCache > 0 { 120 config.TrieCleanCache += config.TrieDirtyCache * 3 / 5 121 config.SnapshotCache += config.TrieDirtyCache * 2 / 5 122 } else { 123 config.TrieCleanCache += config.TrieDirtyCache 124 } 125 config.TrieDirtyCache = 0 126 } 127 log.Info("Allocated trie memory caches", "clean", common.StorageSize(config.TrieCleanCache)*1024*1024, "dirty", common.StorageSize(config.TrieDirtyCache)*1024*1024) 128 129 // Assemble the Ethereum object 130 chainDb, err := stack.OpenDatabaseWithFreezer("chaindata", config.DatabaseCache, config.DatabaseHandles, config.DatabaseFreezer, "eth/db/chaindata/", false) 131 if err != nil { 132 return nil, err 133 } 134 if err := pruner.RecoverPruning(stack.ResolvePath(""), chainDb, stack.ResolvePath(config.TrieCleanCacheJournal)); err != nil { 135 log.Error("Failed to recover state", "error", err) 136 } 137 // Transfer mining-related config to the ethash config. 138 ethashConfig := config.Ethash 139 ethashConfig.NotifyFull = config.Miner.NotifyFull 140 cliqueConfig, err := core.LoadCliqueConfig(chainDb, config.Genesis) 141 if err != nil { 142 return nil, err 143 } 144 engine := ethconfig.CreateConsensusEngine(stack, ðashConfig, cliqueConfig, config.Miner.Notify, config.Miner.Noverify, chainDb) 145 146 eth := &Ethereum{ 147 config: config, 148 merger: consensus.NewMerger(chainDb), 149 chainDb: chainDb, 150 eventMux: stack.EventMux(), 151 accountManager: stack.AccountManager(), 152 engine: engine, 153 closeBloomHandler: make(chan struct{}), 154 networkID: config.NetworkId, 155 gasPrice: config.Miner.GasPrice, 156 etherbase: config.Miner.Etherbase, 157 bloomRequests: make(chan chan *bloombits.Retrieval), 158 bloomIndexer: core.NewBloomIndexer(chainDb, params.BloomBitsBlocks, params.BloomConfirms), 159 p2pServer: stack.Server(), 160 shutdownTracker: shutdowncheck.NewShutdownTracker(chainDb), 161 } 162 163 bcVersion := rawdb.ReadDatabaseVersion(chainDb) 164 var dbVer = "<nil>" 165 if bcVersion != nil { 166 dbVer = fmt.Sprintf("%d", *bcVersion) 167 } 168 log.Info("Initialising Ethereum protocol", "network", config.NetworkId, "dbversion", dbVer) 169 170 if !config.SkipBcVersionCheck { 171 if bcVersion != nil && *bcVersion > core.BlockChainVersion { 172 return nil, fmt.Errorf("database version is v%d, Geth %s only supports v%d", *bcVersion, params.VersionWithMeta, core.BlockChainVersion) 173 } else if bcVersion == nil || *bcVersion < core.BlockChainVersion { 174 if bcVersion != nil { // only print warning on upgrade, not on init 175 log.Warn("Upgrade blockchain database version", "from", dbVer, "to", core.BlockChainVersion) 176 } 177 rawdb.WriteDatabaseVersion(chainDb, core.BlockChainVersion) 178 } 179 } 180 var ( 181 vmConfig = vm.Config{ 182 EnablePreimageRecording: config.EnablePreimageRecording, 183 } 184 cacheConfig = &core.CacheConfig{ 185 TrieCleanLimit: config.TrieCleanCache, 186 TrieCleanJournal: stack.ResolvePath(config.TrieCleanCacheJournal), 187 TrieCleanRejournal: config.TrieCleanCacheRejournal, 188 TrieCleanNoPrefetch: config.NoPrefetch, 189 TrieDirtyLimit: config.TrieDirtyCache, 190 TrieDirtyDisabled: config.NoPruning, 191 TrieTimeLimit: config.TrieTimeout, 192 SnapshotLimit: config.SnapshotCache, 193 Preimages: config.Preimages, 194 } 195 ) 196 // Override the chain config with provided settings. 197 var overrides core.ChainOverrides 198 if config.OverrideShanghai != nil { 199 overrides.OverrideShanghai = config.OverrideShanghai 200 } 201 eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, config.Genesis, &overrides, eth.engine, vmConfig, eth.shouldPreserve, &config.TxLookupLimit) 202 if err != nil { 203 return nil, err 204 } 205 eth.bloomIndexer.Start(eth.blockchain) 206 207 if config.TxPool.Journal != "" { 208 config.TxPool.Journal = stack.ResolvePath(config.TxPool.Journal) 209 } 210 eth.txPool = txpool.NewTxPool(config.TxPool, eth.blockchain.Config(), eth.blockchain) 211 212 // Permit the downloader to use the trie cache allowance during fast sync 213 cacheLimit := cacheConfig.TrieCleanLimit + cacheConfig.TrieDirtyLimit + cacheConfig.SnapshotLimit 214 checkpoint := config.Checkpoint 215 if checkpoint == nil { 216 checkpoint = params.TrustedCheckpoints[eth.blockchain.Genesis().Hash()] 217 } 218 if eth.handler, err = newHandler(&handlerConfig{ 219 Database: chainDb, 220 Chain: eth.blockchain, 221 TxPool: eth.txPool, 222 Merger: eth.merger, 223 Network: config.NetworkId, 224 Sync: config.SyncMode, 225 BloomCache: uint64(cacheLimit), 226 EventMux: eth.eventMux, 227 Checkpoint: checkpoint, 228 RequiredBlocks: config.RequiredBlocks, 229 }); err != nil { 230 return nil, err 231 } 232 233 eth.miner = miner.New(eth, &config.Miner, eth.blockchain.Config(), eth.EventMux(), eth.engine, eth.isLocalBlock) 234 eth.miner.SetExtra(makeExtraData(config.Miner.ExtraData)) 235 236 eth.APIBackend = &EthAPIBackend{stack.Config().ExtRPCEnabled(), stack.Config().AllowUnprotectedTxs, eth, nil} 237 if eth.APIBackend.allowUnprotectedTxs { 238 log.Info("Unprotected transactions allowed") 239 } 240 gpoParams := config.GPO 241 if gpoParams.Default == nil { 242 gpoParams.Default = config.Miner.GasPrice 243 } 244 eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams) 245 246 // Setup DNS discovery iterators. 247 dnsclient := dnsdisc.NewClient(dnsdisc.Config{}) 248 eth.ethDialCandidates, err = dnsclient.NewIterator(eth.config.EthDiscoveryURLs...) 249 if err != nil { 250 return nil, err 251 } 252 eth.snapDialCandidates, err = dnsclient.NewIterator(eth.config.SnapDiscoveryURLs...) 253 if err != nil { 254 return nil, err 255 } 256 257 // Start the RPC service 258 eth.netRPCService = ethapi.NewNetAPI(eth.p2pServer, config.NetworkId) 259 260 // Register the backend on the node 261 stack.RegisterAPIs(eth.APIs()) 262 stack.RegisterProtocols(eth.Protocols()) 263 stack.RegisterLifecycle(eth) 264 265 // Successful startup; push a marker and check previous unclean shutdowns. 266 eth.shutdownTracker.MarkStartup() 267 268 return eth, nil 269 } 270 271 func makeExtraData(extra []byte) []byte { 272 if len(extra) == 0 { 273 // create default extradata 274 extra, _ = rlp.EncodeToBytes([]interface{}{ 275 uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch), 276 "geth", 277 runtime.Version(), 278 runtime.GOOS, 279 }) 280 } 281 if uint64(len(extra)) > params.MaximumExtraDataSize { 282 log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize) 283 extra = nil 284 } 285 return extra 286 } 287 288 // APIs return the collection of RPC services the ethereum package offers. 289 // NOTE, some of these services probably need to be moved to somewhere else. 290 func (s *Ethereum) APIs() []rpc.API { 291 apis := ethapi.GetAPIs(s.APIBackend) 292 293 // Append any APIs exposed explicitly by the consensus engine 294 apis = append(apis, s.engine.APIs(s.BlockChain())...) 295 296 // Append all the local APIs and return 297 return append(apis, []rpc.API{ 298 { 299 Namespace: "eth", 300 Service: NewEthereumAPI(s), 301 }, { 302 Namespace: "miner", 303 Service: NewMinerAPI(s), 304 }, { 305 Namespace: "eth", 306 Service: downloader.NewDownloaderAPI(s.handler.downloader, s.eventMux), 307 }, { 308 Namespace: "admin", 309 Service: NewAdminAPI(s), 310 }, { 311 Namespace: "debug", 312 Service: NewDebugAPI(s), 313 }, { 314 Namespace: "net", 315 Service: s.netRPCService, 316 }, 317 }...) 318 } 319 320 func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) { 321 s.blockchain.ResetWithGenesisBlock(gb) 322 } 323 324 func (s *Ethereum) Etherbase() (eb common.Address, err error) { 325 s.lock.RLock() 326 etherbase := s.etherbase 327 s.lock.RUnlock() 328 329 if etherbase != (common.Address{}) { 330 return etherbase, nil 331 } 332 if wallets := s.AccountManager().Wallets(); len(wallets) > 0 { 333 if accounts := wallets[0].Accounts(); len(accounts) > 0 { 334 etherbase := accounts[0].Address 335 336 s.lock.Lock() 337 s.etherbase = etherbase 338 s.lock.Unlock() 339 340 log.Info("Etherbase automatically configured", "address", etherbase) 341 return etherbase, nil 342 } 343 } 344 return common.Address{}, fmt.Errorf("etherbase must be explicitly specified") 345 } 346 347 // isLocalBlock checks whether the specified block is mined 348 // by local miner accounts. 349 // 350 // We regard two types of accounts as local miner account: etherbase 351 // and accounts specified via `txpool.locals` flag. 352 func (s *Ethereum) isLocalBlock(header *types.Header) bool { 353 author, err := s.engine.Author(header) 354 if err != nil { 355 log.Warn("Failed to retrieve block author", "number", header.Number.Uint64(), "hash", header.Hash(), "err", err) 356 return false 357 } 358 // Check whether the given address is etherbase. 359 s.lock.RLock() 360 etherbase := s.etherbase 361 s.lock.RUnlock() 362 if author == etherbase { 363 return true 364 } 365 // Check whether the given address is specified by `txpool.local` 366 // CLI flag. 367 for _, account := range s.config.TxPool.Locals { 368 if account == author { 369 return true 370 } 371 } 372 return false 373 } 374 375 // shouldPreserve checks whether we should preserve the given block 376 // during the chain reorg depending on whether the author of block 377 // is a local account. 378 func (s *Ethereum) shouldPreserve(header *types.Header) bool { 379 // The reason we need to disable the self-reorg preserving for clique 380 // is it can be probable to introduce a deadlock. 381 // 382 // e.g. If there are 7 available signers 383 // 384 // r1 A 385 // r2 B 386 // r3 C 387 // r4 D 388 // r5 A [X] F G 389 // r6 [X] 390 // 391 // In the round5, the inturn signer E is offline, so the worst case 392 // is A, F and G sign the block of round5 and reject the block of opponents 393 // and in the round6, the last available signer B is offline, the whole 394 // network is stuck. 395 if _, ok := s.engine.(*clique.Clique); ok { 396 return false 397 } 398 return s.isLocalBlock(header) 399 } 400 401 // SetEtherbase sets the mining reward address. 402 func (s *Ethereum) SetEtherbase(etherbase common.Address) { 403 s.lock.Lock() 404 s.etherbase = etherbase 405 s.lock.Unlock() 406 407 s.miner.SetEtherbase(etherbase) 408 } 409 410 // StartMining starts the miner with the given number of CPU threads. If mining 411 // is already running, this method adjust the number of threads allowed to use 412 // and updates the minimum price required by the transaction pool. 413 func (s *Ethereum) StartMining(threads int) error { 414 // Update the thread count within the consensus engine 415 type threaded interface { 416 SetThreads(threads int) 417 } 418 if th, ok := s.engine.(threaded); ok { 419 log.Info("Updated mining threads", "threads", threads) 420 if threads == 0 { 421 threads = -1 // Disable the miner from within 422 } 423 th.SetThreads(threads) 424 } 425 // If the miner was not running, initialize it 426 if !s.IsMining() { 427 // Propagate the initial price point to the transaction pool 428 s.lock.RLock() 429 price := s.gasPrice 430 s.lock.RUnlock() 431 s.txPool.SetGasPrice(price) 432 433 // Configure the local mining address 434 eb, err := s.Etherbase() 435 if err != nil { 436 log.Error("Cannot start mining without etherbase", "err", err) 437 return fmt.Errorf("etherbase missing: %v", err) 438 } 439 var cli *clique.Clique 440 if c, ok := s.engine.(*clique.Clique); ok { 441 cli = c 442 } else if cl, ok := s.engine.(*beacon.Beacon); ok { 443 if c, ok := cl.InnerEngine().(*clique.Clique); ok { 444 cli = c 445 } 446 } 447 if cli != nil { 448 wallet, err := s.accountManager.Find(accounts.Account{Address: eb}) 449 if wallet == nil || err != nil { 450 log.Error("Etherbase account unavailable locally", "err", err) 451 return fmt.Errorf("signer missing: %v", err) 452 } 453 cli.Authorize(eb, wallet.SignData) 454 } 455 // If mining is started, we can disable the transaction rejection mechanism 456 // introduced to speed sync times. 457 atomic.StoreUint32(&s.handler.acceptTxs, 1) 458 459 go s.miner.Start(eb) 460 } 461 return nil 462 } 463 464 // StopMining terminates the miner, both at the consensus engine level as well as 465 // at the block creation level. 466 func (s *Ethereum) StopMining() { 467 // Update the thread count within the consensus engine 468 type threaded interface { 469 SetThreads(threads int) 470 } 471 if th, ok := s.engine.(threaded); ok { 472 th.SetThreads(-1) 473 } 474 // Stop the block creating itself 475 s.miner.Stop() 476 } 477 478 func (s *Ethereum) IsMining() bool { return s.miner.Mining() } 479 func (s *Ethereum) Miner() *miner.Miner { return s.miner } 480 481 func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager } 482 func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain } 483 func (s *Ethereum) TxPool() *txpool.TxPool { return s.txPool } 484 func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux } 485 func (s *Ethereum) Engine() consensus.Engine { return s.engine } 486 func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb } 487 func (s *Ethereum) IsListening() bool { return true } // Always listening 488 func (s *Ethereum) Downloader() *downloader.Downloader { return s.handler.downloader } 489 func (s *Ethereum) Synced() bool { return atomic.LoadUint32(&s.handler.acceptTxs) == 1 } 490 func (s *Ethereum) SetSynced() { atomic.StoreUint32(&s.handler.acceptTxs, 1) } 491 func (s *Ethereum) ArchiveMode() bool { return s.config.NoPruning } 492 func (s *Ethereum) BloomIndexer() *core.ChainIndexer { return s.bloomIndexer } 493 func (s *Ethereum) Merger() *consensus.Merger { return s.merger } 494 func (s *Ethereum) SyncMode() downloader.SyncMode { 495 mode, _ := s.handler.chainSync.modeAndLocalHead() 496 return mode 497 } 498 499 // Protocols returns all the currently configured 500 // network protocols to start. 501 func (s *Ethereum) Protocols() []p2p.Protocol { 502 protos := eth.MakeProtocols((*ethHandler)(s.handler), s.networkID, s.ethDialCandidates) 503 if s.config.SnapshotCache > 0 { 504 protos = append(protos, snap.MakeProtocols((*snapHandler)(s.handler), s.snapDialCandidates)...) 505 } 506 return protos 507 } 508 509 // Start implements node.Lifecycle, starting all internal goroutines needed by the 510 // Ethereum protocol implementation. 511 func (s *Ethereum) Start() error { 512 eth.StartENRUpdater(s.blockchain, s.p2pServer.LocalNode()) 513 514 // Start the bloom bits servicing goroutines 515 s.startBloomHandlers(params.BloomBitsBlocks) 516 517 // Regularly update shutdown marker 518 s.shutdownTracker.Start() 519 520 // Figure out a max peers count based on the server limits 521 maxPeers := s.p2pServer.MaxPeers 522 if s.config.LightServ > 0 { 523 if s.config.LightPeers >= s.p2pServer.MaxPeers { 524 return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, s.p2pServer.MaxPeers) 525 } 526 maxPeers -= s.config.LightPeers 527 } 528 // Start the networking layer and the light server if requested 529 s.handler.Start(maxPeers) 530 return nil 531 } 532 533 // Stop implements node.Lifecycle, terminating all internal goroutines used by the 534 // Ethereum protocol. 535 func (s *Ethereum) Stop() error { 536 // Stop all the peer-related stuff first. 537 s.ethDialCandidates.Close() 538 s.snapDialCandidates.Close() 539 s.handler.Stop() 540 541 // Then stop everything else. 542 s.bloomIndexer.Close() 543 close(s.closeBloomHandler) 544 s.txPool.Stop() 545 s.miner.Close() 546 s.blockchain.Stop() 547 s.engine.Close() 548 549 // Clean shutdown marker as the last thing before closing db 550 s.shutdownTracker.Stop() 551 552 s.chainDb.Close() 553 s.eventMux.Stop() 554 555 return nil 556 }