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