backend.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. "fmt"
  20. "math/big"
  21. "regexp"
  22. "sync"
  23. "github.com/ethereum/go-ethereum/accounts"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus"
  26. "github.com/ethereum/go-ethereum/consensus/ethash"
  27. "github.com/ethereum/go-ethereum/core"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/core/vm"
  30. "github.com/ethereum/go-ethereum/eth/downloader"
  31. "github.com/ethereum/go-ethereum/eth/filters"
  32. "github.com/ethereum/go-ethereum/eth/gasprice"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/internal/ethapi"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/miner"
  38. "github.com/ethereum/go-ethereum/node"
  39. "github.com/ethereum/go-ethereum/p2p"
  40. "github.com/ethereum/go-ethereum/params"
  41. "github.com/ethereum/go-ethereum/rpc"
  42. )
  43. var (
  44. datadirInUseErrnos = map[uint]bool{11: true, 32: true, 35: true}
  45. portInUseErrRE = regexp.MustCompile("address already in use")
  46. )
  47. type Config struct {
  48. // The genesis block, which is inserted if the database is empty.
  49. // If nil, the Ethereum main net block is used.
  50. Genesis *core.Genesis
  51. NetworkId int // Network ID to use for selecting peers to connect to
  52. FastSync bool // Enables the state download based fast synchronisation algorithm
  53. LightMode bool // Running in light client mode
  54. LightServ int // Maximum percentage of time allowed for serving LES requests
  55. LightPeers int // Maximum number of LES client peers
  56. MaxPeers int // Maximum number of global peers
  57. SkipBcVersionCheck bool // e.g. blockchain export
  58. DatabaseCache int
  59. DatabaseHandles int
  60. DocRoot string
  61. PowFake bool
  62. PowTest bool
  63. PowShared bool
  64. ExtraData []byte
  65. EthashCacheDir string
  66. EthashCachesInMem int
  67. EthashCachesOnDisk int
  68. EthashDatasetDir string
  69. EthashDatasetsInMem int
  70. EthashDatasetsOnDisk int
  71. Etherbase common.Address
  72. GasPrice *big.Int
  73. MinerThreads int
  74. SolcPath string
  75. GpoMinGasPrice *big.Int
  76. GpoMaxGasPrice *big.Int
  77. GpoFullBlockRatio int
  78. GpobaseStepDown int
  79. GpobaseStepUp int
  80. GpobaseCorrectionFactor int
  81. EnablePreimageRecording bool
  82. }
  83. type LesServer interface {
  84. Start(srvr *p2p.Server)
  85. Stop()
  86. Protocols() []p2p.Protocol
  87. }
  88. // Ethereum implements the Ethereum full node service.
  89. type Ethereum struct {
  90. chainConfig *params.ChainConfig
  91. // Channel for shutting down the service
  92. shutdownChan chan bool // Channel for shutting down the ethereum
  93. stopDbUpgrade func() // stop chain db sequential key upgrade
  94. // Handlers
  95. txPool *core.TxPool
  96. txMu sync.Mutex
  97. blockchain *core.BlockChain
  98. protocolManager *ProtocolManager
  99. lesServer LesServer
  100. // DB interfaces
  101. chainDb ethdb.Database // Block chain database
  102. eventMux *event.TypeMux
  103. engine consensus.Engine
  104. accountManager *accounts.Manager
  105. ApiBackend *EthApiBackend
  106. miner *miner.Miner
  107. Mining bool
  108. MinerThreads int
  109. etherbase common.Address
  110. solcPath string
  111. netVersionId int
  112. netRPCService *ethapi.PublicNetAPI
  113. }
  114. func (s *Ethereum) AddLesServer(ls LesServer) {
  115. s.lesServer = ls
  116. s.protocolManager.lesServer = ls
  117. }
  118. // New creates a new Ethereum object (including the
  119. // initialisation of the common Ethereum object)
  120. func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
  121. chainDb, err := CreateDB(ctx, config, "chaindata")
  122. if err != nil {
  123. return nil, err
  124. }
  125. stopDbUpgrade := upgradeSequentialKeys(chainDb)
  126. chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
  127. if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
  128. return nil, genesisErr
  129. }
  130. log.Info("Initialised chain configuration", "config", chainConfig)
  131. eth := &Ethereum{
  132. chainDb: chainDb,
  133. chainConfig: chainConfig,
  134. eventMux: ctx.EventMux,
  135. accountManager: ctx.AccountManager,
  136. engine: CreateConsensusEngine(ctx, config, chainConfig, chainDb),
  137. shutdownChan: make(chan bool),
  138. stopDbUpgrade: stopDbUpgrade,
  139. netVersionId: config.NetworkId,
  140. etherbase: config.Etherbase,
  141. MinerThreads: config.MinerThreads,
  142. solcPath: config.SolcPath,
  143. }
  144. if err := addMipmapBloomBins(chainDb); err != nil {
  145. return nil, err
  146. }
  147. log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)
  148. if !config.SkipBcVersionCheck {
  149. bcVersion := core.GetBlockChainVersion(chainDb)
  150. if bcVersion != core.BlockChainVersion && bcVersion != 0 {
  151. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion)
  152. }
  153. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  154. }
  155. vmConfig := vm.Config{EnablePreimageRecording: config.EnablePreimageRecording}
  156. eth.blockchain, err = core.NewBlockChain(chainDb, eth.chainConfig, eth.engine, eth.eventMux, vmConfig)
  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. core.WriteChainConfig(chainDb, genesisHash, chainConfig)
  165. }
  166. newPool := core.NewTxPool(eth.chainConfig, eth.EventMux(), eth.blockchain.State, eth.blockchain.GasLimit)
  167. eth.txPool = newPool
  168. maxPeers := config.MaxPeers
  169. if config.LightServ > 0 {
  170. // if we are running a light server, limit the number of ETH peers so that we reserve some space for incoming LES connections
  171. // temporary solution until the new peer connectivity API is finished
  172. halfPeers := maxPeers / 2
  173. maxPeers -= config.LightPeers
  174. if maxPeers < halfPeers {
  175. maxPeers = halfPeers
  176. }
  177. }
  178. if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.FastSync, config.NetworkId, maxPeers, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb); err != nil {
  179. return nil, err
  180. }
  181. eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.engine)
  182. eth.miner.SetGasPrice(config.GasPrice)
  183. eth.miner.SetExtra(config.ExtraData)
  184. gpoParams := &gasprice.GpoParams{
  185. GpoMinGasPrice: config.GpoMinGasPrice,
  186. GpoMaxGasPrice: config.GpoMaxGasPrice,
  187. GpoFullBlockRatio: config.GpoFullBlockRatio,
  188. GpobaseStepDown: config.GpobaseStepDown,
  189. GpobaseStepUp: config.GpobaseStepUp,
  190. GpobaseCorrectionFactor: config.GpobaseCorrectionFactor,
  191. }
  192. gpo := gasprice.NewGasPriceOracle(eth.blockchain, chainDb, eth.eventMux, gpoParams)
  193. eth.ApiBackend = &EthApiBackend{eth, gpo}
  194. return eth, nil
  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 db, ok := db.(*ethdb.LDBDatabase); ok {
  200. db.Meter("eth/db/chaindata/")
  201. }
  202. return db, err
  203. }
  204. // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
  205. func CreateConsensusEngine(ctx *node.ServiceContext, config *Config, chainConfig *params.ChainConfig, db ethdb.Database) consensus.Engine {
  206. switch {
  207. case config.PowFake:
  208. log.Warn("Ethash used in fake mode")
  209. return ethash.NewFaker()
  210. case config.PowTest:
  211. log.Warn("Ethash used in test mode")
  212. return ethash.NewTester()
  213. case config.PowShared:
  214. log.Warn("Ethash used in shared mode")
  215. return ethash.NewShared()
  216. default:
  217. return ethash.New(ctx.ResolvePath(config.EthashCacheDir), config.EthashCachesInMem, config.EthashCachesOnDisk,
  218. config.EthashDatasetDir, config.EthashDatasetsInMem, config.EthashDatasetsOnDisk)
  219. }
  220. }
  221. // APIs returns 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, s.solcPath)
  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. if s.etherbase != (common.Address{}) {
  280. return s.etherbase, nil
  281. }
  282. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  283. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  284. return accounts[0].Address, nil
  285. }
  286. }
  287. return common.Address{}, fmt.Errorf("etherbase address must be explicitly specified")
  288. }
  289. // set in js console via admin interface or wrapper from cli flags
  290. func (self *Ethereum) SetEtherbase(etherbase common.Address) {
  291. self.etherbase = etherbase
  292. self.miner.SetEtherbase(etherbase)
  293. }
  294. func (s *Ethereum) StartMining() error {
  295. eb, err := s.Etherbase()
  296. if err != nil {
  297. log.Error("Cannot start mining without etherbase", "err", err)
  298. return fmt.Errorf("etherbase missing: %v", err)
  299. }
  300. go s.miner.Start(eb)
  301. return nil
  302. }
  303. func (s *Ethereum) StopMining() { s.miner.Stop() }
  304. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  305. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  306. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  307. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  308. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  309. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  310. func (s *Ethereum) Engine() consensus.Engine { return s.engine }
  311. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  312. func (s *Ethereum) IsListening() bool { return true } // Always listening
  313. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  314. func (s *Ethereum) NetVersion() int { return s.netVersionId }
  315. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  316. // Protocols implements node.Service, returning all the currently configured
  317. // network protocols to start.
  318. func (s *Ethereum) Protocols() []p2p.Protocol {
  319. if s.lesServer == nil {
  320. return s.protocolManager.SubProtocols
  321. } else {
  322. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  323. }
  324. }
  325. // Start implements node.Service, starting all internal goroutines needed by the
  326. // Ethereum protocol implementation.
  327. func (s *Ethereum) Start(srvr *p2p.Server) error {
  328. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  329. s.protocolManager.Start()
  330. if s.lesServer != nil {
  331. s.lesServer.Start(srvr)
  332. }
  333. return nil
  334. }
  335. // Stop implements node.Service, terminating all internal goroutines used by the
  336. // Ethereum protocol.
  337. func (s *Ethereum) Stop() error {
  338. if s.stopDbUpgrade != nil {
  339. s.stopDbUpgrade()
  340. }
  341. s.blockchain.Stop()
  342. s.protocolManager.Stop()
  343. if s.lesServer != nil {
  344. s.lesServer.Stop()
  345. }
  346. s.txPool.Stop()
  347. s.miner.Stop()
  348. s.eventMux.Stop()
  349. s.chainDb.Close()
  350. close(s.shutdownChan)
  351. return nil
  352. }
  353. // This function will wait for a shutdown and resumes main thread execution
  354. func (s *Ethereum) WaitForShutdown() {
  355. <-s.shutdownChan
  356. }