backend.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. // Assemble the Ethereum object
  101. chainDb, err := CreateDB(ctx, config, "chaindata")
  102. if err != nil {
  103. return nil, err
  104. }
  105. chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
  106. if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
  107. return nil, genesisErr
  108. }
  109. log.Info("Initialised chain configuration", "config", chainConfig)
  110. eth := &Ethereum{
  111. config: config,
  112. chainDb: chainDb,
  113. chainConfig: chainConfig,
  114. eventMux: ctx.EventMux,
  115. accountManager: ctx.AccountManager,
  116. engine: CreateConsensusEngine(ctx, chainConfig, &config.Ethash, config.MinerNotify, config.MinerNoverify, chainDb),
  117. shutdownChan: make(chan bool),
  118. networkID: config.NetworkId,
  119. gasPrice: config.MinerGasPrice,
  120. etherbase: config.Etherbase,
  121. bloomRequests: make(chan chan *bloombits.Retrieval),
  122. bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks, params.BloomConfirms),
  123. }
  124. log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)
  125. if !config.SkipBcVersionCheck {
  126. bcVersion := rawdb.ReadDatabaseVersion(chainDb)
  127. if bcVersion != core.BlockChainVersion && bcVersion != 0 {
  128. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d).\n", bcVersion, core.BlockChainVersion)
  129. }
  130. rawdb.WriteDatabaseVersion(chainDb, core.BlockChainVersion)
  131. }
  132. var (
  133. vmConfig = vm.Config{EnablePreimageRecording: config.EnablePreimageRecording}
  134. cacheConfig = &core.CacheConfig{Disabled: config.NoPruning, TrieNodeLimit: config.TrieCache, TrieTimeLimit: config.TrieTimeout}
  135. )
  136. eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, eth.chainConfig, eth.engine, vmConfig)
  137. if err != nil {
  138. return nil, err
  139. }
  140. // Rewind the chain in case of an incompatible config upgrade.
  141. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  142. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  143. eth.blockchain.SetHead(compat.RewindTo)
  144. rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
  145. }
  146. eth.bloomIndexer.Start(eth.blockchain)
  147. if config.TxPool.Journal != "" {
  148. config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal)
  149. }
  150. eth.txPool = core.NewTxPool(config.TxPool, eth.chainConfig, eth.blockchain)
  151. if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb); err != nil {
  152. return nil, err
  153. }
  154. eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.engine, config.MinerRecommit, config.MinerGasFloor, config.MinerGasCeil)
  155. eth.miner.SetExtra(makeExtraData(config.MinerExtraData))
  156. eth.APIBackend = &EthAPIBackend{eth, nil}
  157. gpoParams := config.GPO
  158. if gpoParams.Default == nil {
  159. gpoParams.Default = config.MinerGasPrice
  160. }
  161. eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams)
  162. return eth, nil
  163. }
  164. func makeExtraData(extra []byte) []byte {
  165. if len(extra) == 0 {
  166. // create default extradata
  167. extra, _ = rlp.EncodeToBytes([]interface{}{
  168. uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch),
  169. "geth",
  170. runtime.Version(),
  171. runtime.GOOS,
  172. })
  173. }
  174. if uint64(len(extra)) > params.MaximumExtraDataSize {
  175. log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize)
  176. extra = nil
  177. }
  178. return extra
  179. }
  180. // CreateDB creates the chain database.
  181. func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) {
  182. db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles)
  183. if err != nil {
  184. return nil, err
  185. }
  186. if db, ok := db.(*ethdb.LDBDatabase); ok {
  187. db.Meter("eth/db/chaindata/")
  188. }
  189. return db, nil
  190. }
  191. // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
  192. func CreateConsensusEngine(ctx *node.ServiceContext, chainConfig *params.ChainConfig, config *ethash.Config, notify []string, noverify bool, db ethdb.Database) consensus.Engine {
  193. // If proof-of-authority is requested, set it up
  194. if chainConfig.Clique != nil {
  195. return clique.New(chainConfig.Clique, db)
  196. }
  197. // Otherwise assume proof-of-work
  198. switch config.PowMode {
  199. case ethash.ModeFake:
  200. log.Warn("Ethash used in fake mode")
  201. return ethash.NewFaker()
  202. case ethash.ModeTest:
  203. log.Warn("Ethash used in test mode")
  204. return ethash.NewTester(nil, noverify)
  205. case ethash.ModeShared:
  206. log.Warn("Ethash used in shared mode")
  207. return ethash.NewShared()
  208. default:
  209. engine := ethash.New(ethash.Config{
  210. CacheDir: ctx.ResolvePath(config.CacheDir),
  211. CachesInMem: config.CachesInMem,
  212. CachesOnDisk: config.CachesOnDisk,
  213. DatasetDir: config.DatasetDir,
  214. DatasetsInMem: config.DatasetsInMem,
  215. DatasetsOnDisk: config.DatasetsOnDisk,
  216. }, notify, noverify)
  217. engine.SetThreads(-1) // Disable CPU mining
  218. return engine
  219. }
  220. }
  221. // APIs return the collection of RPC services the ethereum package offers.
  222. // NOTE, some of these services probably need to be moved to somewhere else.
  223. func (s *Ethereum) APIs() []rpc.API {
  224. apis := ethapi.GetAPIs(s.APIBackend)
  225. // Append any APIs exposed explicitly by the consensus engine
  226. apis = append(apis, s.engine.APIs(s.BlockChain())...)
  227. // Append all the local APIs and return
  228. return append(apis, []rpc.API{
  229. {
  230. Namespace: "eth",
  231. Version: "1.0",
  232. Service: NewPublicEthereumAPI(s),
  233. Public: true,
  234. }, {
  235. Namespace: "eth",
  236. Version: "1.0",
  237. Service: NewPublicMinerAPI(s),
  238. Public: true,
  239. }, {
  240. Namespace: "eth",
  241. Version: "1.0",
  242. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  243. Public: true,
  244. }, {
  245. Namespace: "miner",
  246. Version: "1.0",
  247. Service: NewPrivateMinerAPI(s),
  248. Public: false,
  249. }, {
  250. Namespace: "eth",
  251. Version: "1.0",
  252. Service: filters.NewPublicFilterAPI(s.APIBackend, false),
  253. Public: true,
  254. }, {
  255. Namespace: "admin",
  256. Version: "1.0",
  257. Service: NewPrivateAdminAPI(s),
  258. }, {
  259. Namespace: "debug",
  260. Version: "1.0",
  261. Service: NewPublicDebugAPI(s),
  262. Public: true,
  263. }, {
  264. Namespace: "debug",
  265. Version: "1.0",
  266. Service: NewPrivateDebugAPI(s.chainConfig, s),
  267. }, {
  268. Namespace: "net",
  269. Version: "1.0",
  270. Service: s.netRPCService,
  271. Public: true,
  272. },
  273. }...)
  274. }
  275. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  276. s.blockchain.ResetWithGenesisBlock(gb)
  277. }
  278. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  279. s.lock.RLock()
  280. etherbase := s.etherbase
  281. s.lock.RUnlock()
  282. if etherbase != (common.Address{}) {
  283. return etherbase, nil
  284. }
  285. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  286. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  287. etherbase := accounts[0].Address
  288. s.lock.Lock()
  289. s.etherbase = etherbase
  290. s.lock.Unlock()
  291. log.Info("Etherbase automatically configured", "address", etherbase)
  292. return etherbase, nil
  293. }
  294. }
  295. return common.Address{}, fmt.Errorf("etherbase must be explicitly specified")
  296. }
  297. // SetEtherbase sets the mining reward address.
  298. func (s *Ethereum) SetEtherbase(etherbase common.Address) {
  299. s.lock.Lock()
  300. s.etherbase = etherbase
  301. s.lock.Unlock()
  302. s.miner.SetEtherbase(etherbase)
  303. }
  304. // StartMining starts the miner with the given number of CPU threads. If mining
  305. // is already running, this method adjust the number of threads allowed to use
  306. // and updates the minimum price required by the transaction pool.
  307. func (s *Ethereum) StartMining(threads int) error {
  308. // Update the thread count within the consensus engine
  309. type threaded interface {
  310. SetThreads(threads int)
  311. }
  312. if th, ok := s.engine.(threaded); ok {
  313. log.Info("Updated mining threads", "threads", threads)
  314. if threads == 0 {
  315. threads = -1 // Disable the miner from within
  316. }
  317. th.SetThreads(threads)
  318. }
  319. // If the miner was not running, initialize it
  320. if !s.IsMining() {
  321. // Propagate the initial price point to the transaction pool
  322. s.lock.RLock()
  323. price := s.gasPrice
  324. s.lock.RUnlock()
  325. s.txPool.SetGasPrice(price)
  326. // Configure the local mining addess
  327. eb, err := s.Etherbase()
  328. if err != nil {
  329. log.Error("Cannot start mining without etherbase", "err", err)
  330. return fmt.Errorf("etherbase missing: %v", err)
  331. }
  332. if clique, ok := s.engine.(*clique.Clique); ok {
  333. wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
  334. if wallet == nil || err != nil {
  335. log.Error("Etherbase account unavailable locally", "err", err)
  336. return fmt.Errorf("signer missing: %v", err)
  337. }
  338. clique.Authorize(eb, wallet.SignHash)
  339. }
  340. // If mining is started, we can disable the transaction rejection mechanism
  341. // introduced to speed sync times.
  342. atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
  343. go s.miner.Start(eb)
  344. }
  345. return nil
  346. }
  347. // StopMining terminates the miner, both at the consensus engine level as well as
  348. // at the block creation level.
  349. func (s *Ethereum) StopMining() {
  350. // Update the thread count within the consensus engine
  351. type threaded interface {
  352. SetThreads(threads int)
  353. }
  354. if th, ok := s.engine.(threaded); ok {
  355. th.SetThreads(-1)
  356. }
  357. // Stop the block creating itself
  358. s.miner.Stop()
  359. }
  360. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  361. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  362. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  363. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  364. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  365. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  366. func (s *Ethereum) Engine() consensus.Engine { return s.engine }
  367. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  368. func (s *Ethereum) IsListening() bool { return true } // Always listening
  369. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  370. func (s *Ethereum) NetVersion() uint64 { return s.networkID }
  371. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  372. // Protocols implements node.Service, returning all the currently configured
  373. // network protocols to start.
  374. func (s *Ethereum) Protocols() []p2p.Protocol {
  375. if s.lesServer == nil {
  376. return s.protocolManager.SubProtocols
  377. }
  378. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  379. }
  380. // Start implements node.Service, starting all internal goroutines needed by the
  381. // Ethereum protocol implementation.
  382. func (s *Ethereum) Start(srvr *p2p.Server) error {
  383. // Start the bloom bits servicing goroutines
  384. s.startBloomHandlers(params.BloomBitsBlocks)
  385. // Start the RPC service
  386. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  387. // Figure out a max peers count based on the server limits
  388. maxPeers := srvr.MaxPeers
  389. if s.config.LightServ > 0 {
  390. if s.config.LightPeers >= srvr.MaxPeers {
  391. return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, srvr.MaxPeers)
  392. }
  393. maxPeers -= s.config.LightPeers
  394. }
  395. // Start the networking layer and the light server if requested
  396. s.protocolManager.Start(maxPeers)
  397. if s.lesServer != nil {
  398. s.lesServer.Start(srvr)
  399. }
  400. return nil
  401. }
  402. // Stop implements node.Service, terminating all internal goroutines used by the
  403. // Ethereum protocol.
  404. func (s *Ethereum) Stop() error {
  405. s.bloomIndexer.Close()
  406. s.blockchain.Stop()
  407. s.engine.Close()
  408. s.protocolManager.Stop()
  409. if s.lesServer != nil {
  410. s.lesServer.Stop()
  411. }
  412. s.txPool.Stop()
  413. s.miner.Stop()
  414. s.eventMux.Stop()
  415. s.chainDb.Close()
  416. close(s.shutdownChan)
  417. return nil
  418. }