limits: sync streams, listings per author, inbound connections per IP

A peer may hold 4 sync streams and open 1500 a minute; banned peers get none and cannot redial. A node keeps at most 100 unexpired listings per author (--max-per-author); updates, renewals and deletions of held ones still work. At most 16 inbound connections per public IP or IPv6 /64 (--max-conns-per-ip); local and private addresses are exempt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-19 00:30:36 +01:00
co-authored by Claude Sonnet 5.5
parent 0b3ead4b23
commit 5ac02360c4
12 changed files with 527 additions and 23 deletions
+49 -3
View File
@@ -38,8 +38,9 @@ type peerGuard struct {
disconnect func(peer.ID)
self peer.ID
mu sync.Mutex
peers map[peer.ID]*peerCount
mu sync.Mutex
peers map[peer.ID]*peerCount
streams map[peer.ID]int // sync streams open per peer
}
type peerCount struct {
@@ -47,6 +48,9 @@ type peerCount struct {
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) {
@@ -54,7 +58,8 @@ func newPeerGuard(self peer.ID, now func() time.Time, log *slog.Logger, disconne
if err != nil {
return nil, err
}
return &peerGuard{now: now, log: log, bl: bl, disconnect: disconnect, self: self, peers: map[peer.ID]*peerCount{}}, nil
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
@@ -128,5 +133,46 @@ func (g *peerGuard) bad(p peer.ID) {
}
}
// 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) {
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) }
+58
View File
@@ -127,6 +127,64 @@ func TestOurOwnMessagesAreNeverLimited(t *testing.T) {
}
}
func TestAPeerMayOnlyHoldAFewSyncStreamsAtOnce(t *testing.T) {
f := newGuardFixture(t)
var ends []func()
for i := 0; i < maxSyncStreams; i++ {
end, ok := f.g.beginSync("greedy")
if !ok {
t.Fatalf("stream %d refused within the limit", i)
}
ends = append(ends, end)
}
if _, ok := f.g.beginSync("greedy"); ok {
t.Fatal("a stream over the limit was accepted")
}
if _, ok := f.g.beginSync("other"); !ok {
t.Fatal("one peer's streams must not use up another's")
}
ends[0]()
end, ok := f.g.beginSync("greedy")
if !ok {
t.Fatal("a finished stream must free its place")
}
end()
for _, e := range ends[1:] {
e()
}
if len(f.g.streams) != 1 { // only "other" is still open
t.Fatalf("%d peers still have streams recorded", len(f.g.streams))
}
}
func TestSyncRequestsAreRatedAndBannedPeersAreRefused(t *testing.T) {
f := newGuardFixture(t)
for i := 0; i < maxSyncPerWindow; i++ {
end, ok := f.g.beginSync("busy")
if !ok {
t.Fatalf("request %d within the rate refused", i)
}
end()
}
if _, ok := f.g.beginSync("busy"); ok {
t.Fatal("a request over the rate was accepted")
}
f.now = f.now.Add(guardWindow)
if end, ok := f.g.beginSync("busy"); !ok {
t.Fatal("the next minute must start fresh")
} else {
end()
}
f.verdict = pubsub.ValidationReject
for i := 0; i < maxBadPerWindow; i++ {
f.send("mallory")
}
if _, ok := f.g.beginSync("mallory"); ok {
t.Fatal("a banned peer got a sync stream")
}
}
func TestFinishedWindowsAreForgotten(t *testing.T) {
f := newGuardFixture(t)
for i := 0; i < 5000; i++ {
+111
View File
@@ -0,0 +1,111 @@
package p2p
import (
"net"
"sync"
"sync/atomic"
"github.com/libp2p/go-libp2p/core/control"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
)
// DefaultConnsPerIP is how many inbound connections one public IP address may
// hold. A household or an office with a few nodes behind one router stays well
// below it; one machine that mints peer IDs to get around a ban does not.
const DefaultConnsPerIP = 16
// ipGate is the node's connection gater. It refuses an inbound connection when
// its source address already holds the limit, and any connection from a peer the
// guard has banned (so a ban cannot be undone by redialing). Local, private and
// link-local addresses are exempt: a LAN, the simulator and a cluster network
// that hides real source addresses behind one internal address would otherwise
// lock out everyone at once.
type ipGate struct {
max int // per address; 0 means no limit
mu sync.Mutex
counts map[string]int
banned atomic.Pointer[func(peer.ID) bool]
}
func newIPGate(max int) *ipGate { return &ipGate{max: max, counts: map[string]int{}} }
// ipKey names the source of a connection: the IPv4 address, or the /64 of an
// IPv6 one (a single machine usually owns a whole /64). It is empty for
// addresses that are exempt or not IP at all.
func ipKey(a ma.Multiaddr) string {
for _, code := range []int{ma.P_IP4, ma.P_IP6} {
v, err := a.ValueForProtocol(code)
if err != nil {
continue
}
ip := net.ParseIP(v)
if ip == nil || ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsUnspecified() {
return ""
}
if ip4 := ip.To4(); ip4 != nil {
return ip4.String()
}
return ip.Mask(net.CIDRMask(64, 128)).String() + "/64"
}
return ""
}
func (g *ipGate) full(a ma.Multiaddr) bool {
if g.max <= 0 {
return false
}
k := ipKey(a)
if k == "" {
return false
}
g.mu.Lock()
defer g.mu.Unlock()
return g.counts[k] >= g.max
}
// connection gater
func (g *ipGate) InterceptPeerDial(peer.ID) bool { return true }
func (g *ipGate) InterceptAddrDial(peer.ID, ma.Multiaddr) bool { return true }
func (g *ipGate) InterceptAccept(cm network.ConnMultiaddrs) bool {
return !g.full(cm.RemoteMultiaddr())
}
func (g *ipGate) InterceptSecured(dir network.Direction, p peer.ID, _ network.ConnMultiaddrs) bool {
if dir == network.DirInbound {
if f := g.banned.Load(); f != nil && (*f)(p) {
return false
}
}
return true
}
func (g *ipGate) InterceptUpgraded(network.Conn) (bool, control.DisconnectReason) { return true, 0 }
// notifee: count the inbound connections that got established
func (g *ipGate) track(c network.Conn, delta int) {
if g.max <= 0 || c.Stat().Direction != network.DirInbound {
return
}
k := ipKey(c.RemoteMultiaddr())
if k == "" {
return
}
g.mu.Lock()
defer g.mu.Unlock()
if g.counts[k]+delta <= 0 {
delete(g.counts, k)
return
}
g.counts[k] += delta
}
func (g *ipGate) notifee() network.Notifiee {
return &network.NotifyBundle{
ConnectedF: func(_ network.Network, c network.Conn) { g.track(c, 1) },
DisconnectedF: func(_ network.Network, c network.Conn) { g.track(c, -1) },
}
}
+138
View File
@@ -0,0 +1,138 @@
package p2p
import (
"testing"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
)
type fakeConnAddrs struct{ remote ma.Multiaddr }
func (f fakeConnAddrs) LocalMultiaddr() ma.Multiaddr { return nil }
func (f fakeConnAddrs) RemoteMultiaddr() ma.Multiaddr { return f.remote }
func mustAddr(t *testing.T, s string) ma.Multiaddr {
t.Helper()
a, err := ma.NewMultiaddr(s)
if err != nil {
t.Fatal(err)
}
return a
}
func TestIPKeysGroupASourceAndExemptLocalAddresses(t *testing.T) {
for addr, want := range map[string]string{
"/ip4/203.0.113.7/tcp/4001": "203.0.113.7",
"/ip4/203.0.113.7/udp/9/quic-v1": "203.0.113.7",
"/ip6/2001:db8:1:2:aaaa::1/tcp/4001": "2001:db8:1:2::/64",
"/ip6/2001:db8:1:2:bbbb::9/tcp/4001": "2001:db8:1:2::/64",
"/ip4/127.0.0.1/tcp/4001": "",
"/ip4/192.168.1.20/tcp/4001": "",
"/ip4/10.1.2.3/tcp/4001": "",
"/ip6/::1/tcp/4001": "",
"/ip6/fe80::1/tcp/4001": "",
"/ip6/fd00::5/tcp/4001": "",
"/dns4/example.org/tcp/4001": "",
} {
if got := ipKey(mustAddr(t, addr)); got != want {
t.Errorf("ipKey(%s) = %q, want %q", addr, got, want)
}
}
}
func TestOneAddressCannotHoldMoreConnectionsThanTheLimit(t *testing.T) {
g := newIPGate(2)
a := fakeConnAddrs{mustAddr(t, "/ip4/203.0.113.7/tcp/1000")}
other := fakeConnAddrs{mustAddr(t, "/ip4/203.0.113.8/tcp/1000")}
if !g.InterceptAccept(a) {
t.Fatal("first connection refused")
}
g.counts["203.0.113.7"] = 1
if !g.InterceptAccept(a) {
t.Fatal("second connection refused")
}
g.counts["203.0.113.7"] = 2
if g.InterceptAccept(a) {
t.Fatal("a third connection from one address was accepted")
}
if !g.InterceptAccept(other) {
t.Fatal("another address must not be affected")
}
g.counts["203.0.113.7"] = 1 // one closed
if !g.InterceptAccept(a) {
t.Fatal("a closed connection must free its place")
}
local := fakeConnAddrs{mustAddr(t, "/ip4/127.0.0.1/tcp/1000")}
for i := 0; i < 50; i++ {
if !g.InterceptAccept(local) {
t.Fatal("local addresses are exempt")
}
}
if newIPGate(0).full(a.remote) {
t.Fatal("a limit of zero means no limit")
}
}
// fakeConn answers only what the gate asks of a connection.
type fakeConn struct {
network.Conn
remote ma.Multiaddr
dir network.Direction
}
func (c fakeConn) RemoteMultiaddr() ma.Multiaddr { return c.remote }
func (c fakeConn) Stat() network.ConnStats {
return network.ConnStats{Stats: network.Stats{Direction: c.dir}}
}
func TestEstablishedInboundConnectionsAreCountedUntilTheyClose(t *testing.T) {
g := newIPGate(2)
n := g.notifee()
in := func() fakeConn {
return fakeConn{remote: mustAddr(t, "/ip4/203.0.113.7/tcp/1000"), dir: network.DirInbound}
}
out := fakeConn{remote: mustAddr(t, "/ip4/203.0.113.7/tcp/1000"), dir: network.DirOutbound}
a, b := in(), in()
n.Connected(nil, a)
n.Connected(nil, out) // ones we dialed do not count
if g.full(a.remote) {
t.Fatal("one inbound connection fills a limit of two")
}
n.Connected(nil, b)
if !g.full(a.remote) {
t.Fatal("two inbound connections must fill a limit of two")
}
n.Disconnected(nil, out)
if !g.full(a.remote) {
t.Fatal("closing an outbound connection must not free an inbound place")
}
n.Disconnected(nil, a)
if g.full(a.remote) {
t.Fatal("a closed connection must free its place")
}
n.Disconnected(nil, b)
if len(g.counts) != 0 {
t.Fatalf("%d addresses still counted after everything closed", len(g.counts))
}
}
func TestBannedPeersCannotComeBack(t *testing.T) {
g := newIPGate(2)
cm := fakeConnAddrs{mustAddr(t, "/ip4/203.0.113.7/tcp/1000")}
if !g.InterceptSecured(network.DirInbound, "mallory", cm) {
t.Fatal("nobody is banned before the guard says so")
}
banned := func(p peer.ID) bool { return p == "mallory" }
g.banned.Store(&banned)
if g.InterceptSecured(network.DirInbound, "mallory", cm) {
t.Fatal("a banned peer got back in")
}
if !g.InterceptSecured(network.DirInbound, "alice", cm) {
t.Fatal("an innocent peer was refused")
}
if !g.InterceptSecured(network.DirOutbound, "mallory", cm) {
t.Fatal("we may still dial out; only inbound is gated")
}
}
+14 -1
View File
@@ -116,6 +116,10 @@ type Config struct {
// (which scales with memory) for any other; a negative number keeps
// libp2p's default even for a Public node.
MaxConns int
// MaxConnsPerIP is how many inbound connections one public IP address (an
// IPv6 /64) may hold; local and private addresses are exempt. Zero means
// DefaultConnsPerIP, a negative number no limit.
MaxConnsPerIP int
// ExtraOptions are added to the libp2p host's options; the simulator uses
// them to put latency and connection loss on the transport.
ExtraOptions []libp2p.Option
@@ -233,6 +237,12 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
}
opts = append(opts, limits)
}
perIP := cfg.MaxConnsPerIP
if perIP == 0 {
perIP = DefaultConnsPerIP
}
gate := newIPGate(max(perIP, 0))
opts = append(opts, libp2p.ConnectionGater(gate))
opts = append(opts, cfg.ExtraOptions...)
if cfg.Bandwidth != nil {
opts = append(opts, libp2p.BandwidthReporter(cfg.Bandwidth))
@@ -274,6 +284,9 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
n.Close()
return nil, err
}
h.Network().Notify(gate.notifee())
banned := n.guard.banned
gate.banned.Store(&banned)
n.ps, err = pubsub.NewGossipSub(nctx, h,
pubsub.WithMaxMessageSize(listing.MaxSize+4096),
pubsub.WithFloodPublish(true),
@@ -612,7 +625,7 @@ func (n *Node) subscribeRegion(region string) error {
switch out, err := n.cfg.Store.Put(n.ctx, l); {
case err == nil:
n.noteListing(n.ctx, l, out, "gossip", msg.ReceivedFrom)
case errors.Is(err, store.ErrRevoked):
case errors.Is(err, store.ErrRevoked), errors.Is(err, store.ErrQuota):
default:
n.log.Warn("store listing", "err", err)
}
+6
View File
@@ -61,6 +61,12 @@ type syncRequest struct {
func (n *Node) handleSync(s network.Stream) {
defer s.Close()
end, ok := n.guard.beginSync(s.Conn().RemotePeer())
if !ok {
_ = s.Reset()
return
}
defer end()
_ = s.SetDeadline(time.Now().Add(syncTimeout))
var req syncRequest