geth.go 8.0 KB

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