backend.go 18 KB

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