backend.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 := CreateDB(ctx, config, "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. // CreateDB creates the chain database.
  197. func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) {
  198. db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles)
  199. if err != nil {
  200. return nil, err
  201. }
  202. if db, ok := db.(*ethdb.LDBDatabase); ok {
  203. db.Meter("eth/db/chaindata/")
  204. }
  205. return db, nil
  206. }
  207. // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
  208. func CreateConsensusEngine(ctx *node.ServiceContext, chainConfig *params.ChainConfig, config *ethash.Config, notify []string, noverify bool, db ethdb.Database) consensus.Engine {
  209. // If proof-of-authority is requested, set it up
  210. if chainConfig.Clique != nil {
  211. return clique.New(chainConfig.Clique, db)
  212. }
  213. // Otherwise assume proof-of-work
  214. switch config.PowMode {
  215. case ethash.ModeFake:
  216. log.Warn("Ethash used in fake mode")
  217. return ethash.NewFaker()
  218. case ethash.ModeTest:
  219. log.Warn("Ethash used in test mode")
  220. return ethash.NewTester(nil, noverify)
  221. case ethash.ModeShared:
  222. log.Warn("Ethash used in shared mode")
  223. return ethash.NewShared()
  224. default:
  225. engine := ethash.New(ethash.Config{
  226. CacheDir: ctx.ResolvePath(config.CacheDir),
  227. CachesInMem: config.CachesInMem,
  228. CachesOnDisk: config.CachesOnDisk,
  229. DatasetDir: config.DatasetDir,
  230. DatasetsInMem: config.DatasetsInMem,
  231. DatasetsOnDisk: config.DatasetsOnDisk,
  232. }, notify, noverify)
  233. engine.SetThreads(-1) // Disable CPU mining
  234. return engine
  235. }
  236. }
  237. // APIs return the collection of RPC services the ethereum package offers.
  238. // NOTE, some of these services probably need to be moved to somewhere else.
  239. func (s *Ethereum) APIs() []rpc.API {
  240. apis := ethapi.GetAPIs(s.APIBackend)
  241. // Append any APIs exposed explicitly by the les server
  242. if s.lesServer != nil {
  243. apis = append(apis, s.lesServer.APIs()...)
  244. }
  245. // Append any APIs exposed explicitly by the consensus engine
  246. apis = append(apis, s.engine.APIs(s.BlockChain())...)
  247. // Append all the local APIs and return
  248. return append(apis, []rpc.API{
  249. {
  250. Namespace: "eth",
  251. Version: "1.0",
  252. Service: NewPublicEthereumAPI(s),
  253. Public: true,
  254. }, {
  255. Namespace: "eth",
  256. Version: "1.0",
  257. Service: NewPublicMinerAPI(s),
  258. Public: true,
  259. }, {
  260. Namespace: "eth",
  261. Version: "1.0",
  262. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  263. Public: true,
  264. }, {
  265. Namespace: "miner",
  266. Version: "1.0",
  267. Service: NewPrivateMinerAPI(s),
  268. Public: false,
  269. }, {
  270. Namespace: "eth",
  271. Version: "1.0",
  272. Service: filters.NewPublicFilterAPI(s.APIBackend, false),
  273. Public: true,
  274. }, {
  275. Namespace: "admin",
  276. Version: "1.0",
  277. Service: NewPrivateAdminAPI(s),
  278. }, {
  279. Namespace: "debug",
  280. Version: "1.0",
  281. Service: NewPublicDebugAPI(s),
  282. Public: true,
  283. }, {
  284. Namespace: "debug",
  285. Version: "1.0",
  286. Service: NewPrivateDebugAPI(s.chainConfig, s),
  287. }, {
  288. Namespace: "net",
  289. Version: "1.0",
  290. Service: s.netRPCService,
  291. Public: true,
  292. },
  293. }...)
  294. }
  295. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  296. s.blockchain.ResetWithGenesisBlock(gb)
  297. }
  298. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  299. s.lock.RLock()
  300. etherbase := s.etherbase
  301. s.lock.RUnlock()
  302. if etherbase != (common.Address{}) {
  303. return etherbase, nil
  304. }
  305. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  306. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  307. etherbase := accounts[0].Address
  308. s.lock.Lock()
  309. s.etherbase = etherbase
  310. s.lock.Unlock()
  311. log.Info("Etherbase automatically configured", "address", etherbase)
  312. return etherbase, nil
  313. }
  314. }
  315. return common.Address{}, fmt.Errorf("etherbase must be explicitly specified")
  316. }
  317. // isLocalBlock checks whether the specified block is mined
  318. // by local miner accounts.
  319. //
  320. // We regard two types of accounts as local miner account: etherbase
  321. // and accounts specified via `txpool.locals` flag.
  322. func (s *Ethereum) isLocalBlock(block *types.Block) bool {
  323. author, err := s.engine.Author(block.Header())
  324. if err != nil {
  325. log.Warn("Failed to retrieve block author", "number", block.NumberU64(), "hash", block.Hash(), "err", err)
  326. return false
  327. }
  328. // Check whether the given address is etherbase.
  329. s.lock.RLock()
  330. etherbase := s.etherbase
  331. s.lock.RUnlock()
  332. if author == etherbase {
  333. return true
  334. }
  335. // Check whether the given address is specified by `txpool.local`
  336. // CLI flag.
  337. for _, account := range s.config.TxPool.Locals {
  338. if account == author {
  339. return true
  340. }
  341. }
  342. return false
  343. }
  344. // shouldPreserve checks whether we should preserve the given block
  345. // during the chain reorg depending on whether the author of block
  346. // is a local account.
  347. func (s *Ethereum) shouldPreserve(block *types.Block) bool {
  348. // The reason we need to disable the self-reorg preserving for clique
  349. // is it can be probable to introduce a deadlock.
  350. //
  351. // e.g. If there are 7 available signers
  352. //
  353. // r1 A
  354. // r2 B
  355. // r3 C
  356. // r4 D
  357. // r5 A [X] F G
  358. // r6 [X]
  359. //
  360. // In the round5, the inturn signer E is offline, so the worst case
  361. // is A, F and G sign the block of round5 and reject the block of opponents
  362. // and in the round6, the last available signer B is offline, the whole
  363. // network is stuck.
  364. if _, ok := s.engine.(*clique.Clique); ok {
  365. return false
  366. }
  367. return s.isLocalBlock(block)
  368. }
  369. // SetEtherbase sets the mining reward address.
  370. func (s *Ethereum) SetEtherbase(etherbase common.Address) {
  371. s.lock.Lock()
  372. s.etherbase = etherbase
  373. s.lock.Unlock()
  374. s.miner.SetEtherbase(etherbase)
  375. }
  376. // StartMining starts the miner with the given number of CPU threads. If mining
  377. // is already running, this method adjust the number of threads allowed to use
  378. // and updates the minimum price required by the transaction pool.
  379. func (s *Ethereum) StartMining(threads int) error {
  380. // Update the thread count within the consensus engine
  381. type threaded interface {
  382. SetThreads(threads int)
  383. }
  384. if th, ok := s.engine.(threaded); ok {
  385. log.Info("Updated mining threads", "threads", threads)
  386. if threads == 0 {
  387. threads = -1 // Disable the miner from within
  388. }
  389. th.SetThreads(threads)
  390. }
  391. // If the miner was not running, initialize it
  392. if !s.IsMining() {
  393. // Propagate the initial price point to the transaction pool
  394. s.lock.RLock()
  395. price := s.gasPrice
  396. s.lock.RUnlock()
  397. s.txPool.SetGasPrice(price)
  398. // Configure the local mining address
  399. eb, err := s.Etherbase()
  400. if err != nil {
  401. log.Error("Cannot start mining without etherbase", "err", err)
  402. return fmt.Errorf("etherbase missing: %v", err)
  403. }
  404. if clique, ok := s.engine.(*clique.Clique); ok {
  405. wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
  406. if wallet == nil || err != nil {
  407. log.Error("Etherbase account unavailable locally", "err", err)
  408. return fmt.Errorf("signer missing: %v", err)
  409. }
  410. clique.Authorize(eb, wallet.SignData)
  411. }
  412. // If mining is started, we can disable the transaction rejection mechanism
  413. // introduced to speed sync times.
  414. atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
  415. go s.miner.Start(eb)
  416. }
  417. return nil
  418. }
  419. // StopMining terminates the miner, both at the consensus engine level as well as
  420. // at the block creation level.
  421. func (s *Ethereum) StopMining() {
  422. // Update the thread count within the consensus engine
  423. type threaded interface {
  424. SetThreads(threads int)
  425. }
  426. if th, ok := s.engine.(threaded); ok {
  427. th.SetThreads(-1)
  428. }
  429. // Stop the block creating itself
  430. s.miner.Stop()
  431. }
  432. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  433. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  434. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  435. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  436. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  437. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  438. func (s *Ethereum) Engine() consensus.Engine { return s.engine }
  439. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  440. func (s *Ethereum) IsListening() bool { return true } // Always listening
  441. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  442. func (s *Ethereum) NetVersion() uint64 { return s.networkID }
  443. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  444. // Protocols implements node.Service, returning all the currently configured
  445. // network protocols to start.
  446. func (s *Ethereum) Protocols() []p2p.Protocol {
  447. if s.lesServer == nil {
  448. return s.protocolManager.SubProtocols
  449. }
  450. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  451. }
  452. // Start implements node.Service, starting all internal goroutines needed by the
  453. // Ethereum protocol implementation.
  454. func (s *Ethereum) Start(srvr *p2p.Server) error {
  455. // Start the bloom bits servicing goroutines
  456. s.startBloomHandlers(params.BloomBitsBlocks)
  457. // Start the RPC service
  458. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  459. // Figure out a max peers count based on the server limits
  460. maxPeers := srvr.MaxPeers
  461. if s.config.LightServ > 0 {
  462. if s.config.LightPeers >= srvr.MaxPeers {
  463. return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, srvr.MaxPeers)
  464. }
  465. maxPeers -= s.config.LightPeers
  466. }
  467. // Start the networking layer and the light server if requested
  468. s.protocolManager.Start(maxPeers)
  469. if s.lesServer != nil {
  470. s.lesServer.Start(srvr)
  471. }
  472. return nil
  473. }
  474. // Stop implements node.Service, terminating all internal goroutines used by the
  475. // Ethereum protocol.
  476. func (s *Ethereum) Stop() error {
  477. s.bloomIndexer.Close()
  478. s.blockchain.Stop()
  479. s.engine.Close()
  480. s.protocolManager.Stop()
  481. if s.lesServer != nil {
  482. s.lesServer.Stop()
  483. }
  484. s.txPool.Stop()
  485. s.miner.Stop()
  486. s.eventMux.Stop()
  487. s.chainDb.Close()
  488. close(s.shutdownChan)
  489. return nil
  490. }