Add device keys, revocation and libp2p gossip with sync

- identity: 12-word recovery phrase, device certificates, revocations,
  device key storage; the identity key is never stored on a node
- listing: signed by a device with an embedded certificate, domain-separated
  signatures, ErrTimeWindow for clock-related failures, region helpers
- store: revocations purge a device's listings; keyset-paged Since for sync
- p2p: gossipsub topic per geohash region plus a global revocation topic,
  validators run before relaying, /allmende/1/sync catch-up protocol,
  bootstrap peers and mDNS
- docs: key model, replication and conflict rules

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 17:43:25 +01:00
co-authored by Claude Sonnet 5.5
parent 08f6441f03
commit d3efe5a3a7
16 changed files with 2306 additions and 119 deletions
+109
View File
@@ -0,0 +1,109 @@
package identity
import (
"encoding/hex"
"errors"
"time"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
)
const (
CertVersion = 1
MaxCertLifetime = 366 * 24 * time.Hour
certContext = "allmende-cert-v1\n"
)
// Cert is the identity key's statement "this device may sign on my behalf".
// It is public and travels with every listing.
type Cert struct {
Version int `json:"v"`
Author string `json:"author"` // identity public key, hex
Device string `json:"device"` // device public key, hex
IssuedAt int64 `json:"issued_at"`
ExpiresAt int64 `json:"expires_at"`
Sig string `json:"sig,omitempty"`
}
func (c *Cert) signingBytes() ([]byte, error) {
cp := *c
cp.Sig = ""
b, err := jcs.Marshal(&cp)
if err != nil {
return nil, err
}
return append([]byte(certContext), b...), nil
}
// IssueCert signs a certificate for devicePub with the identity key.
func IssueCert(root *Identity, devicePub string, issuedAt, expiresAt time.Time) (*Cert, error) {
c := &Cert{
Version: CertVersion,
Author: root.PublicKeyHex(),
Device: devicePub,
IssuedAt: issuedAt.Unix(),
ExpiresAt: expiresAt.Unix(),
}
if err := c.checkFields(); err != nil {
return nil, err
}
b, err := c.signingBytes()
if err != nil {
return nil, err
}
c.Sig = hex.EncodeToString(root.Sign(b))
return c, nil
}
func (c *Cert) checkFields() error {
switch {
case c.Version != CertVersion:
return errors.New("identity: unsupported cert version")
case !isHex(c.Author, 64) || !isHex(c.Device, 64):
return errors.New("identity: cert keys must be 64 hex characters")
case c.ExpiresAt <= c.IssuedAt:
return errors.New("identity: cert expires before it is issued")
case time.Duration(c.ExpiresAt-c.IssuedAt)*time.Second > MaxCertLifetime:
return errors.New("identity: cert lifetime too long")
}
return nil
}
// Check verifies structure and signature. It does not look at the clock;
// use Covers for that.
func (c *Cert) Check() error {
if err := c.checkFields(); err != nil {
return err
}
sig, err := hex.DecodeString(c.Sig)
if err != nil || len(sig) != 64 {
return errors.New("identity: malformed cert signature")
}
b, err := c.signingBytes()
if err != nil {
return err
}
if !Verify(c.Author, b, sig) {
return errors.New("identity: bad cert signature")
}
return nil
}
// Covers reports whether unix time t lies within the certificate's validity.
func (c *Cert) Covers(t int64) bool {
return t >= c.IssuedAt && t < c.ExpiresAt
}
func isHex(s string, n int) bool {
if len(s) != n {
return false
}
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
return false
}
}
return true
}
+85
View File
@@ -0,0 +1,85 @@
package identity
import (
"crypto/ed25519"
"encoding/json"
"errors"
"os"
"path/filepath"
"time"
)
// Device is what a running node holds: its own key plus the certificate that
// ties it to an identity. The identity key itself is never stored.
type Device struct {
Key *Identity
Cert *Cert
}
// Enroll creates a new device key and certifies it with the identity key.
func Enroll(root *Identity, now time.Time, validFor time.Duration) (*Device, error) {
key, err := Generate()
if err != nil {
return nil, err
}
cert, err := IssueCert(root, key.PublicKeyHex(), now, now.Add(validFor))
if err != nil {
return nil, err
}
return &Device{Key: key, Cert: cert}, nil
}
const (
deviceKeyFile = "device.key"
deviceCertFile = "device.cert"
)
// Save writes the device key (refusing to overwrite) and certificate into dir.
func (d *Device) Save(dir string) error {
if err := d.Key.Save(filepath.Join(dir, deviceKeyFile)); err != nil {
return err
}
return d.SaveCert(dir)
}
// SaveCert (over)writes only the certificate, e.g. after renewal.
func (d *Device) SaveCert(dir string) error {
data, err := json.Marshal(d.Cert)
if err != nil {
return err
}
path := filepath.Join(dir, deviceCertFile)
tmp := path + ".tmp"
if err := os.WriteFile(tmp, data, 0o644); err != nil {
return err
}
return os.Rename(tmp, path)
}
// LoadDevice reads a device saved by Save and checks that key and
// certificate belong together.
func LoadDevice(dir string) (*Device, error) {
key, err := Load(filepath.Join(dir, deviceKeyFile))
if err != nil {
return nil, err
}
data, err := os.ReadFile(filepath.Join(dir, deviceCertFile))
if err != nil {
return nil, err
}
var cert Cert
if err := json.Unmarshal(data, &cert); err != nil {
return nil, err
}
if err := cert.Check(); err != nil {
return nil, err
}
if cert.Device != key.PublicKeyHex() {
return nil, errors.New("identity: certificate does not match device key")
}
return &Device{Key: key, Cert: &cert}, nil
}
// PrivateKey exposes the raw key so the p2p layer can use it as the node's
// libp2p identity. Handle with care.
func (i *Identity) PrivateKey() ed25519.PrivateKey { return i.priv }
+123
View File
@@ -0,0 +1,123 @@
package identity
import (
"strings"
"testing"
"time"
)
var testNow = time.Unix(1_800_000_000, 0)
func TestPhraseRoundTrip(t *testing.T) {
root, phrase, err := NewRoot()
if err != nil {
t.Fatal(err)
}
if n := len(strings.Fields(phrase)); n != 12 {
t.Fatalf("phrase has %d words, want 12", n)
}
again, err := FromPhrase(" " + strings.ToUpper(phrase) + "\n")
if err != nil {
t.Fatal(err)
}
if again.PublicKeyHex() != root.PublicKeyHex() {
t.Fatal("phrase did not recreate the same identity")
}
}
func TestBadPhraseRejected(t *testing.T) {
_, phrase, _ := NewRoot()
words := strings.Fields(phrase)
// Swapping two different words almost always breaks the checksum;
// changing the last word to another one is deterministic enough to try several.
bad := 0
for _, w := range []string{"abandon", "zoo", "legal", "winner"} {
if w == words[11] {
continue
}
cp := append([]string{}, words...)
cp[11] = w
if _, err := FromPhrase(strings.Join(cp, " ")); err != nil {
bad++
}
}
if bad == 0 {
t.Fatal("checksum never rejected a modified phrase")
}
if _, err := FromPhrase("not a real phrase"); err == nil {
t.Fatal("garbage phrase accepted")
}
}
func TestCert(t *testing.T) {
root, _, _ := NewRoot()
dev, err := Enroll(root, testNow, 30*24*time.Hour)
if err != nil {
t.Fatal(err)
}
if err := dev.Cert.Check(); err != nil {
t.Fatal(err)
}
if !dev.Cert.Covers(testNow.Unix()) || dev.Cert.Covers(testNow.Add(31*24*time.Hour).Unix()) ||
dev.Cert.Covers(testNow.Add(-time.Second).Unix()) {
t.Fatal("Covers returned wrong validity window")
}
forged := *dev.Cert
forged.Device = strings.Repeat("a", 64)
if forged.Check() == nil {
t.Fatal("tampered cert accepted")
}
other, _, _ := NewRoot()
swapped := *dev.Cert
swapped.Author = other.PublicKeyHex()
if swapped.Check() == nil {
t.Fatal("cert with swapped author accepted")
}
if _, err := Enroll(root, testNow, 3*366*24*time.Hour); err == nil {
t.Fatal("over-long cert lifetime accepted")
}
}
func TestRevocation(t *testing.T) {
root, _, _ := NewRoot()
dev, _ := Enroll(root, testNow, 24*time.Hour)
r, err := Revoke(root, dev.Cert, testNow, 10)
if err != nil {
t.Fatal(err)
}
if err := r.Check(10); err != nil {
t.Fatal(err)
}
if r.Check(40) == nil {
t.Fatal("insufficient proof-of-work accepted")
}
t2 := *r
t2.Device = strings.Repeat("b", 64)
if t2.Check(0) == nil {
t.Fatal("tampered revocation accepted")
}
other, _, _ := NewRoot()
if _, err := Revoke(other, dev.Cert, testNow, 0); err == nil {
t.Fatal("foreign identity revoked someone else's device")
}
}
func TestDeviceSaveLoad(t *testing.T) {
root, _, _ := NewRoot()
dev, _ := Enroll(root, testNow, 24*time.Hour)
dir := t.TempDir()
if err := dev.Save(dir); err != nil {
t.Fatal(err)
}
got, err := LoadDevice(dir)
if err != nil {
t.Fatal(err)
}
if got.Key.PublicKeyHex() != dev.Key.PublicKeyHex() || got.Cert.Sig != dev.Cert.Sig {
t.Fatal("device differs after reload")
}
if err := dev.Save(dir); err == nil {
t.Fatal("Save must not overwrite an existing device key")
}
}
+53
View File
@@ -0,0 +1,53 @@
package identity
import (
"crypto/ed25519"
"crypto/hkdf"
"crypto/rand"
"crypto/sha256"
"errors"
"strings"
"github.com/tyler-smith/go-bip39"
)
const entropyBytes = 16 // 128 bits = 12 words
// NewRoot creates a fresh identity key together with its 12-word recovery
// phrase. The caller must show the phrase to the user once and then discard
// the key: the phrase alone is enough to recreate it.
func NewRoot() (*Identity, string, error) {
entropy := make([]byte, entropyBytes)
if _, err := rand.Read(entropy); err != nil {
return nil, "", err
}
phrase, err := bip39.NewMnemonic(entropy)
if err != nil {
return nil, "", err
}
id, err := fromEntropy(entropy)
return id, phrase, err
}
// FromPhrase recreates an identity key from its recovery phrase. Extra
// whitespace and letter case are tolerated; the word checksum is verified so
// typos are caught.
func FromPhrase(phrase string) (*Identity, error) {
phrase = strings.ToLower(strings.Join(strings.Fields(phrase), " "))
entropy, err := bip39.EntropyFromMnemonic(phrase)
if err != nil {
return nil, errors.New("identity: invalid recovery phrase")
}
if len(entropy) != entropyBytes {
return nil, errors.New("identity: recovery phrase must have 12 words")
}
return fromEntropy(entropy)
}
func fromEntropy(entropy []byte) (*Identity, error) {
seed, err := hkdf.Key(sha256.New, entropy, nil, "allmende identity key v1", ed25519.SeedSize)
if err != nil {
return nil, err
}
return &Identity{priv: ed25519.NewKeyFromSeed(seed)}, nil
}
+95
View File
@@ -0,0 +1,95 @@
package identity
import (
"encoding/hex"
"errors"
"time"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/pow"
)
const (
RevocationVersion = 1
revocationContext = "allmende-revocation-v1\n"
)
// Revocation voids a device: every signature made by Device is rejected from
// now on. Nodes keep it until the device's certificate would have expired
// anyway (CertExpiresAt). It carries proof-of-work so nobody can flood the
// network with revocations for throwaway identities.
type Revocation struct {
Version int `json:"v"`
Author string `json:"author"`
Device string `json:"device"`
RevokedAt int64 `json:"revoked_at"`
CertExpiresAt int64 `json:"cert_expires_at"`
PoW uint64 `json:"pow"`
Sig string `json:"sig,omitempty"`
}
func (r *Revocation) signingBytes() ([]byte, error) {
cp := *r
cp.Sig = ""
b, err := jcs.Marshal(&cp)
if err != nil {
return nil, err
}
return append([]byte(revocationContext), b...), nil
}
// Revoke signs a revocation of the device named in cert, mining the
// proof-of-work to the given difficulty.
func Revoke(root *Identity, cert *Cert, at time.Time, difficulty int) (*Revocation, error) {
if root.PublicKeyHex() != cert.Author {
return nil, errors.New("identity: cert does not belong to this identity")
}
r := &Revocation{
Version: RevocationVersion,
Author: cert.Author,
Device: cert.Device,
RevokedAt: at.Unix(),
CertExpiresAt: cert.ExpiresAt,
}
for ; ; r.PoW++ {
b, err := r.signingBytes()
if err != nil {
return nil, err
}
if pow.LeadingZeroBits(b) >= difficulty {
r.Sig = hex.EncodeToString(root.Sign(b))
return r, nil
}
}
}
// Check verifies structure, signature and proof-of-work.
func (r *Revocation) Check(difficulty int) error {
if r.Version != RevocationVersion {
return errors.New("identity: unsupported revocation version")
}
if !isHex(r.Author, 64) || !isHex(r.Device, 64) {
return errors.New("identity: revocation keys must be 64 hex characters")
}
if r.PoW > 1<<53-1 {
return errors.New("identity: number out of range")
}
sig, err := hex.DecodeString(r.Sig)
if err != nil || len(sig) != 64 {
return errors.New("identity: malformed revocation signature")
}
b, err := r.signingBytes()
if err != nil {
return err
}
if !Verify(r.Author, b, sig) {
return errors.New("identity: bad revocation signature")
}
if pow.LeadingZeroBits(b) < difficulty {
return errors.New("identity: insufficient proof-of-work")
}
return nil
}
// Bytes returns the canonical encoding including the signature.
func (r *Revocation) Bytes() ([]byte, error) { return jcs.Marshal(r) }
+61 -32
View File
@@ -9,7 +9,6 @@ import (
"encoding/hex"
"errors"
"fmt"
"math/bits"
"strings"
"time"
"unicode"
@@ -17,6 +16,7 @@ import (
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/pow"
)
const (
@@ -24,12 +24,35 @@ const (
MaxLifetime = 30 * 24 * time.Hour
MaxClockSkew = 10 * time.Minute
GeohashPrecision = 6
MaxSize = 16 << 10
maxSafeInt = 1<<53 - 1
// RegionPrecision is the geohash prefix length that names a gossip
// region (~150 km cells).
RegionPrecision = 3
MaxSize = 16 << 10
maxSafeInt = 1<<53 - 1
geohashAlphabet = "0123456789bcdefghjkmnpqrstuvwxyz"
listingContext = "allmende-listing-v1\n"
)
// ErrTimeWindow marks failures caused by the clock (expired, or created in
// the future). They are not the sender's fault, so the p2p layer ignores such
// messages instead of penalizing the peer that relayed them.
var ErrTimeWindow = errors.New("outside time window")
// Region returns the gossip region of a geohash.
func Region(geohash string) string {
if len(geohash) < RegionPrecision {
return geohash
}
return geohash[:RegionPrecision]
}
// ValidRegion reports whether s is a well-formed region name.
func ValidRegion(s string) bool {
return len(s) == RegionPrecision && ValidGeohashPrefix(s)
}
var (
kinds = map[string]bool{"rent": true, "sale": true}
categories = map[string]bool{"apartment": true, "house": true, "room": true, "commercial": true}
@@ -51,7 +74,8 @@ type Image struct {
type Listing struct {
Version int `json:"v"`
ID string `json:"id"` // stable across versions
Author string `json:"author"` // hex ed25519 public key
Author string `json:"author"` // identity public key (hex)
Device string `json:"device"` // signing device's public key (hex)
Seq uint64 `json:"seq"` // higher replaces lower
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
@@ -66,10 +90,12 @@ type Listing struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Images []Image `json:"images,omitempty"`
Endpoint string `json:"endpoint,omitempty"` // owner's peer ID
Delegate string `json:"delegate,omitempty"` // optional always-on host's peer ID
PoW uint64 `json:"pow"`
Sig string `json:"sig,omitempty"` // hex, over canonical bytes without sig
// Cert proves that Device may sign for Author. The owner's node is the
// peer whose ID derives from Device.
Cert *identity.Cert `json:"cert"`
Sig string `json:"sig,omitempty"` // device signature, hex
}
// NewID returns a fresh random listing ID (32 hex characters).
@@ -104,29 +130,20 @@ func (l *Listing) Hash() (string, error) {
return hex.EncodeToString(sum[:]), nil
}
func leadingZeroBits(sum [32]byte) int {
n := 0
for _, b := range sum {
if b == 0 {
n += 8
continue
}
return n + bits.LeadingZeros8(b)
}
return n
}
func (l *Listing) powOK(difficulty int) (bool, error) {
b, err := l.unsignedBytes()
if err != nil {
return false, err
}
return leadingZeroBits(sha256.Sum256(b)) >= difficulty, nil
return pow.LeadingZeroBits(b) >= difficulty, nil
}
// Seal sets the author, mines the proof-of-work and signs the listing.
func (l *Listing) Seal(id *identity.Identity, difficulty int) error {
l.Author = id.PublicKeyHex()
// Seal fills in author, device and certificate from dev, mines the
// proof-of-work and signs the listing with the device key.
func (l *Listing) Seal(dev *identity.Device, difficulty int) error {
l.Author = dev.Cert.Author
l.Device = dev.Cert.Device
l.Cert = dev.Cert
l.Sig = ""
for l.PoW = 0; ; l.PoW++ {
if l.PoW > maxSafeInt {
@@ -144,7 +161,7 @@ func (l *Listing) Seal(id *identity.Identity, difficulty int) error {
if err != nil {
return err
}
l.Sig = hex.EncodeToString(id.Sign(b))
l.Sig = hex.EncodeToString(dev.Key.Sign(append([]byte(listingContext), b...)))
return nil
}
@@ -169,7 +186,7 @@ func (l *Listing) Check(now time.Time, difficulty int) error {
if err != nil || len(sig) != 64 {
return errors.New("listing: malformed signature")
}
if !identity.Verify(l.Author, unsigned, sig) {
if !identity.Verify(l.Device, append([]byte(listingContext), unsigned...), sig) {
return errors.New("listing: bad signature")
}
ok, err := l.powOK(difficulty)
@@ -194,8 +211,23 @@ func (l *Listing) validate(now time.Time) error {
if !isHex(l.ID, 32) {
return errors.New("listing: id must be 32 hex characters")
}
if !isHex(l.Author, 64) {
return errors.New("listing: author must be 64 hex characters")
if !isHex(l.Author, 64) || !isHex(l.Device, 64) {
return errors.New("listing: author and device must be 64 hex characters")
}
if l.Cert == nil {
return errors.New("listing: certificate required")
}
if err := l.Cert.Check(); err != nil {
return fmt.Errorf("listing: %w", err)
}
if l.Cert.Author != l.Author || l.Cert.Device != l.Device {
return errors.New("listing: certificate does not match author and device")
}
if !l.Cert.Covers(l.CreatedAt) {
return errors.New("listing: created outside the certificate's validity")
}
if now.Unix() >= l.Cert.ExpiresAt {
return fmt.Errorf("listing: certificate expired: %w", ErrTimeWindow)
}
if l.Seq > maxSafeInt || l.PoW > maxSafeInt {
return errors.New("listing: number out of range")
@@ -207,10 +239,10 @@ func (l *Listing) validate(now time.Time) error {
return errors.New("listing: lifetime exceeds 30 days")
}
if time.Unix(l.CreatedAt, 0).After(now.Add(MaxClockSkew)) {
return errors.New("listing: created_at is in the future")
return fmt.Errorf("listing: created_at is in the future: %w", ErrTimeWindow)
}
if !time.Unix(l.ExpiresAt, 0).After(now) {
return errors.New("listing: expired")
return fmt.Errorf("listing: expired: %w", ErrTimeWindow)
}
if err := validGeohash(l.Geohash); err != nil {
return err
@@ -224,7 +256,7 @@ func (l *Listing) validate(now time.Time) error {
func (l *Listing) validateTombstone() error {
if l.Kind != "" || l.Category != "" || l.Price != nil || l.AreaM2 != 0 || l.RoomsX2 != 0 ||
len(l.Features) > 0 || l.Title != "" || l.Description != "" || len(l.Images) > 0 ||
l.Endpoint != "" || l.Delegate != "" {
l.Delegate != "" {
return errors.New("listing: tombstone must not carry content")
}
return nil
@@ -276,9 +308,6 @@ func (l *Listing) validateContent() error {
return errors.New("listing: image hashes must be 64 hex characters")
}
}
if !validPeerID(l.Endpoint) {
return errors.New("listing: invalid endpoint")
}
if l.Delegate != "" && !validPeerID(l.Delegate) {
return errors.New("listing: invalid delegate")
}
+126 -31
View File
@@ -1,6 +1,7 @@
package listing
import (
"errors"
"strings"
"testing"
"time"
@@ -12,6 +13,19 @@ const testDifficulty = 12
var now = time.Unix(1_800_000_000, 0)
func newDevice(t *testing.T) *identity.Device {
t.Helper()
root, _, err := identity.NewRoot()
if err != nil {
t.Fatal(err)
}
dev, err := identity.Enroll(root, now.Add(-time.Hour), 90*24*time.Hour)
if err != nil {
t.Fatal(err)
}
return dev
}
func sample(t *testing.T) *Listing {
t.Helper()
id, err := NewID()
@@ -32,28 +46,27 @@ func sample(t *testing.T) *Listing {
RoomsX2: 5,
Features: []string{"balcony", "elevator"},
Title: "Helle 2,5-Zimmer-Wohnung",
Endpoint: "12D3KooWExamplePeerID",
}
}
func sealed(t *testing.T) (*Listing, *identity.Identity) {
func sealed(t *testing.T) (*Listing, *identity.Device) {
t.Helper()
key, err := identity.Generate()
if err != nil {
t.Fatal(err)
}
dev := newDevice(t)
l := sample(t)
if err := l.Seal(key, testDifficulty); err != nil {
if err := l.Seal(dev, testDifficulty); err != nil {
t.Fatal(err)
}
return l, key
return l, dev
}
func TestSealCheckRoundTrip(t *testing.T) {
l, _ := sealed(t)
l, dev := sealed(t)
if err := l.Check(now, testDifficulty); err != nil {
t.Fatal(err)
}
if l.Author != dev.Cert.Author || l.Device != dev.Key.PublicKeyHex() {
t.Fatal("seal did not fill author/device from the device")
}
}
func TestCanonicalBytesDeterministic(t *testing.T) {
@@ -63,7 +76,6 @@ func TestCanonicalBytesDeterministic(t *testing.T) {
if string(a) != string(b) {
t.Fatal("canonical bytes differ between calls")
}
// keys must be sorted: "author" comes first.
if !strings.HasPrefix(string(a), `{"area_m2":55,"author":`) {
t.Fatalf("unexpected canonical prefix: %s", a[:40])
}
@@ -77,50 +89,112 @@ func TestTamperDetected(t *testing.T) {
}
}
func TestForeignSignatureRejected(t *testing.T) {
func TestAuthorMustMatchCertificate(t *testing.T) {
l, _ := sealed(t)
other, _ := identity.Generate()
other, _, _ := identity.NewRoot()
l.Author = other.PublicKeyHex()
if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("listing with swapped author accepted")
t.Fatal("listing claiming a foreign author accepted")
}
}
func TestDeviceWithoutCertificateForAuthorRejected(t *testing.T) {
// A device certified by identity A cannot sign for identity B, even if
// the attacker attaches B's public key as author.
attacker := newDevice(t)
victim, _, _ := identity.NewRoot()
l := sample(t)
if err := l.Seal(attacker, testDifficulty); err != nil {
t.Fatal(err)
}
l.Author = victim.PublicKeyHex()
l.Cert.Author = victim.PublicKeyHex() // forged field; certificate signature breaks
if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("forged identity accepted")
}
}
func TestSignedByWrongDeviceRejected(t *testing.T) {
l, _ := sealed(t)
other := newDevice(t)
// Re-sign with a different device key while keeping the original cert.
l.Sig = ""
b, _ := l.unsignedBytes()
l.Sig = hexSig(other, b)
if err := l.Check(now, testDifficulty); err == nil {
t.Fatal("signature by a different device accepted")
}
}
func hexSig(dev *identity.Device, unsigned []byte) string {
const hexd = "0123456789abcdef"
sig := dev.Key.Sign(append([]byte(listingContext), unsigned...))
out := make([]byte, 0, len(sig)*2)
for _, b := range sig {
out = append(out, hexd[b>>4], hexd[b&0xf])
}
return string(out)
}
func TestCertificateWindow(t *testing.T) {
root, _, _ := identity.NewRoot()
// Listing created before the certificate was issued.
dev, _ := identity.Enroll(root, now.Add(time.Hour), 24*time.Hour)
l := sample(t)
_ = l.Seal(dev, 0)
if err := l.Check(now.Add(2*time.Hour), 0); err == nil {
t.Fatal("listing older than its certificate accepted")
}
// Certificate expired at verification time.
dev, _ = identity.Enroll(root, now.Add(-48*time.Hour), 24*time.Hour)
l = sample(t)
l.CreatedAt = now.Add(-30 * time.Hour).Unix()
l.ExpiresAt = now.Add(24 * time.Hour).Unix()
_ = l.Seal(dev, 0)
err := l.Check(now, 0)
if err == nil || !errors.Is(err, ErrTimeWindow) {
t.Fatalf("expired certificate: got %v, want ErrTimeWindow", err)
}
}
func TestInsufficientPoW(t *testing.T) {
l, _ := sealed(t)
// Difficulty demanded by the verifier is far above what was mined.
if err := l.Check(now, 40); err == nil {
t.Fatal("expected proof-of-work failure")
}
}
func TestExpiryAndLifetime(t *testing.T) {
key, _ := identity.Generate()
dev := newDevice(t)
l := sample(t)
l.ExpiresAt = l.CreatedAt + int64(31*24*3600)
_ = l.Seal(key, 0)
_ = l.Seal(dev, 0)
if err := l.Check(now, 0); err == nil {
t.Fatal("lifetime over 30 days accepted")
}
l = sample(t)
_ = l.Seal(key, 0)
if err := l.Check(now.Add(8*24*time.Hour), 0); err == nil {
t.Fatal("expired listing accepted")
_ = l.Seal(dev, 0)
err := l.Check(now.Add(8*24*time.Hour), 0)
if err == nil || !errors.Is(err, ErrTimeWindow) {
t.Fatalf("expired listing: got %v, want ErrTimeWindow", err)
}
l = sample(t)
l.CreatedAt = now.Add(time.Hour).Unix()
l.ExpiresAt = l.CreatedAt + 3600
_ = l.Seal(key, 0)
if err := l.Check(now, 0); err == nil {
t.Fatal("future-dated listing accepted")
_ = l.Seal(dev, 0)
err = l.Check(now, 0)
if err == nil || !errors.Is(err, ErrTimeWindow) {
t.Fatalf("future-dated listing: got %v, want ErrTimeWindow", err)
}
}
func TestContentValidation(t *testing.T) {
key, _ := identity.Generate()
dev := newDevice(t)
cases := map[string]func(*Listing){
"bad kind": func(l *Listing) { l.Kind = "swap" },
"bad category": func(l *Listing) { l.Category = "castle" },
@@ -132,14 +206,14 @@ func TestContentValidation(t *testing.T) {
"empty title": func(l *Listing) { l.Title = "" },
"control char": func(l *Listing) { l.Title = "a\x00b" },
"bad image hash": func(l *Listing) { l.Images = []Image{{Hash: "zz", ThumbHash: "zz"}} },
"no endpoint": func(l *Listing) { l.Endpoint = "" },
"bad delegate": func(l *Listing) { l.Delegate = "no" },
"huge description": func(l *Listing) { l.Description = strings.Repeat("x", 4001) },
}
for name, mutate := range cases {
t.Run(name, func(t *testing.T) {
l := sample(t)
mutate(l)
if err := l.Seal(key, 0); err != nil {
if err := l.Seal(dev, 0); err != nil {
t.Fatal(err)
}
if err := l.Check(now, 0); err == nil {
@@ -150,7 +224,7 @@ func TestContentValidation(t *testing.T) {
}
func TestTombstoneAndSupersedes(t *testing.T) {
l, key := sealed(t)
l, dev := sealed(t)
ts := &Listing{
Version: Version,
@@ -161,7 +235,7 @@ func TestTombstoneAndSupersedes(t *testing.T) {
Tombstone: true,
Geohash: l.Geohash,
}
if err := ts.Seal(key, testDifficulty); err != nil {
if err := ts.Seal(dev, testDifficulty); err != nil {
t.Fatal(err)
}
if err := ts.Check(now, testDifficulty); err != nil {
@@ -171,17 +245,29 @@ func TestTombstoneAndSupersedes(t *testing.T) {
t.Fatal("tombstone must supersede the original, not the reverse")
}
// A different author cannot supersede someone else's listing.
other, _ := identity.Generate()
// A different identity cannot supersede someone else's listing.
forged := *ts
_ = forged.Seal(other, testDifficulty)
_ = forged.Seal(newDevice(t), testDifficulty)
if forged.Supersedes(l) {
t.Fatal("tombstone by a different author must not supersede")
}
// Another device of the same identity can (e.g. after a node was replaced).
root, _, _ := identity.NewRoot()
devA, _ := identity.Enroll(root, now.Add(-time.Hour), 24*time.Hour)
devB, _ := identity.Enroll(root, now.Add(-time.Hour), 24*time.Hour)
v1 := sample(t)
_ = v1.Seal(devA, 0)
v2 := *v1
v2.Seq = 2
_ = v2.Seal(devB, 0)
if !v2.Supersedes(v1) {
t.Fatal("a second device of the same identity must be able to supersede")
}
// Tombstones must not smuggle content.
ts.Title = "still here"
_ = ts.Seal(key, testDifficulty)
_ = ts.Seal(dev, testDifficulty)
if err := ts.Check(now, testDifficulty); err == nil {
t.Fatal("tombstone with content accepted")
}
@@ -197,3 +283,12 @@ func TestHashChangesWithContent(t *testing.T) {
t.Fatal("hash must differ for different content")
}
}
func TestRegion(t *testing.T) {
if Region("u1xjhx") != "u1x" {
t.Fatal("wrong region")
}
if !ValidRegion("u1x") || ValidRegion("u1") || ValidRegion("u1xa") || ValidRegion("u1a") {
t.Fatal("ValidRegion wrong")
}
}
+437
View File
@@ -0,0 +1,437 @@
// Package p2p connects a node's store to the network.
//
// - Listings are gossiped on one pubsub topic per geohash region
// (precision 3). A node subscribes only to the regions it cares about.
// - Revocations are gossiped on a single global topic.
// - A sync stream protocol lets a node that was offline (or just joined)
// catch up from any peer.
//
// Every message is verified by a topic validator before it is relayed, so a
// node never forwards garbage and misbehaving peers lose reputation.
package p2p
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"github.com/libp2p/go-libp2p"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/discovery/mdns"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
listingTopicPrefix = "/allmende/1/listings/"
// RevocationTopic carries identity revocations for the whole network.
RevocationTopic = "/allmende/1/revocations"
mdnsService = "allmende"
resyncInterval = 5 * time.Minute
maintenanceTick = time.Hour
)
// Config describes a node.
type Config struct {
Device *identity.Device
Store *store.Store
ListenAddrs []string // default: TCP and QUIC on all interfaces, random ports
Bootstrap []string // multiaddrs ending in /p2p/<peer id>
Regions []string // geohash precision-3 cells to replicate
MDNS bool // discover peers on the local network
Difficulty int // required proof-of-work bits
SyncPageSize int // records per sync page (default 500)
Clock func() time.Time // default time.Now
Logger *slog.Logger
}
// Node is a running participant.
type Node struct {
cfg Config
host host.Host
ps *pubsub.PubSub
clock func() time.Time
log *slog.Logger
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
mdns mdns.Service
mu sync.Mutex
topics map[string]*pubsub.Topic
subscribed []string
synced map[peer.ID]time.Time
revTopic *pubsub.Topic
}
// New starts a node. Cancel ctx or call Close to stop it.
func New(ctx context.Context, cfg Config) (*Node, error) {
if cfg.Device == nil || cfg.Store == nil {
return nil, errors.New("p2p: Device and Store are required")
}
for _, r := range cfg.Regions {
if !listing.ValidRegion(r) {
return nil, fmt.Errorf("p2p: invalid region %q (want %d geohash characters)", r, listing.RegionPrecision)
}
}
if len(cfg.ListenAddrs) == 0 {
cfg.ListenAddrs = []string{"/ip4/0.0.0.0/tcp/0", "/ip4/0.0.0.0/udp/0/quic-v1"}
}
if cfg.SyncPageSize <= 0 {
cfg.SyncPageSize = 500
}
priv, err := crypto.UnmarshalEd25519PrivateKey(cfg.Device.Key.PrivateKey())
if err != nil {
return nil, err
}
h, err := libp2p.New(libp2p.Identity(priv), libp2p.ListenAddrStrings(cfg.ListenAddrs...))
if err != nil {
return nil, err
}
nctx, cancel := context.WithCancel(ctx)
n := &Node{
cfg: cfg,
host: h,
clock: cfg.Clock,
log: cfg.Logger,
ctx: nctx,
cancel: cancel,
topics: map[string]*pubsub.Topic{},
synced: map[peer.ID]time.Time{},
}
if n.clock == nil {
n.clock = time.Now
}
if n.log == nil {
n.log = slog.Default()
}
// Flood-publish: the origin sends to every subscribed peer instead of only
// its mesh. Regional topics are small, and without it a listing published
// in the first second after connecting (before the mesh forms) is lost.
n.ps, err = pubsub.NewGossipSub(nctx, h,
pubsub.WithMaxMessageSize(listing.MaxSize+4096),
pubsub.WithFloodPublish(true))
if err != nil {
n.Close()
return nil, err
}
if err := n.startRevocations(); err != nil {
n.Close()
return nil, err
}
for _, r := range cfg.Regions {
if err := n.subscribeRegion(r); err != nil {
n.Close()
return nil, err
}
}
h.SetStreamHandler(SyncProtocol, n.handleSync)
h.Network().Notify(&network.NotifyBundle{
ConnectedF: func(_ network.Network, c network.Conn) { n.syncSoon(c.RemotePeer()) },
})
for _, addr := range cfg.Bootstrap {
if err := n.Connect(nctx, addr); err != nil {
n.log.Warn("bootstrap peer unreachable", "addr", addr, "err", err)
}
}
if cfg.MDNS {
n.mdns = mdns.NewMdnsService(h, mdnsService, &mdnsNotifee{n: n})
if err := n.mdns.Start(); err != nil {
n.Close()
return nil, err
}
}
n.wg.Add(1)
go n.maintain()
return n, nil
}
// ID returns the node's peer ID, which derives from its device key.
func (n *Node) ID() peer.ID { return n.host.ID() }
// Addrs returns dialable multiaddrs including the /p2p/<id> suffix.
func (n *Node) Addrs() []string {
addrs, err := peer.AddrInfoToP2pAddrs(&peer.AddrInfo{ID: n.host.ID(), Addrs: n.host.Addrs()})
if err != nil {
return nil
}
out := make([]string, len(addrs))
for i, a := range addrs {
out[i] = a.String()
}
return out
}
// Connect dials a peer given as a multiaddr ending in /p2p/<peer id>.
func (n *Node) Connect(ctx context.Context, addr string) error {
ai, err := peer.AddrInfoFromString(addr)
if err != nil {
return err
}
return n.host.Connect(ctx, *ai)
}
// RegionPeers lists peers known to be subscribed to the region's topic.
func (n *Node) RegionPeers(region string) []peer.ID {
return n.ps.ListPeers(listingTopicPrefix + region)
}
// Publish stores l locally (which verifies it) and gossips it to its region.
func (n *Node) Publish(ctx context.Context, l *listing.Listing) error {
if _, err := n.cfg.Store.Put(ctx, l); err != nil {
return err
}
data, err := l.Bytes()
if err != nil {
return err
}
t, err := n.regionTopic(listing.Region(l.Geohash))
if err != nil {
return err
}
return t.Publish(ctx, data)
}
// PublishRevocation stores r locally and gossips it to the whole network.
func (n *Node) PublishRevocation(ctx context.Context, r *identity.Revocation) error {
if _, err := n.cfg.Store.PutRevocation(ctx, r); err != nil {
return err
}
data, err := r.Bytes()
if err != nil {
return err
}
return n.revTopic.Publish(ctx, data)
}
// Close stops the node.
func (n *Node) Close() error {
n.cancel()
if n.mdns != nil {
n.mdns.Close()
}
n.wg.Wait()
return n.host.Close()
}
// --- topics ---------------------------------------------------------------
func (n *Node) startRevocations() error {
if err := n.ps.RegisterTopicValidator(RevocationTopic, n.revocationValidator,
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
return err
}
t, err := n.ps.Join(RevocationTopic)
if err != nil {
return err
}
sub, err := t.Subscribe()
if err != nil {
return err
}
n.revTopic = t
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(sub, func(msg *pubsub.Message) {
r, ok := msg.ValidatorData.(*identity.Revocation)
if !ok {
return
}
if _, err := n.cfg.Store.PutRevocation(n.ctx, r); err != nil {
n.log.Warn("store revocation", "err", err)
}
})
}()
return nil
}
func (n *Node) subscribeRegion(region string) error {
t, err := n.regionTopic(region)
if err != nil {
return err
}
sub, err := t.Subscribe()
if err != nil {
return err
}
n.mu.Lock()
n.subscribed = append(n.subscribed, region)
n.mu.Unlock()
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(sub, func(msg *pubsub.Message) {
l, ok := msg.ValidatorData.(*listing.Listing)
if !ok {
return
}
switch _, err := n.cfg.Store.Put(n.ctx, l); {
case err == nil, errors.Is(err, store.ErrRevoked):
default:
n.log.Warn("store listing", "err", err)
}
})
}()
return nil
}
// regionTopic joins (once) the topic for region and installs its validator.
func (n *Node) regionTopic(region string) (*pubsub.Topic, error) {
if !listing.ValidRegion(region) {
return nil, fmt.Errorf("p2p: invalid region %q", region)
}
n.mu.Lock()
defer n.mu.Unlock()
if t, ok := n.topics[region]; ok {
return t, nil
}
name := listingTopicPrefix + region
if err := n.ps.RegisterTopicValidator(name, n.listingValidator(region),
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
return nil, err
}
t, err := n.ps.Join(name)
if err != nil {
return nil, err
}
n.topics[region] = t
return t, nil
}
func (n *Node) consume(sub *pubsub.Subscription, handle func(*pubsub.Message)) {
for {
msg, err := sub.Next(n.ctx)
if err != nil {
return
}
handle(msg)
}
}
// --- validation -----------------------------------------------------------
func (n *Node) listingValidator(region string) pubsub.ValidatorEx {
return func(ctx context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
l, res := n.validateListing(ctx, msg.Data)
if res != pubsub.ValidationAccept {
return res
}
// A listing may only travel on its own region's topic.
if listing.Region(l.Geohash) != region {
return pubsub.ValidationReject
}
msg.ValidatorData = l
return pubsub.ValidationAccept
}
}
func (n *Node) validateListing(ctx context.Context, data []byte) (*listing.Listing, pubsub.ValidationResult) {
if len(data) > listing.MaxSize {
return nil, pubsub.ValidationReject
}
var l listing.Listing
if err := json.Unmarshal(data, &l); err != nil {
return nil, pubsub.ValidationReject
}
// Only the canonical encoding is accepted, so every honest node derives
// the same message ID and nobody can re-encode someone else's listing.
if canon, err := l.Bytes(); err != nil || !bytes.Equal(canon, data) {
return nil, pubsub.ValidationReject
}
if err := l.Check(n.clock(), n.cfg.Difficulty); err != nil {
if errors.Is(err, listing.ErrTimeWindow) {
return nil, pubsub.ValidationIgnore // clocks differ; not the relay's fault
}
return nil, pubsub.ValidationReject
}
if revoked, err := n.cfg.Store.IsRevoked(ctx, l.Author, l.Device); err != nil || revoked {
return nil, pubsub.ValidationIgnore
}
return &l, pubsub.ValidationAccept
}
func (n *Node) revocationValidator(_ context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
r, res := n.validateRevocation(msg.Data)
if res == pubsub.ValidationAccept {
msg.ValidatorData = r
}
return res
}
func (n *Node) validateRevocation(data []byte) (*identity.Revocation, pubsub.ValidationResult) {
if len(data) > 4096 {
return nil, pubsub.ValidationReject
}
var r identity.Revocation
if err := json.Unmarshal(data, &r); err != nil {
return nil, pubsub.ValidationReject
}
if canon, err := r.Bytes(); err != nil || !bytes.Equal(canon, data) {
return nil, pubsub.ValidationReject
}
if err := r.Check(n.cfg.Difficulty); err != nil {
return nil, pubsub.ValidationReject
}
if r.CertExpiresAt <= n.clock().Unix() {
return nil, pubsub.ValidationIgnore
}
return &r, pubsub.ValidationAccept
}
// --- discovery and upkeep -------------------------------------------------
type mdnsNotifee struct{ n *Node }
func (m *mdnsNotifee) HandlePeerFound(pi peer.AddrInfo) {
if pi.ID == m.n.host.ID() {
return
}
go func() {
ctx, cancel := context.WithTimeout(m.n.ctx, 15*time.Second)
defer cancel()
if err := m.n.host.Connect(ctx, pi); err != nil {
m.n.log.Debug("mdns connect", "peer", pi.ID, "err", err)
}
}()
}
// maintain periodically drops expired data.
func (n *Node) maintain() {
defer n.wg.Done()
t := time.NewTicker(maintenanceTick)
defer t.Stop()
for {
select {
case <-n.ctx.Done():
return
case <-t.C:
if removed, err := n.cfg.Store.Expire(n.ctx); err != nil {
n.log.Warn("expire", "err", err)
} else if removed > 0 {
n.log.Info("expired records", "count", removed)
}
}
}
}
+257
View File
@@ -0,0 +1,257 @@
package p2p
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"testing"
"time"
pubsub "github.com/libp2p/go-libp2p-pubsub"
pb "github.com/libp2p/go-libp2p-pubsub/pb"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const difficulty = 6
type tnode struct {
*Node
s *store.Store
root *identity.Identity
dev *identity.Device
}
func startNode(t *testing.T, root *identity.Identity, regions ...string) *tnode {
t.Helper()
if root == nil {
root, _, _ = identity.NewRoot()
}
dev, err := identity.Enroll(root, time.Now().Add(-time.Hour), 90*24*time.Hour)
if err != nil {
t.Fatal(err)
}
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty})
if err != nil {
t.Fatal(err)
}
n, err := New(context.Background(), Config{
Device: dev,
Store: s,
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Regions: regions,
Difficulty: difficulty,
SyncPageSize: 3,
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { n.Close(); s.Close() })
return &tnode{Node: n, s: s, root: root, dev: dev}
}
func (tn *tnode) listing(t *testing.T, geohash string) *listing.Listing {
t.Helper()
id, _ := listing.NewID()
now := time.Now()
l := &listing.Listing{
Version: listing.Version,
ID: id,
Seq: 1,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(7 * 24 * time.Hour).Unix(),
Kind: "rent",
Category: "apartment",
Geohash: geohash,
Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"},
Title: "Wohnung",
}
if err := l.Seal(tn.dev, difficulty); err != nil {
t.Fatal(err)
}
return l
}
func connect(t *testing.T, from, to *tnode) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := from.Connect(ctx, to.Addrs()[0]); err != nil {
t.Fatal(err)
}
}
func eventually(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("timed out waiting for: %s", what)
}
func count(tn *tnode) int {
n, _ := tn.s.Count(context.Background())
return n
}
func TestGossipDeliversWithinRegion(t *testing.T) {
a := startNode(t, nil, "u1x")
b := startNode(t, nil, "u1x")
c := startNode(t, nil, "u30") // different region
connect(t, b, a)
connect(t, c, a)
eventually(t, "a sees b on the region topic", func() bool { return len(a.RegionPeers("u1x")) == 1 })
l := a.listing(t, "u1xjhx")
if err := a.Publish(context.Background(), l); err != nil {
t.Fatal(err)
}
eventually(t, "b receives the listing", func() bool { return count(b) == 1 })
got, err := b.s.Get(context.Background(), l.Author, l.ID)
if err != nil || got.Title != "Wohnung" {
t.Fatalf("b has %v, %v", got, err)
}
time.Sleep(500 * time.Millisecond)
if count(c) != 0 {
t.Fatal("node in another region received the listing")
}
}
func TestSyncCatchesUpLateJoiner(t *testing.T) {
a := startNode(t, nil, "u1x")
ctx := context.Background()
// Seven listings (page size is 3, so three pages), one of them deleted,
// plus one in a region b does not replicate.
var ls []*listing.Listing
for i := 0; i < 7; i++ {
l := a.listing(t, "u1xjhx")
if _, err := a.s.Put(ctx, l); err != nil {
t.Fatal(err)
}
ls = append(ls, l)
}
ts := &listing.Listing{
Version: listing.Version, ID: ls[0].ID, Seq: 2,
CreatedAt: time.Now().Unix(), ExpiresAt: time.Now().Add(30 * 24 * time.Hour).Unix(),
Tombstone: true, Geohash: ls[0].Geohash,
}
if err := ts.Seal(a.dev, difficulty); err != nil {
t.Fatal(err)
}
if _, err := a.s.Put(ctx, ts); err != nil {
t.Fatal(err)
}
other := a.listing(t, "u30000")
if _, err := a.s.Put(ctx, other); err != nil {
t.Fatal(err)
}
b := startNode(t, nil, "u1x") // joins after everything was published
connect(t, b, a)
eventually(t, "b has caught up", func() bool { return count(b) == 6 })
if _, err := b.s.Get(ctx, ls[0].Author, ls[0].ID); !errors.Is(err, store.ErrNotFound) {
t.Fatal("deleted listing was not deleted on the late joiner")
}
if _, err := b.s.Get(ctx, other.Author, other.ID); !errors.Is(err, store.ErrNotFound) {
t.Fatal("b stored a listing from a region it does not replicate")
}
}
func TestRevocationPropagatesAndBlocks(t *testing.T) {
owner, _, _ := identity.NewRoot()
a := startNode(t, owner, "u1x") // the owner's (soon to be compromised) node
b := startNode(t, nil, "u1x")
connect(t, b, a)
eventually(t, "mesh formed", func() bool {
return len(a.RegionPeers("u1x")) == 1 && len(b.RegionPeers("u1x")) == 1
})
ctx := context.Background()
l := a.listing(t, "u1xjhx")
if err := a.Publish(ctx, l); err != nil {
t.Fatal(err)
}
eventually(t, "b has the listing", func() bool { return count(b) == 1 })
// The owner enters the recovery phrase on a new machine and revokes node a.
rev, err := identity.Revoke(owner, a.dev.Cert, time.Now(), difficulty)
if err != nil {
t.Fatal(err)
}
newMachine := startNode(t, owner, "u1x")
connect(t, newMachine, b)
if err := newMachine.PublishRevocation(ctx, rev); err != nil {
t.Fatal(err)
}
eventually(t, "b dropped the revoked device's listing", func() bool { return count(b) == 0 })
eventually(t, "a dropped it too", func() bool { return count(a) == 0 })
// The compromised node can no longer publish anything.
if err := a.Publish(ctx, a.listing(t, "u1xjhx")); !errors.Is(err, store.ErrRevoked) {
t.Fatalf("revoked node could publish: %v", err)
}
// A node joining later learns about the revocation through sync.
late := startNode(t, nil, "u1x")
connect(t, late, b)
eventually(t, "late joiner learns the revocation", func() bool {
ok, _ := late.s.IsRevoked(ctx, a.dev.Cert.Author, a.dev.Cert.Device)
return ok
})
}
func TestValidatorRejectsBadMessages(t *testing.T) {
a := startNode(t, nil, "u1x")
good := a.listing(t, "u1xjhx")
goodBytes, _ := good.Bytes()
validate := func(region string, data []byte) pubsub.ValidationResult {
v := a.listingValidator(region)
return v(context.Background(), "", &pubsub.Message{Message: &pb.Message{Data: data}})
}
if r := validate("u1x", goodBytes); r != pubsub.ValidationAccept {
t.Fatalf("good listing: %v", r)
}
if r := validate("u30", goodBytes); r != pubsub.ValidationReject {
t.Fatalf("listing on the wrong region topic: %v", r)
}
if r := validate("u1x", []byte(`{"v":1`)); r != pubsub.ValidationReject {
t.Fatalf("garbage: %v", r)
}
tampered := *good
tampered.Title = "Betrug"
tb, _ := tampered.Bytes()
if r := validate("u1x", tb); r != pubsub.ValidationReject {
t.Fatalf("tampered listing: %v", r)
}
// Valid content, but not in canonical form (extra whitespace).
var m map[string]any
_ = json.Unmarshal(goodBytes, &m)
pretty, _ := json.MarshalIndent(m, "", " ")
if r := validate("u1x", pretty); r != pubsub.ValidationReject {
t.Fatalf("non-canonical encoding: %v", r)
}
// Expired: ignored (clock difference), not penalized.
old := a.listing(t, "u1xjhx")
a.clock = func() time.Time { return time.Now().Add(30 * 24 * time.Hour) }
ob, _ := old.Bytes()
if r := validate("u1x", ob); r != pubsub.ValidationIgnore {
t.Fatalf("expired listing: %v", r)
}
}
+218
View File
@@ -0,0 +1,218 @@
package p2p
import (
"bufio"
"context"
"encoding/json"
"io"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
// SyncProtocol lets a node catch up with everything a peer holds for a
// region. Gossip only delivers what is published while you are online.
//
// Request: one JSON object. Response: newline-delimited canonical JSON
// records, then EOF. Listings are paged with a keyset cursor over
// (created_at, author, id), so pages are stable and cannot loop.
const SyncProtocol = "/allmende/1/sync"
const (
syncTimeout = 2 * time.Minute
maxSyncPages = 200 // bounds work per region against a misbehaving peer
maxRevocations = 5000
)
type syncRequest struct {
Kind string `json:"kind"` // "listings" or "revocations"
Region string `json:"region,omitempty"`
AfterCreated int64 `json:"after_created,omitempty"`
AfterAuthor string `json:"after_author,omitempty"`
AfterID string `json:"after_id,omitempty"`
Limit int `json:"limit,omitempty"`
}
// --- server ---------------------------------------------------------------
func (n *Node) handleSync(s network.Stream) {
defer s.Close()
_ = s.SetDeadline(time.Now().Add(syncTimeout))
var req syncRequest
if err := json.NewDecoder(io.LimitReader(s, 4096)).Decode(&req); err != nil {
_ = s.Reset()
return
}
w := bufio.NewWriter(s)
write := func(b []byte, err error) bool {
if err != nil {
return false
}
w.Write(b)
w.WriteByte('\n')
return true
}
switch req.Kind {
case "listings":
if !listing.ValidRegion(req.Region) {
_ = s.Reset()
return
}
limit := req.Limit
if limit <= 0 || limit > n.cfg.SyncPageSize {
limit = n.cfg.SyncPageSize
}
items, err := n.cfg.Store.Since(n.ctx, req.Region,
store.Cursor{CreatedAt: req.AfterCreated, Author: req.AfterAuthor, ID: req.AfterID}, limit)
if err != nil {
_ = s.Reset()
return
}
for _, l := range items {
if !write(l.Bytes()) {
_ = s.Reset()
return
}
}
case "revocations":
revs, err := n.cfg.Store.Revocations(n.ctx)
if err != nil {
_ = s.Reset()
return
}
if len(revs) > maxRevocations {
revs = revs[:maxRevocations]
}
for _, r := range revs {
if !write(r.Bytes()) {
_ = s.Reset()
return
}
}
default:
_ = s.Reset()
return
}
_ = w.Flush()
}
// --- client ---------------------------------------------------------------
// syncSoon schedules a catch-up with p, at most once per resyncInterval.
func (n *Node) syncSoon(p peer.ID) {
n.mu.Lock()
if last, ok := n.synced[p]; ok && n.clock().Sub(last) < resyncInterval {
n.mu.Unlock()
return
}
n.synced[p] = n.clock()
n.mu.Unlock()
n.wg.Add(1)
go func() {
defer n.wg.Done()
ctx, cancel := context.WithTimeout(n.ctx, syncTimeout)
defer cancel()
if err := n.SyncFrom(ctx, p); err != nil {
n.log.Debug("sync", "peer", p, "err", err)
}
}()
}
// SyncFrom pulls revocations and then every subscribed region from p.
// Revocations go first so listings from revoked devices are refused.
func (n *Node) SyncFrom(ctx context.Context, p peer.ID) error {
if err := n.syncRevocations(ctx, p); err != nil {
return err
}
n.mu.Lock()
regions := append([]string(nil), n.subscribed...)
n.mu.Unlock()
for _, region := range regions {
if err := n.syncRegion(ctx, p, region); err != nil {
return err
}
}
return nil
}
func (n *Node) syncRevocations(ctx context.Context, p peer.ID) error {
return n.request(ctx, p, syncRequest{Kind: "revocations"}, func(line []byte) {
var r identity.Revocation
if json.Unmarshal(line, &r) != nil {
return
}
if _, err := n.cfg.Store.PutRevocation(ctx, &r); err != nil {
n.log.Debug("sync: revocation rejected", "peer", p, "err", err)
}
})
}
func (n *Node) syncRegion(ctx context.Context, p peer.ID, region string) error {
var cur store.Cursor
for page := 0; page < maxSyncPages; page++ {
var count int
var last *listing.Listing
err := n.request(ctx, p, syncRequest{
Kind: "listings", Region: region, Limit: n.cfg.SyncPageSize,
AfterCreated: cur.CreatedAt, AfterAuthor: cur.Author, AfterID: cur.ID,
}, func(line []byte) {
var l listing.Listing
if json.Unmarshal(line, &l) != nil {
return
}
count++
last = &l
if listing.Region(l.Geohash) != region {
return // peer sent something we did not ask for
}
if _, err := n.cfg.Store.Put(ctx, &l); err != nil {
n.log.Debug("sync: listing rejected", "peer", p, "err", err)
}
})
if err != nil {
return err
}
if count < n.cfg.SyncPageSize || last == nil {
return nil
}
cur = store.CursorOf(last)
}
return nil
}
// request opens a sync stream, sends req and calls handle for each line.
func (n *Node) request(ctx context.Context, p peer.ID, req syncRequest, handle func([]byte)) error {
s, err := n.host.NewStream(ctx, p, SyncProtocol)
if err != nil {
return err
}
defer s.Close()
_ = s.SetDeadline(time.Now().Add(syncTimeout))
if err := json.NewEncoder(s).Encode(req); err != nil {
_ = s.Reset()
return err
}
if err := s.CloseWrite(); err != nil {
_ = s.Reset()
return err
}
sc := bufio.NewScanner(s)
sc.Buffer(make([]byte, 0, 64<<10), listing.MaxSize+4096)
for sc.Scan() {
handle(sc.Bytes())
}
if err := sc.Err(); err != nil {
_ = s.Reset()
return err
}
return nil
}
+22
View File
@@ -0,0 +1,22 @@
// Package pow implements the hashcash-style proof-of-work used to make
// mass-publishing of listings and revocations expensive.
package pow
import (
"crypto/sha256"
"math/bits"
)
// LeadingZeroBits returns the number of leading zero bits of sha256(data).
func LeadingZeroBits(data []byte) int {
sum := sha256.Sum256(data)
n := 0
for _, b := range sum {
if b == 0 {
n += 8
continue
}
return n + bits.LeadingZeros8(b)
}
return n
}
+155 -8
View File
@@ -15,6 +15,7 @@ import (
_ "modernc.org/sqlite"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
)
@@ -23,6 +24,8 @@ var (
ErrInvalid = errors.New("store: invalid listing")
// ErrNotFound is returned when a listing is absent, expired or deleted.
ErrNotFound = errors.New("store: not found")
// ErrRevoked is returned for listings signed by a revoked device.
ErrRevoked = errors.New("store: device revoked")
)
// Outcome tells the caller what Put did, so the p2p layer knows whether a
@@ -54,6 +57,7 @@ const schema = `
CREATE TABLE IF NOT EXISTS listings (
author TEXT NOT NULL,
id TEXT NOT NULL,
device TEXT NOT NULL,
seq INTEGER NOT NULL,
hash TEXT NOT NULL,
tombstone INTEGER NOT NULL,
@@ -70,6 +74,16 @@ CREATE TABLE IF NOT EXISTS listings (
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS listings_geohash ON listings (geohash);
CREATE INDEX IF NOT EXISTS listings_expires ON listings (expires_at);
CREATE INDEX IF NOT EXISTS listings_device ON listings (author, device);
CREATE INDEX IF NOT EXISTS listings_created ON listings (created_at, author, id);
CREATE TABLE IF NOT EXISTS revocations (
author TEXT NOT NULL,
device TEXT NOT NULL,
cert_expires_at INTEGER NOT NULL,
data BLOB NOT NULL,
PRIMARY KEY (author, device)
) WITHOUT ROWID;
`
// Open opens (creating if needed) the database at path. Use ":memory:" for
@@ -125,6 +139,17 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
}
defer tx.Rollback()
var revoked int
err = tx.QueryRowContext(ctx,
`SELECT COUNT(*) FROM revocations WHERE author = ? AND device = ?`, l.Author, l.Device).
Scan(&revoked)
if err != nil {
return Ignored, err
}
if revoked > 0 {
return Ignored, ErrRevoked
}
var curSeq int64
var curHash string
err = tx.QueryRowContext(ctx,
@@ -149,10 +174,10 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) {
}
_, err = tx.ExecContext(ctx, `
INSERT OR REPLACE INTO listings
(author, id, seq, hash, tombstone, created_at, expires_at, geohash,
(author, id, device, seq, hash, tombstone, created_at, expires_at, geohash,
kind, category, price_cents, area_m2, rooms_x2, data)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
l.Author, l.ID, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
l.Author, l.ID, l.Device, int64(l.Seq), hash, boolInt(l.Tombstone), l.CreatedAt, l.ExpiresAt,
l.Geohash, l.Kind, l.Category, price, l.AreaM2, l.RoomsX2, data)
if err != nil {
return Ignored, err
@@ -270,15 +295,137 @@ func (s *Store) Search(ctx context.Context, q Query) ([]*listing.Listing, error)
return out, rows.Err()
}
// Expire deletes everything whose lifetime has ended, tombstones included,
// and returns how many rows were removed. A tombstone outlives any version it
// supersedes because listings live at most 30 days from creation.
// Cursor is a keyset position in the (created_at, author, id) order, used to
// page through listings during sync. The zero Cursor is the very beginning.
type Cursor struct {
CreatedAt int64
Author string
ID string
}
// CursorOf returns the cursor positioned at l.
func CursorOf(l *listing.Listing) Cursor {
return Cursor{CreatedAt: l.CreatedAt, Author: l.Author, ID: l.ID}
}
// Since returns up to limit unexpired records (tombstones included, since
// peers need them to learn about deletions) in region prefix that sort after
// cur, oldest first.
func (s *Store) Since(ctx context.Context, prefix string, cur Cursor, limit int) ([]*listing.Listing, error) {
if !listing.ValidGeohashPrefix(prefix) {
return nil, fmt.Errorf("store: invalid geohash prefix %q", prefix)
}
rows, err := s.db.QueryContext(ctx, `
SELECT data FROM listings
WHERE geohash >= ? AND geohash <= ? AND expires_at > ?
AND (created_at, author, id) > (?, ?, ?)
ORDER BY created_at, author, id LIMIT ?`,
prefix, prefix+"~", s.clock().Unix(), cur.CreatedAt, cur.Author, cur.ID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*listing.Listing
for rows.Next() {
var data []byte
if err := rows.Scan(&data); err != nil {
return nil, err
}
l, err := decode(data)
if err != nil {
return nil, err
}
out = append(out, l)
}
return out, rows.Err()
}
// PutRevocation verifies and stores a revocation, and removes every listing
// the revoked device signed. The owner re-publishes them from a new device.
func (s *Store) PutRevocation(ctx context.Context, r *identity.Revocation) (Outcome, error) {
if err := r.Check(s.difficulty); err != nil {
return Ignored, fmt.Errorf("%w: %v", ErrInvalid, err)
}
if r.CertExpiresAt <= s.clock().Unix() {
return Ignored, nil // the certificate is dead anyway
}
data, err := r.Bytes()
if err != nil {
return Ignored, err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Ignored, err
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx,
`INSERT OR IGNORE INTO revocations (author, device, cert_expires_at, data) VALUES (?, ?, ?, ?)`,
r.Author, r.Device, r.CertExpiresAt, data)
if err != nil {
return Ignored, err
}
if n, _ := res.RowsAffected(); n == 0 {
return Ignored, nil // already known
}
if _, err := tx.ExecContext(ctx,
`DELETE FROM listings WHERE author = ? AND device = ?`, r.Author, r.Device); err != nil {
return Ignored, err
}
if err := tx.Commit(); err != nil {
return Ignored, err
}
return Inserted, nil
}
// Revocations returns every revocation still relevant (certificate unexpired).
func (s *Store) Revocations(ctx context.Context) ([]*identity.Revocation, error) {
rows, err := s.db.QueryContext(ctx,
`SELECT data FROM revocations WHERE cert_expires_at > ? ORDER BY author, device`, s.clock().Unix())
if err != nil {
return nil, err
}
defer rows.Close()
var out []*identity.Revocation
for rows.Next() {
var data []byte
if err := rows.Scan(&data); err != nil {
return nil, err
}
var r identity.Revocation
if err := json.Unmarshal(data, &r); err != nil {
return nil, fmt.Errorf("store: corrupt revocation: %w", err)
}
out = append(out, &r)
}
return out, rows.Err()
}
// IsRevoked reports whether the device has been revoked.
func (s *Store) IsRevoked(ctx context.Context, author, device string) (bool, error) {
var n int
err := s.db.QueryRowContext(ctx,
`SELECT COUNT(*) FROM revocations WHERE author = ? AND device = ?`, author, device).Scan(&n)
return n > 0, err
}
// Expire deletes everything whose lifetime has ended (listings, tombstones
// and revocations) and returns how many rows were removed. A tombstone
// outlives any version it supersedes because listings live at most 30 days
// from creation.
func (s *Store) Expire(ctx context.Context) (int64, error) {
res, err := s.db.ExecContext(ctx, `DELETE FROM listings WHERE expires_at <= ?`, s.clock().Unix())
now := s.clock().Unix()
res, err := s.db.ExecContext(ctx, `DELETE FROM listings WHERE expires_at <= ?`, now)
if err != nil {
return 0, err
}
return res.RowsAffected()
n, _ := res.RowsAffected()
res, err = s.db.ExecContext(ctx, `DELETE FROM revocations WHERE cert_expires_at <= ?`, now)
if err != nil {
return n, err
}
m, _ := res.RowsAffected()
return n + m, nil
}
// Count returns the number of live listings.
+172 -24
View File
@@ -19,15 +19,26 @@ var (
)
type env struct {
s *Store
now time.Time
key *identity.Identity
s *Store
now time.Time
root *identity.Identity
dev *identity.Device
}
func newDevice(t *testing.T, root *identity.Identity) *identity.Device {
t.Helper()
dev, err := identity.Enroll(root, t0.Add(-time.Hour), 180*24*time.Hour)
if err != nil {
t.Fatal(err)
}
return dev
}
func newEnv(t *testing.T) *env {
t.Helper()
e := &env{now: t0}
e.key, _ = identity.Generate()
e.root, _, _ = identity.NewRoot()
e.dev = newDevice(t, e.root)
s, err := Open(":memory:", Options{Difficulty: difficulty, Clock: func() time.Time { return e.now }})
if err != nil {
t.Fatal(err)
@@ -37,6 +48,14 @@ func newEnv(t *testing.T) *env {
return e
}
// sibling returns a second store sharing e's identity and clock.
func (e *env) sibling(t *testing.T) *env {
t.Helper()
e2 := newEnv(t)
e2.root, e2.dev = e.root, e.dev
return e2
}
func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.Listing {
t.Helper()
id, _ := listing.NewID()
@@ -53,12 +72,11 @@ func (e *env) listing(t *testing.T, mutate func(*listing.Listing)) *listing.List
AreaM2: 50,
RoomsX2: 4,
Title: "Wohnung",
Endpoint: "12D3KooWExamplePeerID",
}
if mutate != nil {
mutate(l)
}
if err := l.Seal(e.key, difficulty); err != nil {
if err := l.Seal(e.dev, difficulty); err != nil {
t.Fatal(err)
}
return l
@@ -112,7 +130,7 @@ func TestHigherSeqWinsInAnyOrder(t *testing.T) {
v2 := *v1
v2.Seq = 2
v2.Title = "Neuer Titel"
if err := v2.Seal(e.key, difficulty); err != nil {
if err := v2.Seal(e.dev, difficulty); err != nil {
t.Fatal(err)
}
@@ -129,8 +147,7 @@ func TestHigherSeqWinsInAnyOrder(t *testing.T) {
}
// Fresh store, natural order: second is a replacement.
e2 := newEnv(t)
e2.key = e.key
e2 := e.sibling(t)
e2.put(t, v1)
if o := e2.put(t, &v2); o != Replaced {
t.Fatalf("got %v want replaced", o)
@@ -142,7 +159,7 @@ func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
a := e.listing(t, nil)
b := *a
b.Title = "Anderer Titel"
if err := b.Seal(e.key, difficulty); err != nil {
if err := b.Seal(e.dev, difficulty); err != nil {
t.Fatal(err)
}
ha, _ := a.Hash()
@@ -157,8 +174,7 @@ func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
"loser first": {loser, winner},
} {
t.Run(name, func(t *testing.T) {
e2 := newEnv(t)
e2.key = e.key
e2 := e.sibling(t)
for _, l := range order {
e2.put(t, l)
}
@@ -170,19 +186,25 @@ func TestEqualSeqConvergesOnSmallerHash(t *testing.T) {
}
}
func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) {
e := newEnv(t)
l := e.listing(t, nil)
e.put(t, l)
func (e *env) tombstone(t *testing.T, l *listing.Listing) *listing.Listing {
t.Helper()
ts := &listing.Listing{
Version: listing.Version, ID: l.ID, Seq: l.Seq + 1,
CreatedAt: e.now.Unix(), ExpiresAt: e.now.Add(30 * 24 * time.Hour).Unix(),
Tombstone: true, Geohash: l.Geohash,
}
if err := ts.Seal(e.key, difficulty); err != nil {
if err := ts.Seal(e.dev, difficulty); err != nil {
t.Fatal(err)
}
return ts
}
func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) {
e := newEnv(t)
l := e.listing(t, nil)
e.put(t, l)
ts := e.tombstone(t, l)
if o := e.put(t, ts); o != Replaced {
t.Fatalf("got %v want replaced", o)
}
@@ -197,8 +219,7 @@ func TestTombstoneDeletesAndBlocksResurrection(t *testing.T) {
}
// A tombstone arriving before the listing it deletes still wins.
e2 := newEnv(t)
e2.key = e.key
e2 := e.sibling(t)
e2.put(t, ts)
if o := e2.put(t, l); o != Ignored {
t.Fatalf("listing after tombstone: %v", o)
@@ -210,11 +231,11 @@ func TestSameIDDifferentAuthorsDoNotCollide(t *testing.T) {
victim := e.listing(t, nil)
e.put(t, victim)
other, _ := identity.Generate()
otherRoot, _, _ := identity.NewRoot()
squat := *victim
squat.Seq = 99
squat.Title = "Betrug"
if err := squat.Seal(other, difficulty); err != nil {
if err := squat.Seal(newDevice(t, otherRoot), difficulty); err != nil {
t.Fatal(err)
}
e.put(t, &squat)
@@ -225,6 +246,88 @@ func TestSameIDDifferentAuthorsDoNotCollide(t *testing.T) {
}
}
func TestRevocationVoidsDevice(t *testing.T) {
e := newEnv(t)
stolen := e.dev
mine := e.listing(t, nil)
e.put(t, mine)
// The attacker hijacks the listing with the stolen device and a huge seq.
hijack := *mine
hijack.Seq = 1 << 40
hijack.Title = "Betrug"
if err := hijack.Seal(stolen, difficulty); err != nil {
t.Fatal(err)
}
if o := e.put(t, &hijack); o != Replaced {
t.Fatalf("hijack: %v", o)
}
// The owner restores from the recovery phrase and revokes the device.
rev, err := identity.Revoke(e.root, stolen.Cert, e.now, difficulty)
if err != nil {
t.Fatal(err)
}
if o, err := e.s.PutRevocation(ctx, rev); err != nil || o != Inserted {
t.Fatalf("PutRevocation = %v, %v", o, err)
}
if _, err := e.s.Get(ctx, mine.Author, mine.ID); !errors.Is(err, ErrNotFound) {
t.Fatal("revoked device's listing still readable")
}
if _, err := e.s.Put(ctx, &hijack); !errors.Is(err, ErrRevoked) {
t.Fatalf("revoked device accepted again: %v", err)
}
if o, _ := e.s.PutRevocation(ctx, rev); o != Ignored {
t.Fatalf("duplicate revocation: %v", o)
}
// The owner republishes from a new device with a low seq: it must win,
// because the attacker's huge seq was purged with the revocation.
newDev := newDevice(t, e.root)
again := *mine
again.Seq = 2
if err := again.Seal(newDev, difficulty); err != nil {
t.Fatal(err)
}
if o := e.put(t, &again); o != Inserted {
t.Fatalf("republish from new device: %v", o)
}
got, _ := e.s.Get(ctx, mine.Author, mine.ID)
if got.Title != "Wohnung" {
t.Fatalf("got %q", got.Title)
}
}
func TestRevocationValidation(t *testing.T) {
e := newEnv(t)
other, _, _ := identity.NewRoot()
// Someone else's identity cannot revoke our device.
if _, err := identity.Revoke(other, e.dev.Cert, e.now, difficulty); err == nil {
t.Fatal("foreign identity could create a revocation")
}
rev, _ := identity.Revoke(e.root, e.dev.Cert, e.now, difficulty)
rev.Device = other.PublicKeyHex()
if _, err := e.s.PutRevocation(ctx, rev); !errors.Is(err, ErrInvalid) {
t.Fatalf("tampered revocation: %v", err)
}
}
func TestRevocationExpiresWithCertificate(t *testing.T) {
e := newEnv(t)
rev, _ := identity.Revoke(e.root, e.dev.Cert, e.now, difficulty)
e.s.PutRevocation(ctx, rev)
if list, _ := e.s.Revocations(ctx); len(list) != 1 {
t.Fatalf("got %d revocations, want 1", len(list))
}
e.now = time.Unix(e.dev.Cert.ExpiresAt+1, 0)
if list, _ := e.s.Revocations(ctx); len(list) != 0 {
t.Fatal("expired revocation still listed")
}
if n, _ := e.s.Expire(ctx); n != 1 {
t.Fatalf("Expire removed %d, want 1", n)
}
}
func TestSearch(t *testing.T) {
e := newEnv(t)
mk := func(geo, kind string, cents int64, area, rooms int) {
@@ -278,6 +381,51 @@ func TestSearch(t *testing.T) {
}
}
func TestSinceKeysetPaging(t *testing.T) {
e := newEnv(t)
// Five listings in the same second plus one tombstone and one outside the region.
var all []*listing.Listing
for i := 0; i < 5; i++ {
l := e.listing(t, nil)
e.put(t, l)
all = append(all, l)
}
e.put(t, e.tombstone(t, all[0]))
e.put(t, e.listing(t, func(l *listing.Listing) { l.Geohash = "u30000" }))
var got []*listing.Listing
cur := Cursor{}
for pages := 0; pages < 10; pages++ {
page, err := e.s.Since(ctx, "u1x", cur, 2)
if err != nil {
t.Fatal(err)
}
if len(page) == 0 {
break
}
got = append(got, page...)
cur = CursorOf(page[len(page)-1])
}
// 5 distinct listings; one of them is now a tombstone.
if len(got) != 5 {
t.Fatalf("paged %d records, want 5", len(got))
}
tombstones := 0
seen := map[string]bool{}
for _, l := range got {
if seen[l.ID] {
t.Fatalf("duplicate %s across pages", l.ID)
}
seen[l.ID] = true
if l.Tombstone {
tombstones++
}
}
if tombstones != 1 {
t.Fatalf("got %d tombstones, want 1 (peers need them to learn deletions)", tombstones)
}
}
func TestExpiry(t *testing.T) {
e := newEnv(t)
l := e.listing(t, nil)
@@ -298,14 +446,14 @@ func TestExpiry(t *testing.T) {
func TestPersistence(t *testing.T) {
path := filepath.Join(t.TempDir(), "allmende.db")
key, _ := identity.Generate()
opt := Options{Difficulty: difficulty, Clock: func() time.Time { return t0 }}
s, err := Open(path, opt)
if err != nil {
t.Fatal(err)
}
e := &env{s: s, now: t0, key: key}
e := newEnv(t)
e.s = s
l := e.listing(t, nil)
e.put(t, l)
s.Close()