github.com/xinfinOrg/xdposchain@v1.1.0/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/p2p/enode" 32 "github.com/ethereum/go-ethereum/p2p/enr" 33 "github.com/ethereum/go-ethereum/rlp" 34 ) 35 36 var ( 37 ErrShuttingDown = errors.New("shutting down") 38 ) 39 40 const ( 41 baseProtocolVersion = 5 42 baseProtocolLength = uint64(16) 43 baseProtocolMaxMsgSize = 2 * 1024 44 45 snappyProtocolVersion = 5 46 47 pingInterval = 15 * time.Second 48 ) 49 50 const ( 51 // devp2p message codes 52 handshakeMsg = 0x00 53 discMsg = 0x01 54 pingMsg = 0x02 55 pongMsg = 0x03 56 ) 57 58 // protoHandshake is the RLP structure of the protocol handshake. 59 type protoHandshake struct { 60 Version uint64 61 Name string 62 Caps []Cap 63 ListenPort uint64 64 ID []byte // secp256k1 public key 65 66 // Ignore additional fields (for forward compatibility). 67 Rest []rlp.RawValue `rlp:"tail"` 68 } 69 70 // PeerEventType is the type of peer events emitted by a p2p.Server 71 type PeerEventType string 72 73 const ( 74 // PeerEventTypeAdd is the type of event emitted when a peer is added 75 // to a p2p.Server 76 PeerEventTypeAdd PeerEventType = "add" 77 78 // PeerEventTypeDrop is the type of event emitted when a peer is 79 // dropped from a p2p.Server 80 PeerEventTypeDrop PeerEventType = "drop" 81 82 // PeerEventTypeMsgSend is the type of event emitted when a 83 // message is successfully sent to a peer 84 PeerEventTypeMsgSend PeerEventType = "msgsend" 85 86 // PeerEventTypeMsgRecv is the type of event emitted when a 87 // message is received from a peer 88 PeerEventTypeMsgRecv PeerEventType = "msgrecv" 89 ) 90 91 // PeerEvent is an event emitted when peers are either added or dropped from 92 // a p2p.Server or when a message is sent or received on a peer connection 93 type PeerEvent struct { 94 Type PeerEventType `json:"type"` 95 Peer enode.ID `json:"peer"` 96 Error string `json:"error,omitempty"` 97 Protocol string `json:"protocol,omitempty"` 98 MsgCode *uint64 `json:"msg_code,omitempty"` 99 MsgSize *uint32 `json:"msg_size,omitempty"` 100 } 101 102 // Peer represents a connected remote node. 103 type Peer struct { 104 rw *conn 105 running map[string]*protoRW 106 log log.Logger 107 created mclock.AbsTime 108 109 wg sync.WaitGroup 110 protoErr chan error 111 closed chan struct{} 112 disc chan DiscReason 113 114 // events receives message send / receive events if set 115 events *event.Feed 116 PairPeer *Peer 117 } 118 119 // NewPeer returns a peer for testing purposes. 120 func NewPeer(id enode.ID, name string, caps []Cap) *Peer { 121 pipe, _ := net.Pipe() 122 node := enode.SignNull(new(enr.Record), id) 123 conn := &conn{fd: pipe, transport: nil, node: node, caps: caps, name: name} 124 peer := newPeer(conn, nil) 125 close(peer.closed) // ensures Disconnect doesn't block 126 return peer 127 } 128 129 // ID returns the node's public key. 130 func (p *Peer) ID() enode.ID { 131 return p.rw.node.ID() 132 } 133 134 // Node returns the peer's node descriptor. 135 func (p *Peer) Node() *enode.Node { 136 return p.rw.node 137 } 138 139 // Name returns the node name that the remote node advertised. 140 func (p *Peer) Name() string { 141 return p.rw.name 142 } 143 144 // Caps returns the capabilities (supported subprotocols) of the remote peer. 145 func (p *Peer) Caps() []Cap { 146 // TODO: maybe return copy 147 return p.rw.caps 148 } 149 150 // RemoteAddr returns the remote address of the network connection. 151 func (p *Peer) RemoteAddr() net.Addr { 152 return p.rw.fd.RemoteAddr() 153 } 154 155 // LocalAddr returns the local address of the network connection. 156 func (p *Peer) LocalAddr() net.Addr { 157 return p.rw.fd.LocalAddr() 158 } 159 160 // Disconnect terminates the peer connection with the given reason. 161 // It returns immediately and does not wait until the connection is closed. 162 func (p *Peer) Disconnect(reason DiscReason) { 163 select { 164 case p.disc <- reason: 165 case <-p.closed: 166 } 167 } 168 169 // String implements fmt.Stringer. 170 func (p *Peer) String() string { 171 id := p.ID() 172 return fmt.Sprintf("Peer %x %v", id[:8], p.RemoteAddr()) 173 } 174 175 // Inbound returns true if the peer is an inbound connection 176 func (p *Peer) Inbound() bool { 177 return p.rw.is(inboundConn) 178 } 179 180 func newPeer(conn *conn, protocols []Protocol) *Peer { 181 protomap := matchProtocols(protocols, conn.caps, conn) 182 p := &Peer{ 183 rw: conn, 184 running: protomap, 185 created: mclock.Now(), 186 disc: make(chan DiscReason), 187 protoErr: make(chan error, len(protomap)+1), // protocols + pingLoop 188 closed: make(chan struct{}), 189 log: log.New("id", conn.node.ID(), "conn", conn.flags), 190 } 191 return p 192 } 193 194 func (p *Peer) Log() log.Logger { 195 return p.log 196 } 197 198 func (p *Peer) run() (remoteRequested bool, err error) { 199 var ( 200 writeStart = make(chan struct{}, 1) 201 writeErr = make(chan error, 1) 202 readErr = make(chan error, 1) 203 reason DiscReason // sent to the peer 204 ) 205 p.wg.Add(2) 206 go p.readLoop(readErr) 207 go p.pingLoop() 208 209 // Start all protocol handlers. 210 writeStart <- struct{}{} 211 p.startProtocols(writeStart, writeErr) 212 213 // Wait for an error or disconnect. 214 loop: 215 for { 216 select { 217 case err = <-writeErr: 218 // A write finished. Allow the next write to start if 219 // there was no error. 220 if err != nil { 221 reason = DiscNetworkError 222 break loop 223 } 224 writeStart <- struct{}{} 225 case err = <-readErr: 226 if r, ok := err.(DiscReason); ok { 227 remoteRequested = true 228 reason = r 229 } else { 230 reason = DiscNetworkError 231 } 232 break loop 233 case err = <-p.protoErr: 234 reason = discReasonForError(err) 235 break loop 236 case err = <-p.disc: 237 reason = discReasonForError(err) 238 break loop 239 } 240 } 241 close(p.closed) 242 p.rw.close(reason) 243 p.wg.Wait() 244 if p.PairPeer != nil { 245 go func() { p.PairPeer.Disconnect(DiscPairPeerStop) }() 246 } 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 select { 305 case proto.in <- msg: 306 return nil 307 case <-p.closed: 308 return io.EOF 309 } 310 } 311 return nil 312 } 313 314 func countMatchingProtocols(protocols []Protocol, caps []Cap) int { 315 n := 0 316 for _, cap := range caps { 317 for _, proto := range protocols { 318 if proto.Name == cap.Name && proto.Version == cap.Version { 319 n++ 320 } 321 } 322 } 323 return n 324 } 325 326 // matchProtocols creates structures for matching named subprotocols. 327 func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW { 328 sort.Sort(capsByNameAndVersion(caps)) 329 offset := baseProtocolLength 330 result := make(map[string]*protoRW) 331 332 outer: 333 for _, cap := range caps { 334 for _, proto := range protocols { 335 if proto.Name == cap.Name && proto.Version == cap.Version { 336 // If an old protocol version matched, revert it 337 if old := result[cap.Name]; old != nil { 338 offset -= old.Length 339 } 340 // Assign the new match 341 result[cap.Name] = &protoRW{Protocol: proto, offset: offset, in: make(chan Msg), w: rw} 342 offset += proto.Length 343 344 continue outer 345 } 346 } 347 } 348 return result 349 } 350 351 func (p *Peer) startProtocols(writeStart <-chan struct{}, writeErr chan<- error) { 352 p.wg.Add(len(p.running)) 353 for _, proto := range p.running { 354 proto := proto 355 proto.closed = p.closed 356 proto.wstart = writeStart 357 proto.werr = writeErr 358 var rw MsgReadWriter = proto 359 if p.events != nil { 360 rw = newMsgEventer(rw, p.events, p.ID(), proto.Name) 361 } 362 p.log.Trace(fmt.Sprintf("Starting protocol %s/%d", proto.Name, proto.Version)) 363 364 go func() { 365 err := proto.Run(p, rw) 366 if err == nil { 367 p.log.Trace(fmt.Sprintf("Protocol %s/%d returned", proto.Name, proto.Version)) 368 err = errProtocolReturned 369 } else if err != io.EOF { 370 p.log.Trace(fmt.Sprintf("Protocol %s/%d failed", proto.Name, proto.Version), "err", err) 371 } 372 p.protoErr <- err 373 p.wg.Done() 374 }() 375 } 376 } 377 378 // getProto finds the protocol responsible for handling 379 // the given message code. 380 func (p *Peer) getProto(code uint64) (*protoRW, error) { 381 for _, proto := range p.running { 382 if code >= proto.offset && code < proto.offset+proto.Length { 383 return proto, nil 384 } 385 } 386 return nil, newPeerError(errInvalidMsgCode, "%d", code) 387 } 388 389 type protoRW struct { 390 Protocol 391 in chan Msg // receives read messages 392 closed <-chan struct{} // receives when peer is shutting down 393 wstart <-chan struct{} // receives when write may start 394 werr chan<- error // for write results 395 offset uint64 396 w MsgWriter 397 } 398 399 func (rw *protoRW) WriteMsg(msg Msg) (err error) { 400 if msg.Code >= rw.Length { 401 return newPeerError(errInvalidMsgCode, "not handled") 402 } 403 msg.Code += rw.offset 404 select { 405 case <-rw.wstart: 406 err = rw.w.WriteMsg(msg) 407 // Report write status back to Peer.run. It will initiate 408 // shutdown if the error is non-nil and unblock the next write 409 // otherwise. The calling protocol code should exit for errors 410 // as well but we don't want to rely on that. 411 rw.werr <- err 412 case <-rw.closed: 413 err = ErrShuttingDown 414 } 415 return err 416 } 417 418 func (rw *protoRW) ReadMsg() (Msg, error) { 419 select { 420 case msg := <-rw.in: 421 msg.Code -= rw.offset 422 return msg, nil 423 case <-rw.closed: 424 return Msg{}, io.EOF 425 } 426 } 427 428 // PeerInfo represents a short summary of the information known about a connected 429 // peer. Sub-protocol independent fields are contained and initialized here, with 430 // protocol specifics delegated to all connected sub-protocols. 431 type PeerInfo struct { 432 Enode string `json:"enode"` // Node URL 433 ID string `json:"id"` // Unique node identifier 434 Name string `json:"name"` // Name of the node, including client type, version, OS, custom data 435 Caps []string `json:"caps"` // Protocols advertised by this peer 436 Network struct { 437 LocalAddress string `json:"localAddress"` // Local endpoint of the TCP data connection 438 RemoteAddress string `json:"remoteAddress"` // Remote endpoint of the TCP data connection 439 Inbound bool `json:"inbound"` 440 Trusted bool `json:"trusted"` 441 Static bool `json:"static"` 442 } `json:"network"` 443 Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields 444 } 445 446 // Info gathers and returns a collection of metadata known about a peer. 447 func (p *Peer) Info() *PeerInfo { 448 // Gather the protocol capabilities 449 var caps []string 450 for _, cap := range p.Caps() { 451 caps = append(caps, cap.String()) 452 } 453 // Assemble the generic peer metadata 454 info := &PeerInfo{ 455 Enode: p.Node().String(), 456 ID: p.ID().String(), 457 Name: p.Name(), 458 Caps: caps, 459 Protocols: make(map[string]interface{}), 460 } 461 info.Network.LocalAddress = p.LocalAddr().String() 462 info.Network.RemoteAddress = p.RemoteAddr().String() 463 info.Network.Inbound = p.rw.is(inboundConn) 464 info.Network.Trusted = p.rw.is(trustedConn) 465 info.Network.Static = p.rw.is(staticDialedConn) 466 467 // Gather all the running protocol infos 468 for _, proto := range p.running { 469 protoInfo := interface{}("unknown") 470 if query := proto.Protocol.PeerInfo; query != nil { 471 if metadata := query(p.ID()); metadata != nil { 472 protoInfo = metadata 473 } else { 474 protoInfo = "handshake" 475 } 476 } 477 info.Protocols[proto.Name] = protoInfo 478 } 479 return info 480 }