Files
nilsandClaude Sonnet 5.5 59973cbf43 p2p: peer exchange to find a region without the DHT, region-tagged peer cache, faster anti-entropy
A node with too few peers in a followed region asks its connected peers who they know there (sync kind "peers"); a peer answers even from another region, since gossip tells it which topics its connections subscribe to. Peers of the region are dialed, others only while the region has none. The peer cache records the regions a peer was seen in and a restart redials those first. Anti-entropy now runs every 10 minutes (plus or minus a fifth) with 3 peers per round instead of every 30 with one. Simulator: a newcomer whose remembered peers were all in another region got 0 of 114 listings with the seeds down, now 56 of 56; repair median at the same interval 25.9 s to 5.7 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-19 00:54:48 +01:00

704 lines
21 KiB
Go

// Command allmende-sim runs many real Allmende nodes in one process and
// measures how the network behaves: how fast listings, messages and reports
// spread, what happens when nodes leave and come back, and what it costs in
// memory and traffic.
//
// Every node is the real thing (libp2p host, gossipsub, DHT, store, sync), with
// its own identity and certificate. They talk over loopback, so what it shows
// is the protocol's behaviour and cost, not the internet's latency, packet
// loss or NATs. See "Simulation" in docs/PROTOCOL.md.
//
// go run ./cmd/allmende-sim -nodes 100
package main
import (
"context"
"flag"
"fmt"
"io"
"log/slog"
"math/rand/v2"
"os"
"runtime"
"sort"
"strings"
"sync"
"syscall"
"time"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/metrics"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/p2p"
"git.stinnesbeck.com/nils/allmende/internal/report"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
// Regions the nodes are spread over (3-character geohash cells).
var allRegions = []string{"u1x", "u1w", "u1y", "u1z", "u30", "u31", "u32", "u33", "u1q", "u1r"}
const geohashChars = "0123456789bcdefghjkmnpqrstuvwxyz"
type simNode struct {
idx int
seed bool
root *identity.Identity
dev *identity.Device
st *store.Store
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 {
for _, r := range n.regions {
if r == region {
return true
}
}
return false
}
type sim struct {
ctx context.Context
nodes []*simNode
seedAddrs []string
difficulty int
msgDiff int
discover time.Duration
antiEnt time.Duration
antiPeers int
rng *rand.Rand
extra []libp2p.Option // transport conditions (latency, connection loss)
timeout time.Duration
made []*listing.Listing
mu sync.Mutex // guards nodes against the sampler
seedConns int // the seeds' MaxConns setting
}
func main() {
nodes := flag.Int("nodes", 100, "number of nodes (including the seeds)")
nregions := flag.Int("regions", 5, "number of regions the nodes are spread over (max 10)")
seeds := flag.Int("seeds", 3, "bootstrap nodes: public, follow no region")
listings := flag.Int("listings", 30, "listings to publish")
rate := flag.Float64("rate", 5, "listings published per second")
messages := flag.Int("messages", 20, "buyer messages to send")
reports := flag.Int("reports", 3, "abuse reports to publish")
churn := flag.Float64("churn", 0.2, "fraction of nodes that go offline while listings are published, then come back")
discover := flag.Duration("discover", 5*time.Second, "how often nodes look for region peers (a real node: 1m)")
antiEntropy := flag.Duration("anti-entropy", 10*time.Minute, "anti-entropy interval (a real node: 10m)")
antiPeers := flag.Int("anti-entropy-peers", 3, "peers asked per anti-entropy round (a real node: 3)")
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, "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")
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 {
fmt.Fprintln(os.Stderr, "need 1-10 regions, at least one seed and more nodes than seeds")
os.Exit(2)
}
s := &sim{
ctx: context.Background(), difficulty: 8, msgDiff: 6,
discover: *discover, antiEnt: *antiEntropy, antiPeers: *antiPeers,
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]
rec := newRecorder()
report0 := newReport(rec)
stopSampling := make(chan struct{})
go rec.run(s, stopSampling)
report0.phase("start")
// --- start the network ---------------------------------------------------
fmt.Printf("starting %d nodes (%d seeds), %d regions ...\n", *nodes, *seeds, *nregions)
t0 := time.Now()
for i := 0; i < *nodes; i++ {
n := &simNode{idx: i, seed: i < *seeds}
if !n.seed {
n.regions = []string{regions[i%len(regions)]}
if s.rng.Float64() < 0.2 { // a fifth follow a second region
if r := regions[s.rng.IntN(len(regions))]; r != n.regions[0] {
n.regions = append(n.regions, r)
}
}
}
s.must(s.makeIdentity(n))
s.mu.Lock()
s.nodes = append(s.nodes, n)
s.mu.Unlock()
s.must(s.start(n))
if n.seed {
s.seedAddrs = append(s.seedAddrs, n.node.Addrs()[0])
}
}
startup := time.Since(t0)
report0.row("start", fmt.Sprintf("%d nodes started in %s", *nodes, round(startup)))
report0.phase("mesh")
formed := s.waitFormed(regions, *timeout)
meshSeconds := time.Since(t0).Seconds()
report0.row("mesh", fmt.Sprintf("every node knows regional peers after %s (%s)", round(time.Since(t0)), formed))
report0.resources("after start", s)
// --- listings ------------------------------------------------------------
report0.phase("listings")
fmt.Printf("publishing %d listings at %.0f/s ...\n", *listings, *rate)
var made []*listing.Listing
var pairs []*pair
pubStart := time.Now()
for i := 0; i < *listings; i++ {
owner := s.randomFollower("")
l := s.newListing(owner, owner.regions[0])
must(owner.node.Publish(s.ctx, l))
made = append(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 while waiting for the next publish, so an arrival is timed when
// it happens and not when the loop is over.
poll(pairs, time.Duration(float64(time.Second) / *rate))
}
_ = pubStart
res := await(pairs, *timeout)
report0.latency("listing", "reaches each node following its region", res)
report0.resources("after listings", s)
// --- messages ------------------------------------------------------------
report0.phase("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)
via := s.randomFollower(listing.Region(l.Geohash))
if via == owner {
continue
}
tk, err := message.NewThreadKey()
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)
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)
// --- reports -------------------------------------------------------------
report0.phase("reports")
fmt.Printf("publishing %d abuse reports ...\n", *reports)
pairs = nil
var reps []*report.Report
for i := 0; i < *reports; i++ {
by := s.randomFollower("")
l := made[s.rng.IntN(len(made))]
r := &report.Report{
Listing: report.Ref{Author: l.Author, ID: l.ID}, Category: report.Scam,
CreatedAt: time.Now().Unix(), ExpiresAt: time.Now().Add(7 * 24 * time.Hour).Unix(),
}
must(r.Seal(by.dev, s.difficulty))
if err := by.node.PublishReport(s.ctx, r); err != nil {
fmt.Fprintln(os.Stderr, "report:", err)
continue
}
reps = append(reps, r)
at := time.Now()
for _, n := range s.nodes {
if n != by {
pairs = append(pairs, &pair{start: at, check: s.hasReport(n, r)})
}
}
}
res = await(pairs, *timeout)
report0.latency("report", "reaches every node (a global topic)", res)
// --- churn ---------------------------------------------------------------
down := s.pickDown(int(float64(*nodes) * *churn))
if len(down) > 0 {
report0.phase("churn")
fmt.Printf("taking %d nodes offline, publishing 10 more listings, bringing them back ...\n", len(down))
for _, n := range down {
_ = n.node.Close() // the store (and so what it already knew) stays, as on a real machine
n.node = nil
}
time.Sleep(2 * time.Second)
var extra []*listing.Listing
for i := 0; i < 10; i++ {
owner := s.randomAlive()
l := s.newListing(owner, owner.regions[0])
must(owner.node.Publish(s.ctx, l))
extra = append(extra, l)
}
time.Sleep(2 * time.Second)
pairs = nil
back := time.Now()
for _, n := range down {
s.must(s.start(n))
}
for _, n := range down {
for _, l := range append(append([]*listing.Listing{}, made...), extra...) {
if n.follows(listing.Region(l.Geohash)) {
pairs = append(pairs, &pair{start: back, check: s.hasListing(n, l)})
}
}
}
res = await(pairs, *timeout)
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)
close(stopSampling)
if *jsonOut != "" {
meta := map[string]any{
"nodes": *nodes, "regions": *nregions, "seeds": *seeds, "seed_conns": *seedConns,
"latency_ms": latency.Milliseconds(), "lifetime_s": lifetime.Seconds(),
"mesh_s": meshSeconds, "mesh_complete": formed == "complete", "mesh": formed,
"agreement": s.agreement(regions), "date": time.Now().Format(time.RFC3339),
}
must(rec.write(*jsonOut, meta))
fmt.Println("recorded to", *jsonOut)
}
for _, n := range s.nodes {
if n.node != nil {
_ = n.node.Close()
}
_ = n.st.Close()
}
}
// --- building nodes ------------------------------------------------------------
func (s *sim) makeIdentity(n *simNode) error {
root, _, err := identity.NewRoot()
if err != nil {
return err
}
dev, err := identity.Enroll(root, time.Now().Add(-time.Hour), 90*24*time.Hour)
if err != nil {
return err
}
st, err := store.Open(":memory:", store.Options{Difficulty: s.difficulty, MessageDifficulty: s.msgDiff})
if err != nil {
return err
}
n.root, n.dev, n.st, n.bw = root, dev, st, metrics.NewBandwidthCounter()
return nil
}
// 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
}
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,
MaxConns: maxConns,
ExtraOptions: s.extra,
Regions: n.regions,
DHT: true,
Public: n.seed,
Difficulty: s.difficulty,
MessageDifficulty: s.msgDiff,
RedialInterval: 2 * time.Second,
DiscoverInterval: s.discover,
AntiEntropyInterval: s.antiEnt,
AntiEntropyPeers: s.antiPeers,
RelayBootDelay: 10 * time.Minute,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
Bandwidth: n.bw,
})
if err != nil {
return err
}
n.node = node
return nil
}
func (s *sim) newListing(owner *simNode, region string) *listing.Listing {
id, _ := listing.NewID()
var suffix strings.Builder
for i := 0; i < 3; i++ {
suffix.WriteByte(geohashChars[s.rng.IntN(len(geohashChars))])
}
now := time.Now()
l := &listing.Listing{
Version: listing.Version, ID: id, Seq: 1,
CreatedAt: now.Unix(), ExpiresAt: now.Add(7 * 24 * time.Hour).Unix(),
Kind: "rent", Category: "apartment", Geohash: region + suffix.String(),
Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"},
Title: "Wohnung",
}
must(l.Seal(owner.dev, s.difficulty))
return l
}
// --- who is where ----------------------------------------------------------------
func (s *sim) followers(region string) []*simNode {
var out []*simNode
for _, n := range s.nodes {
if n.node != nil && n.follows(region) {
out = append(out, n)
}
}
return out
}
// randomFollower picks a running node that follows region ("" = any region).
func (s *sim) randomFollower(region string) *simNode {
var pool []*simNode
for _, n := range s.nodes {
if n.node != nil && !n.seed && (region == "" || n.follows(region)) {
pool = append(pool, n)
}
}
return pool[s.rng.IntN(len(pool))]
}
func (s *sim) randomAlive() *simNode { return s.randomFollower("") }
func (s *sim) byAuthor(author string) *simNode {
for _, n := range s.nodes {
if n.dev.Cert.Author == author {
return n
}
}
return nil
}
func (s *sim) pickDown(k int) []*simNode {
var pool []*simNode
for _, n := range s.nodes {
if !n.seed {
pool = append(pool, n)
}
}
s.rng.Shuffle(len(pool), func(i, j int) { pool[i], pool[j] = pool[j], pool[i] })
if k > len(pool) {
k = len(pool)
}
return pool[:k]
}
// waitFormed waits until every node sees a few peers of each region it follows.
func (s *sim) waitFormed(regions []string, timeout time.Duration) string {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
short := 0
for _, n := range s.nodes {
for _, r := range n.regions {
want := min(2, len(s.followers(r))-1)
if len(n.node.RegionPeers(r)) < want {
short++
}
}
}
if short == 0 {
return "complete"
}
time.Sleep(200 * time.Millisecond)
}
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 ---------------------------------------------------------------
func (s *sim) hasListing(n *simNode, l *listing.Listing) func() bool {
return func() bool {
_, err := n.st.Get(s.ctx, l.Author, l.ID)
return err == nil
}
}
func (s *sim) ownerHas(n *simNode, e *message.Envelope) func() bool {
h, _ := e.Hash()
return func() bool {
envs, err := n.st.OwnerMessages(s.ctx, n.dev.Cert.Author)
if err != nil {
return false
}
for _, x := range envs {
if xh, _ := x.Hash(); xh == h {
return true
}
}
return false
}
}
func (s *sim) hasReport(n *simNode, r *report.Report) func() bool {
h, _ := r.Hash()
return func() bool {
rs, err := n.st.Reports(s.ctx, 10000)
if err != nil {
return false
}
for _, x := range rs {
if xh, _ := x.Hash(); xh == h {
return true
}
}
return false
}
}
// agreement says whether the nodes of each region ended up with the same listings,
// and all nodes with the same reports.
func (s *sim) agreement(regions []string) string {
var out []string
for _, r := range regions {
seen := map[string]int{}
for _, n := range s.followers(r) {
d, err := n.st.ListingDigest(s.ctx, r)
must(err)
seen[fmt.Sprintf("%d/%s", d.Count, d.Root[:8])]++
}
if len(seen) == 1 {
continue
}
out = append(out, fmt.Sprintf("region %s: %d different sets of listings among its nodes (%v)", r, len(seen), seen))
}
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])]++
}
if len(reps) > 1 {
out = append(out, fmt.Sprintf("reports: %d different sets among all nodes (%v)", len(reps), reps))
}
if len(out) == 0 {
return "every region's nodes hold identical listings, and all nodes identical reports"
}
return strings.Join(out, "; ")
}
// --- measuring ------------------------------------------------------------------------
// pair is one thing to wait for: check turns true when it has arrived.
type pair struct {
start time.Time
check func() bool
took time.Duration
done bool
}
// poll checks the pairs repeatedly for d, stamping each one when it arrives.
func poll(pairs []*pair, d time.Duration) {
end := time.Now().Add(d)
for time.Now().Before(end) {
for _, p := range pairs {
if !p.done && p.check() {
p.done, p.took = true, time.Since(p.start)
}
}
time.Sleep(10 * time.Millisecond)
}
}
// await polls until every pair has arrived or the timeout passes.
func await(pairs []*pair, timeout time.Duration) []*pair {
deadline := time.Now().Add(timeout)
for {
open := 0
for _, p := range pairs {
if p.done {
continue
}
if p.check() {
p.done, p.took = true, time.Since(p.start)
} else {
open++
}
}
if open == 0 || time.Now().After(deadline) {
return pairs
}
time.Sleep(25 * time.Millisecond)
}
}
type reportTable struct {
rec *recorder
rows [][2]string
res []string
}
func newReport(rec *recorder) *reportTable { return &reportTable{rec: rec} }
// phase marks where a part of the run begins, for the graphs.
func (r *reportTable) phase(name string) { r.rec.phase(name) }
func (r *reportTable) row(k, v string) {
r.rows = append(r.rows, [2]string{k, v})
r.rec.mu.Lock()
r.rec.rows[k] = v
r.rec.mu.Unlock()
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) {
r.rec.addSeries(k, what, ps)
var d []time.Duration
for _, p := range ps {
if p.done {
d = append(d, p.took)
}
}
if len(ps) == 0 {
r.row(k, "nothing to measure")
return
}
sort.Slice(d, func(i, j int) bool { return d[i] < d[j] })
pct := func(q float64) time.Duration {
if len(d) == 0 {
return 0
}
return d[min(len(d)-1, int(q*float64(len(d))))]
}
r.row(k, fmt.Sprintf("%s: %d of %d arrived (%.1f%%); p50 %s, p95 %s, p99 %s, max %s",
what, len(d), len(ps), 100*float64(len(d))/float64(len(ps)), round(pct(0.5)), round(pct(0.95)), round(pct(0.99)), round(pct(1))))
}
var lastIn, lastOut int64
func (r *reportTable) resources(when string, s *sim) {
var in, out int64
for _, n := range s.nodes {
t := n.bw.GetBandwidthTotals()
in += t.TotalIn
out += t.TotalOut
}
var m runtime.MemStats
runtime.ReadMemStats(&m)
var ru syscall.Rusage
_ = syscall.Getrusage(syscall.RUSAGE_SELF, &ru)
cpu := time.Duration(ru.Utime.Nano() + ru.Stime.Nano())
r.res = append(r.res, fmt.Sprintf("%-15s heap %4d MB (sys %4d MB), %5d goroutines, CPU %s, traffic +%s (%s per node), all time %s",
when, m.HeapAlloc>>20, m.Sys>>20, runtime.NumGoroutine(), round(cpu),
bytesText(out-lastOut), bytesText((out-lastOut)/int64(len(s.nodes))), bytesText(out)))
lastIn, lastOut = in, out
}
func (r *reportTable) print(w io.Writer) {
fmt.Fprintln(w, "\n== results ==")
for _, row := range r.rows {
fmt.Fprintf(w, "%-10s %s\n", row[0], row[1])
}
fmt.Fprintln(w, "\n== resources (all nodes together, one process) ==")
for _, l := range r.res {
fmt.Fprintln(w, l)
}
}
func round(d time.Duration) time.Duration {
switch {
case d >= 10*time.Second:
return d.Round(100 * time.Millisecond)
case d >= time.Second:
return d.Round(10 * time.Millisecond)
default:
return d.Round(time.Millisecond)
}
}
func bytesText(n int64) string {
switch {
case n >= 1<<30:
return fmt.Sprintf("%.1f GB", float64(n)/(1<<30))
case n >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
case n >= 1<<10:
return fmt.Sprintf("%.1f KB", float64(n)/(1<<10))
}
return fmt.Sprintf("%d B", n)
}
func (s *sim) must(err error) { must(err) }
func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "allmende-sim:", err)
os.Exit(1)
}
}