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