Files
allmende/internal/message/envelope.go
T
nilsandClaude Sonnet 5.5 52a6d87553 pow: a fast miner that hashes the bytes before the nonce once (about 100 times faster)
pow.Mine finds the smallest nonce, exactly what trying 0, 1, 2, ... finds, so every signed record and golden fixture stays the same. It saves the SHA-256 state after the whole blocks before the nonce, hashes only the number and what follows per attempt, and uses every core but one from difficulty 14 up. Listing, report, revocation and message mining use it; each re-checks the result before signing. One listing at difficulty 16 takes about 19 ms instead of about 2 s. docs/PROTOCOL.md says what proof-of-work can and cannot do against fast hardware.

allmende-load fills a data directory with signed invented listings for capacity tests and measures mining time (-mine-only).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-19 00:15:52 +01:00

389 lines
11 KiB
Go

// Package message implements the end-to-end encrypted messages between a
// buyer and a listing's owner (see "Messaging" in docs/PROTOCOL.md).
//
// What travels through the network is an Envelope: encrypted, anonymous and
// stamped with proof-of-work. Relays can check the stamp, the size and the
// listing it refers to, but not the content.
package message
import (
"crypto/ecdh"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"time"
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/pow"
)
const (
Version = 1
// MaxLifetime is how long a relay keeps an envelope.
MaxLifetime = 14 * 24 * time.Hour
// MaxSize is the largest canonical envelope.
MaxSize = 10 << 10
// DefaultDifficulty is lower than for listings: a message should cost a
// buyer a moment, not a bot's budget.
DefaultDifficulty = 14
// Directions: who an envelope is for.
ToOwner = "owner"
ToBuyer = "buyer"
mailboxContext = "allmende-mailbox-v1\n"
maxSafeInt = 1<<53 - 1
tagSize = 16 // Poly1305
)
// Ref names the listing a thread is about.
type Ref struct {
Author string `json:"author"` // identity public key, hex
ID string `json:"id"` // listing id, hex
}
// Envelope is the gossiped record.
type Envelope struct {
Version int `json:"v"`
Listing Ref `json:"listing"`
To string `json:"to"`
Rcpt string `json:"rcpt"` // owner: device key (64 hex); buyer: mailbox tag (32 hex)
EPK string `json:"epk"` // sender's ephemeral X25519 key, hex
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
CT string `json:"ct"` // hex
PoW uint64 `json:"pow"`
}
// header is the authenticated, unencrypted part: the envelope without the
// ciphertext and the proof-of-work nonce.
type header struct {
Version int `json:"v"`
Listing Ref `json:"listing"`
To string `json:"to"`
Rcpt string `json:"rcpt"`
EPK string `json:"epk"`
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at"`
}
func (e *Envelope) header() header {
return header{e.Version, e.Listing, e.To, e.Rcpt, e.EPK, e.CreatedAt, e.ExpiresAt}
}
func (e *Envelope) headerBytes() ([]byte, error) {
return jcs.Marshal(e.header())
}
// Bytes is the canonical encoding that is gossiped.
func (e *Envelope) Bytes() ([]byte, error) { return jcs.Marshal(e) }
// Hash identifies the envelope (hex sha256 of its canonical bytes).
func (e *Envelope) Hash() (string, error) {
b, err := e.Bytes()
if err != nil {
return "", err
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:]), nil
}
func (e *Envelope) powOK(difficulty int) (bool, error) {
b, err := e.Bytes()
if err != nil {
return false, err
}
return pow.LeadingZeroBits(b) >= difficulty, nil
}
// Work returns the leading zero bits of the envelope's hash: the proof of
// work it carries, used to decide what to evict from a full queue.
func (e *Envelope) Work() (int, error) {
b, err := e.Bytes()
if err != nil {
return 0, err
}
return pow.LeadingZeroBits(b), nil
}
func (e *Envelope) mine(difficulty int) error {
e.PoW = 0
b, err := e.Bytes()
if err != nil {
return err
}
e.PoW, err = pow.Mine(b, difficulty, maxSafeInt)
if errors.Is(err, pow.ErrExhausted) {
return errors.New("message: proof-of-work exhausted")
}
if err != nil {
return err
}
if ok, err := e.powOK(difficulty); err != nil || !ok { // cannot happen; a wrong miner must not send
return errors.New("message: mined nonce does not meet the difficulty")
}
return nil
}
// Check validates a received envelope as a relay can: structure, size,
// lifetime, proof-of-work. It cannot look inside.
func (e *Envelope) Check(now time.Time, difficulty int) error {
if e.Version != Version {
return fmt.Errorf("message: unsupported version %d", e.Version)
}
if !isHex(e.Listing.Author, 64) || !isHex(e.Listing.ID, 32) {
return errors.New("message: malformed listing reference")
}
switch e.To {
case ToOwner:
if !isHex(e.Rcpt, 64) {
return errors.New("message: owner recipient must be 64 hex characters")
}
case ToBuyer:
if !isHex(e.Rcpt, 32) {
return errors.New("message: mailbox tag must be 32 hex characters")
}
default:
return fmt.Errorf("message: invalid direction %q", e.To)
}
if !isHex(e.EPK, 64) {
return errors.New("message: malformed ephemeral key")
}
ct, err := hex.DecodeString(e.CT)
if err != nil || hex.EncodeToString(ct) != e.CT {
return errors.New("message: ciphertext must be lowercase hex")
}
if len(ct) < tagSize+1 || len(ct) > paddingBuckets[len(paddingBuckets)-1]+tagSize {
return errors.New("message: ciphertext size out of range")
}
if e.CreatedAt <= 0 || e.CreatedAt > maxSafeInt || e.ExpiresAt > maxSafeInt || e.PoW > maxSafeInt {
return errors.New("message: number out of range")
}
if e.ExpiresAt <= e.CreatedAt {
return errors.New("message: expires_at must be after created_at")
}
if time.Duration(e.ExpiresAt-e.CreatedAt)*time.Second > MaxLifetime {
return errors.New("message: lifetime exceeds 14 days")
}
if time.Unix(e.CreatedAt, 0).After(now.Add(listing.MaxClockSkew)) {
return fmt.Errorf("message: created_at is in the future: %w", listing.ErrTimeWindow)
}
if !time.Unix(e.ExpiresAt, 0).After(now) {
return fmt.Errorf("message: expired: %w", listing.ErrTimeWindow)
}
full, err := e.Bytes()
if err != nil {
return err
}
if len(full) > MaxSize {
return fmt.Errorf("message: %d bytes exceeds limit of %d", len(full), MaxSize)
}
ok, err := e.powOK(difficulty)
if err != nil {
return err
}
if !ok {
return errors.New("message: insufficient proof-of-work")
}
return nil
}
// build seals plain to rpk and mines the proof-of-work.
func build(ref Ref, to, rcpt string, rpk *ecdh.PublicKey, plain *Plain, now time.Time, difficulty int) (*Envelope, error) {
body, err := jcs.Marshal(plain)
if err != nil {
return nil, err
}
e := &Envelope{
Version: Version,
Listing: ref,
To: to,
Rcpt: rcpt,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(MaxLifetime).Unix(),
}
epk, ct, err := seal(rpk, func(epk string) ([]byte, error) {
e.EPK = epk
return e.headerBytes()
}, body)
if err != nil {
return nil, err
}
e.EPK = epk
e.CT = hex.EncodeToString(ct)
if err := e.mine(difficulty); err != nil {
return nil, err
}
return e, nil
}
// SealToOwner seals a buyer's message to the listing's current device key.
func SealToOwner(l *listing.Listing, thread *ThreadKey, p *Plain, now time.Time, difficulty int) (*Envelope, error) {
if l.Tombstone {
return nil, errors.New("message: listing is deleted")
}
devPub, err := hex.DecodeString(l.Device)
if err != nil || len(devPub) != 32 {
return nil, errors.New("message: bad device key")
}
rpk, err := ed25519PublicToX25519(devPub)
if err != nil {
return nil, err
}
p.Thread = thread.PublicHex()
if err := p.validate(ToOwner); err != nil {
return nil, err
}
return build(Ref{Author: l.Author, ID: l.ID}, ToOwner, l.Device, rpk, p, now, difficulty)
}
// SealToBuyer signs the owner's reply with the device key and seals it to the
// buyer's thread key; it is addressed to the thread's mailbox.
func SealToBuyer(dev *identity.Device, ref Ref, p *Plain, now time.Time, difficulty int) (*Envelope, error) {
if ref.Author != dev.Cert.Author {
return nil, errors.New("message: device does not belong to the listing's author")
}
p.signOwner(dev, ref)
if err := p.validate(ToBuyer); err != nil {
return nil, err
}
pub, err := hex.DecodeString(p.Thread)
if err != nil {
return nil, errors.New("message: bad thread key")
}
rpk, err := x25519.NewPublicKey(pub)
if err != nil {
return nil, errors.New("message: bad thread key")
}
mailbox, err := Mailbox(p.Thread)
if err != nil {
return nil, err
}
return build(ref, ToBuyer, mailbox, rpk, p, now, difficulty)
}
// OpenAsOwner decrypts an envelope addressed to dev and checks the plaintext.
func (e *Envelope) OpenAsOwner(dev *identity.Device) (*Plain, error) {
if e.To != ToOwner || e.Rcpt != dev.Cert.Device {
return nil, errors.New("message: not addressed to this device")
}
sk, err := ed25519SecretToX25519(dev.Key.PrivateKey())
if err != nil {
return nil, err
}
p, err := e.decrypt(sk)
if err != nil {
return nil, err
}
if err := p.validate(ToOwner); err != nil {
return nil, err
}
return p, nil
}
// OpenAsBuyer decrypts a reply with the thread key and verifies that it was
// signed by a device certified by the listing's author.
func (e *Envelope) OpenAsBuyer(t *ThreadKey) (*Plain, error) {
mailbox, err := t.Mailbox()
if err != nil {
return nil, err
}
if e.To != ToBuyer || e.Rcpt != mailbox {
return nil, errors.New("message: not addressed to this thread")
}
p, err := e.decrypt(t.k)
if err != nil {
return nil, err
}
if err := p.validate(ToBuyer); err != nil {
return nil, err
}
if p.Thread != t.PublicHex() {
return nil, errors.New("message: reply belongs to another thread")
}
if *p.Listing != e.Listing {
return nil, errors.New("message: reply refers to another listing")
}
if err := p.verifyOwner(); err != nil {
return nil, err
}
return p, nil
}
// decrypt opens the envelope and decodes the plaintext strictly: it must be
// the canonical encoding of a Plain, so nothing unknown hides in it.
func (e *Envelope) decrypt(sk *ecdh.PrivateKey) (*Plain, error) {
aad, err := e.headerBytes()
if err != nil {
return nil, err
}
ct, err := hex.DecodeString(e.CT)
if err != nil {
return nil, errors.New("message: bad ciphertext")
}
body, err := open(sk, e.EPK, aad, ct)
if err != nil {
return nil, err
}
return decodePlain(body)
}
// ThreadKey is a buyer's per-thread X25519 key pair.
type ThreadKey struct{ k *ecdh.PrivateKey }
// NewThreadKey creates a fresh thread key.
func NewThreadKey() (*ThreadKey, error) {
k, err := x25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
return &ThreadKey{k}, nil
}
// ThreadKeyFromBytes restores a thread key from its 32 secret bytes.
func ThreadKeyFromBytes(b []byte) (*ThreadKey, error) {
k, err := x25519.NewPrivateKey(b)
if err != nil {
return nil, err
}
return &ThreadKey{k}, nil
}
// Bytes returns the secret key.
func (t *ThreadKey) Bytes() []byte { return t.k.Bytes() }
// PublicHex is the thread's public key, which identifies the thread.
func (t *ThreadKey) PublicHex() string { return hex.EncodeToString(t.k.PublicKey().Bytes()) }
// Mailbox is the tag replies for this thread are addressed to.
func (t *ThreadKey) Mailbox() (string, error) { return Mailbox(t.PublicHex()) }
// Mailbox derives the mailbox tag from a thread public key (hex): the first
// 16 bytes of sha256("allmende-mailbox-v1\n" || key), so the key itself never
// appears on the network.
func Mailbox(threadPubHex string) (string, error) {
pub, err := hex.DecodeString(threadPubHex)
if err != nil || len(pub) != 32 {
return "", errors.New("message: bad thread key")
}
sum := sha256.Sum256(append([]byte(mailboxContext), pub...))
return hex.EncodeToString(sum[:16]), nil
}
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
}