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