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