Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

p2p: limit ping requests from a single peer #8113

Merged
merged 1 commit into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion p2p/peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ type Peer struct {
wg sync.WaitGroup
protoErr chan *PeerError
closed chan struct{}
pingRecv chan struct{}
disc chan *PeerError

// events receives message send / receive events if set
Expand Down Expand Up @@ -219,6 +220,7 @@ func newPeer(logger log.Logger, conn *conn, protocols []Protocol, pubkey [64]byt
disc: make(chan *PeerError),
protoErr: make(chan *PeerError, len(protomap)+1), // protocols + pingLoop
closed: make(chan struct{}),
pingRecv: make(chan struct{}, 16),
log: logger.New("id", conn.node.ID(), "conn", conn.flags),
pubkey: pubkey,
metricsEnabled: metricsEnabled,
Expand Down Expand Up @@ -287,6 +289,11 @@ func (p *Peer) pingLoop() {
return
}
ping.Reset(pingInterval)
case <-p.pingRecv:
if err := SendItems(p.rw, pongMsg); err != nil {
p.protoErr <- NewPeerError(PeerErrorPongFailure, DiscNetworkError, err, "Failed to send pongMsg")
return
}
case <-p.closed:
return
}
Expand Down Expand Up @@ -314,7 +321,10 @@ func (p *Peer) handle(msg Msg) error {
switch {
case msg.Code == pingMsg:
msg.Discard()
go SendItems(p.rw, pongMsg)
select {
case p.pingRecv <- struct{}{}:
case <-p.closed:
}
case msg.Code == discMsg:
// This is the last message.
// We don't need to discard because the connection will be closed after it.
Expand Down
2 changes: 2 additions & 0 deletions p2p/peer_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const (
PeerErrorInvalidMessageCode PeerErrorCode = iota
PeerErrorInvalidMessage
PeerErrorPingFailure
PeerErrorPongFailure
PeerErrorDiscReason
PeerErrorDiscReasonRemote
PeerErrorMessageReceive
Expand All @@ -47,6 +48,7 @@ var peerErrorCodeToString = map[PeerErrorCode]string{
PeerErrorInvalidMessageCode: "invalid message code",
PeerErrorInvalidMessage: "invalid message",
PeerErrorPingFailure: "ping failure",
PeerErrorPongFailure: "pong failure",
PeerErrorDiscReason: "disconnect reason",
PeerErrorDiscReasonRemote: "remote disconnect reason",
PeerErrorMessageReceive: "failed to receive a message",
Expand Down