geth.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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/les"
  29. "github.com/ethereum/go-ethereum/node"
  30. "github.com/ethereum/go-ethereum/p2p"
  31. "github.com/ethereum/go-ethereum/p2p/nat"
  32. "github.com/ethereum/go-ethereum/params"
  33. whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
  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. // WhisperEnabled specifies whether the node should run the Whisper protocol.
  62. WhisperEnabled bool
  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. // Node represents a Geth Ethereum node instance.
  79. type Node struct {
  80. node *node.Node
  81. }
  82. // NewNode creates and configures a new Geth node.
  83. func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
  84. // If no or partial configurations were specified, use defaults
  85. if config == nil {
  86. config = NewNodeConfig()
  87. }
  88. if config.MaxPeers == 0 {
  89. config.MaxPeers = defaultNodeConfig.MaxPeers
  90. }
  91. if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
  92. config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
  93. }
  94. // Create the empty networking stack
  95. nodeConf := &node.Config{
  96. Name: clientIdentifier,
  97. Version: params.Version,
  98. DataDir: datadir,
  99. KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
  100. P2P: p2p.Config{
  101. NoDiscovery: true,
  102. DiscoveryV5: true,
  103. DiscoveryV5Addr: ":0",
  104. BootstrapNodesV5: config.BootstrapNodes.nodes,
  105. ListenAddr: ":0",
  106. NAT: nat.Any(),
  107. MaxPeers: config.MaxPeers,
  108. },
  109. }
  110. rawStack, err := node.New(nodeConf)
  111. if err != nil {
  112. return nil, err
  113. }
  114. var genesis *core.Genesis
  115. if config.EthereumGenesis != "" {
  116. // Parse the user supplied genesis spec if not mainnet
  117. genesis = new(core.Genesis)
  118. if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
  119. return nil, fmt.Errorf("invalid genesis spec: %v", err)
  120. }
  121. // If we have the testnet, hard code the chain configs too
  122. if config.EthereumGenesis == TestnetGenesis() {
  123. genesis.Config = params.TestnetChainConfig
  124. if config.EthereumNetworkID == 1 {
  125. config.EthereumNetworkID = 3
  126. }
  127. }
  128. }
  129. // Register the Ethereum protocol if requested
  130. if config.EthereumEnabled {
  131. ethConf := eth.DefaultConfig
  132. ethConf.Genesis = genesis
  133. ethConf.SyncMode = downloader.LightSync
  134. ethConf.NetworkId = uint64(config.EthereumNetworkID)
  135. ethConf.DatabaseCache = config.EthereumDatabaseCache
  136. if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  137. return les.New(ctx, &ethConf)
  138. }); err != nil {
  139. return nil, fmt.Errorf("ethereum init: %v", err)
  140. }
  141. // If netstats reporting is requested, do it
  142. if config.EthereumNetStats != "" {
  143. if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  144. var lesServ *les.LightEthereum
  145. ctx.Service(&lesServ)
  146. return ethstats.New(config.EthereumNetStats, nil, lesServ)
  147. }); err != nil {
  148. return nil, fmt.Errorf("netstats init: %v", err)
  149. }
  150. }
  151. }
  152. // Register the Whisper protocol if requested
  153. if config.WhisperEnabled {
  154. if err := rawStack.Register(func(*node.ServiceContext) (node.Service, error) { return whisper.New(), nil }); err != nil {
  155. return nil, fmt.Errorf("whisper init: %v", err)
  156. }
  157. }
  158. return &Node{rawStack}, nil
  159. }
  160. // Start creates a live P2P node and starts running it.
  161. func (n *Node) Start() error {
  162. return n.node.Start()
  163. }
  164. // Stop terminates a running node along with all it's services. In the node was
  165. // not started, an error is returned.
  166. func (n *Node) Stop() error {
  167. return n.node.Stop()
  168. }
  169. // GetEthereumClient retrieves a client to access the Ethereum subsystem.
  170. func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
  171. rpc, err := n.node.Attach()
  172. if err != nil {
  173. return nil, err
  174. }
  175. return &EthereumClient{ethclient.NewClient(rpc)}, nil
  176. }
  177. // GetNodeInfo gathers and returns a collection of metadata known about the host.
  178. func (n *Node) GetNodeInfo() *NodeInfo {
  179. return &NodeInfo{n.node.Server().NodeInfo()}
  180. }
  181. // GetPeersInfo returns an array of metadata objects describing connected peers.
  182. func (n *Node) GetPeersInfo() *PeerInfos {
  183. return &PeerInfos{n.node.Server().PeersInfo()}
  184. }