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