backend.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. SetBloomBitsIndexer(bbIndexer *core.ChainIndexer)
  54. }
  55. // Ethereum implements the Ethereum full node service.
  56. type Ethereum struct {
  57. config *Config
  58. chainConfig *params.ChainConfig
  59. // Channel for shutting down the service
  60. shutdownChan chan bool // Channel for shutting down the ethereum
  61. stopDbUpgrade func() error // stop chain db sequential key upgrade
  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. if config.SyncMode == downloader.LightSync {
  90. return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum")
  91. }
  92. if !config.SyncMode.IsValid() {
  93. return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode)
  94. }
  95. chainDb, err := CreateDB(ctx, config, "chaindata")
  96. if err != nil {
  97. return nil, err
  98. }
  99. stopDbUpgrade := upgradeDeduplicateData(chainDb)
  100. chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
  101. if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
  102. return nil, genesisErr
  103. }
  104. log.Info("Initialised chain configuration", "config", chainConfig)
  105. eth := &Ethereum{
  106. config: config,
  107. chainDb: chainDb,
  108. chainConfig: chainConfig,
  109. eventMux: ctx.EventMux,
  110. accountManager: ctx.AccountManager,
  111. engine: CreateConsensusEngine(ctx, &config.Ethash, chainConfig, chainDb),
  112. shutdownChan: make(chan bool),
  113. stopDbUpgrade: stopDbUpgrade,
  114. networkId: config.NetworkId,
  115. gasPrice: config.GasPrice,
  116. etherbase: config.Etherbase,
  117. bloomRequests: make(chan chan *bloombits.Retrieval),
  118. bloomIndexer: NewBloomIndexer(chainDb, params.BloomBitsBlocks),
  119. }
  120. log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)
  121. if !config.SkipBcVersionCheck {
  122. bcVersion := core.GetBlockChainVersion(chainDb)
  123. if bcVersion != core.BlockChainVersion && bcVersion != 0 {
  124. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion)
  125. }
  126. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  127. }
  128. var (
  129. vmConfig = vm.Config{EnablePreimageRecording: config.EnablePreimageRecording}
  130. cacheConfig = &core.CacheConfig{Disabled: config.NoPruning, TrieNodeLimit: config.TrieCache, TrieTimeLimit: config.TrieTimeout}
  131. )
  132. eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, eth.chainConfig, eth.engine, vmConfig)
  133. if err != nil {
  134. return nil, err
  135. }
  136. // Rewind the chain in case of an incompatible config upgrade.
  137. if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
  138. log.Warn("Rewinding chain to upgrade configuration", "err", compat)
  139. eth.blockchain.SetHead(compat.RewindTo)
  140. core.WriteChainConfig(chainDb, genesisHash, chainConfig)
  141. }
  142. eth.bloomIndexer.Start(eth.blockchain)
  143. if config.TxPool.Journal != "" {
  144. config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal)
  145. }
  146. eth.txPool = core.NewTxPool(config.TxPool, eth.chainConfig, eth.blockchain)
  147. if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.SyncMode, config.NetworkId, 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 err != nil {
  180. return nil, err
  181. }
  182. if db, ok := db.(*ethdb.LDBDatabase); ok {
  183. db.Meter("eth/db/chaindata/")
  184. }
  185. return db, nil
  186. }
  187. // CreateConsensusEngine creates the required type of consensus engine instance for an Ethereum service
  188. func CreateConsensusEngine(ctx *node.ServiceContext, config *ethash.Config, chainConfig *params.ChainConfig, db ethdb.Database) consensus.Engine {
  189. // If proof-of-authority is requested, set it up
  190. if chainConfig.Clique != nil {
  191. return clique.New(chainConfig.Clique, db)
  192. }
  193. // Otherwise assume proof-of-work
  194. switch {
  195. case config.PowMode == ethash.ModeFake:
  196. log.Warn("Ethash used in fake mode")
  197. return ethash.NewFaker()
  198. case config.PowMode == ethash.ModeTest:
  199. log.Warn("Ethash used in test mode")
  200. return ethash.NewTester()
  201. case config.PowMode == ethash.ModeShared:
  202. log.Warn("Ethash used in shared mode")
  203. return ethash.NewShared()
  204. default:
  205. engine := ethash.New(ethash.Config{
  206. CacheDir: ctx.ResolvePath(config.CacheDir),
  207. CachesInMem: config.CachesInMem,
  208. CachesOnDisk: config.CachesOnDisk,
  209. DatasetDir: config.DatasetDir,
  210. DatasetsInMem: config.DatasetsInMem,
  211. DatasetsOnDisk: config.DatasetsOnDisk,
  212. })
  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)
  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. s.lock.RLock()
  276. etherbase := s.etherbase
  277. s.lock.RUnlock()
  278. if etherbase != (common.Address{}) {
  279. return etherbase, nil
  280. }
  281. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  282. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  283. etherbase := accounts[0].Address
  284. s.lock.Lock()
  285. s.etherbase = etherbase
  286. s.lock.Unlock()
  287. log.Info("Etherbase automatically configured", "address", etherbase)
  288. return etherbase, nil
  289. }
  290. }
  291. return common.Address{}, fmt.Errorf("etherbase must be explicitly specified")
  292. }
  293. // set in js console via admin interface or wrapper from cli flags
  294. func (self *Ethereum) SetEtherbase(etherbase common.Address) {
  295. self.lock.Lock()
  296. self.etherbase = etherbase
  297. self.lock.Unlock()
  298. self.miner.SetEtherbase(etherbase)
  299. }
  300. func (s *Ethereum) StartMining(local bool) error {
  301. eb, err := s.Etherbase()
  302. if err != nil {
  303. log.Error("Cannot start mining without etherbase", "err", err)
  304. return fmt.Errorf("etherbase missing: %v", err)
  305. }
  306. if clique, ok := s.engine.(*clique.Clique); ok {
  307. wallet, err := s.accountManager.Find(accounts.Account{Address: eb})
  308. if wallet == nil || err != nil {
  309. log.Error("Etherbase account unavailable locally", "err", err)
  310. return fmt.Errorf("signer missing: %v", err)
  311. }
  312. clique.Authorize(eb, wallet.SignHash)
  313. }
  314. if local {
  315. // If local (CPU) mining is started, we can disable the transaction rejection
  316. // mechanism introduced to speed sync times. CPU mining on mainnet is ludicrous
  317. // so noone will ever hit this path, whereas marking sync done on CPU mining
  318. // will ensure that private networks work in single miner mode too.
  319. atomic.StoreUint32(&s.protocolManager.acceptTxs, 1)
  320. }
  321. go s.miner.Start(eb)
  322. return nil
  323. }
  324. func (s *Ethereum) StopMining() { s.miner.Stop() }
  325. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  326. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  327. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  328. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  329. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  330. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  331. func (s *Ethereum) Engine() consensus.Engine { return s.engine }
  332. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  333. func (s *Ethereum) IsListening() bool { return true } // Always listening
  334. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  335. func (s *Ethereum) NetVersion() uint64 { return s.networkId }
  336. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  337. // Protocols implements node.Service, returning all the currently configured
  338. // network protocols to start.
  339. func (s *Ethereum) Protocols() []p2p.Protocol {
  340. if s.lesServer == nil {
  341. return s.protocolManager.SubProtocols
  342. }
  343. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  344. }
  345. // Start implements node.Service, starting all internal goroutines needed by the
  346. // Ethereum protocol implementation.
  347. func (s *Ethereum) Start(srvr *p2p.Server) error {
  348. // Start the bloom bits servicing goroutines
  349. s.startBloomHandlers()
  350. // Start the RPC service
  351. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  352. // Figure out a max peers count based on the server limits
  353. maxPeers := srvr.MaxPeers
  354. if s.config.LightServ > 0 {
  355. if s.config.LightPeers >= srvr.MaxPeers {
  356. return fmt.Errorf("invalid peer config: light peer count (%d) >= total peer count (%d)", s.config.LightPeers, srvr.MaxPeers)
  357. }
  358. maxPeers -= s.config.LightPeers
  359. }
  360. // Start the networking layer and the light server if requested
  361. s.protocolManager.Start(maxPeers)
  362. if s.lesServer != nil {
  363. s.lesServer.Start(srvr)
  364. }
  365. return nil
  366. }
  367. // Stop implements node.Service, terminating all internal goroutines used by the
  368. // Ethereum protocol.
  369. func (s *Ethereum) Stop() error {
  370. if s.stopDbUpgrade != nil {
  371. s.stopDbUpgrade()
  372. }
  373. s.bloomIndexer.Close()
  374. s.blockchain.Stop()
  375. s.protocolManager.Stop()
  376. if s.lesServer != nil {
  377. s.lesServer.Stop()
  378. }
  379. s.txPool.Stop()
  380. s.miner.Stop()
  381. s.eventMux.Stop()
  382. s.chainDb.Close()
  383. close(s.shutdownChan)
  384. return nil
  385. }