diff --git a/SPECS.md b/SPECS.md index 5b62716..f0da94c 100644 --- a/SPECS.md +++ b/SPECS.md @@ -148,8 +148,12 @@ starting a design-heavy item; see "Working with the owner". - **Image storage.** Upload, re-encode, strip metadata, size caps, origin hosting, gateways that stream without storing, hash-list matching where access exists. Listings already have an `images` field of hashes. -- **Recovering listings onto an empty database** (after losing the data - directory but not the phrase). +- **Recovering listings onto an empty database** is built + (`internal/p2p/recover.go`, sync kind `author`): the node asks its first 3 + peers per run for everything signed by its own key. It finds only what + connected peers hold, so listings in a region nobody connected follows stay + lost. Messages are not recovered (a recovered device cannot read old ones + anyway). - **Public node memory** was measured (`cmd/allmende-conns`): 1000 inbound connections cost about 130 MB, 156 MB at the peak with 100 listings flooded to all of them, against the 512 MiB pod limit; the manifest sets diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 056cb28..5082e40 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -169,6 +169,17 @@ within 30 days. 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. +- **Getting your own listings back** (`internal/p2p/recover.go`): a node that + starts on an empty or old database (lost disk, restore from the phrase) asks + the first 3 peers it syncs with for everything signed by its own author key + (sync request `{"kind":"author","author":<64 hex>}`, paged by id; deletions + included, expired records not). Region sync only brings back the regions the + node follows; this also finds the rest, and it restores the newest `seq` of + each listing, without which an edit after the restore would lose against the + copy the network holds. Only peers that hold the listings can answer, which + means peers that follow the listing's region; a listing that no connected + peer holds cannot be found this way. Listings are public, so any peer may + ask for any author's. Old nodes do not know the kind and ignore it. - **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 diff --git a/internal/p2p/node.go b/internal/p2p/node.go index 69bddbb..e79c16a 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -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 diff --git a/internal/p2p/recover.go b/internal/p2p/recover.go new file mode 100644 index 0000000..b93501e --- /dev/null +++ b/internal/p2p/recover.go @@ -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 +} diff --git a/internal/p2p/recover_test.go b/internal/p2p/recover_test.go new file mode 100644 index 0000000..c8c5447 --- /dev/null +++ b/internal/p2p/recover_test.go @@ -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") + } +} diff --git a/internal/p2p/sync.go b/internal/p2p/sync.go index 23e0ff8..5259caa 100644 --- a/internal/p2p/sync.go +++ b/internal/p2p/sync.go @@ -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 { diff --git a/internal/store/inventory.go b/internal/store/inventory.go index 2130530..066eca1 100644 --- a/internal/store/inventory.go +++ b/internal/store/inventory.go @@ -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, `