backend.go 18 KB

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