Files
allmende/internal/p2p/recover.go
T

77 lines
2.1 KiB
Go

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
var got []*listing.Listing
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
}
got = append(got, &l)
})
if serr := n.storeSynced(ctx, p, "recover", got); serr != nil {
return serr
}
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
}