backend.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. "sync/atomic"
  24. "github.com/ethereum/go-ethereum/accounts"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/consensus"
  27. "github.com/ethereum/go-ethereum/consensus/ethash"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/core/vm"
  31. "github.com/ethereum/go-ethereum/eth/downloader"
  32. "github.com/ethereum/go-ethereum/eth/filters"
  33. "github.com/ethereum/go-ethereum/eth/gasprice"
  34. "github.com/ethereum/go-ethereum/ethdb"
  35. "github.com/ethereum/go-ethereum/event"
  36. "github.com/ethereum/go-ethereum/internal/ethapi"
  37. "github.com/ethereum/go-ethereum/log"
  38. "github.com/ethereum/go-ethereum/miner"
  39. "github.com/ethereum/go-ethereum/node"
  40. "github.com/ethereum/go-ethereum/p2p"
  41. "github.com/ethereum/go-ethereum/params"
  42. "github.com/ethereum/go-ethereum/rpc"
  43. )
  44. var (
  45. datadirInUseErrnos = map[uint]bool{11: true, 32: true, 35: true}
  46. portInUseErrRE = regexp.MustCompile("address already in use")
  47. )
  48. type Config struct {
  49. // The genesis block, which is inserted if the database is empty.
  50. // If nil, the Ethereum main net block is used.
  51. Genesis *core.Genesis
  52. NetworkId int // Network ID to use for selecting peers to connect to
  53. FastSync bool // Enables the state download based fast synchronisation algorithm
  54. LightMode bool // Running in light client mode
  55. LightServ int // Maximum percentage of time allowed for serving LES requests
  56. LightPeers int // Maximum number of LES client peers
  57. MaxPeers int // Maximum number of global peers
  58. SkipBcVersionCheck bool // e.g. blockchain export
  59. DatabaseCache int
  60. DatabaseHandles int
  61. DocRoot string
  62. PowFake bool
  63. PowTest bool
  64. PowShared bool
  65. ExtraData []byte
  66. EthashCacheDir string
  67. EthashCachesInMem int
  68. EthashCachesOnDisk int
  69. EthashDatasetDir string
  70. EthashDatasetsInMem int
  71. EthashDatasetsOnDisk int
  72. Etherbase common.Address
  73. GasPrice *big.Int
  74. MinerThreads int
  75. SolcPath string
  76. GpoBlocks int
  77. GpoPercentile int
  78. EnablePreimageRecording bool
  79. }
  80. type LesServer interface {
  81. Start(srvr *p2p.Server)
  82. Stop()
  83. Protocols() []p2p.Protocol
  84. }
  85. // Ethereum implements the Ethereum full node service.
  86. type Ethereum struct {
  87. chainConfig *params.ChainConfig
  88. // Channel for shutting down the service
  89. shutdownChan chan bool // Channel for shutting down the ethereum
  90. stopDbUpgrade func() // stop chain db sequential key upgrade
  91. // Handlers
  92. txPool *core.TxPool
  93. txMu sync.Mutex
  94. blockchain *core.BlockChain
  95. protocolManager *ProtocolManager
  96. lesServer LesServer
  97. // DB interfaces
  98. chainDb ethdb.Database // Block chain database
  99. eventMux *event.TypeMux
  100. engine consensus.Engine
  101. accountManager *accounts.Manager
  102. ApiBackend *EthApiBackend
  103. miner *miner.Miner
  104. Mining bool
  105. MinerThreads int
  106. etherbase common.Address
  107. solcPath string
  108. netVersionId int
  109. netRPCService *ethapi.PublicNetAPI
  110. }
  111. func (s *Ethereum) AddLesServer(ls LesServer) {
  112. s.lesServer = ls
  113. s.protocolManager.lesServer = ls
  114. }
  115. // New creates a new Ethereum object (including the
  116. // initialisation of the common Ethereum object)
  117. func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
  118. chainDb, err := CreateDB(ctx, config, "chaindata")
  119. if err != nil {
  120. return nil, err
  121. }
  122. stopDbUpgrade := upgradeSequentialKeys(chainDb)
  123. chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
  124. if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
  125. return nil, genesisErr
  126. }
  127. log.Info("Initialised chain configuration", "config", chainConfig)
  128. eth := &Ethereum{
  129. chainDb: chainDb,
  130. chainConfig: chainConfig,
  131. eventMux: ctx.EventMux,
  132. accountManager: ctx.AccountManager,
  133. engine: CreateConsensusEngine(ctx, config, chainConfig, chainDb),
  134. shutdownChan: make(chan bool),
  135. stopDbUpgrade: stopDbUpgrade,
  136. netVersionId: config.NetworkId,
  137. etherbase: config.Etherbase,
  138. MinerThreads: config.MinerThreads,
  139. solcPath: config.SolcPath,
  140. }
  141. if err := addMipmapBloomBins(chainDb); err != nil {
  142. return nil, err
  143. }
  144. log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)
  145. if !config.SkipBcVersionCheck {
  146. bcVersion := core.GetBlockChainVersion(chainDb)
  147. if bcVersion != core.BlockChainVersion && bcVersion != 0 {
  148. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion)
  149. }
  150. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  151. }
  152. vmConfig := vm.Config{EnablePreimageRecording: config.EnablePreimageRecording}
  153. eth.blockchain, err = core.NewBlockChain(chainDb, eth.chainConfig, eth.engine, eth.eventMux, vmConfig)
  154. if err != nil {
  155. return nil, err
  156. }
  157. // Rewind the chain in case of an incompatible config upgrade.
  158. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  159. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  160. eth.blockchain.SetHead(compat.RewindTo)
  161. core.WriteChainConfig(chainDb, genesisHash, chainConfig)
  162. }
  163. newPool := core.NewTxPool(eth.chainConfig, eth.EventMux(), eth.blockchain.State, eth.blockchain.GasLimit)
  164. eth.txPool = newPool
  165. maxPeers := config.MaxPeers
  166. if config.LightServ > 0 {
  167. // if we are running a light server, limit the number of ETH peers so that we reserve some space for incoming LES connections
  168. // temporary solution until the new peer connectivity API is finished
  169. halfPeers := maxPeers / 2
  170. maxPeers -= config.LightPeers
  171. if maxPeers < halfPeers {
  172. maxPeers = halfPeers
  173. }
  174. }
  175. if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.FastSync, config.NetworkId, maxPeers, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb); err != nil {
  176. return nil, err
  177. }
  178. eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.engine)
  179. eth.miner.SetGasPrice(config.GasPrice)
  180. eth.miner.SetExtra(config.ExtraData)
  181. eth.ApiBackend = &EthApiBackend{eth, nil}
  182. gpoParams := gasprice.Config{
  183. Blocks: config.GpoBlocks,
  184. Percentile: config.GpoPercentile,
  185. Default: config.GasPrice,
  186. }
  187. eth.ApiBackend.gpo = gasprice.NewOracle(eth.ApiBackend, gpoParams)
  188. return eth, nil
  189. }
  190. // CreateDB creates the chain database.
  191. func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) {
  192. db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles)
  193. if db, ok := db.(*ethdb.LDBDatabase); ok {
  194. db.Meter("eth/db/chaindata/")
  195. }
  196. return db, err
  197. }
  198. // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
  199. func CreateConsensusEngine(ctx *node.ServiceContext, config *Config, chainConfig *params.ChainConfig, db ethdb.Database) consensus.Engine {
  200. switch {
  201. case config.PowFake:
  202. log.Warn("Ethash used in fake mode")
  203. return ethash.NewFaker()
  204. case config.PowTest:
  205. log.Warn("Ethash used in test mode")
  206. return ethash.NewTester()
  207. case config.PowShared:
  208. log.Warn("Ethash used in shared mode")
  209. return ethash.NewShared()
  210. default:
  211. engine := ethash.New(ctx.ResolvePath(config.EthashCacheDir), config.EthashCachesInMem, config.EthashCachesOnDisk,
  212. config.EthashDatasetDir, config.EthashDatasetsInMem, config.EthashDatasetsOnDisk)
  213. engine.SetThreads(-1) // Disable CPU mining
  214. return engine
  215. }
  216. }
  217. // APIs returns the collection of RPC services the ethereum package offers.
  218. // NOTE, some of these services probably need to be moved to somewhere else.
  219. func (s *Ethereum) APIs() []rpc.API {
  220. apis := ethapi.GetAPIs(s.ApiBackend, s.solcPath)
  221. // Append any APIs exposed explicitly by the consensus engine
  222. apis = append(apis, s.engine.APIs(s.BlockChain())...)
  223. // Append all the local APIs and return
  224. return append(apis, []rpc.API{
  225. {
  226. Namespace: "eth",
  227. Version: "1.0",
  228. Service: NewPublicEthereumAPI(s),
  229. Public: true,
  230. }, {
  231. Namespace: "eth",
  232. Version: "1.0",
  233. Service: NewPublicMinerAPI(s),
  234. Public: true,
  235. }, {
  236. Namespace: "eth",
  237. Version: "1.0",
  238. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  239. Public: true,
  240. }, {
  241. Namespace: "miner",
  242. Version: "1.0",
  243. Service: NewPrivateMinerAPI(s),
  244. Public: false,
  245. }, {
  246. Namespace: "eth",
  247. Version: "1.0",
  248. Service: filters.NewPublicFilterAPI(s.ApiBackend, false),
  249. Public: true,
  250. }, {
  251. Namespace: "admin",
  252. Version: "1.0",
  253. Service: NewPrivateAdminAPI(s),
  254. }, {
  255. Namespace: "debug",
  256. Version: "1.0",
  257. Service: NewPublicDebugAPI(s),
  258. Public: true,
  259. }, {
  260. Namespace: "debug",
  261. Version: "1.0",
  262. Service: NewPrivateDebugAPI(s.chainConfig, s),
  263. }, {
  264. Namespace: "net",
  265. Version: "1.0",
  266. Service: s.netRPCService,
  267. Public: true,
  268. },
  269. }...)
  270. }
  271. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  272. s.blockchain.ResetWithGenesisBlock(gb)
  273. }
  274. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  275. if s.etherbase != (common.Address{}) {
  276. return s.etherbase, nil
  277. }
  278. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  279. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  280. return accounts[0].Address, nil
  281. }
  282. }
  283. return common.Address{}, fmt.Errorf("etherbase address must be explicitly specified")
  284. }
  285. // set in js console via admin interface or wrapper from cli flags
  286. func (self *Ethereum) SetEtherbase(etherbase common.Address) {
  287. self.etherbase = etherbase
  288. self.miner.SetEtherbase(etherbase)
  289. }
  290. func (s *Ethereum) StartMining(local bool) error {
  291. eb, err := s.Etherbase()
  292. if err != nil {
  293. log.Error("Cannot start mining without etherbase", "err", err)
  294. return fmt.Errorf("etherbase missing: %v", err)
  295. }
  296. if local {
  297. // If local (CPU) mining is started, we can disable the transaction rejection
  298. // mechanism introduced to speed sync times. CPU mining on mainnet is ludicrous
  299. // so noone will ever hit this path, whereas marking sync done on CPU mining
  300. // will ensure that private networks work in single miner mode too.
  301. atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
  302. }
  303. go s.miner.Start(eb)
  304. return nil
  305. }
  306. func (s *Ethereum) StopMining() { s.miner.Stop() }
  307. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  308. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  309. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  310. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  311. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  312. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  313. func (s *Ethereum) Engine() consensus.Engine { return s.engine }
  314. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  315. func (s *Ethereum) IsListening() bool { return true } // Always listening
  316. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  317. func (s *Ethereum) NetVersion() int { return s.netVersionId }
  318. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  319. // Protocols implements node.Service, returning all the currently configured
  320. // network protocols to start.
  321. func (s *Ethereum) Protocols() []p2p.Protocol {
  322. if s.lesServer == nil {
  323. return s.protocolManager.SubProtocols
  324. } else {
  325. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  326. }
  327. }
  328. // Start implements node.Service, starting all internal goroutines needed by the
  329. // Ethereum protocol implementation.
  330. func (s *Ethereum) Start(srvr *p2p.Server) error {
  331. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  332. s.protocolManager.Start()
  333. if s.lesServer != nil {
  334. s.lesServer.Start(srvr)
  335. }
  336. return nil
  337. }
  338. // Stop implements node.Service, terminating all internal goroutines used by the
  339. // Ethereum protocol.
  340. func (s *Ethereum) Stop() error {
  341. if s.stopDbUpgrade != nil {
  342. s.stopDbUpgrade()
  343. }
  344. s.blockchain.Stop()
  345. s.protocolManager.Stop()
  346. if s.lesServer != nil {
  347. s.lesServer.Stop()
  348. }
  349. s.txPool.Stop()
  350. s.miner.Stop()
  351. s.eventMux.Stop()
  352. s.chainDb.Close()
  353. close(s.shutdownChan)
  354. return nil
  355. }
  356. // This function will wait for a shutdown and resumes main thread execution
  357. func (s *Ethereum) WaitForShutdown() {
  358. <-s.shutdownChan
  359. }