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
This commit is contained in:
2026-11-19 00:54:48 +01:00
co-authored by Claude Sonnet 5.5
parent 2e105ef353
commit 59973cbf43
8 changed files with 452 additions and 31 deletions
+22 -14
View File
@@ -98,10 +98,13 @@ type Config struct {
MessageDifficulty int
SyncPageSize int // records per sync page (default 500)
RedialInterval time.Duration // how often lost bootstrap peers are redialed (default 20s)
// AntiEntropyInterval is how often the node syncs with one random peer
// it shares a region with, to repair what gossip lost while connected
// (default 30 min).
// AntiEntropyInterval is how often the node syncs with random peers it
// shares a region with, to repair what gossip lost while connected
// (default 10 min, each round a fifth sooner or later so nodes do not
// all ask at once). AntiEntropyPeers is how many peers a round asks
// (default 3). A round with matching digests costs almost nothing.
AntiEntropyInterval time.Duration
AntiEntropyPeers int
// IntakeSummaryEvery is how often the node logs how many listings reached
// it by gossip since the last time (default 1 min; nothing is logged when
// none did).
@@ -176,7 +179,10 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
cfg.RedialInterval = 20 * time.Second
}
if cfg.AntiEntropyInterval <= 0 {
cfg.AntiEntropyInterval = 30 * time.Minute
cfg.AntiEntropyInterval = 10 * time.Minute
}
if cfg.AntiEntropyPeers <= 0 {
cfg.AntiEntropyPeers = 3
}
if cfg.IntakeSummaryEvery <= 0 {
cfg.IntakeSummaryEvery = defaultIntakeSummary
@@ -615,6 +621,8 @@ func (n *Node) subscribeRegion(region string) error {
n.discoverRegion(rctx, rd, region)
}
n.wg.Add(1)
go n.exchangePeers(rctx, region)
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(rctx, sub, func(msg *pubsub.Message) {
@@ -907,19 +915,18 @@ func (n *Node) redial() {
}
// antiEntropy repairs what gossip lost while the node stayed connected, which
// the sync on a new connection cannot: every interval it syncs with one
// random peer that shares a region. Matching digests make a round nearly free.
// the sync on a new connection cannot: every interval (give or take a fifth)
// it syncs with a few random peers that share a region. Matching digests make
// a round nearly free.
func (n *Node) antiEntropy() {
defer n.wg.Done()
t := time.NewTicker(n.cfg.AntiEntropyInterval)
defer t.Stop()
for {
select {
case <-n.ctx.Done():
d := n.cfg.AntiEntropyInterval
d = d - d/5 + time.Duration(rand.Int64N(int64(d)*2/5+1))
if !sleepCtx(n.ctx, d) {
return
case <-t.C:
n.antiEntropyOnce()
}
n.antiEntropyOnce()
}
}
@@ -937,8 +944,9 @@ func (n *Node) antiEntropyOnce() {
}
}
}
if len(peers) > 0 {
n.syncSoon(peers[rand.IntN(len(peers))])
rand.Shuffle(len(peers), func(i, j int) { peers[i], peers[j] = peers[j], peers[i] })
for _, p := range peers[:min(len(peers), n.cfg.AntiEntropyPeers)] {
n.syncSoon(p)
}
}
+53 -2
View File
@@ -6,6 +6,7 @@ import (
"errors"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
@@ -29,8 +30,15 @@ type cachedPeer struct {
ID string `json:"id"`
Addrs []string `json:"addrs"`
Seen int64 `json:"seen"` // unix seconds
// Regions are the regions this node followed when it saw that the peer
// subscribed to them, so a restart can redial the peers of its own regions
// first instead of only the most recent ones.
Regions []string `json:"regions,omitempty"`
}
// maxCachedRegions bounds the regions remembered per peer.
const maxCachedRegions = 8
type peerFile struct {
Peers []cachedPeer `json:"peers"`
}
@@ -84,6 +92,30 @@ func writePeerCache(path string, peers []cachedPeer) error {
return os.Rename(tmp.Name(), path)
}
// orderForRedial puts the peers seen in one of regions first, keeping the
// order (newest first) within each group.
func orderForRedial(peers []cachedPeer, regions []string) {
slices.SortStableFunc(peers, func(a, b cachedPeer) int {
return boolInt(sharesRegion(b, regions)) - boolInt(sharesRegion(a, regions))
})
}
func sharesRegion(p cachedPeer, regions []string) bool {
for _, r := range p.Regions {
if slices.Contains(regions, r) {
return true
}
}
return false
}
func boolInt(b bool) int {
if b {
return 1
}
return 0
}
// directAddrs keeps the addresses worth remembering: not relayed, which only
// work while that relay does, and not unspecified.
func directAddrs(addrs []ma.Multiaddr) []string {
@@ -107,12 +139,27 @@ func (n *Node) rememberPeers() {
for _, p := range readPeerCache(n.cfg.PeerCache, now) {
byID[p.ID] = p
}
inRegion := map[peer.ID][]string{}
for _, r := range n.Regions() {
for _, p := range n.RegionPeers(r) {
inRegion[p] = append(inRegion[p], r)
}
}
for _, id := range n.host.Network().Peers() {
addrs := directAddrs(n.host.Peerstore().Addrs(id))
if len(addrs) == 0 {
continue
}
byID[id.String()] = cachedPeer{ID: id.String(), Addrs: addrs, Seen: now.Unix()}
regions := byID[id.String()].Regions
for _, r := range inRegion[id] {
if !slices.Contains(regions, r) {
regions = append(regions, r)
}
}
if len(regions) > maxCachedRegions {
regions = regions[len(regions)-maxCachedRegions:]
}
byID[id.String()] = cachedPeer{ID: id.String(), Addrs: addrs, Seen: now.Unix(), Regions: regions}
}
list := make([]cachedPeer, 0, len(byID))
for _, p := range byID {
@@ -149,7 +196,11 @@ func (n *Node) dialCached() {
}
var wg sync.WaitGroup
dialed := 0
for _, p := range readPeerCache(n.cfg.PeerCache, n.clock()) {
cached := readPeerCache(n.cfg.PeerCache, n.clock())
// Peers seen in a region we follow come first (the newest of each group first,
// as the file is sorted), then the rest.
orderForRedial(cached, n.Regions())
for _, p := range cached {
if dialed == dialCachedMax {
break
}
+184
View File
@@ -0,0 +1,184 @@
package p2p
import (
"context"
"encoding/json"
"math/rand/v2"
"slices"
"sync"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
"git.stinnesbeck.com/nils/allmende/internal/listing"
)
// Peer exchange: a node that cannot find its region through the DHT (no DHT
// server is up, or every remembered peer lives in another region) asks the
// peers it is connected to who they know there. A peer can answer even if it
// does not follow the region itself: gossip tells it which topics its own
// connections subscribe to.
const (
maxPeersReply = 20 // peers in one answer
askPeersMax = 6 // connected peers asked per round
exchangeRounds = 3 // how far the search follows new connections
exchangeDials = 24 // dials one search may make
exchangeTimeout = 10 * time.Second
// exchangeEvery is how often a region with too few peers is searched again.
exchangeEvery = 20 * time.Second
)
// peerLine is one peer in a "peers" answer.
type peerLine struct {
ID string `json:"id"`
Addrs []string `json:"addrs"`
// Near is set for a peer the answerer knows to subscribe to the region.
Near bool `json:"near,omitempty"`
}
// offered is a peer named in an answer.
type offered struct {
peer.AddrInfo
near bool
}
// peersFor lists up to maxPeersReply peers that asker could dial: first those
// connected to us that subscribe to the region's listing topic, then other
// connected peers, because a peer in another region may know the way on.
func (n *Node) peersFor(asker peer.ID, region string) []peerLine {
inRegion := map[peer.ID]bool{}
for _, p := range n.RegionPeers(region) {
inRegion[p] = true
}
var near, far []peerLine
for _, id := range n.host.Network().Peers() {
if id == asker || id == n.host.ID() || n.guard.banned(id) {
continue
}
addrs := directAddrs(n.host.Peerstore().Addrs(id))
if len(addrs) == 0 {
continue
}
line := peerLine{ID: id.String(), Addrs: addrs, Near: inRegion[id]}
if inRegion[id] {
near = append(near, line)
} else {
far = append(far, line)
}
}
rand.Shuffle(len(far), func(i, j int) { far[i], far[j] = far[j], far[i] })
out := append(near, far...)
if len(out) > maxPeersReply {
out = out[:maxPeersReply]
}
return out
}
// askForPeers asks p who it knows for region.
func (n *Node) askForPeers(ctx context.Context, p peer.ID, region string) []offered {
ctx, cancel := context.WithTimeout(ctx, exchangeTimeout)
defer cancel()
var out []offered
err := n.request(ctx, p, syncRequest{Kind: "peers", Region: region}, func(line []byte) {
if len(out) >= maxPeersReply {
return
}
var pl peerLine
if json.Unmarshal(line, &pl) != nil {
return
}
id, err := peer.Decode(pl.ID)
if err != nil {
return
}
ai := peer.AddrInfo{ID: id}
for _, a := range pl.Addrs {
if m, err := ma.NewMultiaddr(a); err == nil {
ai.Addrs = append(ai.Addrs, m)
}
}
if len(ai.Addrs) > 0 {
out = append(out, offered{AddrInfo: ai, near: pl.Near})
}
})
if err != nil {
n.log.Debug("ask for peers", "peer", p, "err", err)
}
return out
}
// findRegionPeers asks connected peers for region peers and dials what they
// name, then asks the new connections in turn, for a few rounds. It returns
// when the region has enough peers, the rounds or the dial budget are used up.
func (n *Node) findRegionPeers(ctx context.Context, region string) {
asked := map[peer.ID]bool{}
budget := exchangeDials
frontier := n.host.Network().Peers()
for round := 0; round < exchangeRounds && budget > 0; round++ {
rand.Shuffle(len(frontier), func(i, j int) { frontier[i], frontier[j] = frontier[j], frontier[i] })
var next []peer.ID
var mu sync.Mutex
asks := 0
for _, p := range frontier {
if asked[p] || asks >= askPeersMax || ctx.Err() != nil {
continue
}
asked[p] = true
asks++
for _, o := range n.askForPeers(ctx, p, region) {
ai := o.AddrInfo
if ai.ID == n.host.ID() || n.host.Network().Connectedness(ai.ID) == network.Connected || budget <= 0 {
continue
}
// A peer that is not in the region is only worth a dial as a way
// on, while we know nobody there; otherwise discovery stays
// per region.
if !o.near && len(n.RegionPeers(region)) > 0 {
continue
}
budget--
cctx, cancel := context.WithTimeout(ctx, exchangeTimeout)
err := n.host.Connect(cctx, ai)
cancel()
if err == nil {
mu.Lock()
next = append(next, ai.ID)
mu.Unlock()
n.log.Debug("found a peer through a peer", "peer", ai.ID, "via", p, "region", region)
}
}
if len(n.RegionPeers(region)) >= enoughRegionPeers {
return
}
}
// The next round asks the peers just connected, then the rest again.
frontier = append(next, slices.DeleteFunc(n.host.Network().Peers(), func(p peer.ID) bool { return asked[p] })...)
}
}
// exchangePeers looks for peers of region through the peers we have, as long as
// the region has too few, until ctx ends.
func (n *Node) exchangePeers(ctx context.Context, region string) {
defer n.wg.Done()
if !listing.ValidRegion(region) {
return
}
for {
if !sleepCtx(ctx, n.exchangeInterval()) {
return
}
if len(n.RegionPeers(region)) >= enoughRegionPeers || len(n.host.Network().Peers()) == 0 {
continue
}
n.findRegionPeers(ctx, region)
}
}
func (n *Node) exchangeInterval() time.Duration {
if n.cfg.DiscoverInterval > 0 {
return n.cfg.DiscoverInterval
}
return exchangeEvery
}
+144
View File
@@ -0,0 +1,144 @@
package p2p
import (
"slices"
"testing"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
)
func quickExchange(c *Config) {
c.DiscoverInterval = 200 * time.Millisecond // the exchange runs on the same pace
}
// A newcomer that only knows a peer of another region finds its own region
// through it: that peer is connected to a node of the region and says so.
func TestARegionIsFoundThroughAPeerOfAnotherRegion(t *testing.T) {
a := startNode(t, nil, "u1x") // the region the newcomer wants
b := startNode(t, nil, "u0u") // another region, but connected to a
connect(t, b, a)
eventually(t, "b sees a subscribed to u1x", func() bool {
return slices.Contains(b.RegionPeers("u1x"), a.host.ID())
})
c := startNodeWith(t, nil, quickExchange, "u1x")
connect(t, c, b) // the only peer c knows
eventually(t, "c finds a, the region's node, through b", func() bool {
return slices.Contains(c.RegionPeers("u1x"), a.host.ID()) &&
c.host.Network().Connectedness(a.host.ID()) == network.Connected
})
}
// Listings then flow: the point of finding the region's peers.
func TestAListingReachesANewcomerThatFoundItsRegionThroughAnotherOne(t *testing.T) {
a := startNode(t, nil, "u1x")
l := a.listing(t, "u1xjhx")
a.store(t, l)
b := startNode(t, nil, "u0u")
connect(t, b, a)
eventually(t, "b sees a subscribed to u1x", func() bool {
return slices.Contains(b.RegionPeers("u1x"), a.host.ID())
})
c := startNodeWith(t, nil, quickExchange, "u1x")
connect(t, c, b)
eventually(t, "the listing arrives at c", func() bool { return count(c) == 1 })
}
func TestPeerExchangeNamesRegionPeersFirstAndNeverTheAskerOrABannedPeer(t *testing.T) {
a := startNode(t, nil, "u1x")
b := startNode(t, nil, "u0u")
d := startNode(t, nil, "u0u")
x := startNode(t, nil, "u1x") // asks
connect(t, a, b)
connect(t, a, d)
connect(t, a, x)
eventually(t, "a has three peers", func() bool { return len(a.host.Network().Peers()) == 3 })
eventually(t, "a sees x subscribed", func() bool { return slices.Contains(a.RegionPeers("u1x"), x.host.ID()) })
got := a.peersFor(x.host.ID(), "u1x")
ids := map[string]bool{}
for _, p := range got {
ids[p.ID] = true
}
if ids[x.host.ID().String()] || ids[a.host.ID().String()] {
t.Fatalf("the answer names the asker or the answerer: %v", got)
}
if !ids[b.host.ID().String()] || !ids[d.host.ID().String()] {
t.Fatalf("the answer must offer the other connected peers too: %v", got)
}
// Region peers come first.
y := startNode(t, nil, "u1x")
connect(t, a, y)
eventually(t, "a sees y subscribed", func() bool { return slices.Contains(a.RegionPeers("u1x"), y.host.ID()) })
got = a.peersFor(x.host.ID(), "u1x")
if got[0].ID != y.host.ID().String() {
t.Fatalf("a peer of the region must come first, got %v", got)
}
for i := 0; i < maxBadPerWindow; i++ {
a.guard.bad(b.host.ID())
}
for _, p := range a.peersFor(x.host.ID(), "u1x") {
if p.ID == b.host.ID().String() {
t.Fatal("a banned peer was passed on")
}
}
}
func TestAnOldNodeSimplyDoesNotAnswerAndNothingBreaks(t *testing.T) {
old := startNodeWith(t, nil, func(c *Config) {}, "u0u")
old.oldSync = true
c := startNodeWith(t, nil, quickExchange, "u1x")
connect(t, c, old)
if got := c.askForPeers(c.ctx, old.host.ID(), "u1x"); len(got) != 0 {
t.Fatalf("an old node answered: %v", got)
}
}
func TestRememberedPeersOfMyRegionsAreRedialedFirst(t *testing.T) {
mk := func(id string, seen int64, regions ...string) cachedPeer {
return cachedPeer{ID: id, Seen: seen, Regions: regions}
}
list := []cachedPeer{ // newest first, as the file is read
mk("newest-other", 50, "u0u"),
mk("newer-untagged", 40),
mk("older-mine", 30, "u0u", "u1x"),
mk("oldest-mine", 20, "u1x"),
}
orderForRedial(list, []string{"u1x"})
var got []string
for _, p := range list {
got = append(got, p.ID)
}
want := []string{"older-mine", "oldest-mine", "newest-other", "newer-untagged"}
if !slices.Equal(got, want) {
t.Fatalf("order %v, want %v", got, want)
}
}
func TestPeersAreRememberedWithTheRegionsTheySubscribeTo(t *testing.T) {
dir := t.TempDir()
file := dir + "/peers.json"
a := startNodeWith(t, nil, func(c *Config) { c.PeerCache = file }, "u1x")
same := startNode(t, nil, "u1x")
other := startNode(t, nil, "u0u")
connect(t, a, same)
connect(t, a, other)
eventually(t, "a sees both subscriptions", func() bool {
return slices.Contains(a.RegionPeers("u1x"), same.host.ID())
})
a.rememberPeers()
tags := map[string][]string{}
for _, p := range readPeerCache(file, time.Now()) {
tags[p.ID] = p.Regions
}
if !slices.Equal(tags[peer.ID(same.host.ID()).String()], []string{"u1x"}) {
t.Fatalf("the peer of my region is tagged %v", tags[same.host.ID().String()])
}
if len(tags[other.host.ID().String()]) != 0 {
t.Fatalf("a peer of another region is tagged %v", tags[other.host.ID().String()])
}
}
+12 -1
View File
@@ -74,7 +74,7 @@ func (n *Node) handleSync(s network.Stream) {
_ = s.Reset()
return
}
if n.oldSync && (req.Kind == "digest" || req.Kind == "inventory" || req.Kind == "fetch" || req.Kind == "reports") {
if n.oldSync && (req.Kind == "digest" || req.Kind == "inventory" || req.Kind == "fetch" || req.Kind == "reports" || req.Kind == "peers") {
_ = s.Reset()
return
}
@@ -187,6 +187,17 @@ func (n *Node) handleSync(s network.Stream) {
_ = s.Reset()
return
}
case "peers":
if !listing.ValidRegion(req.Region) {
_ = s.Reset()
return
}
for _, pl := range n.peersFor(s.Conn().RemotePeer(), req.Region) {
if !write(json.Marshal(pl)) {
_ = s.Reset()
return
}
}
case "inventory":
if !listing.ValidRegion(req.Region) {
_ = s.Reset()