backend.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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/types"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/eth/downloader"
  36. "github.com/ethereum/go-ethereum/eth/filters"
  37. "github.com/ethereum/go-ethereum/eth/gasprice"
  38. "github.com/ethereum/go-ethereum/ethdb"
  39. "github.com/ethereum/go-ethereum/event"
  40. "github.com/ethereum/go-ethereum/internal/ethapi"
  41. "github.com/ethereum/go-ethereum/log"
  42. "github.com/ethereum/go-ethereum/miner"
  43. "github.com/ethereum/go-ethereum/node"
  44. "github.com/ethereum/go-ethereum/p2p"
  45. "github.com/ethereum/go-ethereum/params"
  46. "github.com/ethereum/go-ethereum/rlp"
  47. "github.com/ethereum/go-ethereum/rpc"
  48. )
  49. type LesServer interface {
  50. Start(srvr *p2p.Server)
  51. Stop()
  52. Protocols() []p2p.Protocol
  53. }
  54. // Ethereum implements the Ethereum full node service.
  55. type Ethereum struct {
  56. config *Config
  57. chainConfig *params.ChainConfig
  58. // Channel for shutting down the service
  59. shutdownChan chan bool // Channel for shutting down the ethereum
  60. stopDbUpgrade func() error // stop chain db sequential key upgrade
  61. // Handlers
  62. txPool *core.TxPool
  63. blockchain *core.BlockChain
  64. protocolManager *ProtocolManager
  65. lesServer LesServer
  66. // DB interfaces
  67. chainDb ethdb.Database // Block chain database
  68. eventMux *event.TypeMux
  69. engine consensus.Engine
  70. accountManager *accounts.Manager
  71. bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
  72. bloomIndexer *core.ChainIndexer // Bloom indexer operating during block imports
  73. ApiBackend *EthApiBackend
  74. miner *miner.Miner
  75. gasPrice *big.Int
  76. etherbase common.Address
  77. networkId uint64
  78. netRPCService *ethapi.PublicNetAPI
  79. lock sync.RWMutex // Protects the variadic fields (e.g. gas price and etherbase)
  80. }
  81. func (s *Ethereum) AddLesServer(ls LesServer) {
  82. s.lesServer = ls
  83. }
  84. // New creates a new Ethereum object (including the
  85. // initialisation of the common Ethereum object)
  86. func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
  87. if config.SyncMode == downloader.LightSync {
  88. return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum")
  89. }
  90. if !config.SyncMode.IsValid() {
  91. return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode)
  92. }
  93. chainDb, err := CreateDB(ctx, config, "chaindata")
  94. if err != nil {
  95. return nil, err
  96. }
  97. stopDbUpgrade := upgradeDeduplicateData(chainDb)
  98. chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
  99. if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
  100. return nil, genesisErr
  101. }
  102. log.Info("Initialised chain configuration", "config", chainConfig)
  103. eth := &Ethereum{
  104. config: config,
  105. chainDb: chainDb,
  106. chainConfig: chainConfig,
  107. eventMux: ctx.EventMux,
  108. accountManager: ctx.AccountManager,
  109. engine: CreateConsensusEngine(ctx, config, chainConfig, chainDb),
  110. shutdownChan: make(chan bool),
  111. stopDbUpgrade: stopDbUpgrade,
  112. networkId: config.NetworkId,
  113. gasPrice: config.GasPrice,
  114. etherbase: config.Etherbase,
  115. bloomRequests: make(chan chan *bloombits.Retrieval),
  116. bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks),
  117. }
  118. log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)
  119. if !config.SkipBcVersionCheck {
  120. bcVersion := core.GetBlockChainVersion(chainDb)
  121. if bcVersion != core.BlockChainVersion && bcVersion != 0 {
  122. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion)
  123. }
  124. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  125. }
  126. vmConfig := vm.Config{EnablePreimageRecording: config.EnablePreimageRecording}
  127. eth.blockchain, err = core.NewBlockChain(chainDb, eth.chainConfig, eth.engine, vmConfig)
  128. if err != nil {
  129. return nil, err
  130. }
  131. // Rewind the chain in case of an incompatible config upgrade.
  132. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  133. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  134. eth.blockchain.SetHead(compat.RewindTo)
  135. core.WriteChainConfig(chainDb, genesisHash, chainConfig)
  136. }
  137. eth.bloomIndexer.Start(eth.blockchain.CurrentHeader(), eth.blockchain.SubscribeChainEvent)
  138. if config.TxPool.Journal != "" {
  139. config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal)
  140. }
  141. eth.txPool = core.NewTxPool(config.TxPool, eth.chainConfig, eth.blockchain)
  142. if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb); err != nil {
  143. return nil, err
  144. }
  145. eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.engine)
  146. eth.miner.SetExtra(makeExtraData(config.ExtraData))
  147. eth.ApiBackend = &EthApiBackend{eth, nil}
  148. gpoParams := config.GPO
  149. if gpoParams.Default == nil {
  150. gpoParams.Default = config.GasPrice
  151. }
  152. eth.ApiBackend.gpo = gasprice.NewOracle(eth.ApiBackend, gpoParams)
  153. return eth, nil
  154. }
  155. func makeExtraData(extra []byte) []byte {
  156. if len(extra) == 0 {
  157. // create default extradata
  158. extra, _ = rlp.EncodeToBytes([]interface{}{
  159. uint(params.VersionMajor<<16 | params.VersionMinor<<8 | params.VersionPatch),
  160. "geth",
  161. runtime.Version(),
  162. runtime.GOOS,
  163. })
  164. }
  165. if uint64(len(extra)) > params.MaximumExtraDataSize {
  166. log.Warn("Miner extra data exceed limit", "extra", hexutil.Bytes(extra), "limit", params.MaximumExtraDataSize)
  167. extra = nil
  168. }
  169. return extra
  170. }
  171. // CreateDB creates the chain database.
  172. func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) {
  173. db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles)
  174. if err != nil {
  175. return nil, err
  176. }
  177. if db, ok := db.(*ethdb.LDBDatabase); ok {
  178. db.Meter("eth/db/chaindata/")
  179. }
  180. return db, nil
  181. }
  182. // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
  183. func CreateConsensusEngine(ctx *node.ServiceContext, config *Config, chainConfig *params.ChainConfig, db ethdb.Database) consensus.Engine {
  184. // If proof-of-authority is requested, set it up
  185. if chainConfig.Clique != nil {
  186. return clique.New(chainConfig.Clique, db)
  187. }
  188. // Otherwise assume proof-of-work
  189. switch {
  190. case config.PowFake:
  191. log.Warn("Ethash used in fake mode")
  192. return ethash.NewFaker()
  193. case config.PowTest:
  194. log.Warn("Ethash used in test mode")
  195. return ethash.NewTester()
  196. case config.PowShared:
  197. log.Warn("Ethash used in shared mode")
  198. return ethash.NewShared()
  199. default:
  200. engine := ethash.New(ctx.ResolvePath(config.EthashCacheDir), config.EthashCachesInMem, config.EthashCachesOnDisk,
  201. config.EthashDatasetDir, config.EthashDatasetsInMem, config.EthashDatasetsOnDisk)
  202. engine.SetThreads(-1) // Disable CPU mining
  203. return engine
  204. }
  205. }
  206. // APIs returns the collection of RPC services the ethereum package offers.
  207. // NOTE, some of these services probably need to be moved to somewhere else.
  208. func (s *Ethereum) APIs() []rpc.API {
  209. apis := ethapi.GetAPIs(s.ApiBackend)
  210. // Append any APIs exposed explicitly by the consensus engine
  211. apis = append(apis, s.engine.APIs(s.BlockChain())...)
  212. // Append all the local APIs and return
  213. return append(apis, []rpc.API{
  214. {
  215. Namespace: "eth",
  216. Version: "1.0",
  217. Service: NewPublicEthereumAPI(s),
  218. Public: true,
  219. }, {
  220. Namespace: "eth",
  221. Version: "1.0",
  222. Service: NewPublicMinerAPI(s),
  223. Public: true,
  224. }, {
  225. Namespace: "eth",
  226. Version: "1.0",
  227. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  228. Public: true,
  229. }, {
  230. Namespace: "miner",
  231. Version: "1.0",
  232. Service: NewPrivateMinerAPI(s),
  233. Public: false,
  234. }, {
  235. Namespace: "eth",
  236. Version: "1.0",
  237. Service: filters.NewPublicFilterAPI(s.ApiBackend, false),
  238. Public: true,
  239. }, {
  240. Namespace: "admin",
  241. Version: "1.0",
  242. Service: NewPrivateAdminAPI(s),
  243. }, {
  244. Namespace: "debug",
  245. Version: "1.0",
  246. Service: NewPublicDebugAPI(s),
  247. Public: true,
  248. }, {
  249. Namespace: "debug",
  250. Version: "1.0",
  251. Service: NewPrivateDebugAPI(s.chainConfig, s),
  252. }, {
  253. Namespace: "net",
  254. Version: "1.0",
  255. Service: s.netRPCService,
  256. Public: true,
  257. },
  258. }...)
  259. }
  260. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  261. s.blockchain.ResetWithGenesisBlock(gb)
  262. }
  263. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  264. s.lock.RLock()
  265. etherbase := s.etherbase
  266. s.lock.RUnlock()
  267. if etherbase != (common.Address{}) {
  268. return etherbase, nil
  269. }
  270. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  271. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  272. return accounts[0].Address, nil
  273. }
  274. }
  275. return common.Address{}, fmt.Errorf("etherbase address must be explicitly specified")
  276. }
  277. // set in js console via admin interface or wrapper from cli flags
  278. func (self *Ethereum) SetEtherbase(etherbase common.Address) {
  279. self.lock.Lock()
  280. self.etherbase = etherbase
  281. self.lock.Unlock()
  282. self.miner.SetEtherbase(etherbase)
  283. }
  284. func (s *Ethereum) StartMining(local bool) error {
  285. eb, err := s.Etherbase()
  286. if err != nil {
  287. log.Error("Cannot start mining without etherbase", "err", err)
  288. return fmt.Errorf("etherbase missing: %v", err)
  289. }
  290. if clique, ok := s.engine.(*clique.Clique); ok {
  291. wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
  292. if wallet == nil || err != nil {
  293. log.Error("Etherbase account unavailable locally", "err", err)
  294. return fmt.Errorf("singer missing: %v", err)
  295. }
  296. clique.Authorize(eb, wallet.SignHash)
  297. }
  298. if local {
  299. // If local (CPU) mining is started, we can disable the transaction rejection
  300. // mechanism introduced to speed sync times. CPU mining on mainnet is ludicrous
  301. // so noone will ever hit this path, whereas marking sync done on CPU mining
  302. // will ensure that private networks work in single miner mode too.
  303. atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
  304. }
  305. go s.miner.Start(eb)
  306. return nil
  307. }
  308. func (s *Ethereum) StopMining() { s.miner.Stop() }
  309. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  310. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  311. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  312. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  313. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  314. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  315. func (s *Ethereum) Engine() consensus.Engine { return s.engine }
  316. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  317. func (s *Ethereum) IsListening() bool { return true } // Always listening
  318. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  319. func (s *Ethereum) NetVersion() uint64 { return s.networkId }
  320. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  321. // Protocols implements node.Service, returning all the currently configured
  322. // network protocols to start.
  323. func (s *Ethereum) Protocols() []p2p.Protocol {
  324. if s.lesServer == nil {
  325. return s.protocolManager.SubProtocols
  326. }
  327. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  328. }
  329. // Start implements node.Service, starting all internal goroutines needed by the
  330. // Ethereum protocol implementation.
  331. func (s *Ethereum) Start(srvr *p2p.Server) error {
  332. // Start the bloom bits servicing goroutines
  333. s.startBloomHandlers()
  334. // Start the RPC service
  335. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  336. // Figure out a max peers count based on the server limits
  337. maxPeers := srvr.MaxPeers
  338. if s.config.LightServ > 0 {
  339. maxPeers -= s.config.LightPeers
  340. if maxPeers < srvr.MaxPeers/2 {
  341. maxPeers = srvr.MaxPeers / 2
  342. }
  343. }
  344. // Start the networking layer and the light server if requested
  345. s.protocolManager.Start(maxPeers)
  346. if s.lesServer != nil {
  347. s.lesServer.Start(srvr)
  348. }
  349. return nil
  350. }
  351. // Stop implements node.Service, terminating all internal goroutines used by the
  352. // Ethereum protocol.
  353. func (s *Ethereum) Stop() error {
  354. if s.stopDbUpgrade != nil {
  355. s.stopDbUpgrade()
  356. }
  357. s.bloomIndexer.Close()
  358. s.blockchain.Stop()
  359. s.protocolManager.Stop()
  360. if s.lesServer != nil {
  361. s.lesServer.Stop()
  362. }
  363. s.txPool.Stop()
  364. s.miner.Stop()
  365. s.eventMux.Stop()
  366. s.chainDb.Close()
  367. close(s.shutdownChan)
  368. return nil
  369. }