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