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