geth.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. // Ultra Light client options
  67. ULC *eth.ULCConfig
  68. }
  69. // defaultNodeConfig contains the default node configuration values to use if all
  70. // or some fields are missing from the user's specified list.
  71. var defaultNodeConfig = &NodeConfig{
  72. BootstrapNodes: FoundationBootnodes(),
  73. MaxPeers: 25,
  74. EthereumEnabled: true,
  75. EthereumNetworkID: 1,
  76. EthereumDatabaseCache: 16,
  77. }
  78. // NewNodeConfig creates a new node option set, initialized to the default values.
  79. func NewNodeConfig() *NodeConfig {
  80. config := *defaultNodeConfig
  81. return &config
  82. }
  83. // Node represents a Geth Ethereum node instance.
  84. type Node struct {
  85. node *node.Node
  86. }
  87. // NewNode creates and configures a new Geth node.
  88. func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
  89. // If no or partial configurations were specified, use defaults
  90. if config == nil {
  91. config = NewNodeConfig()
  92. }
  93. if config.MaxPeers == 0 {
  94. config.MaxPeers = defaultNodeConfig.MaxPeers
  95. }
  96. if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
  97. config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
  98. }
  99. if config.PprofAddress != "" {
  100. debug.StartPProf(config.PprofAddress)
  101. }
  102. // Create the empty networking stack
  103. nodeConf := &node.Config{
  104. Name: clientIdentifier,
  105. Version: params.VersionWithMeta,
  106. DataDir: datadir,
  107. KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
  108. P2P: p2p.Config{
  109. NoDiscovery: true,
  110. DiscoveryV5: true,
  111. BootstrapNodesV5: config.BootstrapNodes.nodes,
  112. ListenAddr: ":0",
  113. NAT: nat.Any(),
  114. MaxPeers: config.MaxPeers,
  115. },
  116. }
  117. rawStack, err := node.New(nodeConf)
  118. if err != nil {
  119. return nil, err
  120. }
  121. debug.Memsize.Add("node", rawStack)
  122. var genesis *core.Genesis
  123. if config.EthereumGenesis != "" {
  124. // Parse the user supplied genesis spec if not mainnet
  125. genesis = new(core.Genesis)
  126. if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
  127. return nil, fmt.Errorf("invalid genesis spec: %v", err)
  128. }
  129. // If we have the testnet, hard code the chain configs too
  130. if config.EthereumGenesis == TestnetGenesis() {
  131. genesis.Config = params.TestnetChainConfig
  132. if config.EthereumNetworkID == 1 {
  133. config.EthereumNetworkID = 3
  134. }
  135. }
  136. }
  137. // Register the Ethereum protocol if requested
  138. if config.EthereumEnabled {
  139. ethConf := eth.DefaultConfig
  140. ethConf.Genesis = genesis
  141. ethConf.SyncMode = downloader.LightSync
  142. ethConf.NetworkId = uint64(config.EthereumNetworkID)
  143. ethConf.DatabaseCache = config.EthereumDatabaseCache
  144. if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  145. return les.New(ctx, &ethConf)
  146. }); err != nil {
  147. return nil, fmt.Errorf("ethereum init: %v", err)
  148. }
  149. // If netstats reporting is requested, do it
  150. if config.EthereumNetStats != "" {
  151. if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  152. var lesServ *les.LightEthereum
  153. ctx.Service(&lesServ)
  154. return ethstats.New(config.EthereumNetStats, nil, lesServ)
  155. }); err != nil {
  156. return nil, fmt.Errorf("netstats init: %v", err)
  157. }
  158. }
  159. }
  160. // Register the Whisper protocol if requested
  161. if config.WhisperEnabled {
  162. if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) {
  163. return whisper.New(&whisper.DefaultConfig), nil
  164. }); err != nil {
  165. return nil, fmt.Errorf("whisper init: %v", err)
  166. }
  167. }
  168. return &Node{rawStack}, nil
  169. }
  170. // Close terminates a running node along with all it's services, tearing internal
  171. // state doen too. It's not possible to restart a closed node.
  172. func (n *Node) Close() error {
  173. return n.node.Close()
  174. }
  175. // Start creates a live P2P node and starts running it.
  176. func (n *Node) Start() error {
  177. return n.node.Start()
  178. }
  179. // Stop terminates a running node along with all it's services. If the node was
  180. // not started, an error is returned.
  181. func (n *Node) Stop() error {
  182. return n.node.Stop()
  183. }
  184. // GetEthereumClient retrieves a client to access the Ethereum subsystem.
  185. func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
  186. rpc, err := n.node.Attach()
  187. if err != nil {
  188. return nil, err
  189. }
  190. return &EthereumClient{ethclient.NewClient(rpc)}, nil
  191. }
  192. // GetNodeInfo gathers and returns a collection of metadata known about the host.
  193. func (n *Node) GetNodeInfo() *NodeInfo {
  194. return &NodeInfo{n.node.Server().NodeInfo()}
  195. }
  196. // GetPeersInfo returns an array of metadata objects describing connected peers.
  197. func (n *Node) GetPeersInfo() *PeerInfos {
  198. return &PeerInfos{n.node.Server().PeersInfo()}
  199. }