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:
@@ -162,12 +162,13 @@ starting a design-heavy item; see "Working with the owner".
|
||||
real source addresses (`externalTrafficPolicy: Local`; the nodeport overlay
|
||||
uses `Cluster` and hides them), and the API limit needs `TRUSTED_PROXY` to
|
||||
cover the ingress or the whole site shares one allowance.
|
||||
- **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.
|
||||
- **Joining without the seeds**: peer exchange and region-tagged peer cache are
|
||||
built (`internal/p2p/peerexchange.go`), tested with real nodes, and in the
|
||||
sim's "all seeds shut down" scenario a newcomer whose remembered peers are
|
||||
all in another region now gets everything (56 of 56; it was 0 of 114). Still
|
||||
open: a node that remembers no live peer at all needs a seed or the DNS name.
|
||||
- **Repair** is now every 10 min with 3 peers per round (median ~11 min by the
|
||||
sim; was ~2 h). Not measured on a real network.
|
||||
- **Message-sender abuse** (reports cover listings only).
|
||||
|
||||
**Decisions and non-code work (the owner's)**
|
||||
|
||||
@@ -73,6 +73,7 @@ type sim struct {
|
||||
msgDiff int
|
||||
discover time.Duration
|
||||
antiEnt time.Duration
|
||||
antiPeers int
|
||||
rng *rand.Rand
|
||||
extra []libp2p.Option // transport conditions (latency, connection loss)
|
||||
timeout time.Duration
|
||||
@@ -91,7 +92,8 @@ func main() {
|
||||
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", 30*time.Minute, "anti-entropy interval (a real node: 30m)")
|
||||
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")
|
||||
@@ -109,7 +111,7 @@ func main() {
|
||||
|
||||
s := &sim{
|
||||
ctx: context.Background(), difficulty: 8, msgDiff: 6,
|
||||
discover: *discover, antiEnt: *antiEntropy,
|
||||
discover: *discover, antiEnt: *antiEntropy, antiPeers: *antiPeers,
|
||||
rng: rand.New(rand.NewPCG(*seed, 7)), timeout: *timeout, seedConns: *seedConns,
|
||||
}
|
||||
var conditions *netConditions
|
||||
@@ -355,6 +357,7 @@ func (s *sim) start(n *simNode) error {
|
||||
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,
|
||||
|
||||
+25
-6
@@ -154,9 +154,21 @@ within 30 days.
|
||||
existed) is caught up the original way: kinds `revocations`, `listings` and
|
||||
`messages`, paged by `(created_at, author, id)` and `(created_at, hash)`
|
||||
cursors, which servers still answer. Gossip lost *while connected* is only
|
||||
repaired by the next reconnect, and by anti-entropy: every 30 minutes a node
|
||||
runs this sync again with one random connected peer that shares a region (a
|
||||
matching digest makes a round nearly free).
|
||||
repaired by the next reconnect, and by anti-entropy: every 10 minutes (a
|
||||
fifth more or less, so nodes do not ask together) a node runs this sync again
|
||||
with up to 3 random connected peers that share a region (a matching digest
|
||||
makes a round nearly free).
|
||||
- **Peer exchange** (`internal/p2p/peerexchange.go`): while a followed region
|
||||
has fewer than 8 peers, a node asks its connected peers every 20 s who they
|
||||
know there (sync request `{"kind":"peers","region":...}`, answered with up to
|
||||
20 `{"id","addrs"}` lines). A peer answers even if it follows another region:
|
||||
gossip tells it which topics its own connections subscribe to, so it names
|
||||
those first (marked `near`) and then other connected peers. The asker dials
|
||||
the `near` ones, and the others only while it knows nobody in the region, as a
|
||||
way on (so discovery stays per region); then it asks the new connections, for
|
||||
up to 3 rounds and 24 dials. Old nodes
|
||||
do not know the kind and ignore it. The peer cache records which of the
|
||||
node's regions a peer was seen in, and a restart redials those first.
|
||||
- **Reconnection**: bootstrap peers are redialed every 20 s when disconnected.
|
||||
- **Re-announce**: a running node re-gossips its own live listings and
|
||||
revocations every 30 minutes, so newcomers hear about them without waiting
|
||||
@@ -657,7 +669,7 @@ packet loss looks like above TCP), `-hostile` (an attacker with no validators),
|
||||
| 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 |
|
||||
| listing only one node's store has (no gossip) | anti-entropy every 5 s, one peer per round (the old way): 108 of 109, p50 25.9 s, p95 44 s, max 49.9 s. With 3 peers per round: 109 of 109, p50 5.7 s, p95 10.6 s, max 13.7 s. Scaled to the new default of 10 min that is a median of about 11 minutes (it was about 2 hours at 30 min and one peer) |
|
||||
| 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 |
|
||||
|
||||
@@ -738,8 +750,15 @@ Findings (see "What is left" in SPECS.md for the open ones):
|
||||
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).
|
||||
region (the usual case) is fine. Peer exchange (see "Reconnection") now
|
||||
covers the first case: a newcomer connected to any peer that is connected to
|
||||
the region finds it through that peer. Re-run with `-kill-seeds` (100 nodes,
|
||||
seeds down): 6 newcomers whose two remembered peers were all in another
|
||||
region got 56 of 56 listings, after about 5 s (the first exchange round),
|
||||
where before they got none. One that remembers no live peer at all still
|
||||
needs a seed or the DNS name.
|
||||
4. **Repair at the default interval** takes about 11 minutes to the median
|
||||
node (see the table); it was about 2 hours.
|
||||
|
||||
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
|
||||
|
||||
+22
-14
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user