Files
allmende/internal/p2p/peerexchange.go
T
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

185 lines
5.4 KiB
Go

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
}