backend.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. "regexp"
  23. "strings"
  24. "sync"
  25. "time"
  26. "github.com/ethereum/go-ethereum/accounts"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/core/vm"
  31. "github.com/ethereum/go-ethereum/eth/downloader"
  32. "github.com/ethereum/go-ethereum/eth/filters"
  33. "github.com/ethereum/go-ethereum/eth/gasprice"
  34. "github.com/ethereum/go-ethereum/ethdb"
  35. "github.com/ethereum/go-ethereum/event"
  36. "github.com/ethereum/go-ethereum/internal/ethapi"
  37. "github.com/ethereum/go-ethereum/log"
  38. "github.com/ethereum/go-ethereum/miner"
  39. "github.com/ethereum/go-ethereum/node"
  40. "github.com/ethereum/go-ethereum/p2p"
  41. "github.com/ethereum/go-ethereum/params"
  42. "github.com/ethereum/go-ethereum/pow"
  43. "github.com/ethereum/go-ethereum/rpc"
  44. )
  45. const (
  46. epochLength = 30000
  47. ethashRevision = 23
  48. autoDAGcheckInterval = 10 * time.Hour
  49. autoDAGepochHeight = epochLength / 2
  50. )
  51. var (
  52. datadirInUseErrnos = map[uint]bool{11: true, 32: true, 35: true}
  53. portInUseErrRE = regexp.MustCompile("address already in use")
  54. )
  55. type Config struct {
  56. ChainConfig *params.ChainConfig // chain configuration
  57. NetworkId int // Network ID to use for selecting peers to connect to
  58. Genesis string // Genesis JSON to seed the chain database with
  59. FastSync bool // Enables the state download based fast synchronisation algorithm
  60. LightMode bool // Running in light client mode
  61. LightServ int // Maximum percentage of time allowed for serving LES requests
  62. LightPeers int // Maximum number of LES client peers
  63. MaxPeers int // Maximum number of global peers
  64. SkipBcVersionCheck bool // e.g. blockchain export
  65. DatabaseCache int
  66. DatabaseHandles int
  67. DocRoot string
  68. PowFake bool
  69. PowTest bool
  70. PowShared bool
  71. ExtraData []byte
  72. EthashCacheDir string
  73. EthashCachesInMem int
  74. EthashCachesOnDisk int
  75. EthashDatasetDir string
  76. EthashDatasetsInMem int
  77. EthashDatasetsOnDisk int
  78. Etherbase common.Address
  79. GasPrice *big.Int
  80. MinerThreads int
  81. SolcPath string
  82. GpoMinGasPrice *big.Int
  83. GpoMaxGasPrice *big.Int
  84. GpoFullBlockRatio int
  85. GpobaseStepDown int
  86. GpobaseStepUp int
  87. GpobaseCorrectionFactor int
  88. EnablePreimageRecording bool
  89. TestGenesisBlock *types.Block // Genesis block to seed the chain database with (testing only!)
  90. TestGenesisState ethdb.Database // Genesis state to seed the database with (testing only!)
  91. }
  92. type LesServer interface {
  93. Start(srvr *p2p.Server)
  94. Stop()
  95. Protocols() []p2p.Protocol
  96. }
  97. // Ethereum implements the Ethereum full node service.
  98. type Ethereum struct {
  99. chainConfig *params.ChainConfig
  100. // Channel for shutting down the service
  101. shutdownChan chan bool // Channel for shutting down the ethereum
  102. stopDbUpgrade func() // stop chain db sequential key upgrade
  103. // Handlers
  104. txPool *core.TxPool
  105. txMu sync.Mutex
  106. blockchain *core.BlockChain
  107. protocolManager *ProtocolManager
  108. lesServer LesServer
  109. // DB interfaces
  110. chainDb ethdb.Database // Block chain database
  111. eventMux *event.TypeMux
  112. pow pow.PoW
  113. accountManager *accounts.Manager
  114. ApiBackend *EthApiBackend
  115. miner *miner.Miner
  116. Mining bool
  117. MinerThreads int
  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. eth := &Ethereum{
  139. chainDb: chainDb,
  140. eventMux: ctx.EventMux,
  141. accountManager: ctx.AccountManager,
  142. pow: CreatePoW(ctx, config),
  143. shutdownChan: make(chan bool),
  144. stopDbUpgrade: stopDbUpgrade,
  145. netVersionId: config.NetworkId,
  146. etherbase: config.Etherbase,
  147. MinerThreads: config.MinerThreads,
  148. solcPath: config.SolcPath,
  149. }
  150. if err := addMipmapBloomBins(chainDb); err != nil {
  151. return nil, err
  152. }
  153. log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)
  154. if !config.SkipBcVersionCheck {
  155. bcVersion := core.GetBlockChainVersion(chainDb)
  156. if bcVersion != core.BlockChainVersion && bcVersion != 0 {
  157. return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d). Run geth upgradedb.\n", bcVersion, core.BlockChainVersion)
  158. }
  159. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  160. }
  161. // load the genesis block or write a new one if no genesis
  162. // block is prenent in the database.
  163. genesis := core.GetBlock(chainDb, core.GetCanonicalHash(chainDb, 0), 0)
  164. if genesis == nil {
  165. genesis, err = core.WriteDefaultGenesisBlock(chainDb)
  166. if err != nil {
  167. return nil, err
  168. }
  169. log.Warn("Wrote default Ethereum genesis block")
  170. }
  171. if config.ChainConfig == nil {
  172. return nil, errors.New("missing chain config")
  173. }
  174. core.WriteChainConfig(chainDb, genesis.Hash(), config.ChainConfig)
  175. eth.chainConfig = config.ChainConfig
  176. log.Info("Initialised chain configuration", "config", eth.chainConfig)
  177. eth.blockchain, err = core.NewBlockChain(chainDb, eth.chainConfig, eth.pow, eth.EventMux(), vm.Config{EnablePreimageRecording: config.EnablePreimageRecording})
  178. if err != nil {
  179. if err == core.ErrNoGenesis {
  180. return nil, fmt.Errorf(`No chain found. Please initialise a new chain using the "init" subcommand.`)
  181. }
  182. return nil, err
  183. }
  184. newPool := core.NewTxPool(eth.chainConfig, eth.EventMux(), eth.blockchain.State, eth.blockchain.GasLimit)
  185. eth.txPool = newPool
  186. maxPeers := config.MaxPeers
  187. if config.LightServ > 0 {
  188. // if we are running a light server, limit the number of ETH peers so that we reserve some space for incoming LES connections
  189. // temporary solution until the new peer connectivity API is finished
  190. halfPeers := maxPeers / 2
  191. maxPeers -= config.LightPeers
  192. if maxPeers < halfPeers {
  193. maxPeers = halfPeers
  194. }
  195. }
  196. if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.FastSync, config.NetworkId, maxPeers, eth.eventMux, eth.txPool, eth.pow, eth.blockchain, chainDb); err != nil {
  197. return nil, err
  198. }
  199. eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.pow)
  200. eth.miner.SetGasPrice(config.GasPrice)
  201. eth.miner.SetExtra(config.ExtraData)
  202. gpoParams := &gasprice.GpoParams{
  203. GpoMinGasPrice: config.GpoMinGasPrice,
  204. GpoMaxGasPrice: config.GpoMaxGasPrice,
  205. GpoFullBlockRatio: config.GpoFullBlockRatio,
  206. GpobaseStepDown: config.GpobaseStepDown,
  207. GpobaseStepUp: config.GpobaseStepUp,
  208. GpobaseCorrectionFactor: config.GpobaseCorrectionFactor,
  209. }
  210. gpo := gasprice.NewGasPriceOracle(eth.blockchain, chainDb, eth.eventMux, gpoParams)
  211. eth.ApiBackend = &EthApiBackend{eth, gpo}
  212. return eth, nil
  213. }
  214. // CreateDB creates the chain database.
  215. func CreateDB(ctx *node.ServiceContext, config *Config, name string) (ethdb.Database, error) {
  216. db, err := ctx.OpenDatabase(name, config.DatabaseCache, config.DatabaseHandles)
  217. if db, ok := db.(*ethdb.LDBDatabase); ok {
  218. db.Meter("eth/db/chaindata/")
  219. }
  220. return db, err
  221. }
  222. // SetupGenesisBlock initializes the genesis block for an Ethereum service
  223. func SetupGenesisBlock(chainDb *ethdb.Database, config *Config) error {
  224. // Load up any custom genesis block if requested
  225. if len(config.Genesis) > 0 {
  226. block, err := core.WriteGenesisBlock(*chainDb, strings.NewReader(config.Genesis))
  227. if err != nil {
  228. return err
  229. }
  230. log.Info("Successfully wrote custom genesis block", "hash", block.Hash())
  231. }
  232. // Load up a test setup if directly injected
  233. if config.TestGenesisState != nil {
  234. *chainDb = config.TestGenesisState
  235. }
  236. if config.TestGenesisBlock != nil {
  237. core.WriteTd(*chainDb, config.TestGenesisBlock.Hash(), config.TestGenesisBlock.NumberU64(), config.TestGenesisBlock.Difficulty())
  238. core.WriteBlock(*chainDb, config.TestGenesisBlock)
  239. core.WriteCanonicalHash(*chainDb, config.TestGenesisBlock.Hash(), config.TestGenesisBlock.NumberU64())
  240. core.WriteHeadBlockHash(*chainDb, config.TestGenesisBlock.Hash())
  241. }
  242. return nil
  243. }
  244. // CreatePoW creates the required type of PoW instance for an Ethereum service
  245. func CreatePoW(ctx *node.ServiceContext, config *Config) pow.PoW {
  246. switch {
  247. case config.PowFake:
  248. log.Warn("Ethash used in fake mode")
  249. return pow.FakePow{}
  250. case config.PowTest:
  251. log.Warn("Ethash used in test mode")
  252. return pow.NewTestEthash()
  253. case config.PowShared:
  254. log.Warn("Ethash used in shared mode")
  255. return pow.NewSharedEthash()
  256. default:
  257. return pow.NewFullEthash(ctx.ResolvePath(config.EthashCacheDir), config.EthashCachesInMem, config.EthashCachesOnDisk,
  258. config.EthashDatasetDir, config.EthashDatasetsInMem, config.EthashDatasetsOnDisk)
  259. }
  260. }
  261. // APIs returns the collection of RPC services the ethereum package offers.
  262. // NOTE, some of these services probably need to be moved to somewhere else.
  263. func (s *Ethereum) APIs() []rpc.API {
  264. return append(ethapi.GetAPIs(s.ApiBackend, s.solcPath), []rpc.API{
  265. {
  266. Namespace: "eth",
  267. Version: "1.0",
  268. Service: NewPublicEthereumAPI(s),
  269. Public: true,
  270. }, {
  271. Namespace: "eth",
  272. Version: "1.0",
  273. Service: NewPublicMinerAPI(s),
  274. Public: true,
  275. }, {
  276. Namespace: "eth",
  277. Version: "1.0",
  278. Service: downloader.NewPublicDownloaderAPI(s.protocolManager.downloader, s.eventMux),
  279. Public: true,
  280. }, {
  281. Namespace: "miner",
  282. Version: "1.0",
  283. Service: NewPrivateMinerAPI(s),
  284. Public: false,
  285. }, {
  286. Namespace: "eth",
  287. Version: "1.0",
  288. Service: filters.NewPublicFilterAPI(s.ApiBackend, false),
  289. Public: true,
  290. }, {
  291. Namespace: "admin",
  292. Version: "1.0",
  293. Service: NewPrivateAdminAPI(s),
  294. }, {
  295. Namespace: "debug",
  296. Version: "1.0",
  297. Service: NewPublicDebugAPI(s),
  298. Public: true,
  299. }, {
  300. Namespace: "debug",
  301. Version: "1.0",
  302. Service: NewPrivateDebugAPI(s.chainConfig, s),
  303. }, {
  304. Namespace: "net",
  305. Version: "1.0",
  306. Service: s.netRPCService,
  307. Public: true,
  308. },
  309. }...)
  310. }
  311. func (s *Ethereum) ResetWithGenesisBlock(gb *types.Block) {
  312. s.blockchain.ResetWithGenesisBlock(gb)
  313. }
  314. func (s *Ethereum) Etherbase() (eb common.Address, err error) {
  315. if s.etherbase != (common.Address{}) {
  316. return s.etherbase, nil
  317. }
  318. if wallets := s.AccountManager().Wallets(); len(wallets) > 0 {
  319. if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  320. return accounts[0].Address, nil
  321. }
  322. }
  323. return common.Address{}, fmt.Errorf("etherbase address must be explicitly specified")
  324. }
  325. // set in js console via admin interface or wrapper from cli flags
  326. func (self *Ethereum) SetEtherbase(etherbase common.Address) {
  327. self.etherbase = etherbase
  328. self.miner.SetEtherbase(etherbase)
  329. }
  330. func (s *Ethereum) StartMining(threads int) error {
  331. eb, err := s.Etherbase()
  332. if err != nil {
  333. log.Error("Cannot start mining without etherbase", "err", err)
  334. return fmt.Errorf("etherbase missing: %v", err)
  335. }
  336. go s.miner.Start(eb, threads)
  337. return nil
  338. }
  339. func (s *Ethereum) StopMining() { s.miner.Stop() }
  340. func (s *Ethereum) IsMining() bool { return s.miner.Mining() }
  341. func (s *Ethereum) Miner() *miner.Miner { return s.miner }
  342. func (s *Ethereum) AccountManager() *accounts.Manager { return s.accountManager }
  343. func (s *Ethereum) BlockChain() *core.BlockChain { return s.blockchain }
  344. func (s *Ethereum) TxPool() *core.TxPool { return s.txPool }
  345. func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux }
  346. func (s *Ethereum) Pow() pow.PoW { return s.pow }
  347. func (s *Ethereum) ChainDb() ethdb.Database { return s.chainDb }
  348. func (s *Ethereum) IsListening() bool { return true } // Always listening
  349. func (s *Ethereum) EthVersion() int { return int(s.protocolManager.SubProtocols[0].Version) }
  350. func (s *Ethereum) NetVersion() int { return s.netVersionId }
  351. func (s *Ethereum) Downloader() *downloader.Downloader { return s.protocolManager.downloader }
  352. // Protocols implements node.Service, returning all the currently configured
  353. // network protocols to start.
  354. func (s *Ethereum) Protocols() []p2p.Protocol {
  355. if s.lesServer == nil {
  356. return s.protocolManager.SubProtocols
  357. } else {
  358. return append(s.protocolManager.SubProtocols, s.lesServer.Protocols()...)
  359. }
  360. }
  361. // Start implements node.Service, starting all internal goroutines needed by the
  362. // Ethereum protocol implementation.
  363. func (s *Ethereum) Start(srvr *p2p.Server) error {
  364. s.netRPCService = ethapi.NewPublicNetAPI(srvr, s.NetVersion())
  365. s.protocolManager.Start()
  366. if s.lesServer != nil {
  367. s.lesServer.Start(srvr)
  368. }
  369. return nil
  370. }
  371. // Stop implements node.Service, terminating all internal goroutines used by the
  372. // Ethereum protocol.
  373. func (s *Ethereum) Stop() error {
  374. if s.stopDbUpgrade != nil {
  375. s.stopDbUpgrade()
  376. }
  377. s.blockchain.Stop()
  378. s.protocolManager.Stop()
  379. if s.lesServer != nil {
  380. s.lesServer.Stop()
  381. }
  382. s.txPool.Stop()
  383. s.miner.Stop()
  384. s.eventMux.Stop()
  385. s.chainDb.Close()
  386. close(s.shutdownChan)
  387. return nil
  388. }
  389. // This function will wait for a shutdown and resumes main thread execution
  390. func (s *Ethereum) WaitForShutdown() {
  391. <-s.shutdownChan
  392. }