geth.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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)
  99. }
  100. // Create the empty networking stack
  101. nodeConf := &node.Config{
  102. Name: clientIdentifier,
  103. Version: params.Version,
  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 testnet, hard code the chain configs too
  128. if config.EthereumGenesis == TestnetGenesis() {
  129. genesis.Config = params.TestnetChainConfig
  130. if config.EthereumNetworkID == 1 {
  131. config.EthereumNetworkID = 3
  132. }
  133. }
  134. }
  135. // Register the Ethereum protocol if requested
  136. if config.EthereumEnabled {
  137. ethConf := eth.DefaultConfig
  138. ethConf.Genesis = genesis
  139. ethConf.SyncMode = downloader.LightSync
  140. ethConf.NetworkId = uint64(config.EthereumNetworkID)
  141. ethConf.DatabaseCache = config.EthereumDatabaseCache
  142. if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  143. return les.New(ctx, &ethConf)
  144. }); err != nil {
  145. return nil, fmt.Errorf("ethereum init: %v", err)
  146. }
  147. // If netstats reporting is requested, do it
  148. if config.EthereumNetStats != "" {
  149. if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  150. var lesServ *les.LightEthereum
  151. ctx.Service(&lesServ)
  152. return ethstats.New(config.EthereumNetStats, nil, lesServ)
  153. }); err != nil {
  154. return nil, fmt.Errorf("netstats init: %v", err)
  155. }
  156. }
  157. }
  158. // Register the Whisper protocol if requested
  159. if config.WhisperEnabled {
  160. if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) {
  161. return whisper.New(&whisper.DefaultConfig), nil
  162. }); err != nil {
  163. return nil, fmt.Errorf("whisper init: %v", err)
  164. }
  165. }
  166. return &Node{rawStack}, nil
  167. }
  168. // Start creates a live P2P node and starts running it.
  169. func (n *Node) Start() error {
  170. return n.node.Start()
  171. }
  172. // Stop terminates a running node along with all it's services. In the node was
  173. // not started, an error is returned.
  174. func (n *Node) Stop() error {
  175. return n.node.Stop()
  176. }
  177. // GetEthereumClient retrieves a client to access the Ethereum subsystem.
  178. func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
  179. rpc, err := n.node.Attach()
  180. if err != nil {
  181. return nil, err
  182. }
  183. return &EthereumClient{ethclient.NewClient(rpc)}, nil
  184. }
  185. // GetNodeInfo gathers and returns a collection of metadata known about the host.
  186. func (n *Node) GetNodeInfo() *NodeInfo {
  187. return &NodeInfo{n.node.Server().NodeInfo()}
  188. }
  189. // GetPeersInfo returns an array of metadata objects describing connected peers.
  190. func (n *Node) GetPeersInfo() *PeerInfos {
  191. return &PeerInfos{n.node.Server().PeersInfo()}
  192. }