From 86668baf5ada0a96c49fb0462151447e44651f87 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Wed, 18 Nov 2026 22:46:05 +0100 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw --- SPECS.md | 7 ++- cmd/allmende-sim/main.go | 13 +++--- cmd/allmende-sim/scenarios.go | 16 ------- cmd/allmende/run.go | 3 ++ docs/PROTOCOL.md | 42 +++++++++--------- internal/p2p/limits.go | 31 ++++++++++++++ internal/p2p/limits_test.go | 80 +++++++++++++++++++++++++++++++++++ internal/p2p/node.go | 16 +++++++ scripts/sim-report.mjs | 6 +-- scripts/sim-sweep.sh | 9 ++-- 10 files changed, 170 insertions(+), 53 deletions(-) create mode 100644 internal/p2p/limits.go create mode 100644 internal/p2p/limits_test.go diff --git a/SPECS.md b/SPECS.md index e723cdf..4340042 100644 --- a/SPECS.md +++ b/SPECS.md @@ -141,10 +141,9 @@ starting a design-heavy item; see "Working with the owner". access exists. Listings already have an `images` field of hashes. - **Recovering listings onto an empty database** (after losing the data directory but not the phrase). -- **Connection limits for `--public` nodes.** Found by `allmende-sim`: libp2p's - default inbound cap scales with RAM (~190 on 16 GB), so a bootstrap node - strands newcomers beyond that. Set explicit limits for public nodes (and - check the k8s memory limit). +- **Check a public node's memory under load.** `--public` nodes now accept + 1000 inbound connections (`--max-conns`); nobody has measured a node holding + that many against the 512 MiB pod limit. - **Peer scoring and rate limits** beyond what the validators do now. The simulator's attacker stays connected after 500 bad messages. - **Joining without the seeds.** A newcomer whose remembered peers are all in diff --git a/cmd/allmende-sim/main.go b/cmd/allmende-sim/main.go index 1b9863d..60b0b87 100644 --- a/cmd/allmende-sim/main.go +++ b/cmd/allmende-sim/main.go @@ -78,7 +78,7 @@ type sim struct { timeout time.Duration made []*listing.Listing 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() { @@ -95,7 +95,7 @@ func main() { 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") 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") 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") @@ -336,16 +336,17 @@ func (s *sim) start(n *simNode) error { if bootstrap == nil { bootstrap = s.seedAddrs } - extra := s.extra - if n.seed && s.seedConns > 0 { - extra = append(append([]libp2p.Option(nil), extra...), seedLimits(s.seedConns)) + maxConns := 0 // the node's own default: DefaultPublicConns for a seed + if n.seed { + maxConns = s.seedConns } node, err := p2p.New(s.ctx, p2p.Config{ Device: n.dev, Store: n.st, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, Bootstrap: bootstrap, - ExtraOptions: extra, + MaxConns: maxConns, + ExtraOptions: s.extra, Regions: n.regions, DHT: true, Public: n.seed, diff --git a/cmd/allmende-sim/scenarios.go b/cmd/allmende-sim/scenarios.go index 7325482..94ad2e7 100644 --- a/cmd/allmende-sim/scenarios.go +++ b/cmd/allmende-sim/scenarios.go @@ -15,7 +15,6 @@ import ( pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/libp2p/go-libp2p/core/host" "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" ma "github.com/multiformats/go-multiaddr" @@ -79,21 +78,6 @@ func (l *lossyConn) Write(p []byte) (int, error) { 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 ---------------------------------------------------------------------------- // attacker is a bare libp2p and gossipsub peer without any of the node's diff --git a/cmd/allmende/run.go b/cmd/allmende/run.go index 265bba9..d973db0 100644 --- a/cmd/allmende/run.go +++ b/cmd/allmende/run.go @@ -44,6 +44,8 @@ func cmdRun(args []string) error { noDHT := fs.Bool("no-dht", false, "do not look for peers through the DHT") 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)") + 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 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") @@ -146,6 +148,7 @@ func cmdRun(args []string) error { MDNS: !*noMDNS, DHT: !*noDHT, Public: *public, + MaxConns: *maxConns, Announce: announceAddrs, PeerCache: filepath.Join(*data, peersFile), Difficulty: *difficulty, diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index c89c303..ce0c09e 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -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 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% | -| 200 | 6.1 s, 100% (p95 50 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 | -| 400 | 14 s, 100% (p95 97 ms) | 212 nodes without a peer, 16% delivered | -| 600 | 24 s, 100% (p95 111 ms) | not run | +| 100 | complete in 3.4 s, 100% delivered | complete in 3.2 s, 100% | +| 200 | 6.3 s, 100% (p95 57 ms) | **never completed**: 12 nodes without any peer, 91.8% delivered | +| 300 | 9.4 s, 100% (p95 79 ms) | 112 nodes without a peer, 43% delivered | +| 400 | 14 s, 100% (p95 99 ms) | 212 nodes without a peer, 16% delivered | +| 600 | 24.5 s, 100% (p95 117 ms) | not run | -With the limit lifted, delivery stayed at 100% and agreement held up to 600 -nodes; time to form the mesh grows roughly with the square of the network -size (3.5 s at 100, 24 s at 600), and so does the simulator's cost (2.5 GB -heap, 230k goroutines, 255 CPU-seconds at 600). That cost is the sum of all the -nodes sharing one machine, so it measures the limit of the simulation as much -as of the protocol; 800 nodes was left out to avoid exhausting memory. With -the default limit the network stops working where the seeds run out of -inbound connections (three seeds hold about 187 each). +As shipped, delivery stayed at 100% and agreement held up to 600 nodes; time +to form the mesh grows roughly with the square of the network size (3.4 s at +100, 24.5 s at 600), and so does the simulator's cost (2.5 GB heap, 230k +goroutines, 250 CPU-seconds at 600). That cost is the sum of all the nodes +sharing one machine, so it measures the limit of the simulation as much as of +the protocol; 800 nodes was left out to avoid exhausting memory. With libp2p's +default the network stopped working where the seeds ran out of inbound +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 - inbound connections in proportion to memory (about 190 on 16 GB). With 200 - nodes, 12 never got a single peer; with the limit lifted the mesh formed in - 6 s. A bootstrap node in a pod with a small memory limit would cap out much - sooner. Needs explicit limits on `--public` nodes. +1. **Connection limit on the bootstrap node (fixed).** libp2p's resource + manager capped inbound connections in proportion to memory (about 190 on 16 + GB, fewer in a small container): with 200 nodes, 12 never got a single peer. + A `--public` node now accepts 1000 inbound connections (`--max-conns` + 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 dialed after sending 500 bad messages. Nothing was stored, but each message still cost every node its validation work. diff --git a/internal/p2p/limits.go b/internal/p2p/limits.go new file mode 100644 index 0000000..7aa602f --- /dev/null +++ b/internal/p2p/limits.go @@ -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 +} diff --git a/internal/p2p/limits_test.go b/internal/p2p/limits_test.go new file mode 100644 index 0000000..e963661 --- /dev/null +++ b/internal/p2p/limits_test.go @@ -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) + } +} diff --git a/internal/p2p/node.go b/internal/p2p/node.go index fe6a0e7..d0f392c 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -107,6 +107,11 @@ type Config struct { // Bandwidth, if set, counts the bytes this node sends and receives (the // simulator uses it; a real node leaves it nil). 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 // them to put latency and connection loss on the transport. 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 })) } + 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...) if cfg.Bandwidth != nil { opts = append(opts, libp2p.BandwidthReporter(cfg.Bandwidth)) diff --git a/scripts/sim-report.mjs b/scripts/sim-report.mjs index 1a80f68..445bc57 100644 --- a/scripts/sim-report.mjs +++ b/scripts/sim-report.mjs @@ -31,7 +31,7 @@ for (const r of runs) { const alone = /(\d+) of them have no peer at all/.exec(m.mesh ?? ""); scaling.push({ run: r.name, - limit: m.seed_conns > 0 ? "lifted" : "libp2p default", + limit: m.seed_conns < 0 ? "libp2p default" : "fixed", nodes: m.nodes, mesh_s: r1(m.mesh_s), 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 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); if (rs.length) { pick.add(rs[0].run); @@ -93,7 +93,7 @@ for (const r of runs) { if (!lst || !lst.ms?.length) continue; for (let i = 1; i <= 40; i++) { 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)); diff --git a/scripts/sim-sweep.sh b/scripts/sim-sweep.sh index 731a995..0304c82 100755 --- a/scripts/sim-sweep.sh +++ b/scripts/sim-sweep.sh @@ -5,8 +5,9 @@ # scripts/sim-sweep.sh # the default sweep # SIZES="100 200" LIMITED="200" scripts/sim-sweep.sh # -# SIZES run with the seeds' connection limit lifted; LIMITED run again with -# libp2p's default limit (about 190 inbound connections on 16 GB of RAM). +# SIZES run with the seeds' connection limit as shipped (1000 for a --public +# 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 OUT=.tmp/sim mkdir -p "$OUT" @@ -27,6 +28,6 @@ run() { # run NODES SEEDCONNS LABEL return 0 } -for n in $SIZES; do run "$n" 5000 "lifted-$n"; done -for n in $LIMITED; do run "$n" "" "default-$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" -1 "default-$n"; done # libp2p's default, the way it was before the fix echo "done: $(ls $OUT/*.json | wc -l) runs in $OUT"