geth.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. // Copyright 2016 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. // Contains all the wrappers from the node package to support client side node
  17. // management on mobile platforms.
  18. package geth
  19. import (
  20. "encoding/json"
  21. "fmt"
  22. "path/filepath"
  23. "github.com/ethereum/go-ethereum/core"
  24. "github.com/ethereum/go-ethereum/eth"
  25. "github.com/ethereum/go-ethereum/eth/downloader"
  26. "github.com/ethereum/go-ethereum/ethclient"
  27. "github.com/ethereum/go-ethereum/ethstats"
  28. "github.com/ethereum/go-ethereum/internal/debug"
  29. "github.com/ethereum/go-ethereum/les"
  30. "github.com/ethereum/go-ethereum/node"
  31. "github.com/ethereum/go-ethereum/p2p"
  32. "github.com/ethereum/go-ethereum/p2p/nat"
  33. "github.com/ethereum/go-ethereum/params"
  34. whisper "github.com/ethereum/go-ethereum/whisper/whisperv6"
  35. )
  36. // NodeConfig represents the collection of configuration values to fine tune the Geth
  37. // node embedded into a mobile process. The available values are a subset of the
  38. // entire API provided by go-ethereum to reduce the maintenance surface and dev
  39. // complexity.
  40. type NodeConfig struct {
  41. // Bootstrap nodes used to establish connectivity with the rest of the network.
  42. BootstrapNodes *Enodes
  43. // MaxPeers is the maximum number of peers that can be connected. If this is
  44. // set to zero, then only the configured static and trusted peers can connect.
  45. MaxPeers int
  46. // EthereumEnabled specifies whether the node should run the Ethereum protocol.
  47. EthereumEnabled bool
  48. // EthereumNetworkID is the network identifier used by the Ethereum protocol to
  49. // decide if remote peers should be accepted or not.
  50. EthereumNetworkID int64 // uint64 in truth, but Java can't handle that...
  51. // EthereumGenesis is the genesis JSON to use to seed the blockchain with. An
  52. // empty genesis state is equivalent to using the mainnet's state.
  53. EthereumGenesis string
  54. // EthereumDatabaseCache is the system memory in MB to allocate for database caching.
  55. // A minimum of 16MB is always reserved.
  56. EthereumDatabaseCache int
  57. // EthereumNetStats is a netstats connection string to use to report various
  58. // chain, transaction and node stats to a monitoring server.
  59. //
  60. // It has the form "nodename:secret@host:port"
  61. EthereumNetStats string
  62. // WhisperEnabled specifies whether the node should run the Whisper protocol.
  63. WhisperEnabled bool
  64. // Listening address of pprof server.
  65. PprofAddress string
  66. }
  67. // defaultNodeConfig contains the default node configuration values to use if all
  68. // or some fields are missing from the user's specified list.
  69. var defaultNodeConfig = &NodeConfig{
  70. BootstrapNodes: FoundationBootnodes(),
  71. MaxPeers: 25,
  72. EthereumEnabled: true,
  73. EthereumNetworkID: 1,
  74. EthereumDatabaseCache: 16,
  75. }
  76. // NewNodeConfig creates a new node option set, initialized to the default values.
  77. func NewNodeConfig() *NodeConfig {
  78. config := *defaultNodeConfig
  79. return &config
  80. }
  81. // Node represents a Geth Ethereum node instance.
  82. type Node struct {
  83. node *node.Node
  84. }
  85. // NewNode creates and configures a new Geth node.
  86. func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
  87. // If no or partial configurations were specified, use defaults
  88. if config == nil {
  89. config = NewNodeConfig()
  90. }
  91. if config.MaxPeers == 0 {
  92. config.MaxPeers = defaultNodeConfig.MaxPeers
  93. }
  94. if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
  95. config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
  96. }
  97. if config.PprofAddress != "" {
  98. debug.StartPProf(config.PprofAddress, true)
  99. }
  100. // Create the empty networking stack
  101. nodeConf := &node.Config{
  102. Name: clientIdentifier,
  103. Version: params.VersionWithMeta,
  104. DataDir: datadir,
  105. KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
  106. P2P: p2p.Config{
  107. NoDiscovery: true,
  108. DiscoveryV5: true,
  109. BootstrapNodesV5: config.BootstrapNodes.nodes,
  110. ListenAddr: ":0",
  111. NAT: nat.Any(),
  112. MaxPeers: config.MaxPeers,
  113. },
  114. }
  115. rawStack, err := node.New(nodeConf)
  116. if err != nil {
  117. return nil, err
  118. }
  119. debug.Memsize.Add("node", rawStack)
  120. var genesis *core.Genesis
  121. if config.EthereumGenesis != "" {
  122. // Parse the user supplied genesis spec if not mainnet
  123. genesis = new(core.Genesis)
  124. if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
  125. return nil, fmt.Errorf("invalid genesis spec: %v", err)
  126. }
  127. // If we have the Ropsten testnet, hard code the chain configs too
  128. if config.EthereumGenesis == RopstenGenesis() {
  129. genesis.Config = params.RopstenChainConfig
  130. if config.EthereumNetworkID == 1 {
  131. config.EthereumNetworkID = 3
  132. }
  133. }
  134. // If we have the Rinkeby testnet, hard code the chain configs too
  135. if config.EthereumGenesis == RinkebyGenesis() {
  136. genesis.Config = params.RinkebyChainConfig
  137. if config.EthereumNetworkID == 1 {
  138. config.EthereumNetworkID = 4
  139. }
  140. }
  141. // If we have the Goerli testnet, hard code the chain configs too
  142. if config.EthereumGenesis == GoerliGenesis() {
  143. genesis.Config = params.GoerliChainConfig
  144. if config.EthereumNetworkID == 1 {
  145. config.EthereumNetworkID = 5
  146. }
  147. }
  148. }
  149. // Register the Ethereum protocol if requested
  150. if config.EthereumEnabled {
  151. ethConf := eth.DefaultConfig
  152. ethConf.Genesis = genesis
  153. ethConf.SyncMode = downloader.LightSync
  154. ethConf.NetworkId = uint64(config.EthereumNetworkID)
  155. ethConf.DatabaseCache = config.EthereumDatabaseCache
  156. lesBackend, err := les.New(rawStack, &ethConf)
  157. if err != nil {
  158. return nil, fmt.Errorf("ethereum init: %v", err)
  159. }
  160. // If netstats reporting is requested, do it
  161. if config.EthereumNetStats != "" {
  162. if err := ethstats.New(rawStack, lesBackend.ApiBackend, lesBackend.Engine(), config.EthereumNetStats); err != nil {
  163. return nil, fmt.Errorf("netstats init: %v", err)
  164. }
  165. }
  166. }
  167. // Register the Whisper protocol if requested
  168. if config.WhisperEnabled {
  169. if _, err := whisper.New(rawStack, &whisper.DefaultConfig); err != nil {
  170. return nil, fmt.Errorf("whisper init: %v", err)
  171. }
  172. }
  173. return &Node{rawStack}, nil
  174. }
  175. // Close terminates a running node along with all it's services, tearing internal state
  176. // down. It is not possible to restart a closed node.
  177. func (n *Node) Close() error {
  178. return n.node.Close()
  179. }
  180. // Start creates a live P2P node and starts running it.
  181. func (n *Node) Start() error {
  182. // TODO: recreate the node so it can be started multiple times
  183. return n.node.Start()
  184. }
  185. // Stop terminates a running node along with all its services. If the node was not started,
  186. // an error is returned. It is not possible to restart a stopped node.
  187. //
  188. // Deprecated: use Close()
  189. func (n *Node) Stop() error {
  190. return n.node.Close()
  191. }
  192. // GetEthereumClient retrieves a client to access the Ethereum subsystem.
  193. func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
  194. rpc, err := n.node.Attach()
  195. if err != nil {
  196. return nil, err
  197. }
  198. return &EthereumClient{ethclient.NewClient(rpc)}, nil
  199. }
  200. // GetNodeInfo gathers and returns a collection of metadata known about the host.
  201. func (n *Node) GetNodeInfo() *NodeInfo {
  202. return &NodeInfo{n.node.Server().NodeInfo()}
  203. }
  204. // GetPeersInfo returns an array of metadata objects describing connected peers.
  205. func (n *Node) GetPeersInfo() *PeerInfos {
  206. return &PeerInfos{n.node.Server().PeersInfo()}
  207. }