p2p: a node asks its peers for its own listings after losing its database

Sync kind 'author': everything a peer holds from one author key, any region.
A node asks the first 3 peers it syncs with per run.

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 08:03:10 +01:00
co-authored by Claude Sonnet 5.5
parent 2f89a599e3
commit 1f1f649800
7 changed files with 204 additions and 4 deletions
+3
View File
@@ -20,6 +20,7 @@ import (
"math/rand/v2"
"slices"
"sync"
"sync/atomic"
"time"
"github.com/libp2p/go-libp2p"
@@ -139,6 +140,8 @@ type Node struct {
guard *peerGuard
// gossipIn counts listings that arrived by gossip since the last summary.
gossipIn tally
// recoverAsked counts the peers asked for our own listings (see recoverOwn).
recoverAsked atomic.Int32
ctx context.Context
cancel context.CancelFunc
+76
View File
@@ -0,0 +1,76 @@
package p2p
import (
"context"
"encoding/hex"
"encoding/json"
"github.com/libp2p/go-libp2p/core/peer"
"git.stinnesbeck.com/nils/allmende/internal/listing"
)
// Getting your own listings back: a node that starts on an empty or old
// database (a lost disk, a restore from the recovery phrase) asks a few peers
// for everything signed by its own author key. Region sync brings back what is
// in the regions the node follows; this also finds the rest, and above all it
// gives the node the newest seq of each listing, without which an edit made
// after the restore would lose against the copy the network holds.
//
// It asks the first recoverPeers peers it syncs with in a run, then stops: a
// node with nothing of its own pays one small request per peer.
const recoverPeers = 3
// validAuthor reports whether s looks like an author key (64 hex digits).
func validAuthor(s string) bool {
if len(s) != 64 {
return false
}
_, err := hex.DecodeString(s)
return err == nil
}
// recoverOwn asks p for the listings signed by this node's author, until the
// node has asked recoverPeers peers in this run. It does nothing for a node
// whose author key is unknown.
func (n *Node) recoverOwn(ctx context.Context, p peer.ID) error {
author := n.cfg.Device.Cert.Author
if !validAuthor(author) {
return nil
}
if n.recoverAsked.Add(1) > recoverPeers {
return nil
}
var after string
for page := 0; page < maxSyncPages; page++ {
var count int
var last string
err := n.request(ctx, p, syncRequest{
Kind: "author", Author: author, Limit: n.cfg.SyncPageSize, AfterID: after,
}, func(line []byte) {
var l listing.Listing
if json.Unmarshal(line, &l) != nil {
return
}
count++
last = l.ID
if l.Author != author {
return // peer sent something we did not ask for
}
if out, err := n.cfg.Store.Put(ctx, &l); err != nil {
n.log.Debug("recover: listing rejected", "peer", p, "err", err)
} else {
n.noteListing(ctx, &l, out, "recover", p)
}
})
if err != nil {
n.recoverAsked.Add(-1) // this peer could not answer; another may
return err
}
if count < n.cfg.SyncPageSize || last == "" {
return nil
}
after = last
}
return nil
}
+70
View File
@@ -0,0 +1,70 @@
package p2p
import (
"testing"
"time"
)
// A node that lost its database gets its own listings back from a peer, also
// those in a region it does not follow, and nobody else's.
func TestANodeGetsItsOwnListingsBackFromAPeer(t *testing.T) {
root := mustRoot(t)
a := startNode(t, root, "u1x") // holds the listings (any device of the author may have signed them)
for i := 0; i < 7; i++ { // more than two pages of the test's page size 3
a.store(t, a.listing(t, "u1xjhx"))
}
stranger := startNode(t, nil, "u1x")
a.store(t, stranger.listing(t, "u1xjhx"))
// The restored node follows another region, so region sync brings nothing.
r := startNode(t, root, "u0u")
connect(t, r, a)
eventually(t, "r gets its 7 listings back", func() bool { return count(r) == 7 })
time.Sleep(300 * time.Millisecond)
if got := count(r); got != 7 {
t.Fatalf("r holds %d listings; the stranger's must not come along", got)
}
ls, err := r.s.ByAuthor(r.ctx, stranger.dev.Cert.Author)
if err != nil || len(ls) != 0 {
t.Fatalf("the stranger's listing was recovered: %v %v", ls, err)
}
}
// Only the first few peers of a run are asked.
func TestOnlyTheFirstPeersAreAskedForOwnListings(t *testing.T) {
root := mustRoot(t)
a := startNode(t, root, "u1x")
a.store(t, a.listing(t, "u1xjhx"))
r := startNode(t, root, "u0u")
r.recoverAsked.Store(recoverPeers)
connect(t, r, a)
time.Sleep(time.Second)
if got := count(r); got != 0 {
t.Fatalf("r asked beyond its limit and holds %d", got)
}
}
// An old node does not know the request; the sync with it must still succeed
// as far as it goes, and the node asks another peer instead.
func TestAnOldNodeCannotAnswerAndTheNextPeerIsAsked(t *testing.T) {
root := mustRoot(t)
old := startNode(t, root, "u1x")
old.oldSync = true
good := startNode(t, root, "u1x")
good.store(t, good.listing(t, "u1xjhx"))
r := startNode(t, root, "u0u")
connect(t, r, old)
connect(t, r, good)
eventually(t, "r gets the listing from the peer that can answer", func() bool { return count(r) == 1 })
}
func TestAuthorRequestsNeedAValidKey(t *testing.T) {
for _, s := range []string{"", "abc", "zz" + string(make([]byte, 62))} {
if validAuthor(s) {
t.Errorf("%q accepted", s)
}
}
if !validAuthor("00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff") {
t.Error("a 64-digit key was refused")
}
}
+24 -2
View File
@@ -55,6 +55,7 @@ type syncRequest struct {
AfterID string `json:"after_id,omitempty"` // listings
AfterHash string `json:"after_hash,omitempty"` // messages
Limit int `json:"limit,omitempty"`
Author string `json:"author,omitempty"` // "author": whose listings
}
// --- server ---------------------------------------------------------------
@@ -74,7 +75,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" || req.Kind == "peers") {
if n.oldSync && (req.Kind == "digest" || req.Kind == "inventory" || req.Kind == "fetch" || req.Kind == "reports" || req.Kind == "peers" || req.Kind == "author") {
_ = s.Reset()
return
}
@@ -198,6 +199,27 @@ func (n *Node) handleSync(s network.Stream) {
return
}
}
case "author":
// Everything we hold from one author, whatever the region.
if !validAuthor(req.Author) {
_ = s.Reset()
return
}
limit := req.Limit
if limit <= 0 || limit > n.cfg.SyncPageSize {
limit = n.cfg.SyncPageSize
}
items, err := n.cfg.Store.AuthorListings(n.ctx, req.Author, req.AfterID, limit)
if err != nil {
_ = s.Reset()
return
}
for _, l := range items {
if !write(l.Bytes()) {
_ = s.Reset()
return
}
}
case "inventory":
if !listing.ValidRegion(req.Region) {
_ = s.Reset()
@@ -353,7 +375,7 @@ func (n *Node) SyncFrom(ctx context.Context, p peer.ID) error {
return err
}
}
return nil
return n.recoverOwn(ctx, p)
}
func (n *Node) digest(ctx context.Context, p peer.ID, region string, out *digestReply) error {
+14
View File
@@ -157,6 +157,20 @@ func (s *Store) ListingsByKey(ctx context.Context, keys []string) ([]*listing.Li
return out, nil
}
// AuthorListings returns up to limit unexpired records (deletions included)
// signed by author, in id order, after afterID. A node that lost its database
// asks its peers for these to get its own listings back.
func (s *Store) AuthorListings(ctx context.Context, author, afterID string, limit int) ([]*listing.Listing, error) {
rows, err := s.db.QueryContext(ctx, `
SELECT data FROM listings
WHERE author = ? AND id > ? AND expires_at > ?
ORDER BY id LIMIT ?`, author, afterID, s.clock().Unix(), limit)
if err != nil {
return nil, err
}
return collect(rows)
}
// RevocationDigest digests the relevant revocations (see Revocations).
func (s *Store) RevocationDigest(ctx context.Context) (Digest, error) {
rows, err := s.db.QueryContext(ctx, `