Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
197 lines
5.5 KiB
Go
197 lines
5.5 KiB
Go
package p2p
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
pubsub "github.com/libp2p/go-libp2p-pubsub"
|
|
"github.com/libp2p/go-libp2p/core/peer"
|
|
)
|
|
|
|
// Limits on what one peer may send us. They are generous for an honest peer
|
|
// (a node relaying a busy region) and cheap for us to enforce: the rate check
|
|
// runs before a message is parsed or its signature verified.
|
|
const (
|
|
// guardWindow is the span over which a peer's messages and bad messages are counted.
|
|
guardWindow = time.Minute
|
|
// maxPerWindow is how many messages one peer may relay to us per window;
|
|
// more are dropped unread (and not passed on), without penalty.
|
|
maxPerWindow = 1200
|
|
// maxBadPerWindow is how many invalid messages (bad signature, too little
|
|
// proof-of-work, garbage) one peer may send per window before it is banned.
|
|
// Honest peers send none: clock trouble and unknown listings are ignored,
|
|
// not counted as bad.
|
|
maxBadPerWindow = 20
|
|
// banFor is how long a banned peer stays disconnected and ignored.
|
|
banFor = time.Hour
|
|
)
|
|
|
|
// peerGuard counts, per peer, the messages it relays to us and how many were
|
|
// invalid, drops floods and bans peers that keep sending invalid ones. A ban
|
|
// is a pubsub blacklist entry plus a closed connection; it expires by itself.
|
|
type peerGuard struct {
|
|
now func() time.Time
|
|
log *slog.Logger
|
|
bl pubsub.Blacklist
|
|
disconnect func(peer.ID)
|
|
self peer.ID
|
|
|
|
// Totals since the start, for the metrics.
|
|
dropped atomic.Uint64 // messages dropped for exceeding the rate
|
|
invalid atomic.Uint64 // messages rejected as invalid
|
|
bans atomic.Uint64 // peers banned
|
|
syncRefused atomic.Uint64 // sync requests refused
|
|
|
|
mu sync.Mutex
|
|
peers map[peer.ID]*peerCount
|
|
streams map[peer.ID]int // sync streams open per peer
|
|
}
|
|
|
|
type peerCount struct {
|
|
start time.Time // of the current window
|
|
total int
|
|
bad int
|
|
noted bool // the flood was already logged this window
|
|
|
|
syncs int // sync requests this window
|
|
syncNoted bool
|
|
}
|
|
|
|
func newPeerGuard(self peer.ID, now func() time.Time, log *slog.Logger, disconnect func(peer.ID)) (*peerGuard, error) {
|
|
bl, err := pubsub.NewTimeCachedBlacklist(banFor)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &peerGuard{now: now, log: log, bl: bl, disconnect: disconnect, self: self,
|
|
peers: map[peer.ID]*peerCount{}, streams: map[peer.ID]int{}}, nil
|
|
}
|
|
|
|
// wrap puts the guard around a topic validator. Messages we published
|
|
// ourselves are not counted.
|
|
func (g *peerGuard) wrap(v pubsub.ValidatorEx) pubsub.ValidatorEx {
|
|
return func(ctx context.Context, from peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
|
|
if from == g.self {
|
|
return v(ctx, from, msg)
|
|
}
|
|
if !g.admit(from) {
|
|
return pubsub.ValidationIgnore
|
|
}
|
|
res := v(ctx, from, msg)
|
|
if res == pubsub.ValidationReject {
|
|
g.bad(from)
|
|
}
|
|
return res
|
|
}
|
|
}
|
|
|
|
// count returns p's counters for the current window. g.mu must be held.
|
|
func (g *peerGuard) count(p peer.ID) *peerCount {
|
|
now := g.now()
|
|
c := g.peers[p]
|
|
if c == nil || now.Sub(c.start) >= guardWindow {
|
|
if len(g.peers) > 4096 { // forget peers whose windows ended
|
|
for k, v := range g.peers {
|
|
if now.Sub(v.start) >= guardWindow {
|
|
delete(g.peers, k)
|
|
}
|
|
}
|
|
}
|
|
c = &peerCount{start: now}
|
|
g.peers[p] = c
|
|
}
|
|
return c
|
|
}
|
|
|
|
// admit counts one message from p and reports whether it is within the rate.
|
|
func (g *peerGuard) admit(p peer.ID) bool {
|
|
g.mu.Lock()
|
|
defer g.mu.Unlock()
|
|
c := g.count(p)
|
|
c.total++
|
|
if c.total <= maxPerWindow {
|
|
return true
|
|
}
|
|
g.dropped.Add(1)
|
|
if !c.noted {
|
|
c.noted = true
|
|
g.log.Warn("peer sends too much; dropping its messages until the minute is over",
|
|
"peer", p, "limit_per_minute", maxPerWindow)
|
|
}
|
|
return false
|
|
}
|
|
|
|
// bad counts an invalid message from p and bans it past the limit.
|
|
func (g *peerGuard) bad(p peer.ID) {
|
|
g.invalid.Add(1)
|
|
g.mu.Lock()
|
|
c := g.count(p)
|
|
c.bad++
|
|
ban := c.bad == maxBadPerWindow
|
|
g.mu.Unlock()
|
|
if !ban {
|
|
return
|
|
}
|
|
g.bl.Add(p)
|
|
g.bans.Add(1)
|
|
g.log.Warn("banned a peer that kept sending invalid messages", "peer", p,
|
|
"invalid_in_a_minute", maxBadPerWindow, "for", banFor)
|
|
if g.disconnect != nil {
|
|
g.disconnect(p)
|
|
}
|
|
}
|
|
|
|
// Limits on what a peer may ask of us over the sync protocol. A full sync of a
|
|
// region of 100,000 listings is about 200 inventory pages and a thousand
|
|
// fetches, so the rate leaves room for it; the limit on parallel streams is
|
|
// what stops one peer from tying up the node.
|
|
const (
|
|
maxSyncPerWindow = 1500
|
|
maxSyncStreams = 4
|
|
)
|
|
|
|
// beginSync is called when p opens a sync stream. It refuses banned peers,
|
|
// peers asking too often and peers with too many streams open; otherwise it
|
|
// returns the function to call when the stream is done.
|
|
func (g *peerGuard) beginSync(p peer.ID) (end func(), ok bool) {
|
|
end, ok = g.beginSyncUncounted(p)
|
|
if !ok {
|
|
g.syncRefused.Add(1)
|
|
}
|
|
return end, ok
|
|
}
|
|
|
|
func (g *peerGuard) beginSyncUncounted(p peer.ID) (end func(), ok bool) {
|
|
if g.banned(p) {
|
|
return nil, false
|
|
}
|
|
g.mu.Lock()
|
|
defer g.mu.Unlock()
|
|
c := g.count(p)
|
|
c.syncs++
|
|
if c.syncs > maxSyncPerWindow {
|
|
if !c.syncNoted {
|
|
c.syncNoted = true
|
|
g.log.Warn("peer asks for too much sync; refusing its requests until the minute is over",
|
|
"peer", p, "limit_per_minute", maxSyncPerWindow)
|
|
}
|
|
return nil, false
|
|
}
|
|
if g.streams[p] >= maxSyncStreams {
|
|
return nil, false
|
|
}
|
|
g.streams[p]++
|
|
return func() {
|
|
g.mu.Lock()
|
|
defer g.mu.Unlock()
|
|
if g.streams[p]--; g.streams[p] <= 0 {
|
|
delete(g.streams, p)
|
|
}
|
|
}, true
|
|
}
|
|
|
|
// banned reports whether p is currently banned.
|
|
func (g *peerGuard) banned(p peer.ID) bool { return g.bl.Contains(p) }
|