github.com/luckypickle/go-ethereum-vet@v1.14.2/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/luckypickle/go-ethereum-vet/event" 27 "github.com/luckypickle/go-ethereum-vet/log" 28 "github.com/luckypickle/go-ethereum-vet/node" 29 "github.com/luckypickle/go-ethereum-vet/p2p" 30 "github.com/luckypickle/go-ethereum-vet/p2p/discover" 31 "github.com/luckypickle/go-ethereum-vet/p2p/simulations/pipes" 32 "github.com/luckypickle/go-ethereum-vet/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[discover.NodeID]*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[discover.NodeID]*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[discover.NodeID]*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 *discover.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 destintion 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 discover.NodeID) (*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 discover.NodeID) (*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 discover.NodeID 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 // Addr returns the node's discovery address 176 func (sn *SimNode) Addr() []byte { 177 return []byte(sn.Node().String()) 178 } 179 180 // Node returns a discover.Node representing the SimNode 181 func (sn *SimNode) Node() *discover.Node { 182 return discover.NewNode(sn.ID, net.IP{127, 0, 0, 1}, 30303, 30303) 183 } 184 185 // Client returns an rpc.Client which can be used to communicate with the 186 // underlying services (it is set once the node has started) 187 func (sn *SimNode) Client() (*rpc.Client, error) { 188 sn.lock.RLock() 189 defer sn.lock.RUnlock() 190 if sn.client == nil { 191 return nil, errors.New("node not started") 192 } 193 return sn.client, nil 194 } 195 196 // ServeRPC serves RPC requests over the given connection by creating an 197 // in-memory client to the node's RPC server 198 func (sn *SimNode) ServeRPC(conn net.Conn) error { 199 handler, err := sn.node.RPCHandler() 200 if err != nil { 201 return err 202 } 203 handler.ServeCodec(rpc.NewJSONCodec(conn), rpc.OptionMethodInvocation|rpc.OptionSubscriptions) 204 return nil 205 } 206 207 // Snapshots creates snapshots of the services by calling the 208 // simulation_snapshot RPC method 209 func (sn *SimNode) Snapshots() (map[string][]byte, error) { 210 sn.lock.RLock() 211 services := make(map[string]node.Service, len(sn.running)) 212 for name, service := range sn.running { 213 services[name] = service 214 } 215 sn.lock.RUnlock() 216 if len(services) == 0 { 217 return nil, errors.New("no running services") 218 } 219 snapshots := make(map[string][]byte) 220 for name, service := range services { 221 if s, ok := service.(interface { 222 Snapshot() ([]byte, error) 223 }); ok { 224 snap, err := s.Snapshot() 225 if err != nil { 226 return nil, err 227 } 228 snapshots[name] = snap 229 } 230 } 231 return snapshots, nil 232 } 233 234 // Start registers the services and starts the underlying devp2p node 235 func (sn *SimNode) Start(snapshots map[string][]byte) error { 236 newService := func(name string) func(ctx *node.ServiceContext) (node.Service, error) { 237 return func(nodeCtx *node.ServiceContext) (node.Service, error) { 238 ctx := &ServiceContext{ 239 RPCDialer: sn.adapter, 240 NodeContext: nodeCtx, 241 Config: sn.config, 242 } 243 if snapshots != nil { 244 ctx.Snapshot = snapshots[name] 245 } 246 serviceFunc := sn.adapter.services[name] 247 service, err := serviceFunc(ctx) 248 if err != nil { 249 return nil, err 250 } 251 sn.running[name] = service 252 return service, nil 253 } 254 } 255 256 // ensure we only register the services once in the case of the node 257 // being stopped and then started again 258 var regErr error 259 sn.registerOnce.Do(func() { 260 for _, name := range sn.config.Services { 261 if err := sn.node.Register(newService(name)); err != nil { 262 regErr = err 263 break 264 } 265 } 266 }) 267 if regErr != nil { 268 return regErr 269 } 270 271 if err := sn.node.Start(); err != nil { 272 return err 273 } 274 275 // create an in-process RPC client 276 handler, err := sn.node.RPCHandler() 277 if err != nil { 278 return err 279 } 280 281 sn.lock.Lock() 282 sn.client = rpc.DialInProc(handler) 283 sn.lock.Unlock() 284 285 return nil 286 } 287 288 // Stop closes the RPC client and stops the underlying devp2p node 289 func (sn *SimNode) Stop() error { 290 sn.lock.Lock() 291 if sn.client != nil { 292 sn.client.Close() 293 sn.client = nil 294 } 295 sn.lock.Unlock() 296 return sn.node.Stop() 297 } 298 299 // Service returns a running service by name 300 func (sn *SimNode) Service(name string) node.Service { 301 sn.lock.RLock() 302 defer sn.lock.RUnlock() 303 return sn.running[name] 304 } 305 306 // Services returns a copy of the underlying services 307 func (sn *SimNode) Services() []node.Service { 308 sn.lock.RLock() 309 defer sn.lock.RUnlock() 310 services := make([]node.Service, 0, len(sn.running)) 311 for _, service := range sn.running { 312 services = append(services, service) 313 } 314 return services 315 } 316 317 // ServiceMap returns a map by names of the underlying services 318 func (sn *SimNode) ServiceMap() map[string]node.Service { 319 sn.lock.RLock() 320 defer sn.lock.RUnlock() 321 services := make(map[string]node.Service, len(sn.running)) 322 for name, service := range sn.running { 323 services[name] = service 324 } 325 return services 326 } 327 328 // Server returns the underlying p2p.Server 329 func (sn *SimNode) Server() *p2p.Server { 330 return sn.node.Server() 331 } 332 333 // SubscribeEvents subscribes the given channel to peer events from the 334 // underlying p2p.Server 335 func (sn *SimNode) SubscribeEvents(ch chan *p2p.PeerEvent) event.Subscription { 336 srv := sn.Server() 337 if srv == nil { 338 panic("node not running") 339 } 340 return srv.SubscribeEvents(ch) 341 } 342 343 // NodeInfo returns information about the node 344 func (sn *SimNode) NodeInfo() *p2p.NodeInfo { 345 server := sn.Server() 346 if server == nil { 347 return &p2p.NodeInfo{ 348 ID: sn.ID.String(), 349 Enode: sn.Node().String(), 350 } 351 } 352 return server.NodeInfo() 353 } 354 355 func setSocketBuffer(conn net.Conn, socketReadBuffer int, socketWriteBuffer int) error { 356 if v, ok := conn.(*net.UnixConn); ok { 357 err := v.SetReadBuffer(socketReadBuffer) 358 if err != nil { 359 return err 360 } 361 err = v.SetWriteBuffer(socketWriteBuffer) 362 if err != nil { 363 return err 364 } 365 } 366 return nil 367 }