backend.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. // 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.Miner.GasPrice == nil || config.Miner.GasPrice.Cmp(common.Big0) <= 0 {
  97. log.Warn("Sanitizing invalid miner gas price", "provided", config.Miner.GasPrice, "updated", DefaultConfig.Miner.GasPrice)
  98. config.Miner.GasPrice = new(big.Int).Set(DefaultConfig.Miner.GasPrice)
  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 := ctx.OpenDatabaseWithFreezer("chaindata", config.DatabaseCache, config.DatabaseHandles, config.DatabaseFreezer, "eth/db/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. eventMux: ctx.EventMux,
  119. accountManager: ctx.AccountManager,
  120. engine: CreateConsensusEngine(ctx, chainConfig, &config.Ethash, config.Miner.Notify, config.Miner.Noverify, chainDb),
  121. shutdownChan: make(chan bool),
  122. networkID: config.NetworkId,
  123. gasPrice: config.Miner.GasPrice,
  124. etherbase: config.Miner.Etherbase,
  125. bloomRequests: make(chan chan *bloombits.Retrieval),
  126. bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks, params.BloomConfirms),
  127. }
  128. bcVersion := rawdb.ReadDatabaseVersion(chainDb)
  129. var dbVer = "<nil>"
  130. if bcVersion != nil {
  131. dbVer = fmt.Sprintf("%d", *bcVersion)
  132. }
  133. log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId, "dbversion", dbVer)
  134. if !config.SkipBcVersionCheck {
  135. if bcVersion != nil && *bcVersion > core.BlockChainVersion {
  136. return nil, fmt.Errorf("database version is v%d, Geth %s only supports v%d", *bcVersion, params.VersionWithMeta, core.BlockChainVersion)
  137. } else if bcVersion == nil || *bcVersion < core.BlockChainVersion {
  138. log.Warn("Upgrade blockchain database version", "from", dbVer, "to", core.BlockChainVersion)
  139. rawdb.WriteDatabaseVersion(chainDb, core.BlockChainVersion)
  140. }
  141. }
  142. var (
  143. vmConfig = vm.Config{
  144. EnablePreimageRecording: config.EnablePreimageRecording,
  145. EWASMInterpreter: config.EWASMInterpreter,
  146. EVMInterpreter: config.EVMInterpreter,
  147. }
  148. cacheConfig = &core.CacheConfig{
  149. TrieCleanLimit: config.TrieCleanCache,
  150. TrieCleanNoPrefetch: config.NoPrefetch,
  151. TrieDirtyLimit: config.TrieDirtyCache,
  152. TrieDirtyDisabled: config.NoPruning,
  153. TrieTimeLimit: config.TrieTimeout,
  154. }
  155. )
  156. eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, chainConfig, eth.engine, vmConfig, eth.shouldPreserve)
  157. if err != nil {
  158. return nil, err
  159. }
  160. // Rewind the chain in case of an incompatible config upgrade.
  161. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  162. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  163. eth.blockchain.SetHead(compat.RewindTo)
  164. rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
  165. }
  166. eth.bloomIndexer.Start(eth.blockchain)
  167. if config.TxPool.Journal != "" {
  168. config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal)
  169. }
  170. eth.txPool = core.NewTxPool(config.TxPool, chainConfig, eth.blockchain)
  171. // Permit the downloader to use the trie cache allowance during fast sync
  172. cacheLimit := cacheConfig.TrieCleanLimit + cacheConfig.TrieDirtyLimit
  173. if eth.protocolManager, err = NewProtocolManager(chainConfig, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb, cacheLimit, config.Whitelist); err != nil {
  174. return nil, err
  175. }
  176. eth.miner = miner.New(eth, &config.Miner, chainConfig, eth.EventMux(), eth.engine, eth.isLocalBlock)
  177. eth.miner.SetExtra(makeExtraData(config.Miner.ExtraData))
  178. eth.APIBackend = &EthAPIBackend{ctx.ExtRPCEnabled(), eth, nil}
  179. gpoParams := config.GPO
  180. if gpoParams.Default == nil {
  181. gpoParams.Default = config.Miner.GasPrice
  182. }
  183. eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams)
  184. return eth, nil
  185. }
  186. func makeExtraData(extra []byte) []byte {
  187. if len(extra) == 0 {
  188. // create default extradata
  189. extra, _ = rlp.EncodeToBytes([]interface{}{
  190. uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch),
  191. "geth",
  192. runtime.Version(),
  193. runtime.GOOS,
  194. })
  195. }
  196. if uint64(len(extra)) > params.MaximumExtraDataSize {
  197. log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize)
  198. extra = nil
  199. }
  200. return extra
  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 les server
  237. if s.lesServer != nil {
  238. apis = append(apis, s.lesServer.APIs()...)
  239. }
  240. // Append any APIs exposed explicitly by the consensus engine
  241. apis = append(apis, s.engine.APIs(s.BlockChain())...)
  242. // Append all the local APIs and return
  243. return append(apis, []rpc.API{
  244. {
  245. Namespace: "eth",
  246. Version: "1.0",
  247. Service: NewPublicEthereumAPI(s),
  248. Public: true,
  249. }, {
  250. Namespace: "eth",
  251. Version: "1.0",
  252. Service: NewPublicMinerAPI(s),
  253. Public: true,
  254. }, {
  255. Namespace: "eth",
  256. Version: "1.0",
  257. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  258. Public: true,
  259. }, {
  260. Namespace: "miner",
  261. Version: "1.0",
  262. Service: NewPrivateMinerAPI(s),
  263. Public: false,
  264. }, {
  265. Namespace: "eth",
  266. Version: "1.0",
  267. Service: filters.NewPublicFilterAPI(s.APIBackend, false),
  268. Public: true,
  269. }, {
  270. Namespace: "admin",
  271. Version: "1.0",
  272. Service: NewPrivateAdminAPI(s),
  273. }, {
  274. Namespace: "debug",
  275. Version: "1.0",
  276. Service: NewPublicDebugAPI(s),
  277. Public: true,
  278. }, {
  279. Namespace: "debug",
  280. Version: "1.0",
  281. Service: NewPrivateDebugAPI(s),
  282. }, {
  283. Namespace: "net",
  284. Version: "1.0",
  285. Service: s.netRPCService,
  286. Public: true,
  287. },
  288. }...)
  289. }
  290. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  291. s.blockchain.ResetWithGenesisBlock(gb)
  292. }
  293. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  294. s.lock.RLock()
  295. etherbase := s.etherbase
  296. s.lock.RUnlock()
  297. if etherbase != (common.Address{}) {
  298. return etherbase, nil
  299. }
  300. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  301. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  302. etherbase := accounts[0].Address
  303. s.lock.Lock()
  304. s.etherbase = etherbase
  305. s.lock.Unlock()
  306. log.Info("Etherbase automatically configured", "address", etherbase)
  307. return etherbase, nil
  308. }
  309. }
  310. return common.Address{}, fmt.Errorf("etherbase must be explicitly specified")
  311. }
  312. // isLocalBlock checks whether the specified block is mined
  313. // by local miner accounts.
  314. //
  315. // We regard two types of accounts as local miner account: etherbase
  316. // and accounts specified via `txpool.locals` flag.
  317. func (s *Ethereum) isLocalBlock(block *types.Block) bool {
  318. author, err := s.engine.Author(block.Header())
  319. if err != nil {
  320. log.Warn("Failed to retrieve block author", "number", block.NumberU64(), "hash", block.Hash(), "err", err)
  321. return false
  322. }
  323. // Check whether the given address is etherbase.
  324. s.lock.RLock()
  325. etherbase := s.etherbase
  326. s.lock.RUnlock()
  327. if author == etherbase {
  328. return true
  329. }
  330. // Check whether the given address is specified by `txpool.local`
  331. // CLI flag.
  332. for _, account := range s.config.TxPool.Locals {
  333. if account == author {
  334. return true
  335. }
  336. }
  337. return false
  338. }
  339. // shouldPreserve checks whether we should preserve the given block
  340. // during the chain reorg depending on whether the author of block
  341. // is a local account.
  342. func (s *Ethereum) shouldPreserve(block *types.Block) bool {
  343. // The reason we need to disable the self-reorg preserving for clique
  344. // is it can be probable to introduce a deadlock.
  345. //
  346. // e.g. If there are 7 available signers
  347. //
  348. // r1 A
  349. // r2 B
  350. // r3 C
  351. // r4 D
  352. // r5 A [X] F G
  353. // r6 [X]
  354. //
  355. // In the round5, the inturn signer E is offline, so the worst case
  356. // is A, F and G sign the block of round5 and reject the block of opponents
  357. // and in the round6, the last available signer B is offline, the whole
  358. // network is stuck.
  359. if _, ok := s.engine.(*clique.Clique); ok {
  360. return false
  361. }
  362. return s.isLocalBlock(block)
  363. }
  364. // SetEtherbase sets the mining reward address.
  365. func (s *Ethereum) SetEtherbase(etherbase common.Address) {
  366. s.lock.Lock()
  367. s.etherbase = etherbase
  368. s.lock.Unlock()
  369. s.miner.SetEtherbase(etherbase)
  370. }
  371. // StartMining starts the miner with the given number of CPU threads. If mining
  372. // is already running, this method adjust the number of threads allowed to use
  373. // and updates the minimum price required by the transaction pool.
  374. func (s *Ethereum) StartMining(threads int) error {
  375. // Update the thread count within the consensus engine
  376. type threaded interface {
  377. SetThreads(threads int)
  378. }
  379. if th, ok := s.engine.(threaded); ok {
  380. log.Info("Updated mining threads", "threads", threads)
  381. if threads == 0 {
  382. threads = -1 // Disable the miner from within
  383. }
  384. th.SetThreads(threads)
  385. }
  386. // If the miner was not running, initialize it
  387. if !s.IsMining() {
  388. // Propagate the initial price point to the transaction pool
  389. s.lock.RLock()
  390. price := s.gasPrice
  391. s.lock.RUnlock()
  392. s.txPool.SetGasPrice(price)
  393. // Configure the local mining address
  394. eb, err := s.Etherbase()
  395. if err != nil {
  396. log.Error("Cannot start mining without etherbase", "err", err)
  397. return fmt.Errorf("etherbase missing: %v", err)
  398. }
  399. if clique, ok := s.engine.(*clique.Clique); ok {
  400. wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
  401. if wallet == nil || err != nil {
  402. log.Error("Etherbase account unavailable locally", "err", err)
  403. return fmt.Errorf("signer missing: %v", err)
  404. }
  405. clique.Authorize(eb, wallet.SignData)
  406. }
  407. // If mining is started, we can disable the transaction rejection mechanism
  408. // introduced to speed sync times.
  409. atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
  410. go s.miner.Start(eb)
  411. }
  412. return nil
  413. }
  414. // StopMining terminates the miner, both at the consensus engine level as well as
  415. // at the block creation level.
  416. func (s *Ethereum) StopMining() {
  417. // Update the thread count within the consensus engine
  418. type threaded interface {
  419. SetThreads(threads int)
  420. }
  421. if th, ok := s.engine.(threaded); ok {
  422. th.SetThreads(-1)
  423. }
  424. // Stop the block creating itself
  425. s.miner.Stop()
  426. }
  427. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  428. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  429. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  430. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  431. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  432. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  433. func (s *Ethereum) Engine() consensus.Engine { return s.engine }
  434. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  435. func (s *Ethereum) IsListening() bool { return true } // Always listening
  436. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  437. func (s *Ethereum) NetVersion() uint64 { return s.networkID }
  438. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  439. func (s *Ethereum) Synced() bool { return atomic.LoadUint32(&s.protocolManager.acceptTxs) == 1 }
  440. // Protocols implements node.Service, returning all the currently configured
  441. // network protocols to start.
  442. func (s *Ethereum) Protocols() []p2p.Protocol {
  443. if s.lesServer == nil {
  444. return s.protocolManager.SubProtocols
  445. }
  446. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  447. }
  448. // Start implements node.Service, starting all internal goroutines needed by the
  449. // Ethereum protocol implementation.
  450. func (s *Ethereum) Start(srvr *p2p.Server) error {
  451. // Start the bloom bits servicing goroutines
  452. s.startBloomHandlers(params.BloomBitsBlocks)
  453. // Start the RPC service
  454. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  455. // Figure out a max peers count based on the server limits
  456. maxPeers := srvr.MaxPeers
  457. if s.config.LightServ > 0 {
  458. if s.config.LightPeers >= srvr.MaxPeers {
  459. return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, srvr.MaxPeers)
  460. }
  461. maxPeers -= s.config.LightPeers
  462. }
  463. // Start the networking layer and the light server if requested
  464. s.protocolManager.Start(maxPeers)
  465. if s.lesServer != nil {
  466. s.lesServer.Start(srvr)
  467. }
  468. return nil
  469. }
  470. // Stop implements node.Service, terminating all internal goroutines used by the
  471. // Ethereum protocol.
  472. func (s *Ethereum) Stop() error {
  473. s.bloomIndexer.Close()
  474. s.blockchain.Stop()
  475. s.engine.Close()
  476. s.protocolManager.Stop()
  477. if s.lesServer != nil {
  478. s.lesServer.Stop()
  479. }
  480. s.txPool.Stop()
  481. s.miner.Stop()
  482. s.eventMux.Stop()
  483. s.chainDb.Close()
  484. close(s.shutdownChan)
  485. return nil
  486. }