backend.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 := upgradeChainDatabase(chainDb); err != nil {
  156. return nil, err
  157. }
  158. if err := addMipmapBloomBins(chainDb); err != nil {
  159. return nil, err
  160. }
  161. log.Info(fmt.Sprintf("Protocol Versions: %v, Network Id: %v", ProtocolVersions, config.NetworkId))
  162. if !config.SkipBcVersionCheck {
  163. bcVersion := core.GetBlockChainVersion(chainDb)
  164. if bcVersion != core.BlockChainVersion && bcVersion != 0 {
  165. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion)
  166. }
  167. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  168. }
  169. // load the genesis block or write a new one if no genesis
  170. // block is prenent in the database.
  171. genesis := core.GetBlock(chainDb, core.GetCanonicalHash(chainDb, 0), 0)
  172. if genesis == nil {
  173. genesis, err = core.WriteDefaultGenesisBlock(chainDb)
  174. if err != nil {
  175. return nil, err
  176. }
  177. log.Info(fmt.Sprint("WARNING: Wrote default ethereum genesis block"))
  178. }
  179. if config.ChainConfig == nil {
  180. return nil, errors.New("missing chain config")
  181. }
  182. core.WriteChainConfig(chainDb, genesis.Hash(), config.ChainConfig)
  183. eth.chainConfig = config.ChainConfig
  184. log.Info(fmt.Sprint("Chain config:", eth.chainConfig))
  185. eth.blockchain, err = core.NewBlockChain(chainDb, eth.chainConfig, eth.pow, eth.EventMux(), vm.Config{EnablePreimageRecording: config.EnablePreimageRecording})
  186. if err != nil {
  187. if err == core.ErrNoGenesis {
  188. return nil, fmt.Errorf(`No chain found. Please initialise a new chain using the "init" subcommand.`)
  189. }
  190. return nil, err
  191. }
  192. newPool := core.NewTxPool(eth.chainConfig, eth.EventMux(), eth.blockchain.State, eth.blockchain.GasLimit)
  193. eth.txPool = newPool
  194. maxPeers := config.MaxPeers
  195. if config.LightServ > 0 {
  196. // if we are running a light server, limit the number of ETH peers so that we reserve some space for incoming LES connections
  197. // temporary solution until the new peer connectivity API is finished
  198. halfPeers := maxPeers / 2
  199. maxPeers -= config.LightPeers
  200. if maxPeers < halfPeers {
  201. maxPeers = halfPeers
  202. }
  203. }
  204. if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.FastSync, config.NetworkId, maxPeers, eth.eventMux, eth.txPool, eth.pow, eth.blockchain, chainDb); err != nil {
  205. return nil, err
  206. }
  207. eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.pow)
  208. eth.miner.SetGasPrice(config.GasPrice)
  209. eth.miner.SetExtra(config.ExtraData)
  210. gpoParams := &gasprice.GpoParams{
  211. GpoMinGasPrice: config.GpoMinGasPrice,
  212. GpoMaxGasPrice: config.GpoMaxGasPrice,
  213. GpoFullBlockRatio: config.GpoFullBlockRatio,
  214. GpobaseStepDown: config.GpobaseStepDown,
  215. GpobaseStepUp: config.GpobaseStepUp,
  216. GpobaseCorrectionFactor: config.GpobaseCorrectionFactor,
  217. }
  218. gpo := gasprice.NewGasPriceOracle(eth.blockchain, chainDb, eth.eventMux, gpoParams)
  219. eth.ApiBackend = &EthApiBackend{eth, gpo}
  220. return eth, nil
  221. }
  222. // CreateDB creates the chain database.
  223. func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) {
  224. db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles)
  225. if db, ok := db.(*ethdb.LDBDatabase); ok {
  226. db.Meter("eth/db/chaindata/")
  227. }
  228. return db, err
  229. }
  230. // SetupGenesisBlock initializes the genesis block for an Ethereum service
  231. func SetupGenesisBlock(chainDb *ethdb.Database, config *Config) error {
  232. // Load up any custom genesis block if requested
  233. if len(config.Genesis) > 0 {
  234. block, err := core.WriteGenesisBlock(*chainDb, strings.NewReader(config.Genesis))
  235. if err != nil {
  236. return err
  237. }
  238. log.Info(fmt.Sprintf("Successfully wrote custom genesis block: %x", block.Hash()))
  239. }
  240. // Load up a test setup if directly injected
  241. if config.TestGenesisState != nil {
  242. *chainDb = config.TestGenesisState
  243. }
  244. if config.TestGenesisBlock != nil {
  245. core.WriteTd(*chainDb, config.TestGenesisBlock.Hash(), config.TestGenesisBlock.NumberU64(), config.TestGenesisBlock.Difficulty())
  246. core.WriteBlock(*chainDb, config.TestGenesisBlock)
  247. core.WriteCanonicalHash(*chainDb, config.TestGenesisBlock.Hash(), config.TestGenesisBlock.NumberU64())
  248. core.WriteHeadBlockHash(*chainDb, config.TestGenesisBlock.Hash())
  249. }
  250. return nil
  251. }
  252. // CreatePoW creates the required type of PoW instance for an Ethereum service
  253. func CreatePoW(config *Config) (pow.PoW, error) {
  254. switch {
  255. case config.PowFake:
  256. log.Info(fmt.Sprintf("ethash used in fake mode"))
  257. return pow.PoW(core.FakePow{}), nil
  258. case config.PowTest:
  259. log.Info(fmt.Sprintf("ethash used in test mode"))
  260. return ethash.NewForTesting()
  261. case config.PowShared:
  262. log.Info(fmt.Sprintf("ethash used in shared mode"))
  263. return ethash.NewShared(), nil
  264. default:
  265. return ethash.New(), nil
  266. }
  267. }
  268. // APIs returns the collection of RPC services the ethereum package offers.
  269. // NOTE, some of these services probably need to be moved to somewhere else.
  270. func (s *Ethereum) APIs() []rpc.API {
  271. return append(ethapi.GetAPIs(s.ApiBackend, s.solcPath), []rpc.API{
  272. {
  273. Namespace: "eth",
  274. Version: "1.0",
  275. Service: NewPublicEthereumAPI(s),
  276. Public: true,
  277. }, {
  278. Namespace: "eth",
  279. Version: "1.0",
  280. Service: NewPublicMinerAPI(s),
  281. Public: true,
  282. }, {
  283. Namespace: "eth",
  284. Version: "1.0",
  285. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  286. Public: true,
  287. }, {
  288. Namespace: "miner",
  289. Version: "1.0",
  290. Service: NewPrivateMinerAPI(s),
  291. Public: false,
  292. }, {
  293. Namespace: "eth",
  294. Version: "1.0",
  295. Service: filters.NewPublicFilterAPI(s.ApiBackend, false),
  296. Public: true,
  297. }, {
  298. Namespace: "admin",
  299. Version: "1.0",
  300. Service: NewPrivateAdminAPI(s),
  301. }, {
  302. Namespace: "debug",
  303. Version: "1.0",
  304. Service: NewPublicDebugAPI(s),
  305. Public: true,
  306. }, {
  307. Namespace: "debug",
  308. Version: "1.0",
  309. Service: NewPrivateDebugAPI(s.chainConfig, s),
  310. }, {
  311. Namespace: "net",
  312. Version: "1.0",
  313. Service: s.netRPCService,
  314. Public: true,
  315. },
  316. }...)
  317. }
  318. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  319. s.blockchain.ResetWithGenesisBlock(gb)
  320. }
  321. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  322. if s.etherbase != (common.Address{}) {
  323. return s.etherbase, nil
  324. }
  325. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  326. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  327. return accounts[0].Address, nil
  328. }
  329. }
  330. return common.Address{}, fmt.Errorf("etherbase address must be explicitly specified")
  331. }
  332. // set in js console via admin interface or wrapper from cli flags
  333. func (self *Ethereum) SetEtherbase(etherbase common.Address) {
  334. self.etherbase = etherbase
  335. self.miner.SetEtherbase(etherbase)
  336. }
  337. func (s *Ethereum) StartMining(threads int) error {
  338. eb, err := s.Etherbase()
  339. if err != nil {
  340. err = fmt.Errorf("Cannot start mining without etherbase address: %v", err)
  341. log.Error(fmt.Sprint(err))
  342. return err
  343. }
  344. go s.miner.Start(eb, threads)
  345. return nil
  346. }
  347. func (s *Ethereum) StopMining() { s.miner.Stop() }
  348. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  349. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  350. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  351. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  352. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  353. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  354. func (s *Ethereum) Pow() pow.PoW { return s.pow }
  355. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  356. func (s *Ethereum) IsListening() bool { return true } // Always listening
  357. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  358. func (s *Ethereum) NetVersion() int { return s.netVersionId }
  359. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  360. // Protocols implements node.Service, returning all the currently configured
  361. // network protocols to start.
  362. func (s *Ethereum) Protocols() []p2p.Protocol {
  363. if s.lesServer == nil {
  364. return s.protocolManager.SubProtocols
  365. } else {
  366. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  367. }
  368. }
  369. // Start implements node.Service, starting all internal goroutines needed by the
  370. // Ethereum protocol implementation.
  371. func (s *Ethereum) Start(srvr *p2p.Server) error {
  372. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  373. if s.AutoDAG {
  374. s.StartAutoDAG()
  375. }
  376. s.protocolManager.Start()
  377. if s.lesServer != nil {
  378. s.lesServer.Start(srvr)
  379. }
  380. return nil
  381. }
  382. // Stop implements node.Service, terminating all internal goroutines used by the
  383. // Ethereum protocol.
  384. func (s *Ethereum) Stop() error {
  385. if s.stopDbUpgrade != nil {
  386. s.stopDbUpgrade()
  387. }
  388. s.blockchain.Stop()
  389. s.protocolManager.Stop()
  390. if s.lesServer != nil {
  391. s.lesServer.Stop()
  392. }
  393. s.txPool.Stop()
  394. s.miner.Stop()
  395. s.eventMux.Stop()
  396. s.StopAutoDAG()
  397. s.chainDb.Close()
  398. close(s.shutdownChan)
  399. return nil
  400. }
  401. // This function will wait for a shutdown and resumes main thread execution
  402. func (s *Ethereum) WaitForShutdown() {
  403. <-s.shutdownChan
  404. }
  405. // StartAutoDAG() spawns a go routine that checks the DAG every autoDAGcheckInterval
  406. // by default that is 10 times per epoch
  407. // in epoch n, if we past autoDAGepochHeight within-epoch blocks,
  408. // it calls ethash.MakeDAG to pregenerate the DAG for the next epoch n+1
  409. // if it does not exist yet as well as remove the DAG for epoch n-1
  410. // the loop quits if autodagquit channel is closed, it can safely restart and
  411. // stop any number of times.
  412. // For any more sophisticated pattern of DAG generation, use CLI subcommand
  413. // makedag
  414. func (self *Ethereum) StartAutoDAG() {
  415. if self.autodagquit != nil {
  416. return // already started
  417. }
  418. go func() {
  419. log.Info(fmt.Sprintf("Automatic pregeneration of ethash DAG ON (ethash dir: %s)", ethash.DefaultDir))
  420. var nextEpoch uint64
  421. timer := time.After(0)
  422. self.autodagquit = make(chan bool)
  423. for {
  424. select {
  425. case <-timer:
  426. log.Info(fmt.Sprintf("checking DAG (ethash dir: %s)", ethash.DefaultDir))
  427. currentBlock := self.BlockChain().CurrentBlock().NumberU64()
  428. thisEpoch := currentBlock / epochLength
  429. if nextEpoch <= thisEpoch {
  430. if currentBlock%epochLength > autoDAGepochHeight {
  431. if thisEpoch > 0 {
  432. previousDag, previousDagFull := dagFiles(thisEpoch - 1)
  433. os.Remove(filepath.Join(ethash.DefaultDir, previousDag))
  434. os.Remove(filepath.Join(ethash.DefaultDir, previousDagFull))
  435. log.Info(fmt.Sprintf("removed DAG for epoch %d (%s)", thisEpoch-1, previousDag))
  436. }
  437. nextEpoch = thisEpoch + 1
  438. dag, _ := dagFiles(nextEpoch)
  439. if _, err := os.Stat(dag); os.IsNotExist(err) {
  440. log.Info(fmt.Sprintf("Pregenerating DAG for epoch %d (%s)", nextEpoch, dag))
  441. err := ethash.MakeDAG(nextEpoch*epochLength, "") // "" -> ethash.DefaultDir
  442. if err != nil {
  443. log.Error(fmt.Sprintf("Error generating DAG for epoch %d (%s)", nextEpoch, dag))
  444. return
  445. }
  446. } else {
  447. log.Error(fmt.Sprintf("DAG for epoch %d (%s)", nextEpoch, dag))
  448. }
  449. }
  450. }
  451. timer = time.After(autoDAGcheckInterval)
  452. case <-self.autodagquit:
  453. return
  454. }
  455. }
  456. }()
  457. }
  458. // stopAutoDAG stops automatic DAG pregeneration by quitting the loop
  459. func (self *Ethereum) StopAutoDAG() {
  460. if self.autodagquit != nil {
  461. close(self.autodagquit)
  462. self.autodagquit = nil
  463. }
  464. log.Info(fmt.Sprintf("Automatic pregeneration of ethash DAG OFF (ethash dir: %s)", ethash.DefaultDir))
  465. }
  466. // dagFiles(epoch) returns the two alternative DAG filenames (not a path)
  467. // 1) <revision>-<hex(seedhash[8])> 2) full-R<revision>-<hex(seedhash[8])>
  468. func dagFiles(epoch uint64) (string, string) {
  469. seedHash, _ := ethash.GetSeedHash(epoch * epochLength)
  470. dag := fmt.Sprintf("full-R%d-%x", ethashRevision, seedHash[:8])
  471. return dag, "full-R" + dag
  472. }