github.com/openethereum/go-ethereum@v1.9.7/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 } 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 metrics.GetOrRegisterMeter(fmt.Sprintf("%s/%s/%d/%#02x", MetricsInboundTraffic, proto.Name, proto.Version, msg.Code-proto.offset), nil).Mark(int64(msg.meterSize)) 306 } 307 select { 308 case proto.in <- msg: 309 return nil 310 case <-p.closed: 311 return io.EOF 312 } 313 } 314 return nil 315 } 316 317 func countMatchingProtocols(protocols []Protocol, caps []Cap) int { 318 n := 0 319 for _, cap := range caps { 320 for _, proto := range protocols { 321 if proto.Name == cap.Name && proto.Version == cap.Version { 322 n++ 323 } 324 } 325 } 326 return n 327 } 328 329 // matchProtocols creates structures for matching named subprotocols. 330 func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW { 331 sort.Sort(capsByNameAndVersion(caps)) 332 offset := baseProtocolLength 333 result := make(map[string]*protoRW) 334 335 outer: 336 for _, cap := range caps { 337 for _, proto := range protocols { 338 if proto.Name == cap.Name && proto.Version == cap.Version { 339 // If an old protocol version matched, revert it 340 if old := result[cap.Name]; old != nil { 341 offset -= old.Length 342 } 343 // Assign the new match 344 result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw} 345 offset += proto.Length 346 347 continue outer 348 } 349 } 350 } 351 return result 352 } 353 354 func (p *Peer) startProtocols(writeStart <-chan struct{}, writeErr chan<- error) { 355 p.wg.Add(len(p.running)) 356 for _, proto := range p.running { 357 proto := proto 358 proto.closed = p.closed 359 proto.wstart = writeStart 360 proto.werr = writeErr 361 var rw MsgReadWriter = proto 362 if p.events != nil { 363 rw = newMsgEventer(rw, p.events, p.ID(), proto.Name, p.Info().Network.RemoteAddress, p.Info().Network.LocalAddress) 364 } 365 p.log.Trace(fmt.Sprintf("Starting protocol %s/%d", proto.Name, proto.Version)) 366 go func() { 367 err := proto.Run(p, rw) 368 if err == nil { 369 p.log.Trace(fmt.Sprintf("Protocol %s/%d returned", proto.Name, proto.Version)) 370 err = errProtocolReturned 371 } else if err != io.EOF { 372 p.log.Trace(fmt.Sprintf("Protocol %s/%d failed", proto.Name, proto.Version), "err", err) 373 } 374 p.protoErr <- err 375 p.wg.Done() 376 }() 377 } 378 } 379 380 // getProto finds the protocol responsible for handling 381 // the given message code. 382 func (p *Peer) getProto(code uint64) (*protoRW, error) { 383 for _, proto := range p.running { 384 if code >= proto.offset && code < proto.offset+proto.Length { 385 return proto, nil 386 } 387 } 388 return nil, newPeerError(errInvalidMsgCode, "%d", code) 389 } 390 391 type protoRW struct { 392 Protocol 393 in chan Msg // receives read messages 394 closed <-chan struct{} // receives when peer is shutting down 395 wstart <-chan struct{} // receives when write may start 396 werr chan<- error // for write results 397 offset uint64 398 w MsgWriter 399 } 400 401 func (rw *protoRW) WriteMsg(msg Msg) (err error) { 402 if msg.Code >= rw.Length { 403 return newPeerError(errInvalidMsgCode, "not handled") 404 } 405 msg.meterCap = rw.cap() 406 msg.meterCode = msg.Code 407 408 msg.Code += rw.offset 409 410 select { 411 case <-rw.wstart: 412 err = rw.w.WriteMsg(msg) 413 // Report write status back to Peer.run. It will initiate 414 // shutdown if the error is non-nil and unblock the next write 415 // otherwise. The calling protocol code should exit for errors 416 // as well but we don't want to rely on that. 417 rw.werr <- err 418 case <-rw.closed: 419 err = ErrShuttingDown 420 } 421 return err 422 } 423 424 func (rw *protoRW) ReadMsg() (Msg, error) { 425 select { 426 case msg := <-rw.in: 427 msg.Code -= rw.offset 428 return msg, nil 429 case <-rw.closed: 430 return Msg{}, io.EOF 431 } 432 } 433 434 // PeerInfo represents a short summary of the information known about a connected 435 // peer. Sub-protocol independent fields are contained and initialized here, with 436 // protocol specifics delegated to all connected sub-protocols. 437 type PeerInfo struct { 438 ENR string `json:"enr,omitempty"` // Ethereum Node Record 439 Enode string `json:"enode"` // Node URL 440 ID string `json:"id"` // Unique node identifier 441 Name string `json:"name"` // Name of the node, including client type, version, OS, custom data 442 Caps []string `json:"caps"` // Protocols advertised by this peer 443 Network struct { 444 LocalAddress string `json:"localAddress"` // Local endpoint of the TCP data connection 445 RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection 446 Inbound bool `json:"inbound"` 447 Trusted bool `json:"trusted"` 448 Static bool `json:"static"` 449 } `json:"network"` 450 Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields 451 } 452 453 // Info gathers and returns a collection of metadata known about a peer. 454 func (p *Peer) Info() *PeerInfo { 455 // Gather the protocol capabilities 456 var caps []string 457 for _, cap := range p.Caps() { 458 caps = append(caps, cap.String()) 459 } 460 // Assemble the generic peer metadata 461 info := &PeerInfo{ 462 Enode: p.Node().URLv4(), 463 ID: p.ID().String(), 464 Name: p.Name(), 465 Caps: caps, 466 Protocols: make(map[string]interface{}), 467 } 468 if p.Node().Seq() > 0 { 469 info.ENR = p.Node().String() 470 } 471 info.Network.LocalAddress = p.LocalAddr().String() 472 info.Network.RemoteAddress = p.RemoteAddr().String() 473 info.Network.Inbound = p.rw.is(inboundConn) 474 info.Network.Trusted = p.rw.is(trustedConn) 475 info.Network.Static = p.rw.is(staticDialedConn) 476 477 // Gather all the running protocol infos 478 for _, proto := range p.running { 479 protoInfo := interface{}("unknown") 480 if query := proto.Protocol.PeerInfo; query != nil { 481 if metadata := query(p.ID()); metadata != nil { 482 protoInfo = metadata 483 } else { 484 protoInfo = "handshake" 485 } 486 } 487 info.Protocols[proto.Name] = protoInfo 488 } 489 return info 490 }