github.com/jincm/wesharechain@v0.0.0-20210122032815-1537409ce26a/chain/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 } 112 s.nodes[id] = simNode 113 return simNode, nil 114 } 115 116 // Dial implements the p2p.NodeDialer interface by connecting to the node using 117 // an in-memory net.Pipe 118 func (s *SimAdapter) Dial(dest *enode.Node) (conn net.Conn, err error) { 119 node, ok := s.GetNode(dest.ID()) 120 if !ok { 121 return nil, fmt.Errorf("unknown node: %s", dest.ID()) 122 } 123 srv := node.Server() 124 if srv == nil { 125 return nil, fmt.Errorf("node not running: %s", dest.ID()) 126 } 127 // SimAdapter.pipe is net.Pipe (NewSimAdapter) 128 pipe1, pipe2, err := s.pipe() 129 if err != nil { 130 return nil, err 131 } 132 // this is simulated 'listening' 133 // asynchronously call the dialed destination node's p2p server 134 // to set up connection on the 'listening' side 135 go srv.SetupConn(pipe1, 0, nil) 136 return pipe2, nil 137 } 138 139 // DialRPC implements the RPCDialer interface by creating an in-memory RPC 140 // client of the given node 141 func (s *SimAdapter) DialRPC(id enode.ID) (*rpc.Client, error) { 142 node, ok := s.GetNode(id) 143 if !ok { 144 return nil, fmt.Errorf("unknown node: %s", id) 145 } 146 handler, err := node.node.RPCHandler() 147 if err != nil { 148 return nil, err 149 } 150 return rpc.DialInProc(handler), nil 151 } 152 153 // GetNode returns the node with the given ID if it exists 154 func (s *SimAdapter) GetNode(id enode.ID) (*SimNode, bool) { 155 s.mtx.RLock() 156 defer s.mtx.RUnlock() 157 node, ok := s.nodes[id] 158 return node, ok 159 } 160 161 // SimNode is an in-memory simulation node which connects to other nodes using 162 // net.Pipe (see SimAdapter.Dial), running devp2p protocols directly over that 163 // pipe 164 type SimNode struct { 165 lock sync.RWMutex 166 ID enode.ID 167 config *NodeConfig 168 adapter *SimAdapter 169 node *node.Node 170 running map[string]node.Service 171 client *rpc.Client 172 registerOnce sync.Once 173 } 174 175 // Close closes the underlaying node.Node to release 176 // acquired resources. 177 func (sn *SimNode) Close() error { 178 return sn.node.Close() 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 }