backend.go 13 KB

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