From 5db90c272018444210d4b0e6a7711b9844bb206e Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Wed, 18 Nov 2026 22:00:19 +0100 Subject: [PATCH] allmende-sim: latency and connection loss, attackers, seeds down, anti-entropy repair, 300 nodes Findings: default libp2p connection limits strand nodes on a bootstrap node beyond ~190 peers, there is no peer scoring, and newcomers cannot find their region without DHT servers when their remembered peers are elsewhere. Documented in docs/PROTOCOL.md and SPECS.md. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw --- SPECS.md | 14 +- cmd/allmende-sim/main.go | 87 ++++++- cmd/allmende-sim/scenarios.go | 427 ++++++++++++++++++++++++++++++++++ docs/PROTOCOL.md | 40 +++- internal/p2p/node.go | 4 + 5 files changed, 562 insertions(+), 10 deletions(-) create mode 100644 cmd/allmende-sim/scenarios.go diff --git a/SPECS.md b/SPECS.md index 35168ef..e723cdf 100644 --- a/SPECS.md +++ b/SPECS.md @@ -111,6 +111,7 @@ in the middle. | Expiry reminder in the terminal (≤5 days left) | done | | Packaging: Dockerfile, Nix flake and module, `make image` | done | | Kubernetes bootstrap node (`k8s/`, kustomize, Traefik IngressRoute) | written and **deployed by the owner**; running image is older than digest sync, anti-entropy, reports | +| Network simulator `cmd/allmende-sim`: 100-300 real nodes, latency, connection loss, attackers, seeds down, repair (results in docs/PROTOCOL.md) | done | | Tests: Go (`-race`), web (`node:test` + jsdom), end-to-end with real binaries (`make e2e`) | all passing | The public bootstrap node is `bootstrap.allmende.stinnesbeck.com` (TCP and UDP @@ -140,7 +141,18 @@ 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). -- **Peer scoring and rate limits** beyond what the validators do now. +- **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). +- **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 + another region cannot find its region when no DHT server is up (sim: 0 of + 114 listings). Remember region peers separately, or ask connected peers. +- **Faster repair.** Anti-entropy at 30 min takes hours to spread one missed + listing (median ~2 h by the sim); consider a shorter interval or syncing + with several peers per round. - **Message-sender abuse** (reports cover listings only). **Decisions and non-code work (the owner's)** diff --git a/cmd/allmende-sim/main.go b/cmd/allmende-sim/main.go index 395610d..eb1b730 100644 --- a/cmd/allmende-sim/main.go +++ b/cmd/allmende-sim/main.go @@ -25,6 +25,7 @@ import ( "syscall" "time" + "github.com/libp2p/go-libp2p" "github.com/libp2p/go-libp2p/core/metrics" "git.stinnesbeck.com/nils/allmende/internal/identity" @@ -49,6 +50,9 @@ type simNode struct { node *p2p.Node // nil while the node is down bw *metrics.BandwidthCounter regions []string + // bootstrap, if set, is where this node looks for its first peers instead + // of the seeds. + bootstrap []string } func (n *simNode) follows(region string) bool { @@ -69,6 +73,10 @@ type sim struct { discover time.Duration antiEnt time.Duration rng *rand.Rand + extra []libp2p.Option // transport conditions (latency, connection loss) + timeout time.Duration + made []*listing.Listing + seedConns int // raised connection limit of the seeds; 0 keeps libp2p's default } func main() { @@ -83,6 +91,12 @@ func main() { discover := flag.Duration("discover", 5*time.Second, "how often nodes look for region peers (a real node: 1m)") antiEntropy := flag.Duration("anti-entropy", 30*time.Minute, "anti-entropy interval (a real node: 30m)") 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)") + 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") + repair := flag.Bool("repair", false, "also test anti-entropy: a listing only one node has, nobody told (set -anti-entropy to a few seconds)") seed := flag.Uint64("seed", 1, "random seed, so a run can be repeated") flag.Parse() if *nregions < 1 || *nregions > len(allRegions) || *seeds < 1 || *nodes <= *seeds+1 { @@ -93,7 +107,12 @@ func main() { s := &sim{ ctx: context.Background(), difficulty: 8, msgDiff: 6, discover: *discover, antiEnt: *antiEntropy, - rng: rand.New(rand.NewPCG(*seed, 7)), + rng: rand.New(rand.NewPCG(*seed, 7)), timeout: *timeout, seedConns: *seedConns, + } + var conditions *netConditions + if *latency > 0 || *lifetime > 0 { + conditions = &netConditions{latency: *latency, lifetime: *lifetime} + s.extra = conditions.options() } regions := allRegions[:*nregions] report0 := newReport() @@ -153,6 +172,7 @@ func main() { // --- messages ------------------------------------------------------------ fmt.Printf("sending %d buyer messages ...\n", *messages) pairs = nil + refused := 0 for i := 0; i < *messages; i++ { l := made[s.rng.IntN(len(made))] owner := s.byAuthor(l.Author) @@ -164,9 +184,15 @@ func main() { must(err) env, err := message.SealToOwner(l, tk, &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: "Ist die Wohnung noch frei?"}, time.Now(), s.msgDiff) must(err) - must(via.node.PublishMessage(s.ctx, listing.Region(l.Geohash), env)) + if err := via.node.PublishMessage(s.ctx, listing.Region(l.Geohash), env); err != nil { + refused++ // the buyer's gateway does not hold the listing (yet) + continue + } pairs = append(pairs, &pair{start: time.Now(), check: s.ownerHas(owner, env)}) } + if refused > 0 { + report0.row("message!", fmt.Sprintf("%d of %d messages were refused by the buyer's own node: it did not hold the listing", refused, *messages)) + } res = await(pairs, *timeout) report0.latency("message", "from a random node of the region to the listing's owner", res) @@ -230,8 +256,23 @@ func main() { report0.latency("rejoin", "a node back from offline has every listing of its regions", res) made = append(made, extra...) } + s.made = made + + if *hostile { + s.hostile(regions, report0) + } + if *repair { + s.repair(report0) + } + if *killSeeds { + s.killSeeds(regions, report0) + } // --- do all nodes agree? --------------------------------------------------- + if conditions != nil { + report0.row("network", fmt.Sprintf("latency %s (±50%%) per write on dialed connections, mean connection life %s: %d connections were cut", + *latency, *lifetime, conditions.cuts.Load())) + } report0.row("agreement", s.agreement(regions)) report0.resources("at the end", s) report0.print(os.Stdout) @@ -265,11 +306,20 @@ func (s *sim) makeIdentity(n *simNode) error { // start (re)starts a node's p2p side on its existing identity and store. func (s *sim) start(n *simNode) error { + bootstrap := n.bootstrap + 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)) + } node, err := p2p.New(s.ctx, p2p.Config{ Device: n.dev, Store: n.st, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, - Bootstrap: s.seedAddrs, + Bootstrap: bootstrap, + ExtraOptions: extra, Regions: n.regions, DHT: true, Public: n.seed, @@ -373,7 +423,28 @@ func (s *sim) waitFormed(regions []string, timeout time.Duration) string { } time.Sleep(200 * time.Millisecond) } - return "timed out: some nodes still lack regional peers" + alone, short := 0, 0 + for _, n := range s.nodes { + if n.seed { + continue + } + if n.node.PeerCount() == 0 { + alone++ + } + for _, r := range n.regions { + if len(n.node.RegionPeers(r)) < min(2, len(s.followers(r))-1) { + short++ + break + } + } + } + var seedPeers []int + for _, n := range s.nodes { + if n.seed { + seedPeers = append(seedPeers, n.node.PeerCount()) + } + } + return fmt.Sprintf("timed out: %d nodes lack regional peers, %d of them have no peer at all; the seeds each hold %v connections", short, alone, seedPeers) } // --- what a node has --------------------------------------------------------------- @@ -435,6 +506,9 @@ func (s *sim) agreement(regions []string) string { } reps := map[string]int{} for _, n := range s.nodes { + if n.node == nil { + continue // a node that is down holds what it held + } d, err := n.st.ReportDigest(s.ctx) must(err) reps[fmt.Sprintf("%d/%s", d.Count, d.Root[:8])]++ @@ -500,7 +574,10 @@ type reportTable struct { func newReport() *reportTable { return &reportTable{} } -func (r *reportTable) row(k, v string) { r.rows = append(r.rows, [2]string{k, v}) } +func (r *reportTable) row(k, v string) { + r.rows = append(r.rows, [2]string{k, v}) + fmt.Printf(" %-10s %s\n", k, v) // live, so a crash later does not lose it +} func (r *reportTable) latency(k, what string, ps []*pair) { var d []time.Duration diff --git a/cmd/allmende-sim/scenarios.go b/cmd/allmende-sim/scenarios.go new file mode 100644 index 0000000..f969dc2 --- /dev/null +++ b/cmd/allmende-sim/scenarios.go @@ -0,0 +1,427 @@ +package main + +// The harder scenarios of the simulator: conditions on the network, attackers, +// the seeds going away, and repair of what gossip never delivered. + +import ( + "context" + "fmt" + "math/rand/v2" + "net" + "sync/atomic" + "time" + + "github.com/libp2p/go-libp2p" + 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" + + "git.stinnesbeck.com/nils/allmende/internal/listing" + "git.stinnesbeck.com/nils/allmende/internal/message" +) + +// --- latency and connection loss ------------------------------------------------------ + +// netConditions puts a delay on every write of the connections a node dials, +// and cuts those connections after a random time. TCP itself never loses +// bytes, so this is what packet loss looks like to the layers above: slow +// writes, and connections that die and have to be redialed and resynced. +// Only dialed connections are touched, so a delay applies in one direction. +type netConditions struct { + latency, lifetime time.Duration + cuts atomic.Int64 +} + +func (c *netConditions) options() []libp2p.Option { + return []libp2p.Option{libp2p.Transport(tcp.NewTCPTransport, + tcp.WithDialerForAddr(func(ma.Multiaddr) (tcp.ContextDialer, error) { + return &lossyDialer{c: c}, nil + }))} +} + +type lossyDialer struct{ c *netConditions } + +func (d *lossyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { + conn, err := (&net.Dialer{}).DialContext(ctx, network, address) + if err != nil { + return nil, err + } + if d.c.lifetime > 0 { + time.AfterFunc(time.Duration(rand.ExpFloat64()*float64(d.c.lifetime)), func() { + d.c.cuts.Add(1) + _ = conn.Close() + }) + } + return &lossyConn{Conn: conn, c: d.c}, nil +} + +type lossyConn struct { + net.Conn + c *netConditions +} + +// The transport sets TCP keepalives on the connection it is given. +func (l *lossyConn) SetKeepAlive(on bool) error { + return l.Conn.(*net.TCPConn).SetKeepAlive(on) +} + +func (l *lossyConn) SetKeepAlivePeriod(d time.Duration) error { + return l.Conn.(*net.TCPConn).SetKeepAlivePeriod(d) +} + +func (l *lossyConn) Write(p []byte) (int, error) { + if d := l.c.latency; d > 0 { + time.Sleep(d/2 + time.Duration(rand.Int64N(int64(d)))) // 50% to 150% + } + 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 +// validators, so it can put whatever it likes on a topic. +type attacker struct { + h host.Host + topics map[string]*pubsub.Topic + cancel context.CancelFunc +} + +func (s *sim) newAttacker(targets []*simNode, topics ...string) *attacker { + ctx, cancel := context.WithCancel(s.ctx) + h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0")) + s.must(err) + ps, err := pubsub.NewGossipSub(ctx, h, pubsub.WithMaxMessageSize(1<<20), pubsub.WithFloodPublish(true)) + s.must(err) + a := &attacker{h: h, topics: map[string]*pubsub.Topic{}, cancel: cancel} + for _, name := range topics { + t, err := ps.Join(name) + s.must(err) + sub, err := t.Subscribe() + s.must(err) + go func() { + for { + if _, err := sub.Next(ctx); err != nil { + return + } + } + }() + a.topics[name] = t + } + for _, n := range targets { + ai, err := peer.AddrInfoFromString(n.node.Addrs()[0]) + s.must(err) + s.must(h.Connect(ctx, *ai)) + } + time.Sleep(2 * time.Second) // let the topic subscriptions reach the targets + return a +} + +func (a *attacker) publish(ctx context.Context, topic string, data []byte) { + _ = a.topics[topic].Publish(ctx, data) // a refusal is the attacker's loss, not the test's +} + +func (a *attacker) close() { + a.cancel() + _ = a.h.Close() +} + +// totalListings counts the listings the running nodes hold. +func (s *sim) totalListings() int { + total := 0 + for _, n := range s.nodes { + if n.node == nil { + continue + } + c, err := n.st.Count(s.ctx) + s.must(err) + total += c + } + return total +} + +// hostile attacks one region: junk and forged listings, then a flood of valid +// messages at one listing. It checks that nothing invalid is stored anywhere, +// that honest traffic still gets through, and what the flood costs a sender. +func (s *sim) hostile(regions []string, rep *reportTable) { + region := regions[0] + fmt.Printf("attacking region %s: forged listings and a message flood ...\n", region) + pool := s.followers(region) + targets := pool[:min(10, len(pool))] + lt := "/allmende/1/listings/" + region + mt := "/allmende/1/messages/" + region + atk := s.newAttacker(targets, lt, mt) + defer atk.close() + + // 1. listings that must never be stored + ident := &simNode{} + s.must(s.makeIdentity(ident)) + defer ident.st.Close() + before := s.totalListings() + sent := map[string]int{} + send := func(kind string, data []byte) { + atk.publish(s.ctx, lt, data) + sent[kind]++ + } + for i := 0; i < 150; i++ { + junk := make([]byte, 100+s.rng.IntN(400)) + for j := range junk { + junk[j] = byte(s.rng.IntN(256)) + } + send("garbage", junk) + + l := s.newListing(ident, region) // valid, then changed after signing + l.Title = "Geaendert nach der Signatur" + b, _ := l.Bytes() + send("forged signature", b) + + weak := s.newListing(ident, region) // signed, with too little proof-of-work + for tries := 0; tries < 50; tries++ { + id, _ := listing.NewID() + weak.ID = id + s.must(weak.Seal(ident.dev, 1)) + if weak.Check(time.Now(), s.difficulty) != nil { + break + } + } + if weak.Check(time.Now(), s.difficulty) != nil { + b, _ = weak.Bytes() + send("too little work", b) + } + } + other := regions[len(regions)-1] + for i := 0; i < 50 && other != region; i++ { + l := s.newListing(ident, other) // valid, on the wrong region's topic + b, _ := l.Bytes() + send("wrong region", b) + } + time.Sleep(3 * time.Second) + grew := s.totalListings() - before + total := 0 + for _, c := range sent { + total += c + } + rep.row("attack 1", fmt.Sprintf("%d bad listings sent (%v): the nodes stored %d of them", total, sent, grew)) + + // honest listings must still arrive while the attacker is connected + var pairs []*pair + for i := 0; i < 10; i++ { + owner := s.randomFollower(region) + l := s.newListing(owner, region) + must(owner.node.Publish(s.ctx, l)) + s.made = append(s.made, l) + at := time.Now() + for _, f := range s.followers(region) { + if f != owner { + pairs = append(pairs, &pair{start: at, check: s.hasListing(f, l)}) + } + } + poll(pairs, 100*time.Millisecond) + } + rep.latency("attack 1b", "honest listings published while the attacker is connected", await(pairs, s.timeout)) + rep.row("attack 1c", fmt.Sprintf("the attacker is still connected to %d of %d nodes it dialed (there is no peer scoring: nobody cuts it off)", + len(atk.h.Network().Peers()), len(targets))) + + // 2. a message flood at one listing, with real (cheap) proof-of-work + var target *listing.Listing + for _, l := range s.made { + if listing.Region(l.Geohash) == region && s.byAuthor(l.Author) != nil && s.byAuthor(l.Author).node != nil { + target = l + break + } + } + if target == nil { + rep.row("attack 2", "no live listing in the region to flood") + return + } + owner := s.byAuthor(target.Author) + ref := message.Ref{Author: target.Author, ID: target.ID} + queue := func(n *simNode) int { + envs, err := n.st.OwnerMessages(s.ctx, target.Author) + s.must(err) + c := 0 + for _, e := range envs { + if e.Listing == ref { + c++ + } + } + return c + } + const flood = 400 + for i := 0; i < flood; i++ { + tk, err := message.NewThreadKey() + s.must(err) + env, err := message.SealToOwner(target, tk, &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: "Kaufen Sie jetzt"}, time.Now(), s.msgDiff) + s.must(err) + b, _ := env.Bytes() + atk.publish(s.ctx, mt, b) + } + time.Sleep(4 * time.Second) + lo, hi := 1<<30, 0 + for _, f := range s.followers(region) { + q := queue(f) + lo, hi = min(lo, q), max(hi, q) + } + ownerPrice, err := owner.st.RequiredWork(s.ctx, ref) + s.must(err) + rep.row("attack 2", fmt.Sprintf("%d valid envelopes at the base price (%d bits) flooded at one listing: queue at its owner %d (limit 200), across the region's nodes %d to %d; the price there is now %d bits", + flood, s.msgDiff, queue(owner), lo, hi, ownerPrice)) + + // a real buyer asks the node it uses (not the owner) for the price and pays it + via := s.randomFollower(region) + for via == owner { + via = s.randomFollower(region) + } + viaPrice, err := via.st.RequiredWork(s.ctx, ref) + s.must(err) + buy := func(bits int) (time.Duration, bool) { + tk, err := message.NewThreadKey() + s.must(err) + env, err := message.SealToOwner(target, tk, &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: "Ist die Wohnung noch frei?"}, time.Now(), bits) + s.must(err) + if err := via.node.PublishMessage(s.ctx, region, env); err != nil { + return 0, false + } + p := &pair{start: time.Now(), check: s.ownerHas(owner, env)} + await([]*pair{p}, 10*time.Second) + return p.took, p.done + } + if took, ok := buy(viaPrice); ok { + rep.row("attack 2b", fmt.Sprintf("a buyer paying its gateway's price (%d bits; the owner's is %d) reached the owner in %s", viaPrice, ownerPrice, round(took))) + } else if took, ok := buy(max(viaPrice, ownerPrice)); ok { + rep.row("attack 2b", fmt.Sprintf("a buyer paying its gateway's price (%d bits) did NOT reach the owner (whose price is %d); paying the owner's price did, in %s", + viaPrice, ownerPrice, round(took))) + } else { + rep.row("attack 2b", fmt.Sprintf("a buyer did NOT reach the owner at the gateway's price (%d) nor the owner's (%d)", viaPrice, ownerPrice)) + } +} + +// --- anti-entropy ---------------------------------------------------------------------------- + +// repair puts listings into one node's store and tells nobody. Only +// anti-entropy (or a new connection's sync) can carry them to the region. +func (s *sim) repair(rep *reportTable) { + fmt.Println("anti-entropy: listings only one node has ...") + var pairs []*pair + for i := 0; i < 5; i++ { + owner := s.randomFollower("") + l := s.newListing(owner, owner.regions[0]) + _, err := owner.st.Put(s.ctx, l) + s.must(err) + s.made = append(s.made, l) + at := time.Now() + for _, f := range s.followers(listing.Region(l.Geohash)) { + if f != owner { + pairs = append(pairs, &pair{start: at, check: s.hasListing(f, l)}) + } + } + } + rep.latency("repair", fmt.Sprintf("listings no one gossiped, spread by anti-entropy every %s (and by new connections)", s.antiEnt), + await(pairs, s.timeout)) +} + +// --- the seeds go away ----------------------------------------------------------------------- + +func (s *sim) killSeeds(regions []string, rep *reportTable) { + fmt.Println("shutting down the seeds ...") + for _, n := range s.nodes { + if n.seed && n.node != nil { + _ = n.node.Close() + n.node = nil + } + } + time.Sleep(2 * time.Second) + + // the network goes on without them + var pairs []*pair + for i := 0; i < 15; i++ { + owner := s.randomFollower("") + l := s.newListing(owner, owner.regions[0]) + must(owner.node.Publish(s.ctx, l)) + s.made = append(s.made, l) + at := time.Now() + for _, f := range s.followers(listing.Region(l.Geohash)) { + if f != owner { + pairs = append(pairs, &pair{start: at, check: s.hasListing(f, l)}) + } + } + poll(pairs, 100*time.Millisecond) + } + rep.latency("no seeds", "listings published after every seed is gone", await(pairs, s.timeout)) + + // A node that was here before remembers some peers (peers.json). Those are + // mostly of its own regions; the unlucky case is that they are not. + cachedIn := func(want func(*simNode) bool) []string { + var addrs []string + for _, n := range s.nodes { + if !n.seed && n.node != nil && want(n) && len(addrs) < 2 { + addrs = append(addrs, n.node.Addrs()[0]) + } + } + return addrs + } + newcomers := func(row, what string, n int, pick func(region string) []string) []*simNode { + var fresh []*simNode + for i := 0; i < n; i++ { + region := regions[i%len(regions)] + fresh = append(fresh, s.spawn([]string{region}, pick(region))) + } + start := time.Now() + var pairs []*pair + for _, f := range fresh { + for _, l := range s.made { + if f.follows(listing.Region(l.Geohash)) { + pairs = append(pairs, &pair{start: start, check: s.hasListing(f, l)}) + } + } + } + rep.latency(row, what, await(pairs, s.timeout)) + return fresh + } + newcomers("newcomers", "10 new nodes that remember two live peers of their own region get every listing of it", 10, + func(region string) []string { return cachedIn(func(n *simNode) bool { return n.follows(region) }) }) + newcomers("newcomers 2", "6 new nodes whose two remembered peers are all in another region", 6, + func(region string) []string { return cachedIn(func(n *simNode) bool { return !n.follows(region) }) }) + + // a newcomer that only knows the seeds + var lost []*simNode + for i := 0; i < 5; i++ { + lost = append(lost, s.spawn([]string{regions[i%len(regions)]}, s.seedAddrs)) + } + time.Sleep(min(s.timeout, 15*time.Second)) + joined := 0 + for _, n := range lost { + if n.node.PeerCount() > 0 { + joined++ + } + _ = n.node.Close() // left out of the final comparison: they never joined + n.node = nil + } + rep.row("lost", fmt.Sprintf("5 new nodes that only know the dead seeds: %d found a peer after 15 s", joined)) +} + +// spawn starts one more node on a fresh identity. +func (s *sim) spawn(regions, bootstrap []string) *simNode { + n := &simNode{idx: len(s.nodes), regions: regions, bootstrap: bootstrap} + s.must(s.makeIdentity(n)) + s.nodes = append(s.nodes, n) + s.must(s.start(n)) + return n +} diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index a5977f2..0fd7a1e 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -606,10 +606,42 @@ reached its owner (p95 0.4 s), a report reached all 99 other nodes (p95 0.17 s), returning nodes caught up in under 3 s, and all nodes agreed afterwards. About 165 KB of traffic per node in total. -It shows protocol behaviour and cost, **not** internet conditions: loopback has -no latency, packet loss, NATs or hostile peers, and nodes are always reachable. -Treat the times as a lower bound and the agreement and cost figures as the -useful part. +More scenarios, each a flag: `-latency 60ms -lifetime 30s` (delay on every +write of dialed connections, ±50%, and connections cut at random; this is what +packet loss looks like above TCP), `-hostile` (an attacker with no validators), +`-kill-seeds`, `-repair` (with `-anti-entropy 5s`), `-seed-conns N`. Ran on +2026-11-18 (100 nodes, 5 regions unless noted): + +| Scenario | Result | +|---|---| +| 60 ms latency, 1130 connections cut in the run | 100% delivered; listings p95 67 ms, messages p95 0.4 s; returning nodes 6 s; all nodes agreed | +| 500 junk, forged, under-worked and wrong-region listings at one region | **0 stored**; honest listings during the attack 100% (p95 31 ms) | +| 400 valid envelopes flooding one listing | queue stayed under the limit (138 of 200 at the owner); the price rose from 6 to 7 bits; a buyer paying its own gateway's price still got through (43 ms) | +| listing only one node's store has (no gossip) | anti-entropy every 5 s delivered all 105: p50 18 s, p95 38 s, max 63 s. At the default 30 min that is a median of about 2 hours | +| all seeds shut down | the network keeps working (329 of 329 listings); newcomers that remember two live peers of their own region got everything (160 of 160) | +| 300 nodes, 8 regions | 100% delivered (listings p95 75 ms, messages p95 0.8 s, reports p95 0.5 s), all agreed; 1.3 GB heap, 100k goroutines, 137 KB per node | + +Findings (nothing here is fixed yet; see "What is left" in SPECS.md): + +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. +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. +3. **The DHT is only as good as its servers.** Only publicly reachable nodes + serve it. With every seed gone, a newcomer whose remembered peers are all in + another region found nobody (0 of 114 listings), and one that remembers no + live peer found no peer at all. A node that remembers peers of its own + region (the usual case) is fine. +4. **Repair is slow at the default interval** (see the table). + +It shows protocol behaviour and cost, **not** the internet: no real packet +loss, NATs, clock skew or bandwidth limits, and all nodes share one machine, so +CPU and memory figures are totals for all of them. Treat the times as a lower +bound and the agreement and cost figures as the useful part. ## Open diff --git a/internal/p2p/node.go b/internal/p2p/node.go index f6e2bec..fe6a0e7 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -107,6 +107,9 @@ 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 + // 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 } // Node is a running participant. @@ -203,6 +206,7 @@ func New(ctx context.Context, cfg Config) (*Node, error) { } opts = append(opts, libp2p.AddrsFactory(func([]ma.Multiaddr) []ma.Multiaddr { return announce })) } + opts = append(opts, cfg.ExtraOptions...) if cfg.Bandwidth != nil { opts = append(opts, libp2p.BandwidthReporter(cfg.Bandwidth)) }