p2p: a --public node accepts 1000 inbound connections (--max-conns), instead of libp2p's memory-scaled default

The simulator showed libp2p's default cap (about 190 on 16 GB) stranding newcomers
on a bootstrap node: 12 of 200 and 212 of 400 nodes never found a peer. As
shipped, the same networks now form and deliver 100% up to 600 nodes.

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-18 22:46:05 +01:00
co-authored by Claude Sonnet 5.5
parent 130ba5dc65
commit 86668baf5a
10 changed files with 170 additions and 53 deletions
+3 -4
View File
@@ -141,10 +141,9 @@ starting a design-heavy item; see "Working with the owner".
access exists. Listings already have an `images` field of hashes. access exists. Listings already have an `images` field of hashes.
- **Recovering listings onto an empty database** (after losing the data - **Recovering listings onto an empty database** (after losing the data
directory but not the phrase). directory but not the phrase).
- **Connection limits for `--public` nodes.** Found by `allmende-sim`: libp2p's - **Check a public node's memory under load.** `--public` nodes now accept
default inbound cap scales with RAM (~190 on 16 GB), so a bootstrap node 1000 inbound connections (`--max-conns`); nobody has measured a node holding
strands newcomers beyond that. Set explicit limits for public nodes (and that many against the 512 MiB pod limit.
check the k8s memory limit).
- **Peer scoring and rate limits** beyond what the validators do now. The - **Peer scoring and rate limits** beyond what the validators do now. The
simulator's attacker stays connected after 500 bad messages. simulator's attacker stays connected after 500 bad messages.
- **Joining without the seeds.** A newcomer whose remembered peers are all in - **Joining without the seeds.** A newcomer whose remembered peers are all in
+7 -6
View File
@@ -78,7 +78,7 @@ type sim struct {
timeout time.Duration timeout time.Duration
made []*listing.Listing made []*listing.Listing
mu sync.Mutex // guards nodes against the sampler mu sync.Mutex // guards nodes against the sampler
seedConns int // raised connection limit of the seeds; 0 keeps libp2p's default seedConns int // the seeds' MaxConns setting
} }
func main() { func main() {
@@ -95,7 +95,7 @@ func main() {
timeout := flag.Duration("timeout", 60*time.Second, "how long to wait for each thing to spread") timeout := flag.Duration("timeout", 60*time.Second, "how long to wait for each thing to spread")
latency := flag.Duration("latency", 0, "delay added to every write on connections a node dials (one direction), with up to 50% jitter") latency := flag.Duration("latency", 0, "delay added to every write on connections a node dials (one direction), with up to 50% jitter")
lifetime := flag.Duration("lifetime", 0, "mean lifetime of a dialed connection before it is cut (0: never); redials and resyncs follow") lifetime := flag.Duration("lifetime", 0, "mean lifetime of a dialed connection before it is cut (0: never); redials and resyncs follow")
seedConns := flag.Int("seed-conns", 0, "raise the seeds' inbound connection limit to this many (0: libp2p's default, which scales with RAM)") seedConns := flag.Int("seed-conns", 0, "the seeds' inbound connection limit (0: the node's default for --public, 1000; -1: libp2p's own, which scales with RAM)")
jsonOut := flag.String("json", "", "write the run (samples every second, phases, arrival times) to this JSON file, for graphs") jsonOut := flag.String("json", "", "write the run (samples every second, phases, arrival times) to this JSON file, for graphs")
hostile := flag.Bool("hostile", false, "also run attackers: invalid listings, a message flood") hostile := flag.Bool("hostile", false, "also run attackers: invalid listings, a message flood")
killSeeds := flag.Bool("kill-seeds", false, "also shut the seeds down and see what the network and newcomers do") killSeeds := flag.Bool("kill-seeds", false, "also shut the seeds down and see what the network and newcomers do")
@@ -336,16 +336,17 @@ func (s *sim) start(n *simNode) error {
if bootstrap == nil { if bootstrap == nil {
bootstrap = s.seedAddrs bootstrap = s.seedAddrs
} }
extra := s.extra maxConns := 0 // the node's own default: DefaultPublicConns for a seed
if n.seed && s.seedConns > 0 { if n.seed {
extra = append(append([]libp2p.Option(nil), extra...), seedLimits(s.seedConns)) maxConns = s.seedConns
} }
node, err := p2p.New(s.ctx, p2p.Config{ node, err := p2p.New(s.ctx, p2p.Config{
Device: n.dev, Device: n.dev,
Store: n.st, Store: n.st,
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Bootstrap: bootstrap, Bootstrap: bootstrap,
ExtraOptions: extra, MaxConns: maxConns,
ExtraOptions: s.extra,
Regions: n.regions, Regions: n.regions,
DHT: true, DHT: true,
Public: n.seed, Public: n.seed,
-16
View File
@@ -15,7 +15,6 @@ import (
pubsub "github.com/libp2p/go-libp2p-pubsub" pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/host" "github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/peer"
rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"
"github.com/libp2p/go-libp2p/p2p/transport/tcp" "github.com/libp2p/go-libp2p/p2p/transport/tcp"
ma "github.com/multiformats/go-multiaddr" ma "github.com/multiformats/go-multiaddr"
@@ -79,21 +78,6 @@ func (l *lossyConn) Write(p []byte) (int, error) {
return l.Conn.Write(p) return l.Conn.Write(p)
} }
// seedLimits lifts libp2p's connection limits (which scale with the machine's
// memory, and by default allow only about 190 inbound connections on 16 GB of
// RAM) so a run can show what they do to a network of a few hundred nodes.
func seedLimits(conns int) libp2p.Option {
limits := rcmgr.DefaultLimits
libp2p.SetDefaultServiceLimits(&limits)
cfg := rcmgr.PartialLimitConfig{
System: rcmgr.ResourceLimits{Conns: rcmgr.LimitVal(conns * 2), ConnsInbound: rcmgr.LimitVal(conns)},
Transient: rcmgr.ResourceLimits{Conns: rcmgr.LimitVal(conns), ConnsInbound: rcmgr.LimitVal(conns)},
}
mgr, err := rcmgr.NewResourceManager(rcmgr.NewFixedLimiter(cfg.Build(limits.AutoScale())))
must(err)
return libp2p.ResourceManager(mgr)
}
// --- attackers ---------------------------------------------------------------------------- // --- attackers ----------------------------------------------------------------------------
// attacker is a bare libp2p and gossipsub peer without any of the node's // attacker is a bare libp2p and gossipsub peer without any of the node's
+3
View File
@@ -44,6 +44,8 @@ func cmdRun(args []string) error {
noDHT := fs.Bool("no-dht", false, "do not look for peers through the DHT") noDHT := fs.Bool("no-dht", false, "do not look for peers through the DHT")
public := fs.Bool("public", false, public := fs.Bool("public", false,
"this node is reachable from the internet: serve the DHT and relay for nodes behind a NAT (for bootstrap nodes)") "this node is reachable from the internet: serve the DHT and relay for nodes behind a NAT (for bootstrap nodes)")
maxConns := fs.Int("max-conns", 0,
fmt.Sprintf("inbound connections to accept (0: %d for --public nodes, libp2p's default, which scales with memory, for others; -1: libp2p's default always)", p2p.DefaultPublicConns))
var announceAddrs listFlag var announceAddrs listFlag
fs.Var(&announceAddrs, "announce", fs.Var(&announceAddrs, "announce",
"address others should dial, when this node sits behind a router or in a container, e.g. /dns4/node.example.org/tcp/4001; repeatable") "address others should dial, when this node sits behind a router or in a container, e.g. /dns4/node.example.org/tcp/4001; repeatable")
@@ -146,6 +148,7 @@ func cmdRun(args []string) error {
MDNS: !*noMDNS, MDNS: !*noMDNS,
DHT: !*noDHT, DHT: !*noDHT,
Public: *public, Public: *public,
MaxConns: *maxConns,
Announce: announceAddrs, Announce: announceAddrs,
PeerCache: filepath.Join(*data, peersFile), PeerCache: filepath.Join(*data, peersFile),
Difficulty: *difficulty, Difficulty: *difficulty,
+22 -20
View File
@@ -626,30 +626,32 @@ networks (8 regions, 3 seeds, 30 listings, 20 messages, 3 reports, 10% churn)
and records each as JSON in `.tmp/sim/`; `scripts/sim-report.mjs` turns them and records each as JSON in `.tmp/sim/`; `scripts/sim-report.mjs` turns them
into the tables behind the graphs. Result on a 16 GB, 8-core machine: into the tables behind the graphs. Result on a 16 GB, 8-core machine:
| Nodes | Seed limit lifted | libp2p default limit | | Nodes | As shipped (`--public` accepts 1000) | libp2p's own default limit (before the fix) |
|---|---|---| |---|---|---|
| 100 | complete in 3.5 s, 100% delivered | complete in 3.2 s, 100% | | 100 | complete in 3.4 s, 100% delivered | complete in 3.2 s, 100% |
| 200 | 6.1 s, 100% (p95 50 ms) | **never completed**: 12 nodes without any peer, 91.8% delivered | | 200 | 6.3 s, 100% (p95 57 ms) | **never completed**: 12 nodes without any peer, 91.8% delivered |
| 300 | 9.5 s, 100% (p95 75 ms) | 112 nodes without a peer, 43% delivered | | 300 | 9.4 s, 100% (p95 79 ms) | 112 nodes without a peer, 43% delivered |
| 400 | 14 s, 100% (p95 97 ms) | 212 nodes without a peer, 16% delivered | | 400 | 14 s, 100% (p95 99 ms) | 212 nodes without a peer, 16% delivered |
| 600 | 24 s, 100% (p95 111 ms) | not run | | 600 | 24.5 s, 100% (p95 117 ms) | not run |
With the limit lifted, delivery stayed at 100% and agreement held up to 600 As shipped, delivery stayed at 100% and agreement held up to 600 nodes; time
nodes; time to form the mesh grows roughly with the square of the network to form the mesh grows roughly with the square of the network size (3.4 s at
size (3.5 s at 100, 24 s at 600), and so does the simulator's cost (2.5 GB 100, 24.5 s at 600), and so does the simulator's cost (2.5 GB heap, 230k
heap, 230k goroutines, 255 CPU-seconds at 600). That cost is the sum of all the goroutines, 250 CPU-seconds at 600). That cost is the sum of all the nodes
nodes sharing one machine, so it measures the limit of the simulation as much sharing one machine, so it measures the limit of the simulation as much as of
as of the protocol; 800 nodes was left out to avoid exhausting memory. With the protocol; 800 nodes was left out to avoid exhausting memory. With libp2p's
the default limit the network stops working where the seeds run out of default the network stopped working where the seeds ran out of inbound
inbound connections (three seeds hold about 187 each). connections (three seeds held about 187 each).
Findings (nothing here is fixed yet; see "What is left" in SPECS.md): Findings (see "What is left" in SPECS.md for the open ones):
1. **Connection limit on the bootstrap node.** libp2p's resource manager caps 1. **Connection limit on the bootstrap node (fixed).** libp2p's resource
inbound connections in proportion to memory (about 190 on 16 GB). With 200 manager capped inbound connections in proportion to memory (about 190 on 16
nodes, 12 never got a single peer; with the limit lifted the mesh formed in GB, fewer in a small container): with 200 nodes, 12 never got a single peer.
6 s. A bootstrap node in a pod with a small memory limit would cap out much A `--public` node now accepts 1000 inbound connections (`--max-conns`
sooner. Needs explicit limits on `--public` nodes. changes it; `-1` restores libp2p's default), and the table above shows the
result. Not measured: the memory of a seed holding 1000 connections against
the 512 MiB limit in `k8s/base/statefulset.yaml`.
2. **No peer scoring.** The attacker stayed connected to all 10 nodes it 2. **No peer scoring.** The attacker stayed connected to all 10 nodes it
dialed after sending 500 bad messages. Nothing was stored, but each message dialed after sending 500 bad messages. Nothing was stored, but each message
still cost every node its validation work. still cost every node its validation work.
+31
View File
@@ -0,0 +1,31 @@
package p2p
import (
"github.com/libp2p/go-libp2p"
rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"
)
// DefaultPublicConns is how many inbound connections a --public node accepts
// unless told otherwise. libp2p's own cap scales with the machine's memory
// (about 190 on 16 GB, fewer in a small container), which strands newcomers
// once a bootstrap node has that many peers: the simulator showed 12 of 200
// nodes and 212 of 400 never finding a single peer. A connection costs a few
// tens of kilobytes, so 1000 fits a 512 MiB pod.
const DefaultPublicConns = 1000
// connectionLimits is libp2p's resource manager with the connection caps set
// to conns inbound (and twice that in total, which includes the node's own
// dials). Everything else keeps libp2p's defaults, scaled to the machine.
func connectionLimits(conns int) (libp2p.Option, error) {
limits := rcmgr.DefaultLimits
libp2p.SetDefaultServiceLimits(&limits)
cfg := rcmgr.PartialLimitConfig{
System: rcmgr.ResourceLimits{Conns: rcmgr.LimitVal(2 * conns), ConnsInbound: rcmgr.LimitVal(conns)},
Transient: rcmgr.ResourceLimits{Conns: rcmgr.LimitVal(conns), ConnsInbound: rcmgr.LimitVal(conns)},
}
mgr, err := rcmgr.NewResourceManager(rcmgr.NewFixedLimiter(cfg.Build(limits.AutoScale())))
if err != nil {
return nil, err
}
return libp2p.ResourceManager(mgr), nil
}
+80
View File
@@ -0,0 +1,80 @@
package p2p
import (
"context"
"testing"
"time"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"
)
// inboundLimit is the cap on inbound connections the node's resource manager enforces.
func inboundLimit(t *testing.T, n *Node) int {
t.Helper()
var limit int
err := n.host.Network().ResourceManager().ViewSystem(func(s network.ResourceScope) error {
l, ok := s.(rcmgr.ResourceScopeLimiter)
if !ok {
t.Fatalf("the system scope %T exposes no limit", s)
}
limit = l.Limit().GetConnLimit(network.DirInbound)
return nil
})
if err != nil {
t.Fatal(err)
}
return limit
}
func TestAPublicNodeAcceptsManyMoreConnectionsThanLibp2pDoesByDefault(t *testing.T) {
public := startNodeWith(t, nil, func(c *Config) { c.Public = true })
if got := inboundLimit(t, public.Node); got != DefaultPublicConns {
t.Errorf("a --public node accepts %d inbound connections, want %d", got, DefaultPublicConns)
}
private := startNode(t, nil)
if got := inboundLimit(t, private.Node); got == DefaultPublicConns {
t.Errorf("a node that is not --public must keep libp2p's own default, got %d", got)
}
opted := startNodeWith(t, nil, func(c *Config) { c.Public = true; c.MaxConns = -1 })
if got := inboundLimit(t, opted.Node); got == DefaultPublicConns {
t.Errorf("MaxConns -1 must keep libp2p's default even when public, got %d", got)
}
}
func TestTheConnectionLimitIsEnforced(t *testing.T) {
const limit = 3
n := startNodeWith(t, nil, func(c *Config) { c.Public = true; c.MaxConns = limit })
if got := inboundLimit(t, n.Node); got != limit {
t.Fatalf("limit is %d, want %d", got, limit)
}
info, err := peer.AddrInfoFromString(n.Addrs()[0])
if err != nil {
t.Fatal(err)
}
connected := 0
for i := 0; i < 8; i++ {
h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { h.Close() })
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
if h.Connect(ctx, *info) == nil {
connected++
}
cancel()
}
if connected < limit {
t.Errorf("only %d of the first %d connections were accepted", connected, limit)
}
time.Sleep(500 * time.Millisecond)
if got := len(n.host.Network().Conns()); got > limit {
t.Errorf("the node holds %d connections, over its limit of %d", got, limit)
}
}
+16
View File
@@ -107,6 +107,11 @@ type Config struct {
// Bandwidth, if set, counts the bytes this node sends and receives (the // Bandwidth, if set, counts the bytes this node sends and receives (the
// simulator uses it; a real node leaves it nil). // simulator uses it; a real node leaves it nil).
Bandwidth metrics.Reporter Bandwidth metrics.Reporter
// MaxConns is the number of inbound connections the node accepts. Zero
// means DefaultPublicConns for a Public node and libp2p's own default
// (which scales with memory) for any other; a negative number keeps
// libp2p's default even for a Public node.
MaxConns int
// ExtraOptions are added to the libp2p host's options; the simulator uses // ExtraOptions are added to the libp2p host's options; the simulator uses
// them to put latency and connection loss on the transport. // them to put latency and connection loss on the transport.
ExtraOptions []libp2p.Option ExtraOptions []libp2p.Option
@@ -206,6 +211,17 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
} }
opts = append(opts, libp2p.AddrsFactory(func([]ma.Multiaddr) []ma.Multiaddr { return announce })) opts = append(opts, libp2p.AddrsFactory(func([]ma.Multiaddr) []ma.Multiaddr { return announce }))
} }
conns := cfg.MaxConns
if conns == 0 && cfg.Public {
conns = DefaultPublicConns
}
if conns > 0 {
limits, err := connectionLimits(conns)
if err != nil {
return nil, fmt.Errorf("connection limits: %w", err)
}
opts = append(opts, limits)
}
opts = append(opts, cfg.ExtraOptions...) opts = append(opts, cfg.ExtraOptions...)
if cfg.Bandwidth != nil { if cfg.Bandwidth != nil {
opts = append(opts, libp2p.BandwidthReporter(cfg.Bandwidth)) opts = append(opts, libp2p.BandwidthReporter(cfg.Bandwidth))
+3 -3
View File
@@ -31,7 +31,7 @@ for (const r of runs) {
const alone = /(\d+) of them have no peer at all/.exec(m.mesh ?? ""); const alone = /(\d+) of them have no peer at all/.exec(m.mesh ?? "");
scaling.push({ scaling.push({
run: r.name, run: r.name,
limit: m.seed_conns > 0 ? "lifted" : "libp2p default", limit: m.seed_conns < 0 ? "libp2p default" : "fixed",
nodes: m.nodes, nodes: m.nodes,
mesh_s: r1(m.mesh_s), mesh_s: r1(m.mesh_s),
mesh_complete: m.mesh_complete, mesh_complete: m.mesh_complete,
@@ -58,7 +58,7 @@ writeFileSync(join(out, "scaling.json"), JSON.stringify(scaling));
// per-second series of the runs worth looking at over time: the smallest, a middle one and the largest of each limit // per-second series of the runs worth looking at over time: the smallest, a middle one and the largest of each limit
const pick = new Set(); const pick = new Set();
for (const limit of ["lifted", "libp2p default"]) { for (const limit of ["fixed", "libp2p default"]) {
const rs = scaling.filter((x) => x.limit === limit); const rs = scaling.filter((x) => x.limit === limit);
if (rs.length) { if (rs.length) {
pick.add(rs[0].run); pick.add(rs[0].run);
@@ -93,7 +93,7 @@ for (const r of runs) {
if (!lst || !lst.ms?.length) continue; if (!lst || !lst.ms?.length) continue;
for (let i = 1; i <= 40; i++) { for (let i = 1; i <= 40; i++) {
const q = i / 40; const q = i / 40;
arrival.push({ run: r.name, nodes: r.meta.nodes, limit: r.meta.seed_conns > 0 ? "lifted" : "libp2p default", ms: r1(pct(lst.ms, q - 1e-9)), share: Math.round(((q * lst.ms.length) / lst.sent) * 1000) / 10 }); arrival.push({ run: r.name, nodes: r.meta.nodes, limit: r.meta.seed_conns < 0 ? "libp2p default" : "fixed", ms: r1(pct(lst.ms, q - 1e-9)), share: Math.round(((q * lst.ms.length) / lst.sent) * 1000) / 10 });
} }
} }
writeFileSync(join(out, "arrival.json"), JSON.stringify(arrival)); writeFileSync(join(out, "arrival.json"), JSON.stringify(arrival));
+5 -4
View File
@@ -5,8 +5,9 @@
# scripts/sim-sweep.sh # the default sweep # scripts/sim-sweep.sh # the default sweep
# SIZES="100 200" LIMITED="200" scripts/sim-sweep.sh # SIZES="100 200" LIMITED="200" scripts/sim-sweep.sh
# #
# SIZES run with the seeds' connection limit lifted; LIMITED run again with # SIZES run with the seeds' connection limit as shipped (1000 for a --public
# libp2p's default limit (about 190 inbound connections on 16 GB of RAM). # node); LIMITED run again with libp2p's own default (about 190 inbound
# connections on 16 GB of RAM), which is how it was before the limit was set.
cd "$(dirname "$0")/.." || exit 1 cd "$(dirname "$0")/.." || exit 1
OUT=.tmp/sim OUT=.tmp/sim
mkdir -p "$OUT" mkdir -p "$OUT"
@@ -27,6 +28,6 @@ run() { # run NODES SEEDCONNS LABEL
return 0 return 0
} }
for n in $SIZES; do run "$n" 5000 "lifted-$n"; done for n in $SIZES; do run "$n" 0 "fixed-$n"; done # the node's own default for a --public node
for n in $LIMITED; do run "$n" "" "default-$n"; done for n in $LIMITED; do run "$n" -1 "default-$n"; done # libp2p's default, the way it was before the fix
echo "done: $(ls $OUT/*.json | wc -l) runs in $OUT" echo "done: $(ls $OUT/*.json | wc -l) runs in $OUT"