github.com/theQRL/go-zond@v0.1.1/p2p/peer.go (about) 1 // Copyright 2014 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 p2p 18 19 import ( 20 "errors" 21 "fmt" 22 "io" 23 "net" 24 "sync" 25 "time" 26 27 "github.com/theQRL/go-zond/common/mclock" 28 "github.com/theQRL/go-zond/event" 29 "github.com/theQRL/go-zond/log" 30 "github.com/theQRL/go-zond/metrics" 31 "github.com/theQRL/go-zond/p2p/enode" 32 "github.com/theQRL/go-zond/p2p/enr" 33 "github.com/theQRL/go-zond/rlp" 34 "golang.org/x/exp/slices" 35 ) 36 37 var ( 38 ErrShuttingDown = errors.New("shutting down") 39 ) 40 41 const ( 42 baseProtocolVersion = 5 43 baseProtocolLength = uint64(16) 44 baseProtocolMaxMsgSize = 2 * 1024 45 46 snappyProtocolVersion = 5 47 48 pingInterval = 15 * time.Second 49 ) 50 51 const ( 52 // devp2p message codes 53 handshakeMsg = 0x00 54 discMsg = 0x01 55 pingMsg = 0x02 56 pongMsg = 0x03 57 ) 58 59 // protoHandshake is the RLP structure of the protocol handshake. 60 type protoHandshake struct { 61 Version uint64 62 Name string 63 Caps []Cap 64 ListenPort uint64 65 ID []byte // secp256k1 public key 66 67 // Ignore additional fields (for forward compatibility). 68 Rest []rlp.RawValue `rlp:"tail"` 69 } 70 71 // PeerEventType is the type of peer events emitted by a p2p.Server 72 type PeerEventType string 73 74 const ( 75 // PeerEventTypeAdd is the type of event emitted when a peer is added 76 // to a p2p.Server 77 PeerEventTypeAdd PeerEventType = "add" 78 79 // PeerEventTypeDrop is the type of event emitted when a peer is 80 // dropped from a p2p.Server 81 PeerEventTypeDrop PeerEventType = "drop" 82 83 // PeerEventTypeMsgSend is the type of event emitted when a 84 // message is successfully sent to a peer 85 PeerEventTypeMsgSend PeerEventType = "msgsend" 86 87 // PeerEventTypeMsgRecv is the type of event emitted when a 88 // message is received from a peer 89 PeerEventTypeMsgRecv PeerEventType = "msgrecv" 90 ) 91 92 // PeerEvent is an event emitted when peers are either added or dropped from 93 // a p2p.Server or when a message is sent or received on a peer connection 94 type PeerEvent struct { 95 Type PeerEventType `json:"type"` 96 Peer enode.ID `json:"peer"` 97 Error string `json:"error,omitempty"` 98 Protocol string `json:"protocol,omitempty"` 99 MsgCode *uint64 `json:"msg_code,omitempty"` 100 MsgSize *uint32 `json:"msg_size,omitempty"` 101 LocalAddress string `json:"local,omitempty"` 102 RemoteAddress string `json:"remote,omitempty"` 103 } 104 105 // Peer represents a connected remote node. 106 type Peer struct { 107 rw *conn 108 running map[string]*protoRW 109 log log.Logger 110 created mclock.AbsTime 111 112 wg sync.WaitGroup 113 protoErr chan error 114 closed chan struct{} 115 pingRecv chan struct{} 116 disc chan DiscReason 117 118 // events receives message send / receive events if set 119 events *event.Feed 120 testPipe *MsgPipeRW // for testing 121 } 122 123 // NewPeer returns a peer for testing purposes. 124 func NewPeer(id enode.ID, name string, caps []Cap) *Peer { 125 // Generate a fake set of local protocols to match as running caps. Almost 126 // no fields needs to be meaningful here as we're only using it to cross- 127 // check with the "remote" caps array. 128 protos := make([]Protocol, len(caps)) 129 for i, cap := range caps { 130 protos[i].Name = cap.Name 131 protos[i].Version = cap.Version 132 } 133 pipe, _ := net.Pipe() 134 node := enode.SignNull(new(enr.Record), id) 135 conn := &conn{fd: pipe, transport: nil, node: node, caps: caps, name: name} 136 peer := newPeer(log.Root(), conn, protos) 137 close(peer.closed) // ensures Disconnect doesn't block 138 return peer 139 } 140 141 // NewPeerPipe creates a peer for testing purposes. 142 // The message pipe given as the last parameter is closed when 143 // Disconnect is called on the peer. 144 func NewPeerPipe(id enode.ID, name string, caps []Cap, pipe *MsgPipeRW) *Peer { 145 p := NewPeer(id, name, caps) 146 p.testPipe = pipe 147 return p 148 } 149 150 // ID returns the node's public key. 151 func (p *Peer) ID() enode.ID { 152 return p.rw.node.ID() 153 } 154 155 // Node returns the peer's node descriptor. 156 func (p *Peer) Node() *enode.Node { 157 return p.rw.node 158 } 159 160 // Name returns an abbreviated form of the name 161 func (p *Peer) Name() string { 162 s := p.rw.name 163 if len(s) > 20 { 164 return s[:20] + "..." 165 } 166 return s 167 } 168 169 // Fullname returns the node name that the remote node advertised. 170 func (p *Peer) Fullname() string { 171 return p.rw.name 172 } 173 174 // Caps returns the capabilities (supported subprotocols) of the remote peer. 175 func (p *Peer) Caps() []Cap { 176 // TODO: maybe return copy 177 return p.rw.caps 178 } 179 180 // RunningCap returns true if the peer is actively connected using any of the 181 // enumerated versions of a specific protocol, meaning that at least one of the 182 // versions is supported by both this node and the peer p. 183 func (p *Peer) RunningCap(protocol string, versions []uint) bool { 184 if proto, ok := p.running[protocol]; ok { 185 for _, ver := range versions { 186 if proto.Version == ver { 187 return true 188 } 189 } 190 } 191 return false 192 } 193 194 // RemoteAddr returns the remote address of the network connection. 195 func (p *Peer) RemoteAddr() net.Addr { 196 return p.rw.fd.RemoteAddr() 197 } 198 199 // LocalAddr returns the local address of the network connection. 200 func (p *Peer) LocalAddr() net.Addr { 201 return p.rw.fd.LocalAddr() 202 } 203 204 // Disconnect terminates the peer connection with the given reason. 205 // It returns immediately and does not wait until the connection is closed. 206 func (p *Peer) Disconnect(reason DiscReason) { 207 if p.testPipe != nil { 208 p.testPipe.Close() 209 } 210 211 select { 212 case p.disc <- reason: 213 case <-p.closed: 214 } 215 } 216 217 // String implements fmt.Stringer. 218 func (p *Peer) String() string { 219 id := p.ID() 220 return fmt.Sprintf("Peer %x %v", id[:8], p.RemoteAddr()) 221 } 222 223 // Inbound returns true if the peer is an inbound connection 224 func (p *Peer) Inbound() bool { 225 return p.rw.is(inboundConn) 226 } 227 228 func newPeer(log log.Logger, conn *conn, protocols []Protocol) *Peer { 229 protomap := matchProtocols(protocols, conn.caps, conn) 230 p := &Peer{ 231 rw: conn, 232 running: protomap, 233 created: mclock.Now(), 234 disc: make(chan DiscReason), 235 protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop 236 closed: make(chan struct{}), 237 pingRecv: make(chan struct{}, 16), 238 log: log.New("id", conn.node.ID(), "conn", conn.flags), 239 } 240 return p 241 } 242 243 func (p *Peer) Log() log.Logger { 244 return p.log 245 } 246 247 func (p *Peer) run() (remoteRequested bool, err error) { 248 var ( 249 writeStart = make(chan struct{}, 1) 250 writeErr = make(chan error, 1) 251 readErr = make(chan error, 1) 252 reason DiscReason // sent to the peer 253 ) 254 p.wg.Add(2) 255 go p.readLoop(readErr) 256 go p.pingLoop() 257 258 // Start all protocol handlers. 259 writeStart <- struct{}{} 260 p.startProtocols(writeStart, writeErr) 261 262 // Wait for an error or disconnect. 263 loop: 264 for { 265 select { 266 case err = <-writeErr: 267 // A write finished. Allow the next write to start if 268 // there was no error. 269 if err != nil { 270 reason = DiscNetworkError 271 break loop 272 } 273 writeStart <- struct{}{} 274 case err = <-readErr: 275 if r, ok := err.(DiscReason); ok { 276 remoteRequested = true 277 reason = r 278 } else { 279 reason = DiscNetworkError 280 } 281 break loop 282 case err = <-p.protoErr: 283 reason = discReasonForError(err) 284 break loop 285 case err = <-p.disc: 286 reason = discReasonForError(err) 287 break loop 288 } 289 } 290 291 close(p.closed) 292 p.rw.close(reason) 293 p.wg.Wait() 294 return remoteRequested, err 295 } 296 297 func (p *Peer) pingLoop() { 298 defer p.wg.Done() 299 300 ping := time.NewTimer(pingInterval) 301 defer ping.Stop() 302 303 for { 304 select { 305 case <-ping.C: 306 if err := SendItems(p.rw, pingMsg); err != nil { 307 p.protoErr <- err 308 return 309 } 310 ping.Reset(pingInterval) 311 312 case <-p.pingRecv: 313 SendItems(p.rw, pongMsg) 314 315 case <-p.closed: 316 return 317 } 318 } 319 } 320 321 func (p *Peer) readLoop(errc chan<- error) { 322 defer p.wg.Done() 323 for { 324 msg, err := p.rw.ReadMsg() 325 if err != nil { 326 errc <- err 327 return 328 } 329 msg.ReceivedAt = time.Now() 330 if err = p.handle(msg); err != nil { 331 errc <- err 332 return 333 } 334 } 335 } 336 337 func (p *Peer) handle(msg Msg) error { 338 switch { 339 case msg.Code == pingMsg: 340 msg.Discard() 341 select { 342 case p.pingRecv <- struct{}{}: 343 case <-p.closed: 344 } 345 case msg.Code == discMsg: 346 // This is the last message. We don't need to discard or 347 // check errors because, the connection will be closed after it. 348 var m struct{ R DiscReason } 349 rlp.Decode(msg.Payload, &m) 350 return m.R 351 case msg.Code < baseProtocolLength: 352 // ignore other base protocol messages 353 return msg.Discard() 354 default: 355 // it's a subprotocol message 356 proto, err := p.getProto(msg.Code) 357 if err != nil { 358 return fmt.Errorf("msg code out of range: %v", msg.Code) 359 } 360 if metrics.Enabled { 361 m := fmt.Sprintf("%s/%s/%d/%#02x", ingressMeterName, proto.Name, proto.Version, msg.Code-proto.offset) 362 metrics.GetOrRegisterMeter(m, nil).Mark(int64(msg.meterSize)) 363 metrics.GetOrRegisterMeter(m+"/packets", nil).Mark(1) 364 } 365 select { 366 case proto.in <- msg: 367 return nil 368 case <-p.closed: 369 return io.EOF 370 } 371 } 372 return nil 373 } 374 375 func countMatchingProtocols(protocols []Protocol, caps []Cap) int { 376 n := 0 377 for _, cap := range caps { 378 for _, proto := range protocols { 379 if proto.Name == cap.Name && proto.Version == cap.Version { 380 n++ 381 } 382 } 383 } 384 return n 385 } 386 387 // matchProtocols creates structures for matching named subprotocols. 388 func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW { 389 slices.SortFunc(caps, Cap.Cmp) 390 offset := baseProtocolLength 391 result := make(map[string]*protoRW) 392 393 outer: 394 for _, cap := range caps { 395 for _, proto := range protocols { 396 if proto.Name == cap.Name && proto.Version == cap.Version { 397 // If an old protocol version matched, revert it 398 if old := result[cap.Name]; old != nil { 399 offset -= old.Length 400 } 401 // Assign the new match 402 result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw} 403 offset += proto.Length 404 405 continue outer 406 } 407 } 408 } 409 return result 410 } 411 412 func (p *Peer) startProtocols(writeStart <-chan struct{}, writeErr chan<- error) { 413 p.wg.Add(len(p.running)) 414 for _, proto := range p.running { 415 proto := proto 416 proto.closed = p.closed 417 proto.wstart = writeStart 418 proto.werr = writeErr 419 var rw MsgReadWriter = proto 420 if p.events != nil { 421 rw = newMsgEventer(rw, p.events, p.ID(), proto.Name, p.Info().Network.RemoteAddress, p.Info().Network.LocalAddress) 422 } 423 p.log.Trace(fmt.Sprintf("Starting protocol %s/%d", proto.Name, proto.Version)) 424 go func() { 425 defer p.wg.Done() 426 err := proto.Run(p, rw) 427 if err == nil { 428 p.log.Trace(fmt.Sprintf("Protocol %s/%d returned", proto.Name, proto.Version)) 429 err = errProtocolReturned 430 } else if !errors.Is(err, io.EOF) { 431 p.log.Trace(fmt.Sprintf("Protocol %s/%d failed", proto.Name, proto.Version), "err", err) 432 } 433 p.protoErr <- err 434 }() 435 } 436 } 437 438 // getProto finds the protocol responsible for handling 439 // the given message code. 440 func (p *Peer) getProto(code uint64) (*protoRW, error) { 441 for _, proto := range p.running { 442 if code >= proto.offset && code < proto.offset+proto.Length { 443 return proto, nil 444 } 445 } 446 return nil, newPeerError(errInvalidMsgCode, "%d", code) 447 } 448 449 type protoRW struct { 450 Protocol 451 in chan Msg // receives read messages 452 closed <-chan struct{} // receives when peer is shutting down 453 wstart <-chan struct{} // receives when write may start 454 werr chan<- error // for write results 455 offset uint64 456 w MsgWriter 457 } 458 459 func (rw *protoRW) WriteMsg(msg Msg) (err error) { 460 if msg.Code >= rw.Length { 461 return newPeerError(errInvalidMsgCode, "not handled") 462 } 463 msg.meterCap = rw.cap() 464 msg.meterCode = msg.Code 465 466 msg.Code += rw.offset 467 468 select { 469 case <-rw.wstart: 470 err = rw.w.WriteMsg(msg) 471 // Report write status back to Peer.run. It will initiate 472 // shutdown if the error is non-nil and unblock the next write 473 // otherwise. The calling protocol code should exit for errors 474 // as well but we don't want to rely on that. 475 rw.werr <- err 476 case <-rw.closed: 477 err = ErrShuttingDown 478 } 479 return err 480 } 481 482 func (rw *protoRW) ReadMsg() (Msg, error) { 483 select { 484 case msg := <-rw.in: 485 msg.Code -= rw.offset 486 return msg, nil 487 case <-rw.closed: 488 return Msg{}, io.EOF 489 } 490 } 491 492 // PeerInfo represents a short summary of the information known about a connected 493 // peer. Sub-protocol independent fields are contained and initialized here, with 494 // protocol specifics delegated to all connected sub-protocols. 495 type PeerInfo struct { 496 ENR string `json:"enr,omitempty"` // Ethereum Node Record 497 Enode string `json:"enode"` // Node URL 498 ID string `json:"id"` // Unique node identifier 499 Name string `json:"name"` // Name of the node, including client type, version, OS, custom data 500 Caps []string `json:"caps"` // Protocols advertised by this peer 501 Network struct { 502 LocalAddress string `json:"localAddress"` // Local endpoint of the TCP data connection 503 RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection 504 Inbound bool `json:"inbound"` 505 Trusted bool `json:"trusted"` 506 Static bool `json:"static"` 507 } `json:"network"` 508 Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields 509 } 510 511 // Info gathers and returns a collection of metadata known about a peer. 512 func (p *Peer) Info() *PeerInfo { 513 // Gather the protocol capabilities 514 var caps []string 515 for _, cap := range p.Caps() { 516 caps = append(caps, cap.String()) 517 } 518 // Assemble the generic peer metadata 519 info := &PeerInfo{ 520 Enode: p.Node().URLv4(), 521 ID: p.ID().String(), 522 Name: p.Fullname(), 523 Caps: caps, 524 Protocols: make(map[string]interface{}, len(p.running)), 525 } 526 if p.Node().Seq() > 0 { 527 info.ENR = p.Node().String() 528 } 529 info.Network.LocalAddress = p.LocalAddr().String() 530 info.Network.RemoteAddress = p.RemoteAddr().String() 531 info.Network.Inbound = p.rw.is(inboundConn) 532 info.Network.Trusted = p.rw.is(trustedConn) 533 info.Network.Static = p.rw.is(staticDialedConn) 534 535 // Gather all the running protocol infos 536 for _, proto := range p.running { 537 protoInfo := interface{}("unknown") 538 if query := proto.Protocol.PeerInfo; query != nil { 539 if metadata := query(p.ID()); metadata != nil { 540 protoInfo = metadata 541 } else { 542 protoInfo = "handshake" 543 } 544 } 545 info.Protocols[proto.Name] = protoInfo 546 } 547 return info 548 }