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) }