github.com/xinfinOrg/xdposchain@v1.1.0/p2p/simulations/adapters/inproc.go (about) 1 // Copyright 2017 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 17 package adapters 18 19 import ( 20 "errors" 21 "fmt" 22 "math" 23 "net" 24 "sync" 25 26 "github.com/ethereum/go-ethereum/event" 27 "github.com/ethereum/go-ethereum/log" 28 "github.com/ethereum/go-ethereum/node" 29 "github.com/ethereum/go-ethereum/p2p" 30 "github.com/ethereum/go-ethereum/p2p/enode" 31 "github.com/ethereum/go-ethereum/p2p/simulations/pipes" 32 "github.com/ethereum/go-ethereum/rpc" 33 ) 34 35 // SimAdapter is a NodeAdapter which creates in-memory simulation nodes and 36 // connects them using net.Pipe 37 type SimAdapter struct { 38 pipe func() (net.Conn, net.Conn, error) 39 mtx sync.RWMutex 40 nodes map[enode.ID]*SimNode 41 services map[string]ServiceFunc 42 } 43 44 // NewSimAdapter creates a SimAdapter which is capable of running in-memory 45 // simulation nodes running any of the given services (the services to run on a 46 // particular node are passed to the NewNode function in the NodeConfig) 47 // the adapter uses a net.Pipe for in-memory simulated network connections 48 func NewSimAdapter(services map[string]ServiceFunc) *SimAdapter { 49 return &SimAdapter{ 50 pipe: pipes.NetPipe, 51 nodes: make(map[enode.ID]*SimNode), 52 services: services, 53 } 54 } 55 56 func NewTCPAdapter(services map[string]ServiceFunc) *SimAdapter { 57 return &SimAdapter{ 58 pipe: pipes.TCPPipe, 59 nodes: make(map[enode.ID]*SimNode), 60 services: services, 61 } 62 } 63 64 // Name returns the name of the adapter for logging purposes 65 func (s *SimAdapter) Name() string { 66 return "sim-adapter" 67 } 68 69 // NewNode returns a new SimNode using the given config 70 func (s *SimAdapter) NewNode(config *NodeConfig) (Node, error) { 71 s.mtx.Lock() 72 defer s.mtx.Unlock() 73 74 // check a node with the ID doesn't already exist 75 id := config.ID 76 if _, exists := s.nodes[id]; exists { 77 return nil, fmt.Errorf("node already exists: %s", id) 78 } 79 80 // check the services are valid 81 if len(config.Services) == 0 { 82 return nil, errors.New("node must have at least one service") 83 } 84 for _, service := range config.Services { 85 if _, exists := s.services[service]; !exists { 86 return nil, fmt.Errorf("unknown node service %q", service) 87 } 88 } 89 90 n, err := node.New(&node.Config{ 91 P2P: p2p.Config{ 92 PrivateKey: config.PrivateKey, 93 MaxPeers: math.MaxInt32, 94 NoDiscovery: true, 95 Dialer: s, 96 EnableMsgEvents: config.EnableMsgEvents, 97 }, 98 NoUSB: true, 99 Logger: log.New("node.id", id.String()), 100 }) 101 if err != nil { 102 return nil, err 103 } 104 105 simNode := &SimNode{ 106 ID: id, 107 config: config, 108 node: n, 109 adapter: s, 110 running: make(map[string]node.Service), 111 connected: make(map[enode.ID]bool), 112 } 113 s.nodes[id] = simNode 114 return simNode, nil 115 } 116 117 // Dial implements the p2p.NodeDialer interface by connecting to the node using 118 // an in-memory net.Pipe 119 func (s *SimAdapter) Dial(dest *enode.Node) (conn net.Conn, err error) { 120 node, ok := s.GetNode(dest.ID()) 121 if !ok { 122 return nil, fmt.Errorf("unknown node: %s", dest.ID()) 123 } 124 if node.connected[dest.ID()] { 125 return nil, fmt.Errorf("dialed node: %s", dest.ID()) 126 } 127 srv := node.Server() 128 if srv == nil { 129 return nil, fmt.Errorf("node not running: %s", dest.ID()) 130 } 131 // SimAdapter.pipe is net.Pipe (NewSimAdapter) 132 pipe1, pipe2, err := s.pipe() 133 if err != nil { 134 return nil, err 135 } 136 // this is simulated 'listening' 137 // asynchronously call the dialed destination node's p2p server 138 // to set up connection on the 'listening' side 139 go srv.SetupConn(pipe1, 0, nil) 140 node.connected[dest.ID()] = true 141 return pipe2, nil 142 } 143 144 // DialRPC implements the RPCDialer interface by creating an in-memory RPC 145 // client of the given node 146 func (s *SimAdapter) DialRPC(id enode.ID) (*rpc.Client, error) { 147 node, ok := s.GetNode(id) 148 if !ok { 149 return nil, fmt.Errorf("unknown node: %s", id) 150 } 151 handler, err := node.node.RPCHandler() 152 if err != nil { 153 return nil, err 154 } 155 return rpc.DialInProc(handler), nil 156 } 157 158 // GetNode returns the node with the given ID if it exists 159 func (s *SimAdapter) GetNode(id enode.ID) (*SimNode, bool) { 160 s.mtx.RLock() 161 defer s.mtx.RUnlock() 162 node, ok := s.nodes[id] 163 return node, ok 164 } 165 166 // SimNode is an in-memory simulation node which connects to other nodes using 167 // net.Pipe (see SimAdapter.Dial), running devp2p protocols directly over that 168 // pipe 169 type SimNode struct { 170 lock sync.RWMutex 171 ID enode.ID 172 config *NodeConfig 173 adapter *SimAdapter 174 node *node.Node 175 running map[string]node.Service 176 client *rpc.Client 177 registerOnce sync.Once 178 connected map[enode.ID]bool 179 } 180 181 // Addr returns the node's discovery address 182 func (sn *SimNode) Addr() []byte { 183 return []byte(sn.Node().String()) 184 } 185 186 // Node returns a node descriptor representing the SimNode 187 func (sn *SimNode) Node() *enode.Node { 188 return sn.config.Node() 189 } 190 191 // Client returns an rpc.Client which can be used to communicate with the 192 // underlying services (it is set once the node has started) 193 func (sn *SimNode) Client() (*rpc.Client, error) { 194 sn.lock.RLock() 195 defer sn.lock.RUnlock() 196 if sn.client == nil { 197 return nil, errors.New("node not started") 198 } 199 return sn.client, nil 200 } 201 202 // ServeRPC serves RPC requests over the given connection by creating an 203 // in-memory client to the node's RPC server 204 func (sn *SimNode) ServeRPC(conn net.Conn) error { 205 handler, err := sn.node.RPCHandler() 206 if err != nil { 207 return err 208 } 209 handler.ServeCodec(rpc.NewJSONCodec(conn), rpc.OptionMethodInvocation|rpc.OptionSubscriptions) 210 return nil 211 } 212 213 // Snapshots creates snapshots of the services by calling the 214 // simulation_snapshot RPC method 215 func (sn *SimNode) Snapshots() (map[string][]byte, error) { 216 sn.lock.RLock() 217 services := make(map[string]node.Service, len(sn.running)) 218 for name, service := range sn.running { 219 services[name] = service 220 } 221 sn.lock.RUnlock() 222 if len(services) == 0 { 223 return nil, errors.New("no running services") 224 } 225 snapshots := make(map[string][]byte) 226 for name, service := range services { 227 if s, ok := service.(interface { 228 Snapshot() ([]byte, error) 229 }); ok { 230 snap, err := s.Snapshot() 231 if err != nil { 232 return nil, err 233 } 234 snapshots[name] = snap 235 } 236 } 237 return snapshots, nil 238 } 239 240 // Start registers the services and starts the underlying devp2p node 241 func (sn *SimNode) Start(snapshots map[string][]byte) error { 242 newService := func(name string) func(ctx *node.ServiceContext) (node.Service, error) { 243 return func(nodeCtx *node.ServiceContext) (node.Service, error) { 244 ctx := &ServiceContext{ 245 RPCDialer: sn.adapter, 246 NodeContext: nodeCtx, 247 Config: sn.config, 248 } 249 if snapshots != nil { 250 ctx.Snapshot = snapshots[name] 251 } 252 serviceFunc := sn.adapter.services[name] 253 service, err := serviceFunc(ctx) 254 if err != nil { 255 return nil, err 256 } 257 sn.running[name] = service 258 return service, nil 259 } 260 } 261 262 // ensure we only register the services once in the case of the node 263 // being stopped and then started again 264 var regErr error 265 sn.registerOnce.Do(func() { 266 for _, name := range sn.config.Services { 267 if err := sn.node.Register(newService(name)); err != nil { 268 regErr = err 269 break 270 } 271 } 272 }) 273 if regErr != nil { 274 return regErr 275 } 276 277 if err := sn.node.Start(); err != nil { 278 return err 279 } 280 281 // create an in-process RPC client 282 handler, err := sn.node.RPCHandler() 283 if err != nil { 284 return err 285 } 286 287 sn.lock.Lock() 288 sn.client = rpc.DialInProc(handler) 289 sn.lock.Unlock() 290 291 return nil 292 } 293 294 // Stop closes the RPC client and stops the underlying devp2p node 295 func (sn *SimNode) Stop() error { 296 sn.lock.Lock() 297 if sn.client != nil { 298 sn.client.Close() 299 sn.client = nil 300 } 301 sn.lock.Unlock() 302 return sn.node.Stop() 303 } 304 305 // Service returns a running service by name 306 func (sn *SimNode) Service(name string) node.Service { 307 sn.lock.RLock() 308 defer sn.lock.RUnlock() 309 return sn.running[name] 310 } 311 312 // Services returns a copy of the underlying services 313 func (sn *SimNode) Services() []node.Service { 314 sn.lock.RLock() 315 defer sn.lock.RUnlock() 316 services := make([]node.Service, 0, len(sn.running)) 317 for _, service := range sn.running { 318 services = append(services, service) 319 } 320 return services 321 } 322 323 // ServiceMap returns a map by names of the underlying services 324 func (sn *SimNode) ServiceMap() map[string]node.Service { 325 sn.lock.RLock() 326 defer sn.lock.RUnlock() 327 services := make(map[string]node.Service, len(sn.running)) 328 for name, service := range sn.running { 329 services[name] = service 330 } 331 return services 332 } 333 334 // Server returns the underlying p2p.Server 335 func (sn *SimNode) Server() *p2p.Server { 336 return sn.node.Server() 337 } 338 339 // SubscribeEvents subscribes the given channel to peer events from the 340 // underlying p2p.Server 341 func (sn *SimNode) SubscribeEvents(ch chan *p2p.PeerEvent) event.Subscription { 342 srv := sn.Server() 343 if srv == nil { 344 panic("node not running") 345 } 346 return srv.SubscribeEvents(ch) 347 } 348 349 // NodeInfo returns information about the node 350 func (sn *SimNode) NodeInfo() *p2p.NodeInfo { 351 server := sn.Server() 352 if server == nil { 353 return &p2p.NodeInfo{ 354 ID: sn.ID.String(), 355 Enode: sn.Node().String(), 356 } 357 } 358 return server.NodeInfo() 359 }