git.pirl.io/community/pirl@v0.0.0-20201111064343-9d3d31ff74be/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 "git.pirl.io/community/pirl/accounts" 29 "git.pirl.io/community/pirl/accounts/abi/bind" 30 "git.pirl.io/community/pirl/common" 31 "git.pirl.io/community/pirl/common/hexutil" 32 "git.pirl.io/community/pirl/consensus" 33 "git.pirl.io/community/pirl/consensus/clique" 34 "git.pirl.io/community/pirl/consensus/ethash" 35 "git.pirl.io/community/pirl/core" 36 "git.pirl.io/community/pirl/core/bloombits" 37 "git.pirl.io/community/pirl/core/rawdb" 38 "git.pirl.io/community/pirl/core/types" 39 "git.pirl.io/community/pirl/core/vm" 40 "git.pirl.io/community/pirl/eth/downloader" 41 "git.pirl.io/community/pirl/eth/filters" 42 "git.pirl.io/community/pirl/eth/gasprice" 43 "git.pirl.io/community/pirl/ethdb" 44 "git.pirl.io/community/pirl/event" 45 "git.pirl.io/community/pirl/internal/ethapi" 46 "git.pirl.io/community/pirl/log" 47 "git.pirl.io/community/pirl/miner" 48 "git.pirl.io/community/pirl/node" 49 "git.pirl.io/community/pirl/p2p" 50 "git.pirl.io/community/pirl/p2p/enode" 51 "git.pirl.io/community/pirl/p2p/enr" 52 "git.pirl.io/community/pirl/params" 53 "git.pirl.io/community/pirl/rlp" 54 "git.pirl.io/community/pirl/rpc" 55 ) 56 57 type LesServer interface { 58 Start(srvr *p2p.Server) 59 Stop() 60 APIs() []rpc.API 61 Protocols() []p2p.Protocol 62 SetBloomBitsIndexer(bbIndexer *core.ChainIndexer) 63 SetContractBackend(bind.ContractBackend) 64 } 65 66 // Ethereum implements the Ethereum full node service. 67 type Ethereum struct { 68 config *Config 69 70 // Channel for shutting down the service 71 shutdownChan chan bool 72 73 // Handlers 74 txPool *core.TxPool 75 blockchain *core.BlockChain 76 protocolManager *ProtocolManager 77 lesServer LesServer 78 dialCandiates enode.Iterator 79 80 // DB interfaces 81 chainDb ethdb.Database // Block chain database 82 83 eventMux *event.TypeMux 84 engine consensus.Engine 85 accountManager *accounts.Manager 86 87 bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests 88 bloomIndexer *core.ChainIndexer // Bloom indexer operating during block imports 89 90 APIBackend *EthAPIBackend 91 92 miner *miner.Miner 93 gasPrice *big.Int 94 etherbase common.Address 95 96 networkID uint64 97 netRPCService *ethapi.PublicNetAPI 98 99 lock sync.RWMutex // Protects the variadic fields (e.g. gas price and etherbase) 100 } 101 102 func (s *Ethereum) AddLesServer(ls LesServer) { 103 s.lesServer = ls 104 ls.SetBloomBitsIndexer(s.bloomIndexer) 105 } 106 107 // SetClient sets a rpc client which connecting to our local node. 108 func (s *Ethereum) SetContractBackend(backend bind.ContractBackend) { 109 // Pass the rpc client to les server if it is enabled. 110 if s.lesServer != nil { 111 s.lesServer.SetContractBackend(backend) 112 } 113 } 114 115 // New creates a new Ethereum object (including the 116 // initialisation of the common Ethereum object) 117 func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { 118 // Ensure configuration values are compatible and sane 119 if config.SyncMode == downloader.LightSync { 120 return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum") 121 } 122 if !config.SyncMode.IsValid() { 123 return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode) 124 } 125 if config.Miner.GasPrice == nil || config.Miner.GasPrice.Cmp(common.Big0) <= 0 { 126 log.Warn("Sanitizing invalid miner gas price", "provided", config.Miner.GasPrice, "updated", DefaultConfig.Miner.GasPrice) 127 config.Miner.GasPrice = new(big.Int).Set(DefaultConfig.Miner.GasPrice) 128 } 129 if config.NoPruning && config.TrieDirtyCache > 0 { 130 config.TrieCleanCache += config.TrieDirtyCache 131 config.TrieDirtyCache = 0 132 } 133 log.Info("Allocated trie memory caches", "clean", common.StorageSize(config.TrieCleanCache)*1024*1024, "dirty", common.StorageSize(config.TrieDirtyCache)*1024*1024) 134 135 // Assemble the Ethereum object 136 chainDb, err := ctx.OpenDatabaseWithFreezer("chaindata", config.DatabaseCache, config.DatabaseHandles, config.DatabaseFreezer, "eth/db/chaindata/") 137 if err != nil { 138 return nil, err 139 } 140 chainConfig, genesisHash, genesisErr := core.SetupGenesisBlockWithOverride(chainDb, config.Genesis, config.OverrideIstanbul, config.OverrideMuirGlacier) 141 if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok { 142 return nil, genesisErr 143 } 144 log.Info("Initialised chain configuration", "config", chainConfig) 145 146 eth := &Ethereum{ 147 config: config, 148 chainDb: chainDb, 149 eventMux: ctx.EventMux, 150 accountManager: ctx.AccountManager, 151 engine: CreateConsensusEngine(ctx, chainConfig, &config.Ethash, config.Miner.Notify, config.Miner.Noverify, chainDb), 152 shutdownChan: make(chan bool), 153 networkID: config.NetworkId, 154 gasPrice: config.Miner.GasPrice, 155 etherbase: config.Miner.Etherbase, 156 bloomRequests: make(chan chan *bloombits.Retrieval), 157 bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks, params.BloomConfirms), 158 } 159 160 bcVersion := rawdb.ReadDatabaseVersion(chainDb) 161 var dbVer = "<nil>" 162 if bcVersion != nil { 163 dbVer = fmt.Sprintf("%d", *bcVersion) 164 } 165 log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId, "dbversion", dbVer) 166 167 if !config.SkipBcVersionCheck { 168 if bcVersion != nil && *bcVersion > core.BlockChainVersion { 169 return nil, fmt.Errorf("database version is v%d, Geth %s only supports v%d", *bcVersion, params.VersionWithMeta, core.BlockChainVersion) 170 } else if bcVersion == nil || *bcVersion < core.BlockChainVersion { 171 log.Warn("Upgrade blockchain database version", "from", dbVer, "to", core.BlockChainVersion) 172 rawdb.WriteDatabaseVersion(chainDb, core.BlockChainVersion) 173 } 174 } 175 var ( 176 vmConfig = vm.Config{ 177 EnablePreimageRecording: config.EnablePreimageRecording, 178 EWASMInterpreter: config.EWASMInterpreter, 179 EVMInterpreter: config.EVMInterpreter, 180 } 181 cacheConfig = &core.CacheConfig{ 182 TrieCleanLimit: config.TrieCleanCache, 183 TrieCleanNoPrefetch: config.NoPrefetch, 184 TrieDirtyLimit: config.TrieDirtyCache, 185 TrieDirtyDisabled: config.NoPruning, 186 TrieTimeLimit: config.TrieTimeout, 187 } 188 ) 189 eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, chainConfig, eth.engine, vmConfig, eth.shouldPreserve) 190 if err != nil { 191 return nil, err 192 } 193 // Rewind the chain in case of an incompatible config upgrade. 194 if compat, ok := genesisErr.(*params.ConfigCompatError); ok { 195 log.Warn("Rewinding chain to upgrade configuration", "err", compat) 196 eth.blockchain.SetHead(compat.RewindTo) 197 rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig) 198 } 199 eth.bloomIndexer.Start(eth.blockchain) 200 201 if config.TxPool.Journal != "" { 202 config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal) 203 } 204 eth.txPool = core.NewTxPool(config.TxPool, chainConfig, eth.blockchain) 205 206 // Permit the downloader to use the trie cache allowance during fast sync 207 cacheLimit := cacheConfig.TrieCleanLimit + cacheConfig.TrieDirtyLimit 208 checkpoint := config.Checkpoint 209 if checkpoint == nil { 210 checkpoint = params.TrustedCheckpoints[genesisHash] 211 } 212 if eth.protocolManager, err = NewProtocolManager(chainConfig, checkpoint, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb, cacheLimit, config.Whitelist); err != nil { 213 return nil, err 214 } 215 eth.miner = miner.New(eth, &config.Miner, chainConfig, eth.EventMux(), eth.engine, eth.isLocalBlock) 216 eth.miner.SetExtra(makeExtraData(config.Miner.ExtraData)) 217 218 eth.APIBackend = &EthAPIBackend{ctx.ExtRPCEnabled(), eth, nil} 219 gpoParams := config.GPO 220 if gpoParams.Default == nil { 221 gpoParams.Default = config.Miner.GasPrice 222 } 223 eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams) 224 225 eth.dialCandiates, err = eth.setupDiscovery(&ctx.Config.P2P) 226 if err != nil { 227 return nil, err 228 } 229 230 return eth, nil 231 } 232 233 func makeExtraData(extra []byte) []byte { 234 if len(extra) == 0 { 235 // create default extradata 236 extra, _ = rlp.EncodeToBytes([]interface{}{ 237 uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch), 238 "geth", 239 runtime.Version(), 240 runtime.GOOS, 241 }) 242 } 243 if uint64(len(extra)) > params.MaximumExtraDataSize { 244 log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize) 245 extra = nil 246 } 247 return extra 248 } 249 250 // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service 251 func CreateConsensusEngine(ctx *node.ServiceContext, chainConfig *params.ChainConfig, config *ethash.Config, notify []string, noverify bool, db ethdb.Database) consensus.Engine { 252 // If proof-of-authority is requested, set it up 253 if chainConfig.Clique != nil { 254 return clique.New(chainConfig.Clique, db) 255 } 256 // Otherwise assume proof-of-work 257 switch config.PowMode { 258 case ethash.ModeFake: 259 log.Warn("Ethash used in fake mode") 260 return ethash.NewFaker() 261 case ethash.ModeTest: 262 log.Warn("Ethash used in test mode") 263 return ethash.NewTester(nil, noverify) 264 case ethash.ModeShared: 265 log.Warn("Ethash used in shared mode") 266 return ethash.NewShared() 267 default: 268 engine := ethash.New(ethash.Config{ 269 CacheDir: ctx.ResolvePath(config.CacheDir), 270 CachesInMem: config.CachesInMem, 271 CachesOnDisk: config.CachesOnDisk, 272 DatasetDir: config.DatasetDir, 273 DatasetsInMem: config.DatasetsInMem, 274 DatasetsOnDisk: config.DatasetsOnDisk, 275 }, notify, noverify) 276 engine.SetThreads(-1) // Disable CPU mining 277 return engine 278 } 279 } 280 281 // APIs return the collection of RPC services the ethereum package offers. 282 // NOTE, some of these services probably need to be moved to somewhere else. 283 func (s *Ethereum) APIs() []rpc.API { 284 apis := ethapi.GetAPIs(s.APIBackend) 285 286 // Append any APIs exposed explicitly by the les server 287 if s.lesServer != nil { 288 apis = append(apis, s.lesServer.APIs()...) 289 } 290 // Append any APIs exposed explicitly by the consensus engine 291 apis = append(apis, s.engine.APIs(s.BlockChain())...) 292 293 // Append any APIs exposed explicitly by the les server 294 if s.lesServer != nil { 295 apis = append(apis, s.lesServer.APIs()...) 296 } 297 298 // Append all the local APIs and return 299 return append(apis, []rpc.API{ 300 { 301 Namespace: "eth", 302 Version: "1.0", 303 Service: NewPublicEthereumAPI(s), 304 Public: true, 305 }, { 306 Namespace: "eth", 307 Version: "1.0", 308 Service: NewPublicMinerAPI(s), 309 Public: true, 310 }, { 311 Namespace: "eth", 312 Version: "1.0", 313 Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux), 314 Public: true, 315 }, { 316 Namespace: "miner", 317 Version: "1.0", 318 Service: NewPrivateMinerAPI(s), 319 Public: false, 320 }, { 321 Namespace: "eth", 322 Version: "1.0", 323 Service: filters.NewPublicFilterAPI(s.APIBackend, false), 324 Public: true, 325 }, { 326 Namespace: "admin", 327 Version: "1.0", 328 Service: NewPrivateAdminAPI(s), 329 }, { 330 Namespace: "debug", 331 Version: "1.0", 332 Service: NewPublicDebugAPI(s), 333 Public: true, 334 }, { 335 Namespace: "debug", 336 Version: "1.0", 337 Service: NewPrivateDebugAPI(s), 338 }, { 339 Namespace: "net", 340 Version: "1.0", 341 Service: s.netRPCService, 342 Public: true, 343 }, 344 }...) 345 } 346 347 func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) { 348 s.blockchain.ResetWithGenesisBlock(gb) 349 } 350 351 func (s *Ethereum) Etherbase() (eb common.Address, err error) { 352 s.lock.RLock() 353 etherbase := s.etherbase 354 s.lock.RUnlock() 355 356 if etherbase != (common.Address{}) { 357 return etherbase, nil 358 } 359 if wallets := s.AccountManager().Wallets(); len(wallets) > 0 { 360 if accounts := wallets[0].Accounts(); len(accounts) > 0 { 361 etherbase := accounts[0].Address 362 363 s.lock.Lock() 364 s.etherbase = etherbase 365 s.lock.Unlock() 366 367 log.Info("Etherbase automatically configured", "address", etherbase) 368 return etherbase, nil 369 } 370 } 371 return common.Address{}, fmt.Errorf("etherbase must be explicitly specified") 372 } 373 374 // isLocalBlock checks whether the specified block is mined 375 // by local miner accounts. 376 // 377 // We regard two types of accounts as local miner account: etherbase 378 // and accounts specified via `txpool.locals` flag. 379 func (s *Ethereum) isLocalBlock(block *types.Block) bool { 380 author, err := s.engine.Author(block.Header()) 381 if err != nil { 382 log.Warn("Failed to retrieve block author", "number", block.NumberU64(), "hash", block.Hash(), "err", err) 383 return false 384 } 385 // Check whether the given address is etherbase. 386 s.lock.RLock() 387 etherbase := s.etherbase 388 s.lock.RUnlock() 389 if author == etherbase { 390 return true 391 } 392 // Check whether the given address is specified by `txpool.local` 393 // CLI flag. 394 for _, account := range s.config.TxPool.Locals { 395 if account == author { 396 return true 397 } 398 } 399 return false 400 } 401 402 // shouldPreserve checks whether we should preserve the given block 403 // during the chain reorg depending on whether the author of block 404 // is a local account. 405 func (s *Ethereum) shouldPreserve(block *types.Block) bool { 406 // The reason we need to disable the self-reorg preserving for clique 407 // is it can be probable to introduce a deadlock. 408 // 409 // e.g. If there are 7 available signers 410 // 411 // r1 A 412 // r2 B 413 // r3 C 414 // r4 D 415 // r5 A [X] F G 416 // r6 [X] 417 // 418 // In the round5, the inturn signer E is offline, so the worst case 419 // is A, F and G sign the block of round5 and reject the block of opponents 420 // and in the round6, the last available signer B is offline, the whole 421 // network is stuck. 422 if _, ok := s.engine.(*clique.Clique); ok { 423 return false 424 } 425 return s.isLocalBlock(block) 426 } 427 428 // SetEtherbase sets the mining reward address. 429 func (s *Ethereum) SetEtherbase(etherbase common.Address) { 430 s.lock.Lock() 431 s.etherbase = etherbase 432 s.lock.Unlock() 433 434 s.miner.SetEtherbase(etherbase) 435 } 436 437 // StartMining starts the miner with the given number of CPU threads. If mining 438 // is already running, this method adjust the number of threads allowed to use 439 // and updates the minimum price required by the transaction pool. 440 func (s *Ethereum) StartMining(threads int) error { 441 // Update the thread count within the consensus engine 442 type threaded interface { 443 SetThreads(threads int) 444 } 445 if th, ok := s.engine.(threaded); ok { 446 log.Info("Updated mining threads", "threads", threads) 447 if threads == 0 { 448 threads = -1 // Disable the miner from within 449 } 450 th.SetThreads(threads) 451 } 452 // If the miner was not running, initialize it 453 if !s.IsMining() { 454 // Propagate the initial price point to the transaction pool 455 s.lock.RLock() 456 price := s.gasPrice 457 s.lock.RUnlock() 458 s.txPool.SetGasPrice(price) 459 460 // Configure the local mining address 461 eb, err := s.Etherbase() 462 if err != nil { 463 log.Error("Cannot start mining without etherbase", "err", err) 464 return fmt.Errorf("etherbase missing: %v", err) 465 } 466 if clique, ok := s.engine.(*clique.Clique); ok { 467 wallet, err := s.accountManager.Find(accounts.Account{Address: eb}) 468 if wallet == nil || err != nil { 469 log.Error("Etherbase account unavailable locally", "err", err) 470 return fmt.Errorf("signer missing: %v", err) 471 } 472 clique.Authorize(eb, wallet.SignData) 473 } 474 // If mining is started, we can disable the transaction rejection mechanism 475 // introduced to speed sync times. 476 atomic.StoreUint32(&s.protocolManager.acceptTxs, 1) 477 478 go s.miner.Start(eb) 479 } 480 return nil 481 } 482 483 // StopMining terminates the miner, both at the consensus engine level as well as 484 // at the block creation level. 485 func (s *Ethereum) StopMining() { 486 // Update the thread count within the consensus engine 487 type threaded interface { 488 SetThreads(threads int) 489 } 490 if th, ok := s.engine.(threaded); ok { 491 th.SetThreads(-1) 492 } 493 // Stop the block creating itself 494 s.miner.Stop() 495 } 496 497 func (s *Ethereum) IsMining() bool { return s.miner.Mining() } 498 func (s *Ethereum) Miner() *miner.Miner { return s.miner } 499 500 func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager } 501 func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain } 502 func (s *Ethereum) TxPool() *core.TxPool { return s.txPool } 503 func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux } 504 func (s *Ethereum) Engine() consensus.Engine { return s.engine } 505 func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb } 506 func (s *Ethereum) IsListening() bool { return true } // Always listening 507 func (s *Ethereum) EthVersion() int { return int(ProtocolVersions[0]) } 508 func (s *Ethereum) NetVersion() uint64 { return s.networkID } 509 func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader } 510 func (s *Ethereum) Synced() bool { return atomic.LoadUint32(&s.protocolManager.acceptTxs) == 1 } 511 func (s *Ethereum) ArchiveMode() bool { return s.config.NoPruning } 512 513 // Protocols implements node.Service, returning all the currently configured 514 // network protocols to start. 515 func (s *Ethereum) Protocols() []p2p.Protocol { 516 protos := make([]p2p.Protocol, len(ProtocolVersions)) 517 for i, vsn := range ProtocolVersions { 518 protos[i] = s.protocolManager.makeProtocol(vsn) 519 protos[i].Attributes = []enr.Entry{s.currentEthEntry()} 520 protos[i].DialCandidates = s.dialCandiates 521 } 522 if s.lesServer != nil { 523 protos = append(protos, s.lesServer.Protocols()...) 524 } 525 return protos 526 } 527 528 // Start implements node.Service, starting all internal goroutines needed by the 529 // Ethereum protocol implementation. 530 func (s *Ethereum) Start(srvr *p2p.Server) error { 531 s.startEthEntryUpdate(srvr.LocalNode()) 532 533 // Start the bloom bits servicing goroutines 534 s.startBloomHandlers(params.BloomBitsBlocks) 535 536 // Start the RPC service 537 s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion()) 538 539 // Figure out a max peers count based on the server limits 540 maxPeers := srvr.MaxPeers 541 if s.config.LightServ > 0 { 542 if s.config.LightPeers >= srvr.MaxPeers { 543 return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, srvr.MaxPeers) 544 } 545 maxPeers -= s.config.LightPeers 546 } 547 // Start the networking layer and the light server if requested 548 s.protocolManager.Start(maxPeers) 549 if s.lesServer != nil { 550 s.lesServer.Start(srvr) 551 } 552 return nil 553 } 554 555 // Stop implements node.Service, terminating all internal goroutines used by the 556 // Ethereum protocol. 557 func (s *Ethereum) Stop() error { 558 s.bloomIndexer.Close() 559 s.blockchain.Stop() 560 s.engine.Close() 561 s.protocolManager.Stop() 562 if s.lesServer != nil { 563 s.lesServer.Stop() 564 } 565 s.txPool.Stop() 566 s.miner.Stop() 567 s.eventMux.Stop() 568 569 s.chainDb.Close() 570 close(s.shutdownChan) 571 return nil 572 }