backend.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. "os"
  23. "path/filepath"
  24. "regexp"
  25. "strings"
  26. "sync"
  27. "time"
  28. "github.com/ethereum/ethash"
  29. "github.com/ethereum/go-ethereum/accounts"
  30. "github.com/ethereum/go-ethereum/common"
  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/pow"
  46. "github.com/ethereum/go-ethereum/rpc"
  47. )
  48. const (
  49. epochLength = 30000
  50. ethashRevision = 23
  51. autoDAGcheckInterval = 10 * time.Hour
  52. autoDAGepochHeight = epochLength / 2
  53. )
  54. var (
  55. datadirInUseErrnos = map[uint]bool{11: true, 32: true, 35: true}
  56. portInUseErrRE = regexp.MustCompile("address already in use")
  57. )
  58. type Config struct {
  59. ChainConfig *params.ChainConfig // chain configuration
  60. NetworkId int // Network ID to use for selecting peers to connect to
  61. Genesis string // Genesis JSON to seed the chain database with
  62. FastSync bool // Enables the state download based fast synchronisation algorithm
  63. LightMode bool // Running in light client mode
  64. LightServ int // Maximum percentage of time allowed for serving LES requests
  65. LightPeers int // Maximum number of LES client peers
  66. MaxPeers int // Maximum number of global peers
  67. SkipBcVersionCheck bool // e.g. blockchain export
  68. DatabaseCache int
  69. DatabaseHandles int
  70. DocRoot string
  71. AutoDAG bool
  72. PowFake bool
  73. PowTest bool
  74. PowShared bool
  75. ExtraData []byte
  76. Etherbase common.Address
  77. GasPrice *big.Int
  78. MinerThreads int
  79. SolcPath string
  80. GpoMinGasPrice *big.Int
  81. GpoMaxGasPrice *big.Int
  82. GpoFullBlockRatio int
  83. GpobaseStepDown int
  84. GpobaseStepUp int
  85. GpobaseCorrectionFactor int
  86. EnablePreimageRecording bool
  87. TestGenesisBlock *types.Block // Genesis block to seed the chain database with (testing only!)
  88. TestGenesisState ethdb.Database // Genesis state to seed the database with (testing only!)
  89. }
  90. type LesServer interface {
  91. Start(srvr *p2p.Server)
  92. Stop()
  93. Protocols() []p2p.Protocol
  94. }
  95. // Ethereum implements the Ethereum full node service.
  96. type Ethereum struct {
  97. chainConfig *params.ChainConfig
  98. // Channel for shutting down the service
  99. shutdownChan chan bool // Channel for shutting down the ethereum
  100. stopDbUpgrade func() // stop chain db sequential key upgrade
  101. // Handlers
  102. txPool *core.TxPool
  103. txMu sync.Mutex
  104. blockchain *core.BlockChain
  105. protocolManager *ProtocolManager
  106. lesServer LesServer
  107. // DB interfaces
  108. chainDb ethdb.Database // Block chain database
  109. eventMux *event.TypeMux
  110. pow pow.PoW
  111. accountManager *accounts.Manager
  112. ApiBackend *EthApiBackend
  113. miner *miner.Miner
  114. Mining bool
  115. MinerThreads int
  116. AutoDAG bool
  117. autodagquit chan bool
  118. etherbase common.Address
  119. solcPath string
  120. netVersionId int
  121. netRPCService *ethapi.PublicNetAPI
  122. }
  123. func (s *Ethereum) AddLesServer(ls LesServer) {
  124. s.lesServer = ls
  125. s.protocolManager.lesServer = ls
  126. }
  127. // New creates a new Ethereum object (including the
  128. // initialisation of the common Ethereum object)
  129. func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
  130. chainDb, err := CreateDB(ctx, config, "chaindata")
  131. if err != nil {
  132. return nil, err
  133. }
  134. stopDbUpgrade := upgradeSequentialKeys(chainDb)
  135. if err := SetupGenesisBlock(&chainDb, config); err != nil {
  136. return nil, err
  137. }
  138. pow, err := CreatePoW(config)
  139. if err != nil {
  140. return nil, err
  141. }
  142. eth := &Ethereum{
  143. chainDb: chainDb,
  144. eventMux: ctx.EventMux,
  145. accountManager: ctx.AccountManager,
  146. pow: pow,
  147. shutdownChan: make(chan bool),
  148. stopDbUpgrade: stopDbUpgrade,
  149. netVersionId: config.NetworkId,
  150. etherbase: config.Etherbase,
  151. MinerThreads: config.MinerThreads,
  152. AutoDAG: config.AutoDAG,
  153. solcPath: config.SolcPath,
  154. }
  155. if err := addMipmapBloomBins(chainDb); err != nil {
  156. return nil, err
  157. }
  158. log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)
  159. if !config.SkipBcVersionCheck {
  160. bcVersion := core.GetBlockChainVersion(chainDb)
  161. if bcVersion != core.BlockChainVersion && bcVersion != 0 {
  162. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion)
  163. }
  164. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  165. }
  166. // load the genesis block or write a new one if no genesis
  167. // block is prenent in the database.
  168. genesis := core.GetBlock(chainDb, core.GetCanonicalHash(chainDb, 0), 0)
  169. if genesis == nil {
  170. genesis, err = core.WriteDefaultGenesisBlock(chainDb)
  171. if err != nil {
  172. return nil, err
  173. }
  174. log.Warn("Wrote default Ethereum genesis block")
  175. }
  176. if config.ChainConfig == nil {
  177. return nil, errors.New("missing chain config")
  178. }
  179. core.WriteChainConfig(chainDb, genesis.Hash(), config.ChainConfig)
  180. eth.chainConfig = config.ChainConfig
  181. log.Info("Initialised chain configuration", "config", eth.chainConfig)
  182. eth.blockchain, err = core.NewBlockChain(chainDb, eth.chainConfig, eth.pow, eth.EventMux(), vm.Config{EnablePreimageRecording: config.EnablePreimageRecording})
  183. if err != nil {
  184. if err == core.ErrNoGenesis {
  185. return nil, fmt.Errorf(`No chain found. Please initialise a new chain using the "init" subcommand.`)
  186. }
  187. return nil, err
  188. }
  189. newPool := core.NewTxPool(eth.chainConfig, eth.EventMux(), eth.blockchain.State, eth.blockchain.GasLimit)
  190. eth.txPool = newPool
  191. maxPeers := config.MaxPeers
  192. if config.LightServ > 0 {
  193. // if we are running a light server, limit the number of ETH peers so that we reserve some space for incoming LES connections
  194. // temporary solution until the new peer connectivity API is finished
  195. halfPeers := maxPeers / 2
  196. maxPeers -= config.LightPeers
  197. if maxPeers < halfPeers {
  198. maxPeers = halfPeers
  199. }
  200. }
  201. if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.FastSync, config.NetworkId, maxPeers, eth.eventMux, eth.txPool, eth.pow, eth.blockchain, chainDb); err != nil {
  202. return nil, err
  203. }
  204. eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.pow)
  205. eth.miner.SetGasPrice(config.GasPrice)
  206. eth.miner.SetExtra(config.ExtraData)
  207. gpoParams := &gasprice.GpoParams{
  208. GpoMinGasPrice: config.GpoMinGasPrice,
  209. GpoMaxGasPrice: config.GpoMaxGasPrice,
  210. GpoFullBlockRatio: config.GpoFullBlockRatio,
  211. GpobaseStepDown: config.GpobaseStepDown,
  212. GpobaseStepUp: config.GpobaseStepUp,
  213. GpobaseCorrectionFactor: config.GpobaseCorrectionFactor,
  214. }
  215. gpo := gasprice.NewGasPriceOracle(eth.blockchain, chainDb, eth.eventMux, gpoParams)
  216. eth.ApiBackend = &EthApiBackend{eth, gpo}
  217. return eth, nil
  218. }
  219. // CreateDB creates the chain database.
  220. func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) {
  221. db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles)
  222. if db, ok := db.(*ethdb.LDBDatabase); ok {
  223. db.Meter("eth/db/chaindata/")
  224. }
  225. return db, err
  226. }
  227. // SetupGenesisBlock initializes the genesis block for an Ethereum service
  228. func SetupGenesisBlock(chainDb *ethdb.Database, config *Config) error {
  229. // Load up any custom genesis block if requested
  230. if len(config.Genesis) > 0 {
  231. block, err := core.WriteGenesisBlock(*chainDb, strings.NewReader(config.Genesis))
  232. if err != nil {
  233. return err
  234. }
  235. log.Info("Successfully wrote custom genesis block", "hash", block.Hash())
  236. }
  237. // Load up a test setup if directly injected
  238. if config.TestGenesisState != nil {
  239. *chainDb = config.TestGenesisState
  240. }
  241. if config.TestGenesisBlock != nil {
  242. core.WriteTd(*chainDb, config.TestGenesisBlock.Hash(), config.TestGenesisBlock.NumberU64(), config.TestGenesisBlock.Difficulty())
  243. core.WriteBlock(*chainDb, config.TestGenesisBlock)
  244. core.WriteCanonicalHash(*chainDb, config.TestGenesisBlock.Hash(), config.TestGenesisBlock.NumberU64())
  245. core.WriteHeadBlockHash(*chainDb, config.TestGenesisBlock.Hash())
  246. }
  247. return nil
  248. }
  249. // CreatePoW creates the required type of PoW instance for an Ethereum service
  250. func CreatePoW(config *Config) (pow.PoW, error) {
  251. switch {
  252. case config.PowFake:
  253. log.Warn("Ethash used in fake mode")
  254. return pow.PoW(core.FakePow{}), nil
  255. case config.PowTest:
  256. log.Warn("Ethash used in test mode")
  257. return ethash.NewForTesting()
  258. case config.PowShared:
  259. log.Warn("Ethash used in shared mode")
  260. return ethash.NewShared(), nil
  261. default:
  262. return ethash.New(), nil
  263. }
  264. }
  265. // APIs returns the collection of RPC services the ethereum package offers.
  266. // NOTE, some of these services probably need to be moved to somewhere else.
  267. func (s *Ethereum) APIs() []rpc.API {
  268. return append(ethapi.GetAPIs(s.ApiBackend, s.solcPath), []rpc.API{
  269. {
  270. Namespace: "eth",
  271. Version: "1.0",
  272. Service: NewPublicEthereumAPI(s),
  273. Public: true,
  274. }, {
  275. Namespace: "eth",
  276. Version: "1.0",
  277. Service: NewPublicMinerAPI(s),
  278. Public: true,
  279. }, {
  280. Namespace: "eth",
  281. Version: "1.0",
  282. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  283. Public: true,
  284. }, {
  285. Namespace: "miner",
  286. Version: "1.0",
  287. Service: NewPrivateMinerAPI(s),
  288. Public: false,
  289. }, {
  290. Namespace: "eth",
  291. Version: "1.0",
  292. Service: filters.NewPublicFilterAPI(s.ApiBackend, false),
  293. Public: true,
  294. }, {
  295. Namespace: "admin",
  296. Version: "1.0",
  297. Service: NewPrivateAdminAPI(s),
  298. }, {
  299. Namespace: "debug",
  300. Version: "1.0",
  301. Service: NewPublicDebugAPI(s),
  302. Public: true,
  303. }, {
  304. Namespace: "debug",
  305. Version: "1.0",
  306. Service: NewPrivateDebugAPI(s.chainConfig, s),
  307. }, {
  308. Namespace: "net",
  309. Version: "1.0",
  310. Service: s.netRPCService,
  311. Public: true,
  312. },
  313. }...)
  314. }
  315. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  316. s.blockchain.ResetWithGenesisBlock(gb)
  317. }
  318. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  319. if s.etherbase != (common.Address{}) {
  320. return s.etherbase, nil
  321. }
  322. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  323. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  324. return accounts[0].Address, nil
  325. }
  326. }
  327. return common.Address{}, fmt.Errorf("etherbase address must be explicitly specified")
  328. }
  329. // set in js console via admin interface or wrapper from cli flags
  330. func (self *Ethereum) SetEtherbase(etherbase common.Address) {
  331. self.etherbase = etherbase
  332. self.miner.SetEtherbase(etherbase)
  333. }
  334. func (s *Ethereum) StartMining(threads int) error {
  335. eb, err := s.Etherbase()
  336. if err != nil {
  337. log.Error("Cannot start mining without etherbase", "err", err)
  338. return fmt.Errorf("etherbase missing: %v", err)
  339. }
  340. go s.miner.Start(eb, threads)
  341. return nil
  342. }
  343. func (s *Ethereum) StopMining() { s.miner.Stop() }
  344. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  345. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  346. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  347. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  348. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  349. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  350. func (s *Ethereum) Pow() pow.PoW { return s.pow }
  351. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  352. func (s *Ethereum) IsListening() bool { return true } // Always listening
  353. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  354. func (s *Ethereum) NetVersion() int { return s.netVersionId }
  355. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  356. // Protocols implements node.Service, returning all the currently configured
  357. // network protocols to start.
  358. func (s *Ethereum) Protocols() []p2p.Protocol {
  359. if s.lesServer == nil {
  360. return s.protocolManager.SubProtocols
  361. } else {
  362. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  363. }
  364. }
  365. // Start implements node.Service, starting all internal goroutines needed by the
  366. // Ethereum protocol implementation.
  367. func (s *Ethereum) Start(srvr *p2p.Server) error {
  368. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  369. if s.AutoDAG {
  370. s.StartAutoDAG()
  371. }
  372. s.protocolManager.Start()
  373. if s.lesServer != nil {
  374. s.lesServer.Start(srvr)
  375. }
  376. return nil
  377. }
  378. // Stop implements node.Service, terminating all internal goroutines used by the
  379. // Ethereum protocol.
  380. func (s *Ethereum) Stop() error {
  381. if s.stopDbUpgrade != nil {
  382. s.stopDbUpgrade()
  383. }
  384. s.blockchain.Stop()
  385. s.protocolManager.Stop()
  386. if s.lesServer != nil {
  387. s.lesServer.Stop()
  388. }
  389. s.txPool.Stop()
  390. s.miner.Stop()
  391. s.eventMux.Stop()
  392. s.StopAutoDAG()
  393. s.chainDb.Close()
  394. close(s.shutdownChan)
  395. return nil
  396. }
  397. // This function will wait for a shutdown and resumes main thread execution
  398. func (s *Ethereum) WaitForShutdown() {
  399. <-s.shutdownChan
  400. }
  401. // StartAutoDAG() spawns a go routine that checks the DAG every autoDAGcheckInterval
  402. // by default that is 10 times per epoch
  403. // in epoch n, if we past autoDAGepochHeight within-epoch blocks,
  404. // it calls ethash.MakeDAG to pregenerate the DAG for the next epoch n+1
  405. // if it does not exist yet as well as remove the DAG for epoch n-1
  406. // the loop quits if autodagquit channel is closed, it can safely restart and
  407. // stop any number of times.
  408. // For any more sophisticated pattern of DAG generation, use CLI subcommand
  409. // makedag
  410. func (self *Ethereum) StartAutoDAG() {
  411. if self.autodagquit != nil {
  412. return // already started
  413. }
  414. go func() {
  415. log.Info("Pre-generation of ethash DAG on", "dir", ethash.DefaultDir)
  416. var nextEpoch uint64
  417. timer := time.After(0)
  418. self.autodagquit = make(chan bool)
  419. for {
  420. select {
  421. case <-timer:
  422. log.Info("Checking DAG availability", "dir", ethash.DefaultDir)
  423. currentBlock := self.BlockChain().CurrentBlock().NumberU64()
  424. thisEpoch := currentBlock / epochLength
  425. if nextEpoch <= thisEpoch {
  426. if currentBlock%epochLength > autoDAGepochHeight {
  427. if thisEpoch > 0 {
  428. previousDag, previousDagFull := dagFiles(thisEpoch - 1)
  429. os.Remove(filepath.Join(ethash.DefaultDir, previousDag))
  430. os.Remove(filepath.Join(ethash.DefaultDir, previousDagFull))
  431. log.Info("Removed previous DAG", "epoch", thisEpoch-1, "dag", previousDag)
  432. }
  433. nextEpoch = thisEpoch + 1
  434. dag, _ := dagFiles(nextEpoch)
  435. if _, err := os.Stat(dag); os.IsNotExist(err) {
  436. log.Info("Pre-generating next DAG", "epoch", nextEpoch, "dag", dag)
  437. err := ethash.MakeDAG(nextEpoch*epochLength, "") // "" -> ethash.DefaultDir
  438. if err != nil {
  439. log.Error("Error generating DAG", "epoch", nextEpoch, "dag", dag, "err", err)
  440. return
  441. }
  442. } else {
  443. log.Warn("DAG already exists", "epoch", nextEpoch, "dag", dag)
  444. }
  445. }
  446. }
  447. timer = time.After(autoDAGcheckInterval)
  448. case <-self.autodagquit:
  449. return
  450. }
  451. }
  452. }()
  453. }
  454. // stopAutoDAG stops automatic DAG pregeneration by quitting the loop
  455. func (self *Ethereum) StopAutoDAG() {
  456. if self.autodagquit != nil {
  457. close(self.autodagquit)
  458. self.autodagquit = nil
  459. }
  460. log.Info("Pre-generation of ethash DAG off", "dir", ethash.DefaultDir)
  461. }
  462. // dagFiles(epoch) returns the two alternative DAG filenames (not a path)
  463. // 1) <revision>-<hex(seedhash[8])> 2) full-R<revision>-<hex(seedhash[8])>
  464. func dagFiles(epoch uint64) (string, string) {
  465. seedHash, _ := ethash.GetSeedHash(epoch * epochLength)
  466. dag := fmt.Sprintf("full-R%d-%x", ethashRevision, seedHash[:8])
  467. return dag, "full-R" + dag
  468. }