Implement end-to-end encrypted buyer/seller messaging
Wire format (internal/message): sealed boxes to the listing's device key (X25519 + HKDF + ChaCha20-Poly1305), padded, proof-of-work stamped, with signed owner replies and address grants. Relay validation, bounded queues, gossip on per-region message topics and sync (store, p2p). Owner side (internal/inbox, API): inbox with hidden link messages and a per-day new-thread limit, replies, grants, and a private per-listing address. Public POST/GET /api/v1/messages for buyers. Browser: noble-based sealing and reply verification checked against a Go fixture, contact form, conversation view, message list, de/en strings. Docs: PROTOCOL.md messaging section matches the implementation. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+31
-2
@@ -19,6 +19,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/inbox"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
@@ -39,10 +40,20 @@ type Config struct {
|
||||
Token string // admin bearer token; empty disables all writes
|
||||
Difficulty int
|
||||
Clock func() time.Time
|
||||
|
||||
// MessageDifficulty is reported to browsers so they can mine the
|
||||
// proof-of-work of the messages they send.
|
||||
MessageDifficulty int
|
||||
// PostsPerMinute limits envelopes accepted per client address; 0 means 30.
|
||||
PostsPerMinute int
|
||||
// Inbox is the owner's conversations. Without it the owner endpoints are
|
||||
// absent; relaying messages for buyers still works.
|
||||
Inbox *inbox.Inbox
|
||||
}
|
||||
|
||||
type server struct {
|
||||
Config
|
||||
limiter *limiter
|
||||
}
|
||||
|
||||
// New returns the HTTP handler.
|
||||
@@ -50,7 +61,10 @@ func New(cfg Config) http.Handler {
|
||||
if cfg.Clock == nil {
|
||||
cfg.Clock = time.Now
|
||||
}
|
||||
s := &server{cfg}
|
||||
if cfg.PostsPerMinute <= 0 {
|
||||
cfg.PostsPerMinute = defaultPostsPerMinute
|
||||
}
|
||||
s := &server{Config: cfg, limiter: newLimiter(cfg.PostsPerMinute, time.Minute, cfg.Clock)}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/v1/status", s.status)
|
||||
mux.HandleFunc("GET /api/v1/listings", s.search)
|
||||
@@ -58,6 +72,20 @@ func New(cfg Config) http.Handler {
|
||||
mux.HandleFunc("POST /api/v1/listings", s.admin(s.create))
|
||||
mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update))
|
||||
mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove))
|
||||
|
||||
// Messaging: public relay endpoints for buyers' browsers...
|
||||
mux.HandleFunc("POST /api/v1/messages", s.postMessage)
|
||||
mux.HandleFunc("GET /api/v1/messages", s.getMailbox)
|
||||
// ...and the owner's inbox and private address, behind the admin token.
|
||||
if cfg.Inbox != nil {
|
||||
mux.HandleFunc("GET /api/v1/inbox", s.admin(s.listThreads))
|
||||
mux.HandleFunc("GET /api/v1/inbox/{id}/{thread}", s.admin(s.getThread))
|
||||
mux.HandleFunc("POST /api/v1/inbox/{id}/{thread}", s.admin(s.reply))
|
||||
mux.HandleFunc("DELETE /api/v1/inbox/{id}/{thread}", s.admin(s.deleteThread))
|
||||
mux.HandleFunc("PUT /api/v1/listings/{id}/address", s.admin(s.putAddress))
|
||||
mux.HandleFunc("GET /api/v1/listings/{id}/address", s.admin(s.getAddress))
|
||||
mux.HandleFunc("DELETE /api/v1/listings/{id}/address", s.admin(s.deleteAddress))
|
||||
}
|
||||
mux.Handle("GET /", s.ui())
|
||||
return secure(mux)
|
||||
}
|
||||
@@ -106,7 +134,8 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
|
||||
"peers": s.Node.PeerCount(),
|
||||
"listings": n,
|
||||
// Lets the browser report how much anti-spam work a listing carries.
|
||||
"difficulty": s.Difficulty,
|
||||
"difficulty": s.Difficulty,
|
||||
"message_difficulty": s.MessageDifficulty,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/inbox"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
@@ -29,28 +30,37 @@ type fixture struct {
|
||||
dev *identity.Device
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T, tok string) *fixture {
|
||||
const msgDifficulty = 4
|
||||
|
||||
func newFixture(t *testing.T, tok string, tweak ...func(*Config)) *fixture {
|
||||
t.Helper()
|
||||
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})
|
||||
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty, MessageDifficulty: msgDifficulty})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
node, err := p2p.New(context.Background(), p2p.Config{
|
||||
Device: dev, Store: s, Regions: []string{"u1x"}, Difficulty: difficulty,
|
||||
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
MessageDifficulty: msgDifficulty,
|
||||
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(New(Config{
|
||||
cfg := Config{
|
||||
Store: s, Node: node, Device: dev, Regions: []string{"u1x"}, Token: tok, Difficulty: difficulty,
|
||||
}))
|
||||
MessageDifficulty: msgDifficulty,
|
||||
Inbox: &inbox.Inbox{Store: s, Device: dev, Publisher: node, Difficulty: msgDifficulty},
|
||||
}
|
||||
for _, f := range tweak {
|
||||
f(&cfg)
|
||||
}
|
||||
srv := httptest.NewServer(New(cfg))
|
||||
t.Cleanup(func() { srv.Close(); node.Close(); s.Close() })
|
||||
return &fixture{srv: srv, s: s, dev: dev}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/inbox"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPostsPerMinute = 30
|
||||
maxMailboxPage = 100
|
||||
)
|
||||
|
||||
// --- public relay endpoints -------------------------------------------------
|
||||
//
|
||||
// A browser-only buyer talks to the network through these: it posts an
|
||||
// encrypted envelope and polls its mailbox. The node sees only ciphertext.
|
||||
|
||||
func (s *server) postMessage(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.limiter.allow(clientIP(r)) {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
fail(w, http.StatusTooManyRequests, "too many messages from this address; try again in a minute")
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, message.MaxSize+1))
|
||||
if err != nil {
|
||||
fail(w, http.StatusRequestEntityTooLarge, "message too large")
|
||||
return
|
||||
}
|
||||
var e message.Envelope
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&e); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
// Only the canonical encoding travels, so everyone derives the same hash.
|
||||
if canon, err := e.Bytes(); err != nil || !bytes.Equal(canon, body) {
|
||||
fail(w, http.StatusBadRequest, "the envelope must be in canonical JSON form")
|
||||
return
|
||||
}
|
||||
region, err := s.Store.Region(r.Context(), e.Listing.Author, e.Listing.ID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
fail(w, http.StatusNotFound, "this node does not know that listing")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
if err := s.Node.PublishMessage(r.Context(), region, &e); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrInvalid):
|
||||
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), store.ErrInvalid.Error()+": "))
|
||||
case errors.Is(err, store.ErrNoListing):
|
||||
fail(w, http.StatusNotFound, "that listing is not live here (anymore), or its owner changed device")
|
||||
case errors.Is(err, store.ErrQueueFull):
|
||||
fail(w, http.StatusTooManyRequests, "the queue for this listing is full of messages with more proof-of-work; mine more and retry")
|
||||
default:
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
}
|
||||
return
|
||||
}
|
||||
h, _ := e.Hash()
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"hash": h})
|
||||
}
|
||||
|
||||
func (s *server) getMailbox(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
tag := q.Get("mailbox")
|
||||
if len(tag) != 32 || !isLowerHex(tag) {
|
||||
fail(w, http.StatusBadRequest, "mailbox must be 32 hex characters")
|
||||
return
|
||||
}
|
||||
var since int64
|
||||
if v := q.Get("since"); v != "" {
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil || n < 0 {
|
||||
fail(w, http.StatusBadRequest, "since must be a non-negative integer")
|
||||
return
|
||||
}
|
||||
since = n
|
||||
}
|
||||
limit := maxMailboxPage
|
||||
if v := q.Get("limit"); v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 1 || n > maxMailboxPage {
|
||||
fail(w, http.StatusBadRequest, "limit must be 1-100")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
items, err := s.Store.Mailbox(r.Context(), tag, since, limit)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
// Ciphertext addressed by an unguessable tag: any site may read it, but it
|
||||
// must not be cached, or a reply would show up late.
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte("["))
|
||||
for i, e := range items {
|
||||
b, err := e.Bytes()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if i > 0 {
|
||||
w.Write([]byte(","))
|
||||
}
|
||||
w.Write(b)
|
||||
}
|
||||
w.Write([]byte("]"))
|
||||
}
|
||||
|
||||
func isLowerHex(s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// --- the owner's inbox (admin token) ------------------------------------------
|
||||
|
||||
type threadView struct {
|
||||
Listing string `json:"listing"`
|
||||
Thread string `json:"thread"`
|
||||
Messages int `json:"messages"`
|
||||
Hidden int `json:"hidden"`
|
||||
Replied bool `json:"replied"`
|
||||
FirstAt int64 `json:"first_at"`
|
||||
LastAt int64 `json:"last_at"`
|
||||
}
|
||||
|
||||
func (s *server) listThreads(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := s.Inbox.Collect(r.Context()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
threads, err := s.Store.Threads(r.Context(), s.Device.Cert.Author)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
out := make([]threadView, 0, len(threads))
|
||||
for _, t := range threads {
|
||||
out = append(out, threadView{t.Listing.ID, t.Thread, t.Messages, t.Hidden, t.Replied, t.FirstAt, t.LastAt})
|
||||
}
|
||||
noStore(w)
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
type messageView struct {
|
||||
Hash string `json:"hash"`
|
||||
Dir string `json:"dir"`
|
||||
Hidden bool `json:"hidden,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
ReceivedAt int64 `json:"received_at"`
|
||||
Type string `json:"type"`
|
||||
N int64 `json:"n"`
|
||||
SentAt int64 `json:"sent_at"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Address string `json:"address,omitempty"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
ValidUntil int64 `json:"valid_until,omitempty"`
|
||||
}
|
||||
|
||||
func (s *server) getThread(w http.ResponseWriter, r *http.Request) {
|
||||
ref, thread, ok := s.threadRef(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := s.Inbox.Collect(r.Context()); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
msgs, err := s.Store.ThreadMessages(r.Context(), ref, thread)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
if len(msgs) == 0 {
|
||||
fail(w, http.StatusNotFound, "no such conversation")
|
||||
return
|
||||
}
|
||||
out := make([]messageView, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
p := m.Plain
|
||||
v := messageView{Hash: m.Hash, Dir: m.Dir, ReceivedAt: m.ReceivedAt, Type: p.Type, N: p.N, SentAt: p.SentAt,
|
||||
Text: p.Text, Address: p.Address, Phone: p.Phone, Email: p.Email, Note: p.Note, ValidUntil: p.ValidUntil}
|
||||
if m.Hidden {
|
||||
// Withheld: the buyer broke the first-message rules (a link, or too long).
|
||||
v.Hidden, v.Reason, v.Text = true, "a first message must be short and contain no links", ""
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
noStore(w)
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
type replyBody struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Address string `json:"address"`
|
||||
Phone string `json:"phone"`
|
||||
Email string `json:"email"`
|
||||
Note string `json:"note"`
|
||||
ValidDays int `json:"valid_days"`
|
||||
}
|
||||
|
||||
func (s *server) reply(w http.ResponseWriter, r *http.Request) {
|
||||
ref, thread, ok := s.threadRef(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var b replyBody
|
||||
if !decodeBody(w, r, &b) {
|
||||
return
|
||||
}
|
||||
env, err := s.Inbox.Send(r.Context(), ref, thread, inbox.Reply{
|
||||
Type: b.Type, Text: b.Text, Address: b.Address, Phone: b.Phone, Email: b.Email, Note: b.Note, ValidDays: b.ValidDays,
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
h, _ := env.Hash()
|
||||
writeJSON(w, http.StatusOK, map[string]string{"hash": h})
|
||||
case errors.Is(err, inbox.ErrNoThread), errors.Is(err, inbox.ErrNotOwner):
|
||||
fail(w, http.StatusNotFound, "no such conversation")
|
||||
case errors.Is(err, inbox.ErrInvalid):
|
||||
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), inbox.ErrInvalid.Error()+": "))
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
fail(w, http.StatusConflict, "the listing is gone, so the reply cannot be routed")
|
||||
default:
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) deleteThread(w http.ResponseWriter, r *http.Request) {
|
||||
ref, thread, ok := s.threadRef(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
found, err := s.Store.DeleteThread(r.Context(), ref, thread)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
fail(w, http.StatusNotFound, "no such conversation")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// threadRef reads {id} and {thread} from the path. The listing is always the
|
||||
// node's own: the inbox holds nobody else's conversations.
|
||||
func (s *server) threadRef(w http.ResponseWriter, r *http.Request) (message.Ref, string, bool) {
|
||||
id, thread := r.PathValue("id"), r.PathValue("thread")
|
||||
if len(id) != 32 || !isLowerHex(id) || len(thread) != 64 || !isLowerHex(thread) {
|
||||
fail(w, http.StatusBadRequest, "malformed listing id or thread")
|
||||
return message.Ref{}, "", false
|
||||
}
|
||||
return message.Ref{Author: s.Device.Cert.Author, ID: id}, thread, true
|
||||
}
|
||||
|
||||
// --- the exact address (admin token) ------------------------------------------
|
||||
|
||||
func (s *server) putAddress(w http.ResponseWriter, r *http.Request) {
|
||||
l, ok := s.own(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var a store.Address
|
||||
if !decodeBody(w, r, &a) {
|
||||
return
|
||||
}
|
||||
for _, f := range []struct {
|
||||
name, v string
|
||||
min, max int
|
||||
nl bool
|
||||
}{
|
||||
{"address", a.Address, 1, message.MaxAddress, true},
|
||||
{"phone", a.Phone, 0, message.MaxPhone, false},
|
||||
{"email", a.Email, 0, message.MaxEmail, false},
|
||||
} {
|
||||
if len(f.v) > f.max {
|
||||
fail(w, http.StatusBadRequest, f.name+" is too long")
|
||||
return
|
||||
}
|
||||
if err := listing.ValidText(f.v, f.min, f.max, f.nl); err != nil {
|
||||
fail(w, http.StatusBadRequest, f.name+": "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.Store.SetAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID}, a); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *server) getAddress(w http.ResponseWriter, r *http.Request) {
|
||||
l, ok := s.own(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
a, err := s.Store.GetAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID})
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
fail(w, http.StatusNotFound, "no address saved for this listing")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
noStore(w)
|
||||
writeJSON(w, http.StatusOK, a)
|
||||
}
|
||||
|
||||
func (s *server) deleteAddress(w http.ResponseWriter, r *http.Request) {
|
||||
l, ok := s.own(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.Store.DeleteAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID}); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// --- helpers ------------------------------------------------------------------
|
||||
|
||||
func noStore(w http.ResponseWriter) { w.Header().Set("Cache-Control", "no-store") }
|
||||
|
||||
// decodeBody reads a small JSON object strictly: no unknown fields, no
|
||||
// trailing data.
|
||||
func decodeBody(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
|
||||
return false
|
||||
}
|
||||
if _, err := dec.Token(); err != io.EOF {
|
||||
fail(w, http.StatusBadRequest, "unexpected data after JSON body")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// clientIP is the peer address of the connection. Forwarding headers are not
|
||||
// trusted: they are trivial to forge. Behind a reverse proxy every client then
|
||||
// shares one allowance, which is the safe failure.
|
||||
func clientIP(r *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
// limiter allows each key a number of events per fixed window.
|
||||
type limiter struct {
|
||||
mu sync.Mutex
|
||||
limit int
|
||||
window time.Duration
|
||||
clock func() time.Time
|
||||
hits map[string]*bucket
|
||||
}
|
||||
|
||||
type bucket struct {
|
||||
start time.Time
|
||||
n int
|
||||
}
|
||||
|
||||
func newLimiter(limit int, window time.Duration, clock func() time.Time) *limiter {
|
||||
return &limiter{limit: limit, window: window, clock: clock, hits: map[string]*bucket{}}
|
||||
}
|
||||
|
||||
func (l *limiter) allow(key string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := l.clock()
|
||||
if len(l.hits) > 10000 { // forget idle clients
|
||||
for k, b := range l.hits {
|
||||
if now.Sub(b.start) >= l.window {
|
||||
delete(l.hits, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
b := l.hits[key]
|
||||
if b == nil || now.Sub(b.start) >= l.window {
|
||||
l.hits[key] = &bucket{start: now, n: 1}
|
||||
return true
|
||||
}
|
||||
if b.n >= l.limit {
|
||||
return false
|
||||
}
|
||||
b.n++
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
func (f *fixture) publish(t *testing.T) *listing.Listing {
|
||||
t.Helper()
|
||||
code, body := f.do(t, "POST", "/api/v1/listings", draftJSON, true)
|
||||
if code != 200 {
|
||||
t.Fatalf("create: %d %s", code, body)
|
||||
}
|
||||
var l listing.Listing
|
||||
if err := json.Unmarshal(body, &l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &l
|
||||
}
|
||||
|
||||
// send posts an envelope the way a buyer's browser does (no token).
|
||||
func (f *fixture) send(t *testing.T, e *message.Envelope) (int, []byte) {
|
||||
t.Helper()
|
||||
b, err := e.Bytes()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return f.sendRaw(t, b)
|
||||
}
|
||||
|
||||
func (f *fixture) sendRaw(t *testing.T, b []byte) (int, []byte) {
|
||||
t.Helper()
|
||||
resp, err := http.Post(f.srv.URL+"/api/v1/messages", "application/json", bytes.NewReader(b))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var buf bytes.Buffer
|
||||
buf.ReadFrom(resp.Body)
|
||||
return resp.StatusCode, buf.Bytes()
|
||||
}
|
||||
|
||||
func buyerHello(t *testing.T, l *listing.Listing, tk *message.ThreadKey, text string) *message.Envelope {
|
||||
t.Helper()
|
||||
p := &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: text}
|
||||
e, err := message.SealToOwner(l, tk, p, time.Now(), msgDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func newThread(t *testing.T) *message.ThreadKey {
|
||||
t.Helper()
|
||||
tk, err := message.NewThreadKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tk
|
||||
}
|
||||
|
||||
func TestMessagingOverHTTP(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
tk := newThread(t)
|
||||
thread := tk.PublicHex()
|
||||
|
||||
// 1. The buyer's browser posts an encrypted envelope. No token.
|
||||
code, body := f.send(t, buyerHello(t, l, tk, "Ist die Wohnung noch frei?"))
|
||||
if code != http.StatusAccepted || !bytes.Contains(body, []byte(`"hash"`)) {
|
||||
t.Fatalf("post: %d %s", code, body)
|
||||
}
|
||||
|
||||
// 2. The owner sees one conversation, with the decrypted text.
|
||||
code, body = f.do(t, "GET", "/api/v1/inbox", "", true)
|
||||
var threads []threadView
|
||||
if code != 200 || json.Unmarshal([]byte(body), &threads) != nil || len(threads) != 1 {
|
||||
t.Fatalf("inbox: %d %s", code, body)
|
||||
}
|
||||
if threads[0].Listing != l.ID || threads[0].Thread != thread || threads[0].Replied || threads[0].Messages != 1 {
|
||||
t.Fatalf("thread summary: %+v", threads[0])
|
||||
}
|
||||
path := "/api/v1/inbox/" + l.ID + "/" + thread
|
||||
code, body = f.do(t, "GET", path, "", true)
|
||||
var msgs []messageView
|
||||
if code != 200 || json.Unmarshal([]byte(body), &msgs) != nil || len(msgs) != 1 || msgs[0].Text != "Ist die Wohnung noch frei?" || msgs[0].Dir != "in" {
|
||||
t.Fatalf("thread: %d %s", code, body)
|
||||
}
|
||||
|
||||
// 3. The owner answers with text, then saves the address and grants it.
|
||||
if code, body = f.do(t, "POST", path, `{"type":"text","text":"Ja, noch frei."}`, true); code != 200 {
|
||||
t.Fatalf("reply: %d %s", code, body)
|
||||
}
|
||||
if code, body = f.do(t, "PUT", "/api/v1/listings/"+l.ID+"/address",
|
||||
`{"address":"Musterstraße 12, 20255 Hamburg","phone":"+49 40 1"}`, true); code != 204 {
|
||||
t.Fatalf("put address: %d %s", code, body)
|
||||
}
|
||||
if code, body = f.do(t, "POST", path,
|
||||
`{"type":"grant","note":"Samstag 10 Uhr, bitte zweimal klingeln","valid_days":3}`, true); code != 200 {
|
||||
t.Fatalf("grant: %d %s", code, body)
|
||||
}
|
||||
|
||||
// 4. The buyer polls its mailbox and decrypts both, verified as the owner's.
|
||||
mb, _ := tk.Mailbox()
|
||||
resp, err := http.Get(f.srv.URL + "/api/v1/messages?mailbox=" + mb)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 || resp.Header.Get("Cache-Control") != "no-store" || resp.Header.Get("Access-Control-Allow-Origin") != "*" {
|
||||
t.Fatalf("mailbox headers: %d %v", resp.StatusCode, resp.Header)
|
||||
}
|
||||
var box []message.Envelope
|
||||
if err := json.NewDecoder(resp.Body).Decode(&box); err != nil || len(box) != 2 {
|
||||
t.Fatalf("mailbox: %d envelopes, %v", len(box), err)
|
||||
}
|
||||
var sawText, sawGrant bool
|
||||
for i := range box {
|
||||
p, err := box[i].OpenAsBuyer(tk)
|
||||
if err != nil {
|
||||
t.Fatalf("buyer cannot open a reply: %v", err)
|
||||
}
|
||||
switch p.Type {
|
||||
case message.TypeText:
|
||||
sawText = p.Text == "Ja, noch frei."
|
||||
case message.TypeGrant:
|
||||
sawGrant = p.Address == "Musterstraße 12, 20255 Hamburg" && p.Phone == "+49 40 1" &&
|
||||
p.Note == "Samstag 10 Uhr, bitte zweimal klingeln"
|
||||
}
|
||||
}
|
||||
if !sawText || !sawGrant {
|
||||
t.Fatalf("text=%v grant=%v", sawText, sawGrant)
|
||||
}
|
||||
|
||||
// The owner's view now shows the replies too and marks the thread answered.
|
||||
_, body = f.do(t, "GET", "/api/v1/inbox", "", true)
|
||||
_ = json.Unmarshal([]byte(body), &threads)
|
||||
if !threads[0].Replied || threads[0].Messages != 3 {
|
||||
t.Fatalf("after replying: %+v", threads[0])
|
||||
}
|
||||
|
||||
// 5. Erasing the conversation removes it from the node.
|
||||
if code, _ = f.do(t, "DELETE", path, "", true); code != 204 {
|
||||
t.Fatalf("delete: %d", code)
|
||||
}
|
||||
if code, _ = f.do(t, "GET", path, "", true); code != 404 {
|
||||
t.Fatalf("deleted thread still served: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHiddenFirstMessageTextIsWithheld(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
tk := newThread(t)
|
||||
if code, body := f.send(t, buyerHello(t, l, tk, "Hier: https://example.com/kaution")); code != 202 {
|
||||
t.Fatalf("post: %d %s", code, body)
|
||||
}
|
||||
code, body := f.do(t, "GET", "/api/v1/inbox/"+l.ID+"/"+tk.PublicHex(), "", true)
|
||||
if code != 200 || bytes.Contains(body, []byte("example.com")) {
|
||||
t.Fatalf("the link text must not be served: %d %s", code, body)
|
||||
}
|
||||
var msgs []messageView
|
||||
_ = json.Unmarshal([]byte(body), &msgs)
|
||||
if len(msgs) != 1 || !msgs[0].Hidden || msgs[0].Reason == "" {
|
||||
t.Fatalf("message should be marked hidden: %+v", msgs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostingRules(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
good := buyerHello(t, l, newThread(t), "hallo")
|
||||
goodBytes, _ := good.Bytes()
|
||||
|
||||
// Not canonical: same content, different spelling.
|
||||
var pretty bytes.Buffer
|
||||
_ = json.Indent(&pretty, goodBytes, "", " ")
|
||||
for name, tc := range map[string]struct {
|
||||
body []byte
|
||||
want int
|
||||
}{
|
||||
"not JSON": {[]byte("hello"), 400},
|
||||
"not canonical": {pretty.Bytes(), 400},
|
||||
"unknown field": {bytes.Replace(goodBytes, []byte(`{"created_at"`), []byte(`{"extra":1,"created_at"`), 1), 400},
|
||||
"too large": {bytes.Repeat([]byte("a"), message.MaxSize+100), 413},
|
||||
"empty": {nil, 400},
|
||||
"unknown listing": {func() []byte {
|
||||
other := *l
|
||||
other.ID = strings.Repeat("ab", 16)
|
||||
e := buyerHello(t, &other, newThread(t), "x")
|
||||
b, _ := e.Bytes()
|
||||
return b
|
||||
}(), 404},
|
||||
"weak work": {func() []byte {
|
||||
for {
|
||||
e, err := message.SealToOwner(l, newThread(t), &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: "x"}, time.Now(), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, _ := e.Work(); w < msgDifficulty {
|
||||
b, _ := e.Bytes()
|
||||
return b
|
||||
}
|
||||
}
|
||||
}(), 400},
|
||||
} {
|
||||
if code, body := f.sendRaw(t, tc.body); code != tc.want {
|
||||
t.Errorf("%s: %d %s, want %d", name, code, body, tc.want)
|
||||
}
|
||||
}
|
||||
if code, body := f.sendRaw(t, goodBytes); code != 202 {
|
||||
t.Fatalf("the valid one: %d %s", code, body)
|
||||
}
|
||||
// Posting it again is harmless.
|
||||
if code, _ := f.sendRaw(t, goodBytes); code != 202 {
|
||||
t.Fatalf("duplicate: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostingIsRateLimited(t *testing.T) {
|
||||
f := newFixture(t, token, func(c *Config) { c.PostsPerMinute = 3 })
|
||||
l := f.publish(t)
|
||||
for i := 0; i < 3; i++ {
|
||||
if code, body := f.send(t, buyerHello(t, l, newThread(t), "hallo")); code != 202 {
|
||||
t.Fatalf("post %d: %d %s", i, code, body)
|
||||
}
|
||||
}
|
||||
resp, err := http.Post(f.srv.URL+"/api/v1/messages", "application/json", strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != 429 || resp.Header.Get("Retry-After") == "" {
|
||||
t.Fatalf("fourth post: %d retry-after=%q", resp.StatusCode, resp.Header.Get("Retry-After"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailboxQueryIsValidated(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
for _, q := range []string{
|
||||
"", "?mailbox=zz", "?mailbox=" + strings.Repeat("A", 32), "?mailbox=" + strings.Repeat("0", 31),
|
||||
"?mailbox=" + strings.Repeat("0", 32) + "&since=-1", "?mailbox=" + strings.Repeat("0", 32) + "&limit=0",
|
||||
"?mailbox=" + strings.Repeat("0", 32) + "&limit=1000", "?mailbox=" + strings.Repeat("0", 32) + "&since=abc",
|
||||
} {
|
||||
if code, _ := f.do(t, "GET", "/api/v1/messages"+q, "", false); code != 400 {
|
||||
t.Errorf("%q: %d, want 400", q, code)
|
||||
}
|
||||
}
|
||||
code, body := f.do(t, "GET", "/api/v1/messages?mailbox="+strings.Repeat("0", 32), "", false)
|
||||
if code != 200 || string(body) != "[]" {
|
||||
t.Fatalf("empty mailbox: %d %s", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnerEndpointsNeedTheToken(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
thread := strings.Repeat("ab", 32)
|
||||
for _, c := range []struct{ method, path string }{
|
||||
{"GET", "/api/v1/inbox"},
|
||||
{"GET", "/api/v1/inbox/" + l.ID + "/" + thread},
|
||||
{"POST", "/api/v1/inbox/" + l.ID + "/" + thread},
|
||||
{"DELETE", "/api/v1/inbox/" + l.ID + "/" + thread},
|
||||
{"PUT", "/api/v1/listings/" + l.ID + "/address"},
|
||||
{"GET", "/api/v1/listings/" + l.ID + "/address"},
|
||||
{"DELETE", "/api/v1/listings/" + l.ID + "/address"},
|
||||
} {
|
||||
if code, _ := f.do(t, c.method, c.path, "{}", false); code != 401 {
|
||||
t.Errorf("%s %s without token: %d, want 401", c.method, c.path, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplyErrors(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
tk := newThread(t)
|
||||
f.send(t, buyerHello(t, l, tk, "hallo"))
|
||||
path := "/api/v1/inbox/" + l.ID + "/" + tk.PublicHex()
|
||||
f.do(t, "GET", "/api/v1/inbox", "", true) // collect
|
||||
|
||||
for name, c := range map[string]struct {
|
||||
path, body string
|
||||
want int
|
||||
}{
|
||||
"unknown thread": {"/api/v1/inbox/" + l.ID + "/" + strings.Repeat("ab", 32), `{"type":"text","text":"x"}`, 404},
|
||||
"malformed thread": {"/api/v1/inbox/" + l.ID + "/xyz", `{"type":"text","text":"x"}`, 400},
|
||||
"unknown field": {path, `{"type":"text","text":"x","bogus":1}`, 400},
|
||||
"grant with no address": {path, `{"type":"grant"}`, 400},
|
||||
"grant for 31 days": {path, `{"type":"grant","address":"Weg 1","valid_days":31}`, 400},
|
||||
"empty text": {path, `{"type":"text","text":""}`, 400},
|
||||
"unknown type": {path, `{"type":"image"}`, 400},
|
||||
"text over the limit": {path, `{"type":"text","text":"` + strings.Repeat("a", message.MaxText+1) + `"}`, 400},
|
||||
"trailing data": {path, `{"type":"text","text":"x"} {}`, 400},
|
||||
"someone else's listing": {"/api/v1/inbox/" + strings.Repeat("cd", 16) + "/" + tk.PublicHex(), `{"type":"text","text":"x"}`, 404},
|
||||
} {
|
||||
if code, body := f.do(t, "POST", c.path, c.body, true); code != c.want {
|
||||
t.Errorf("%s: %d %s, want %d", name, code, body, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddressEndpoints(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
path := "/api/v1/listings/" + l.ID + "/address"
|
||||
|
||||
if code, _ := f.do(t, "GET", path, "", true); code != 404 {
|
||||
t.Fatalf("before saving: %d", code)
|
||||
}
|
||||
if code, body := f.do(t, "PUT", path, `{"address":"Weg 1, 20095 Hamburg","email":"a@example.com"}`, true); code != 204 {
|
||||
t.Fatalf("put: %d %s", code, body)
|
||||
}
|
||||
code, body := f.do(t, "GET", path, "", true)
|
||||
if code != 200 || !strings.Contains(string(body), "Weg 1") || !strings.Contains(string(body), "a@example.com") {
|
||||
t.Fatalf("get: %d %s", code, body)
|
||||
}
|
||||
// The exact address is nowhere on the public side.
|
||||
if _, pub := f.do(t, "GET", "/api/v1/listings/"+l.Author+"/"+l.ID, "", false); strings.Contains(string(pub), "Weg 1") {
|
||||
t.Fatal("the address leaked into the public listing")
|
||||
}
|
||||
if code, _ := f.do(t, "PUT", path, `{"address":""}`, true); code != 400 {
|
||||
t.Errorf("empty address: %d", code)
|
||||
}
|
||||
if code, _ := f.do(t, "PUT", path, `{"address":"`+strings.Repeat("a", message.MaxAddress+1)+`"}`, true); code != 400 {
|
||||
t.Errorf("long address: %d", code)
|
||||
}
|
||||
if code, _ := f.do(t, "PUT", "/api/v1/listings/"+strings.Repeat("cd", 16)+"/address", `{"address":"x"}`, true); code != 404 {
|
||||
t.Errorf("someone else's listing: %d", code)
|
||||
}
|
||||
if code, _ := f.do(t, "DELETE", path, "", true); code != 204 {
|
||||
t.Fatalf("delete: %d", code)
|
||||
}
|
||||
if code, _ := f.do(t, "GET", path, "", true); code != 404 {
|
||||
t.Fatalf("address survived deletion: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusReportsMessageDifficulty(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
_, body := f.do(t, "GET", "/api/v1/status", "", false)
|
||||
var st map[string]any
|
||||
_ = json.Unmarshal(body, &st)
|
||||
if st["message_difficulty"] != float64(msgDifficulty) {
|
||||
t.Fatalf("message_difficulty = %v", st["message_difficulty"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// Package inbox is the owner's side of messaging: it collects the encrypted
|
||||
// envelopes the network holds for the owner's listings, decrypts them with the
|
||||
// device key, keeps the conversations, and sends replies and address grants.
|
||||
//
|
||||
// Everything here stays on the owner's node. Relays only ever see ciphertext.
|
||||
package inbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultMaxNewThreads is how many conversations a listing can start per
|
||||
// day before further first messages wait.
|
||||
DefaultMaxNewThreads = 20
|
||||
// DefaultGrantDays is how long an address grant is shown to the buyer.
|
||||
DefaultGrantDays = 7
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNoThread means no such conversation exists.
|
||||
ErrNoThread = errors.New("inbox: no such conversation")
|
||||
// ErrNotOwner means the listing belongs to another author.
|
||||
ErrNotOwner = errors.New("inbox: not this node's listing")
|
||||
// ErrInvalid wraps a reply that cannot be sent as given (the caller's
|
||||
// mistake, as opposed to a failure of the node).
|
||||
ErrInvalid = errors.New("inbox: invalid reply")
|
||||
)
|
||||
|
||||
// Publisher sends an envelope into the network (p2p.Node implements it).
|
||||
type Publisher interface {
|
||||
PublishMessage(ctx context.Context, region string, e *message.Envelope) error
|
||||
}
|
||||
|
||||
// Inbox belongs to one device.
|
||||
type Inbox struct {
|
||||
Store *store.Store
|
||||
Device *identity.Device
|
||||
Publisher Publisher
|
||||
|
||||
// Difficulty is the proof-of-work of the replies this node sends.
|
||||
Difficulty int
|
||||
// MaxNewThreads is the per-listing, per-24-hours limit on new
|
||||
// conversations; 0 means DefaultMaxNewThreads.
|
||||
MaxNewThreads int
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
func (i *Inbox) now() time.Time {
|
||||
if i.Clock != nil {
|
||||
return i.Clock()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func (i *Inbox) maxNewThreads() int {
|
||||
if i.MaxNewThreads > 0 {
|
||||
return i.MaxNewThreads
|
||||
}
|
||||
return DefaultMaxNewThreads
|
||||
}
|
||||
|
||||
type candidate struct {
|
||||
hash string
|
||||
env *message.Envelope
|
||||
plain *message.Plain
|
||||
work int
|
||||
}
|
||||
|
||||
type threadKey struct {
|
||||
ref message.Ref
|
||||
thread string
|
||||
}
|
||||
|
||||
// Collect reads the envelopes the node holds for the owner's listings,
|
||||
// decrypts the ones it has not seen and files them into conversations. It
|
||||
// returns how many messages were added.
|
||||
//
|
||||
// Two owner-side rules are applied here, because relays cannot see content:
|
||||
// - until the owner has replied, a buyer's message must be short and free of
|
||||
// links; a violating message is kept but hidden;
|
||||
// - at most MaxNewThreads new conversations per listing start every 24
|
||||
// hours. Surplus first messages stay queued, unread, until there is room
|
||||
// (strongest proof-of-work first, then oldest) or they expire.
|
||||
func (i *Inbox) Collect(ctx context.Context) (int, error) {
|
||||
envs, err := i.Store.OwnerMessages(ctx, i.Device.Cert.Author)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
hashes := make([]string, len(envs))
|
||||
for k, e := range envs {
|
||||
if hashes[k], err = e.Hash(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
seen, err := i.Store.SeenEnvelopes(ctx, hashes)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var known []candidate
|
||||
fresh := map[threadKey][]candidate{}
|
||||
for k, e := range envs {
|
||||
h := hashes[k]
|
||||
if seen[h] {
|
||||
continue
|
||||
}
|
||||
p, err := e.OpenAsOwner(i.Device)
|
||||
if err != nil {
|
||||
// Not for this device, damaged, or malformed: never look again.
|
||||
if err := i.Store.MarkSeen(ctx, h, e.ExpiresAt); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
work, _ := e.Work()
|
||||
c := candidate{hash: h, env: e, plain: p, work: work}
|
||||
key := threadKey{e.Listing, p.Thread}
|
||||
exists, err := i.Store.HasThread(ctx, e.Listing, p.Thread)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if exists {
|
||||
known = append(known, c)
|
||||
} else {
|
||||
fresh[key] = append(fresh[key], c)
|
||||
}
|
||||
}
|
||||
|
||||
added := 0
|
||||
admit := func(cs []candidate) error {
|
||||
sort.Slice(cs, func(a, b int) bool {
|
||||
if cs[a].plain.SentAt != cs[b].plain.SentAt {
|
||||
return cs[a].plain.SentAt < cs[b].plain.SentAt
|
||||
}
|
||||
return cs[a].plain.N < cs[b].plain.N
|
||||
})
|
||||
for _, c := range cs {
|
||||
if err := i.file(ctx, c); err != nil {
|
||||
return err
|
||||
}
|
||||
added++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := admit(known); err != nil {
|
||||
return added, err
|
||||
}
|
||||
|
||||
// New conversations, strongest first, within each listing's daily budget.
|
||||
byListing := map[message.Ref][]threadKey{}
|
||||
for key := range fresh {
|
||||
byListing[key.ref] = append(byListing[key.ref], key)
|
||||
}
|
||||
since := i.now().Add(-24 * time.Hour).Unix()
|
||||
for ref, keys := range byListing {
|
||||
used, err := i.Store.NewThreadsSince(ctx, ref, since)
|
||||
if err != nil {
|
||||
return added, err
|
||||
}
|
||||
room := i.maxNewThreads() - used
|
||||
strength := func(k threadKey) (work int, oldest int64) {
|
||||
oldest = 1<<62 - 1
|
||||
for _, c := range fresh[k] {
|
||||
if c.work > work {
|
||||
work = c.work
|
||||
}
|
||||
if c.env.CreatedAt < oldest {
|
||||
oldest = c.env.CreatedAt
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
sort.Slice(keys, func(a, b int) bool {
|
||||
wa, oa := strength(keys[a])
|
||||
wb, ob := strength(keys[b])
|
||||
if wa != wb {
|
||||
return wa > wb
|
||||
}
|
||||
if oa != ob {
|
||||
return oa < ob
|
||||
}
|
||||
return keys[a].thread < keys[b].thread
|
||||
})
|
||||
for k := 0; k < len(keys) && k < room; k++ {
|
||||
if err := admit(fresh[keys[k]]); err != nil {
|
||||
return added, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return added, nil
|
||||
}
|
||||
|
||||
func (i *Inbox) file(ctx context.Context, c candidate) error {
|
||||
replied, err := i.Store.Replied(ctx, c.env.Listing, c.plain.Thread)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hidden := !replied && c.plain.CheckBuyerFirst() != nil
|
||||
return i.Store.AddInbox(ctx, store.InboxMessage{
|
||||
Hash: c.hash, Listing: c.env.Listing, Thread: c.plain.Thread, Dir: store.InboxIn,
|
||||
Plain: c.plain, Hidden: hidden, ReceivedAt: i.now().Unix(),
|
||||
}, c.env.ExpiresAt)
|
||||
}
|
||||
|
||||
// Reply is what the owner sends back.
|
||||
type Reply struct {
|
||||
Type string // message.TypeText or message.TypeGrant
|
||||
|
||||
Text string // text
|
||||
|
||||
// Grant fields. Address, Phone and Email default to the values saved for
|
||||
// the listing when left empty.
|
||||
Address, Phone, Email, Note string
|
||||
ValidDays int // 0 means DefaultGrantDays
|
||||
}
|
||||
|
||||
// Send signs a reply, publishes it to the buyer's mailbox and records it in
|
||||
// the conversation.
|
||||
func (i *Inbox) Send(ctx context.Context, ref message.Ref, thread string, r Reply) (*message.Envelope, error) {
|
||||
if ref.Author != i.Device.Cert.Author {
|
||||
return nil, ErrNotOwner
|
||||
}
|
||||
ok, err := i.Store.HasThread(ctx, ref, thread)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNoThread
|
||||
}
|
||||
region, err := i.Store.Region(ctx, ref.Author, ref.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inbox: the listing is gone, so the reply cannot be routed: %w", err)
|
||||
}
|
||||
n, err := i.Store.NextOut(ctx, ref, thread)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := i.now()
|
||||
p := &message.Plain{Type: r.Type, Thread: thread, N: n, SentAt: now.Unix()}
|
||||
|
||||
switch r.Type {
|
||||
case message.TypeText:
|
||||
p.Text = r.Text
|
||||
case message.TypeGrant:
|
||||
p.Address, p.Phone, p.Email, p.Note = r.Address, r.Phone, r.Email, r.Note
|
||||
if p.Address == "" {
|
||||
saved, err := i.Store.GetAddress(ctx, ref)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil, fmt.Errorf("%w: no address given and none saved for this listing", ErrInvalid)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Address = saved.Address
|
||||
if p.Phone == "" {
|
||||
p.Phone = saved.Phone
|
||||
}
|
||||
if p.Email == "" {
|
||||
p.Email = saved.Email
|
||||
}
|
||||
}
|
||||
days := r.ValidDays
|
||||
if days == 0 {
|
||||
days = DefaultGrantDays
|
||||
}
|
||||
if days < 0 || time.Duration(days)*24*time.Hour > message.MaxGrantValidity {
|
||||
return nil, fmt.Errorf("%w: valid_days must be between 1 and 30", ErrInvalid)
|
||||
}
|
||||
p.ValidUntil = now.Add(time.Duration(days) * 24 * time.Hour).Unix()
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: unknown reply type %q", ErrInvalid, r.Type)
|
||||
}
|
||||
|
||||
env, err := message.SealToBuyer(i.Device, ref, p, now, i.Difficulty)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrInvalid, err)
|
||||
}
|
||||
if err := i.Publisher.PublishMessage(ctx, region, env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h, err := env.Hash()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = i.Store.AddInbox(ctx, store.InboxMessage{
|
||||
Hash: h, Listing: ref, Thread: thread, Dir: store.InboxOut, Plain: p, ReceivedAt: now.Unix(),
|
||||
}, env.ExpiresAt)
|
||||
return env, err
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package inbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
listingDifficulty = 6
|
||||
msgDifficulty = 4
|
||||
region = "u1x"
|
||||
)
|
||||
|
||||
var (
|
||||
ctx = context.Background()
|
||||
t0 = time.Unix(1_800_000_000, 0)
|
||||
)
|
||||
|
||||
// relay stands in for the network: it stores what the owner publishes, like
|
||||
// a gateway would.
|
||||
type relay struct {
|
||||
st *store.Store
|
||||
sent []*message.Envelope
|
||||
fail error
|
||||
}
|
||||
|
||||
func (r *relay) PublishMessage(ctx context.Context, region string, e *message.Envelope) error {
|
||||
if r.fail != nil {
|
||||
return r.fail
|
||||
}
|
||||
if _, err := r.st.PutMessage(ctx, region, e); err != nil {
|
||||
return err
|
||||
}
|
||||
r.sent = append(r.sent, e)
|
||||
return nil
|
||||
}
|
||||
|
||||
type fixture struct {
|
||||
t *testing.T
|
||||
now time.Time
|
||||
st *store.Store
|
||||
dev *identity.Device
|
||||
relay *relay
|
||||
in *Inbox
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T, maxNew int) *fixture {
|
||||
t.Helper()
|
||||
f := &fixture{t: t, now: t0}
|
||||
root, _, _ := identity.NewRoot()
|
||||
dev, err := identity.Enroll(root, t0.Add(-time.Hour), 90*24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.dev = dev
|
||||
f.st, err = store.Open(":memory:", store.Options{
|
||||
Difficulty: listingDifficulty, MessageDifficulty: msgDifficulty,
|
||||
Clock: func() time.Time { return f.now },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { f.st.Close() })
|
||||
f.relay = &relay{st: f.st}
|
||||
f.in = &Inbox{Store: f.st, Device: dev, Publisher: f.relay, Difficulty: msgDifficulty,
|
||||
MaxNewThreads: maxNew, Clock: func() time.Time { return f.now }}
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fixture) listing() *listing.Listing {
|
||||
f.t.Helper()
|
||||
id, _ := listing.NewID()
|
||||
l := &listing.Listing{
|
||||
Version: listing.Version, ID: id, Seq: 1, CreatedAt: f.now.Unix(),
|
||||
ExpiresAt: f.now.Add(7 * 24 * time.Hour).Unix(), Kind: "rent", Category: "apartment",
|
||||
Geohash: "u1xjhx", Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"},
|
||||
Title: "Wohnung",
|
||||
}
|
||||
if err := l.Seal(f.dev, listingDifficulty); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
if _, err := f.st.Put(ctx, l); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// buyer sends a message with exactly `work` bits of proof-of-work.
|
||||
func (f *fixture) buyer(l *listing.Listing, tk *message.ThreadKey, n int64, text string, work int) {
|
||||
f.t.Helper()
|
||||
for {
|
||||
p := &message.Plain{Type: message.TypeText, N: n, SentAt: f.now.Unix() + n, Text: text}
|
||||
e, err := message.SealToOwner(l, tk, p, f.now, work)
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
if w, _ := e.Work(); w != work {
|
||||
continue
|
||||
}
|
||||
if _, err := f.st.PutMessage(ctx, region, e); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fixture) newThread() *message.ThreadKey {
|
||||
f.t.Helper()
|
||||
tk, err := message.NewThreadKey()
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return tk
|
||||
}
|
||||
|
||||
func (f *fixture) collect() int {
|
||||
f.t.Helper()
|
||||
n, err := f.in.Collect(ctx)
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestCollectFilesConversationsOnce(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l, l2 := f.listing(), f.listing()
|
||||
a, b := f.newThread(), f.newThread()
|
||||
f.buyer(l, a, 1, "Ist die Wohnung noch frei?", msgDifficulty)
|
||||
f.buyer(l, a, 2, "Ich könnte morgen vorbeikommen.", msgDifficulty)
|
||||
f.buyer(l2, b, 1, "Guten Tag", msgDifficulty)
|
||||
|
||||
if n := f.collect(); n != 3 {
|
||||
t.Fatalf("collected %d, want 3", n)
|
||||
}
|
||||
if n := f.collect(); n != 0 {
|
||||
t.Fatalf("a second collection added %d", n)
|
||||
}
|
||||
threads, err := f.st.Threads(ctx, l.Author)
|
||||
if err != nil || len(threads) != 2 {
|
||||
t.Fatalf("threads = %d, %v", len(threads), err)
|
||||
}
|
||||
msgs, _ := f.st.ThreadMessages(ctx, message.Ref{Author: l.Author, ID: l.ID}, a.PublicHex())
|
||||
if len(msgs) != 2 || msgs[0].Plain.Text != "Ist die Wohnung noch frei?" || msgs[1].Plain.N != 2 {
|
||||
t.Fatalf("conversation is wrong: %+v", msgs)
|
||||
}
|
||||
for _, m := range msgs {
|
||||
if m.Dir != store.InboxIn || m.Hidden {
|
||||
t.Fatalf("unexpected %+v", m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinksInFirstMessagesAreHiddenUntilTheOwnerReplies(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
tk := f.newThread()
|
||||
|
||||
f.buyer(l, tk, 1, "Schaut euch https://example.com/kaution an", msgDifficulty)
|
||||
f.buyer(l, tk, 2, strings.Repeat("x", message.MaxFirstText+1), msgDifficulty)
|
||||
f.collect()
|
||||
msgs, _ := f.st.ThreadMessages(ctx, ref, tk.PublicHex())
|
||||
if len(msgs) != 2 || !msgs[0].Hidden || !msgs[1].Hidden {
|
||||
t.Fatalf("violating first messages must be hidden: %+v", msgs)
|
||||
}
|
||||
|
||||
if _, err := f.in.Send(ctx, ref, tk.PublicHex(), Reply{Type: message.TypeText, Text: "Hallo!"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.buyer(l, tk, 3, "Hier ist mein Profil: https://example.com/me", msgDifficulty)
|
||||
f.collect()
|
||||
msgs, _ = f.st.ThreadMessages(ctx, ref, tk.PublicHex())
|
||||
for _, m := range msgs {
|
||||
if m.Dir != store.InboxIn {
|
||||
continue
|
||||
}
|
||||
wantHidden := m.Plain.N < 3 // the first two broke the rules before any reply
|
||||
if m.Hidden != wantHidden {
|
||||
t.Errorf("message %d: hidden = %v, want %v", m.Plain.N, m.Hidden, wantHidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewConversationsAreLimitedPerDay(t *testing.T) {
|
||||
f := newFixture(t, 2)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
|
||||
weakest := f.newThread()
|
||||
f.buyer(l, weakest, 1, "schwach", 4)
|
||||
strong := f.newThread()
|
||||
f.buyer(l, strong, 1, "stark", 10)
|
||||
mid := f.newThread()
|
||||
f.buyer(l, mid, 1, "mittel", 7)
|
||||
mid2 := f.newThread()
|
||||
f.buyer(l, mid2, 1, "mittel2", 7)
|
||||
|
||||
f.collect()
|
||||
has := func(tk *message.ThreadKey) bool {
|
||||
ok, _ := f.st.HasThread(ctx, ref, tk.PublicHex())
|
||||
return ok
|
||||
}
|
||||
if !has(strong) || !(has(mid) != has(mid2)) || has(weakest) {
|
||||
t.Fatalf("room for 2 goes to the strongest: strong=%v mid=%v mid2=%v weakest=%v",
|
||||
has(strong), has(mid), has(mid2), has(weakest))
|
||||
}
|
||||
|
||||
// Follow-ups to an existing conversation are never held back.
|
||||
f.buyer(l, strong, 2, "noch eine Frage", 4)
|
||||
if n := f.collect(); n != 1 {
|
||||
t.Fatalf("follow-up not filed (%d)", n)
|
||||
}
|
||||
// The waiting ones stay queued and are not marked as seen...
|
||||
if has(weakest) {
|
||||
t.Fatal("limit exceeded")
|
||||
}
|
||||
// ...so they get in once a day has passed and the window has moved on.
|
||||
f.now = f.now.Add(25 * time.Hour)
|
||||
f.collect()
|
||||
if !has(weakest) || !has(mid) || !has(mid2) {
|
||||
t.Fatalf("queued conversations should be admitted the next day: weakest=%v mid=%v mid2=%v",
|
||||
has(weakest), has(mid), has(mid2))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepliesReachTheBuyerAndAreSigned(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
tk := f.newThread()
|
||||
f.buyer(l, tk, 1, "Hallo", msgDifficulty)
|
||||
f.collect()
|
||||
|
||||
if _, err := f.in.Send(ctx, ref, tk.PublicHex(), Reply{Type: message.TypeText, Text: "Ja, noch frei."}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.st.SetAddress(ctx, ref, store.Address{Address: "Musterstraße 12, 20255 Hamburg", Phone: "+49 40 1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A grant prefilled from the saved address, with the owner's own words.
|
||||
if _, err := f.in.Send(ctx, ref, tk.PublicHex(), Reply{
|
||||
Type: message.TypeGrant, Note: "Samstag 10 Uhr, bitte zweimal klingeln", ValidDays: 3,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mb, _ := tk.Mailbox()
|
||||
box, err := f.st.Mailbox(ctx, mb, 0, 10)
|
||||
if err != nil || len(box) != 2 {
|
||||
t.Fatalf("mailbox = %d, %v", len(box), err)
|
||||
}
|
||||
var text, grant *message.Plain
|
||||
for _, e := range box {
|
||||
p, err := e.OpenAsBuyer(tk)
|
||||
if err != nil {
|
||||
t.Fatalf("buyer cannot open a reply: %v", err)
|
||||
}
|
||||
if p.Type == message.TypeGrant {
|
||||
grant = p
|
||||
} else {
|
||||
text = p
|
||||
}
|
||||
}
|
||||
if text == nil || text.Text != "Ja, noch frei." || text.N != 1 {
|
||||
t.Fatalf("text reply: %+v", text)
|
||||
}
|
||||
if grant == nil || grant.Address != "Musterstraße 12, 20255 Hamburg" || grant.Phone != "+49 40 1" ||
|
||||
grant.Note != "Samstag 10 Uhr, bitte zweimal klingeln" || grant.N != 2 ||
|
||||
grant.ValidUntil != f.now.Add(3*24*time.Hour).Unix() {
|
||||
t.Fatalf("grant: %+v", grant)
|
||||
}
|
||||
|
||||
// The conversation keeps both our replies, in order.
|
||||
msgs, _ := f.st.ThreadMessages(ctx, ref, tk.PublicHex())
|
||||
var outs int
|
||||
for _, m := range msgs {
|
||||
if m.Dir == store.InboxOut {
|
||||
outs++
|
||||
}
|
||||
}
|
||||
if outs != 2 {
|
||||
t.Fatalf("recorded %d outgoing messages, want 2", outs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendRefusals(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
tk := f.newThread()
|
||||
f.buyer(l, tk, 1, "Hallo", msgDifficulty)
|
||||
f.collect()
|
||||
th := tk.PublicHex()
|
||||
|
||||
if _, err := f.in.Send(ctx, ref, strings.Repeat("ab", 32), Reply{Type: message.TypeText, Text: "x"}); !errors.Is(err, ErrNoThread) {
|
||||
t.Errorf("unknown thread: %v", err)
|
||||
}
|
||||
if _, err := f.in.Send(ctx, message.Ref{Author: strings.Repeat("cd", 32), ID: l.ID}, th, Reply{Type: message.TypeText, Text: "x"}); !errors.Is(err, ErrNotOwner) {
|
||||
t.Errorf("foreign listing: %v", err)
|
||||
}
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeGrant}); err == nil || !strings.Contains(err.Error(), "no address") {
|
||||
t.Errorf("grant without any address: %v", err)
|
||||
}
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeGrant, Address: "Weg 1", ValidDays: 31}); err == nil {
|
||||
t.Error("a grant valid for 31 days was accepted")
|
||||
}
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: "image"}); err == nil {
|
||||
t.Error("unknown reply type accepted")
|
||||
}
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeText, Text: ""}); err == nil {
|
||||
t.Error("empty reply accepted")
|
||||
}
|
||||
|
||||
// A failed publish leaves nothing behind.
|
||||
f.relay.fail = errors.New("network down")
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeText, Text: "x"}); err == nil {
|
||||
t.Error("publish failure was swallowed")
|
||||
}
|
||||
msgs, _ := f.st.ThreadMessages(ctx, ref, th)
|
||||
if len(msgs) != 1 {
|
||||
t.Fatalf("a failed send was recorded: %d messages", len(msgs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddressesAndThreadsCanBeErased(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
tk := f.newThread()
|
||||
f.buyer(l, tk, 1, "Hallo", msgDifficulty)
|
||||
f.collect()
|
||||
|
||||
if _, err := f.st.GetAddress(ctx, ref); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("address before saving: %v", err)
|
||||
}
|
||||
f.st.SetAddress(ctx, ref, store.Address{Address: "A"})
|
||||
f.st.SetAddress(ctx, ref, store.Address{Address: "B", Email: "x@example.com"})
|
||||
if a, _ := f.st.GetAddress(ctx, ref); a.Address != "B" || a.Email != "x@example.com" {
|
||||
t.Fatalf("address was not replaced: %+v", a)
|
||||
}
|
||||
f.st.DeleteAddress(ctx, ref)
|
||||
if _, err := f.st.GetAddress(ctx, ref); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatal("address survived deletion")
|
||||
}
|
||||
|
||||
if ok, _ := f.st.DeleteThread(ctx, ref, tk.PublicHex()); !ok {
|
||||
t.Fatal("thread not deleted")
|
||||
}
|
||||
if th, _ := f.st.Threads(ctx, l.Author); len(th) != 0 {
|
||||
t.Fatal("thread survived deletion")
|
||||
}
|
||||
// The envelope was marked seen, so deleting a thread does not resurrect it.
|
||||
if n := f.collect(); n != 0 {
|
||||
t.Fatalf("an erased conversation came back (%d)", n)
|
||||
}
|
||||
}
|
||||
@@ -368,6 +368,13 @@ func validPeerID(s string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// ValidText applies the text rules shared by listings and messages: valid
|
||||
// UTF-8, a length of min to max characters and no control characters
|
||||
// (newlines only if allowNewlines).
|
||||
func ValidText(s string, min, max int, allowNewlines bool) error {
|
||||
return validText(s, min, max, allowNewlines)
|
||||
}
|
||||
|
||||
func validText(s string, min, max int, allowNewlines bool) error {
|
||||
if !utf8.ValidString(s) {
|
||||
return errors.New("invalid UTF-8")
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdh"
|
||||
"crypto/ed25519"
|
||||
"crypto/hkdf"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"filippo.io/edwards25519"
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
)
|
||||
|
||||
const sealInfo = "allmende-seal-v1"
|
||||
|
||||
var x25519 = ecdh.X25519()
|
||||
|
||||
// entropy is where ephemeral keys come from. Tests replace it to produce the
|
||||
// deterministic golden fixture the browser implementation is checked against.
|
||||
var entropy io.Reader = rand.Reader
|
||||
|
||||
// paddingBuckets are the sizes plaintexts are padded to, so the ciphertext
|
||||
// length reveals little about a message.
|
||||
var paddingBuckets = []int{512, 1024, 2048, 4096}
|
||||
|
||||
// MaxPlain is the largest plaintext before padding. One byte is reserved for
|
||||
// the padding marker so the largest padded plaintext is 4096 bytes.
|
||||
const MaxPlain = 4095
|
||||
|
||||
// ed25519PublicToX25519 converts a device's signing key to the X25519 key
|
||||
// used to seal messages to it (the birational map libsodium uses for
|
||||
// crypto_sign_ed25519_pk_to_curve25519).
|
||||
func ed25519PublicToX25519(pub ed25519.PublicKey) (*ecdh.PublicKey, error) {
|
||||
p, err := new(edwards25519.Point).SetBytes(pub)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("message: bad device key: %w", err)
|
||||
}
|
||||
return x25519.NewPublicKey(p.BytesMontgomery())
|
||||
}
|
||||
|
||||
// ed25519SecretToX25519 derives the X25519 secret matching
|
||||
// ed25519PublicToX25519 of the corresponding public key.
|
||||
func ed25519SecretToX25519(priv ed25519.PrivateKey) (*ecdh.PrivateKey, error) {
|
||||
h := sha512.Sum512(priv.Seed())
|
||||
return x25519.NewPrivateKey(h[:32])
|
||||
}
|
||||
|
||||
func newEphemeral() (*ecdh.PrivateKey, error) {
|
||||
var b [32]byte
|
||||
if _, err := io.ReadFull(entropy, b[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x25519.NewPrivateKey(b[:])
|
||||
}
|
||||
|
||||
func sealKey(shared, epk, rpk []byte) ([]byte, error) {
|
||||
salt := append(append([]byte{}, epk...), rpk...)
|
||||
return hkdf.Key(sha256.New, shared, salt, sealInfo, 32)
|
||||
}
|
||||
|
||||
// seal encrypts padded plaintext to rpk. aadFor receives the hex of the fresh
|
||||
// ephemeral public key and returns the header bytes that are authenticated.
|
||||
func seal(rpk *ecdh.PublicKey, aadFor func(epk string) ([]byte, error), plain []byte) (epk string, ct []byte, err error) {
|
||||
esk, err := newEphemeral()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
shared, err := esk.ECDH(rpk) // rejects the all-zero result of low-order points
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
epkBytes := esk.PublicKey().Bytes()
|
||||
key, err := sealKey(shared, epkBytes, rpk.Bytes())
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
epk = hex.EncodeToString(epkBytes)
|
||||
aad, err := aadFor(epk)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
padded, err := pad(plain)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
aead, err := chacha20poly1305.New(key)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// A zero nonce is safe: the key is unique to this envelope (fresh esk).
|
||||
return epk, aead.Seal(nil, make([]byte, aead.NonceSize()), padded, aad), nil
|
||||
}
|
||||
|
||||
// open decrypts ct with the recipient's secret key.
|
||||
func open(sk *ecdh.PrivateKey, epkHex string, aad, ct []byte) ([]byte, error) {
|
||||
epkBytes, err := hex.DecodeString(epkHex)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ephemeral key")
|
||||
}
|
||||
epk, err := x25519.NewPublicKey(epkBytes)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ephemeral key")
|
||||
}
|
||||
shared, err := sk.ECDH(epk)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ephemeral key")
|
||||
}
|
||||
key, err := sealKey(shared, epkBytes, sk.PublicKey().Bytes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead, err := chacha20poly1305.New(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
padded, err := aead.Open(nil, make([]byte, aead.NonceSize()), ct, aad)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: cannot decrypt")
|
||||
}
|
||||
return unpad(padded)
|
||||
}
|
||||
|
||||
// pad appends 0x80 and zeros up to the next bucket size.
|
||||
func pad(b []byte) ([]byte, error) {
|
||||
if len(b) > MaxPlain {
|
||||
return nil, fmt.Errorf("message: plaintext of %d bytes exceeds %d", len(b), MaxPlain)
|
||||
}
|
||||
size := paddingBuckets[len(paddingBuckets)-1]
|
||||
for _, s := range paddingBuckets {
|
||||
if len(b)+1 <= s {
|
||||
size = s
|
||||
break
|
||||
}
|
||||
}
|
||||
out := make([]byte, size)
|
||||
copy(out, b)
|
||||
out[len(b)] = 0x80
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func unpad(b []byte) ([]byte, error) {
|
||||
b = bytes.TrimRight(b, "\x00")
|
||||
if len(b) == 0 || b[len(b)-1] != 0x80 {
|
||||
return nil, errors.New("message: bad padding")
|
||||
}
|
||||
return b[:len(b)-1], nil
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
// 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 {
|
||||
for e.PoW = 0; ; e.PoW++ {
|
||||
if e.PoW > maxSafeInt {
|
||||
return errors.New("message: proof-of-work exhausted")
|
||||
}
|
||||
ok, err := e.powOK(difficulty)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
)
|
||||
|
||||
// The browser seals buyer messages and opens owner replies. This golden file
|
||||
// is produced by the Go implementation and consumed by the TypeScript tests
|
||||
// (web/test), which must reproduce every byte: same envelope from the same
|
||||
// ephemeral key, same plaintext from the same thread key.
|
||||
//
|
||||
// Refresh it after an intentional format change with:
|
||||
//
|
||||
// UPDATE_FIXTURES=1 go test ./internal/message -run TestGoldenFixture
|
||||
const fixturePath = "testdata/fixture.json"
|
||||
|
||||
const (
|
||||
fixtureNow = 1_800_000_000
|
||||
fixtureDifficulty = 8
|
||||
)
|
||||
|
||||
type fixtureEnvelope struct {
|
||||
EphemeralSecret string `json:"esk"` // hex; the only randomness in the envelope
|
||||
Plain json.RawMessage `json:"plain"` // what was sealed, as plain JSON
|
||||
PlainCanonical string `json:"plain_canonical"`
|
||||
PaddedLen int `json:"padded_len"`
|
||||
Canonical string `json:"canonical"` // the exact envelope bytes
|
||||
Hash string `json:"hash"`
|
||||
Work int `json:"work"`
|
||||
}
|
||||
|
||||
type linkCase struct {
|
||||
Text string `json:"text"`
|
||||
Link bool `json:"link"`
|
||||
}
|
||||
|
||||
type fixtureFile struct {
|
||||
Now int64 `json:"now"`
|
||||
Difficulty int `json:"difficulty"`
|
||||
Listing Ref `json:"listing"`
|
||||
Device string `json:"device"`
|
||||
DeviceSeed string `json:"device_seed"`
|
||||
ThreadSecret string `json:"thread_secret"`
|
||||
ThreadPublic string `json:"thread_public"`
|
||||
Mailbox string `json:"mailbox"`
|
||||
ToOwner fixtureEnvelope `json:"to_owner"`
|
||||
ToBuyer fixtureEnvelope `json:"to_buyer"`
|
||||
Links []linkCase `json:"links"`
|
||||
}
|
||||
|
||||
func withEntropy(t *testing.T, b []byte) {
|
||||
t.Helper()
|
||||
old := entropy
|
||||
entropy = io.Reader(bytes.NewReader(b))
|
||||
t.Cleanup(func() { entropy = old })
|
||||
}
|
||||
|
||||
func buildFixture(t *testing.T) *fixtureFile {
|
||||
t.Helper()
|
||||
root, err := identity.FromPhrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deviceSeed := bytes.Repeat([]byte{7}, 32)
|
||||
devKey, err := identity.FromSeed(deviceSeed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := time.Unix(fixtureNow, 0)
|
||||
cert, err := identity.IssueCert(root, devKey.PublicKeyHex(), at.Add(-time.Hour), at.Add(90*24*time.Hour))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dev := &identity.Device{Key: devKey, Cert: cert}
|
||||
l := &listing.Listing{ID: "00112233445566778899aabbccddeeff", Author: cert.Author, Device: cert.Device}
|
||||
ref := Ref{Author: l.Author, ID: l.ID}
|
||||
|
||||
threadSecret := bytes.Repeat([]byte{0x11}, 32)
|
||||
tk, err := ThreadKeyFromBytes(threadSecret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mailbox, _ := tk.Mailbox()
|
||||
f := &fixtureFile{
|
||||
Now: fixtureNow, Difficulty: fixtureDifficulty, Listing: ref, Device: cert.Device,
|
||||
DeviceSeed: hex.EncodeToString(deviceSeed), ThreadSecret: hex.EncodeToString(threadSecret),
|
||||
ThreadPublic: tk.PublicHex(), Mailbox: mailbox,
|
||||
}
|
||||
|
||||
fill := func(e *Envelope, p *Plain, esk []byte) fixtureEnvelope {
|
||||
canon, _ := e.Bytes()
|
||||
hash, _ := e.Hash()
|
||||
work, _ := e.Work()
|
||||
plain, _ := json.Marshal(p)
|
||||
pc, _ := jcs.Marshal(p) // p was filled in by sealing: thread, and the owner's signature
|
||||
padded, _ := pad(pc)
|
||||
return fixtureEnvelope{
|
||||
EphemeralSecret: hex.EncodeToString(esk), Plain: plain, PlainCanonical: string(pc),
|
||||
PaddedLen: len(padded), Canonical: string(canon), Hash: hash, Work: work,
|
||||
}
|
||||
}
|
||||
|
||||
// Awkward text on purpose: umlauts, an emoji, a newline and U+2028.
|
||||
esk1 := bytes.Repeat([]byte{0x22}, 32)
|
||||
withEntropy(t, esk1)
|
||||
hello := &Plain{Type: TypeText, N: 1, SentAt: fixtureNow,
|
||||
Text: "Guten Tag, ist die Wohnung noch frei? Schöne Grüße \U0001F3E0\nZeile 2
Zeile 3"}
|
||||
e1, err := SealToOwner(l, tk, hello, at, fixtureDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.ToOwner = fill(e1, hello, esk1)
|
||||
|
||||
esk2 := bytes.Repeat([]byte{0x33}, 32)
|
||||
withEntropy(t, esk2)
|
||||
grant := &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 1, SentAt: fixtureNow,
|
||||
Address: "Musterstraße 12, 20255 Hamburg", Phone: "+49 40 123456",
|
||||
Note: "Samstag 10 Uhr, bitte zweimal klingeln \U0001F514", ValidUntil: fixtureNow + 7*24*3600}
|
||||
e2, err := SealToBuyer(dev, ref, grant, at, fixtureDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The grant now carries the owner's certificate and signature.
|
||||
f.ToBuyer = fill(e2, grant, esk2)
|
||||
|
||||
for _, c := range []struct {
|
||||
text string
|
||||
link bool
|
||||
}{
|
||||
{"Guten Tag, ist die Wohnung noch frei?", false},
|
||||
{"Ich komme z. B. am Samstag, ca. 10 Uhr.", false},
|
||||
{"Preis 1.200 Euro, ok? Ja. Gut.", false},
|
||||
{"Hallo, wir sind 2 Personen (u.a. Nichtraucher).", false},
|
||||
{"schaut mal https://example.com/x", true},
|
||||
{"WWW.example", true},
|
||||
{"auf beispiel.de gibt es mehr", true},
|
||||
{"mail an max@example.com", true},
|
||||
{"Hallo.Ich komme morgen", true},
|
||||
{"Beispiel.DE", true},
|
||||
{"auf straße-1.com", true},
|
||||
{"bit.ly/abc", true},
|
||||
} {
|
||||
if got := ContainsLink(c.text); got != c.link {
|
||||
t.Fatalf("ContainsLink(%q) = %v, want %v", c.text, got, c.link)
|
||||
}
|
||||
f.Links = append(f.Links, linkCase{c.text, c.link})
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func TestGoldenFixture(t *testing.T) {
|
||||
f := buildFixture(t)
|
||||
got, err := json.MarshalIndent(f, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, '\n')
|
||||
|
||||
if os.Getenv("UPDATE_FIXTURES") != "" {
|
||||
if err := os.MkdirAll("testdata", 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(fixturePath, got, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
want, err := os.ReadFile(fixturePath)
|
||||
if err != nil {
|
||||
t.Fatalf("%v (create it with UPDATE_FIXTURES=1)", err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("fixture is out of date: the wire format changed; if intended, refresh with UPDATE_FIXTURES=1 and update the TypeScript side")
|
||||
}
|
||||
|
||||
// The fixture must be self-consistent: both envelopes pass the relay
|
||||
// checks and open with the keys from the file.
|
||||
for name, c := range map[string]fixtureEnvelope{"to_owner": f.ToOwner, "to_buyer": f.ToBuyer} {
|
||||
var e Envelope
|
||||
if err := json.Unmarshal([]byte(c.Canonical), &e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.Check(time.Unix(fixtureNow, 0), fixtureDifficulty); err != nil {
|
||||
t.Errorf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
)
|
||||
|
||||
const testDifficulty = 6
|
||||
|
||||
var now = time.Unix(1_800_000_000, 0)
|
||||
|
||||
type party struct {
|
||||
dev *identity.Device
|
||||
l *listing.Listing
|
||||
ref Ref
|
||||
}
|
||||
|
||||
func newOwner(t *testing.T) *party {
|
||||
t.Helper()
|
||||
root, err := identity.Generate()
|
||||
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)
|
||||
}
|
||||
l := &listing.Listing{ID: strings.Repeat("ab", 16), Author: dev.Cert.Author, Device: dev.Cert.Device}
|
||||
return &party{dev: dev, l: l, ref: Ref{Author: l.Author, ID: l.ID}}
|
||||
}
|
||||
|
||||
func hello(text string) *Plain {
|
||||
return &Plain{Type: TypeText, N: 1, SentAt: now.Unix(), Text: text}
|
||||
}
|
||||
|
||||
func thread(t *testing.T) *ThreadKey {
|
||||
t.Helper()
|
||||
k, err := NewThreadKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
func TestKeyConversionAgrees(t *testing.T) {
|
||||
for i := 0; i < 20; i++ {
|
||||
id, _ := identity.Generate()
|
||||
priv := id.PrivateKey()
|
||||
sk, err := ed25519SecretToX25519(priv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pk, err := ed25519PublicToX25519(priv.Public().(ed25519.PublicKey))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(sk.PublicKey().Bytes(), pk.Bytes()) {
|
||||
t.Fatal("converted secret and converted public key do not match")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuyerToOwnerRoundTrip(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
e, err := SealToOwner(o.l, tk, hello("Ist die Wohnung noch frei? 🏠"), now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.Check(now, testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := e.Bytes()
|
||||
if bytes.Contains(b, []byte("Wohnung")) {
|
||||
t.Fatal("plaintext visible in the envelope")
|
||||
}
|
||||
if strings.Contains(string(b), tk.PublicHex()) {
|
||||
t.Fatal("thread key must not appear in the envelope")
|
||||
}
|
||||
p, err := e.OpenAsOwner(o.dev)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Text != "Ist die Wohnung noch frei? 🏠" || p.Thread != tk.PublicHex() || p.N != 1 {
|
||||
t.Fatalf("unexpected plaintext %+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnerReplyAndGrantRoundTrip(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
|
||||
reply := &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "Ja, noch frei."}
|
||||
e, err := SealToBuyer(o.dev, o.ref, reply, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.Check(now, testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mb, _ := tk.Mailbox()
|
||||
if e.Rcpt != mb || e.To != ToBuyer {
|
||||
t.Fatal("reply is not addressed to the thread's mailbox")
|
||||
}
|
||||
got, err := e.OpenAsBuyer(tk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Text != "Ja, noch frei." || got.Device != o.dev.Cert.Device {
|
||||
t.Fatalf("unexpected reply %+v", got)
|
||||
}
|
||||
|
||||
grant := &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 2, SentAt: now.Unix(),
|
||||
Address: "Musterstraße 12, 20255 Hamburg", Phone: "+49 40 123456",
|
||||
Note: "Samstag 10 Uhr, bitte zweimal klingeln", ValidUntil: now.Add(7 * 24 * time.Hour).Unix()}
|
||||
e, err = SealToBuyer(o.dev, o.ref, grant, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = e.OpenAsBuyer(tk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Address != grant.Address || got.Note != grant.Note || got.ValidUntil != grant.ValidUntil {
|
||||
t.Fatalf("grant changed in transit: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTamperingWithTheHeaderBreaksDecryption(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
e, _ := SealToOwner(o.l, thread(t), hello("hallo"), now, testDifficulty)
|
||||
for name, mutate := range map[string]func(*Envelope){
|
||||
"created_at": func(e *Envelope) { e.CreatedAt++ },
|
||||
"expires_at": func(e *Envelope) { e.ExpiresAt-- },
|
||||
"listing id": func(e *Envelope) { e.Listing.ID = strings.Repeat("cd", 16) },
|
||||
"author": func(e *Envelope) { e.Listing.Author = strings.Repeat("ee", 32) },
|
||||
"ciphertext": func(e *Envelope) {
|
||||
flipped := byte('0')
|
||||
if e.CT[0] == '0' {
|
||||
flipped = '1'
|
||||
}
|
||||
e.CT = string(flipped) + e.CT[1:]
|
||||
},
|
||||
} {
|
||||
c := *e
|
||||
mutate(&c)
|
||||
if _, err := c.OpenAsOwner(o.dev); err == nil {
|
||||
t.Errorf("tampering with %s went unnoticed", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyTheRightKeysOpen(t *testing.T) {
|
||||
o, other := newOwner(t), newOwner(t)
|
||||
tk := thread(t)
|
||||
e, _ := SealToOwner(o.l, tk, hello("hallo"), now, testDifficulty)
|
||||
if _, err := e.OpenAsOwner(other.dev); err == nil {
|
||||
t.Fatal("another device opened the message")
|
||||
}
|
||||
// Same recipient field, wrong secret.
|
||||
c := *e
|
||||
c.Rcpt = other.dev.Cert.Device
|
||||
if _, err := c.OpenAsOwner(other.dev); err == nil {
|
||||
t.Fatal("re-addressed envelope decrypted")
|
||||
}
|
||||
|
||||
r, _ := SealToBuyer(o.dev, o.ref, &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "x"}, now, testDifficulty)
|
||||
if _, err := r.OpenAsBuyer(thread(t)); err == nil {
|
||||
t.Fatal("another thread opened the reply")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImpersonationAndReplayAreRejected(t *testing.T) {
|
||||
o, imp := newOwner(t), newOwner(t)
|
||||
tk := thread(t)
|
||||
|
||||
// A different identity signs a reply that claims to come from o's listing.
|
||||
p := &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "Überweisen Sie die Kaution"}
|
||||
if _, err := SealToBuyer(imp.dev, o.ref, p, now, testDifficulty); err == nil {
|
||||
t.Fatal("SealToBuyer must refuse a device of another author")
|
||||
}
|
||||
p.signOwner(imp.dev, o.ref) // forge it by hand
|
||||
pub, _ := hex.DecodeString(p.Thread)
|
||||
rpk, _ := x25519.NewPublicKey(pub)
|
||||
mb, _ := Mailbox(p.Thread)
|
||||
forged, err := build(o.ref, ToBuyer, mb, rpk, p, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := forged.OpenAsBuyer(tk); err == nil || !strings.Contains(err.Error(), "certificate") {
|
||||
t.Fatalf("forged reply accepted or wrong error: %v", err)
|
||||
}
|
||||
|
||||
// A genuine reply for thread A, moved into thread B, fails its signature.
|
||||
a, b := thread(t), thread(t)
|
||||
genuine := &Plain{Type: TypeText, Thread: a.PublicHex(), N: 1, SentAt: now.Unix(), Text: "für A"}
|
||||
if _, err := SealToBuyer(o.dev, o.ref, genuine, now, testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
moved := *genuine
|
||||
moved.Thread = b.PublicHex()
|
||||
pubB, _ := hex.DecodeString(moved.Thread)
|
||||
rpkB, _ := x25519.NewPublicKey(pubB)
|
||||
mbB, _ := Mailbox(moved.Thread)
|
||||
e, err := build(o.ref, ToBuyer, mbB, rpkB, &moved, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := e.OpenAsBuyer(b); err == nil || !strings.Contains(err.Error(), "signature") {
|
||||
t.Fatalf("replayed reply accepted or wrong error: %v", err)
|
||||
}
|
||||
|
||||
// A reply for another listing of the same envelope header fails too.
|
||||
g, _ := SealToBuyer(o.dev, o.ref, &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "x"}, now, testDifficulty)
|
||||
g.Listing.ID = strings.Repeat("cd", 16)
|
||||
if _, err := g.OpenAsBuyer(tk); err == nil {
|
||||
t.Fatal("reply accepted for a different listing id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayChecks(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
good, _ := SealToOwner(o.l, thread(t), hello("hallo"), now, testDifficulty)
|
||||
if err := good.Check(now, testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
remine := func(e *Envelope) *Envelope {
|
||||
if err := e.mine(testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
mutate func(*Envelope)
|
||||
wantErr string
|
||||
window bool
|
||||
}{
|
||||
{"version", func(e *Envelope) { e.Version = 2 }, "version", false},
|
||||
{"direction", func(e *Envelope) { e.To = "everyone" }, "direction", false},
|
||||
{"owner rcpt too short", func(e *Envelope) { e.Rcpt = e.Rcpt[:32] }, "64 hex", false},
|
||||
{"buyer rcpt too long", func(e *Envelope) { e.To = ToBuyer }, "32 hex", false},
|
||||
{"uppercase ct", func(e *Envelope) { e.CT = strings.ToUpper(e.CT) }, "lowercase", false},
|
||||
{"ct too small", func(e *Envelope) { e.CT = "00" }, "size", false},
|
||||
{"lifetime over 14 days", func(e *Envelope) { e.ExpiresAt = e.CreatedAt + 15*24*3600 }, "14 days", false},
|
||||
{"expiry before creation", func(e *Envelope) { e.ExpiresAt = e.CreatedAt }, "after created_at", false},
|
||||
{"expired", func(e *Envelope) { e.CreatedAt -= 20 * 24 * 3600; e.ExpiresAt -= 20 * 24 * 3600 }, "expired", true},
|
||||
{"from the future", func(e *Envelope) { e.CreatedAt += 3600; e.ExpiresAt += 3600 }, "future", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
e := *good
|
||||
c.mutate(&e)
|
||||
remine(&e)
|
||||
err := e.Check(now, testDifficulty)
|
||||
if err == nil || !strings.Contains(err.Error(), c.wantErr) {
|
||||
t.Errorf("%s: err = %v, want %q", c.name, err, c.wantErr)
|
||||
continue
|
||||
}
|
||||
if errors.Is(err, listing.ErrTimeWindow) != c.window {
|
||||
t.Errorf("%s: ErrTimeWindow = %v, want %v", c.name, !c.window, c.window)
|
||||
}
|
||||
}
|
||||
|
||||
// Proof-of-work is checked against the node's difficulty.
|
||||
if err := good.Check(now, 40); err == nil || !strings.Contains(err.Error(), "proof-of-work") {
|
||||
t.Errorf("weak work accepted: %v", err)
|
||||
}
|
||||
// Any change after mining invalidates the work (with overwhelming probability).
|
||||
c := *good
|
||||
c.CreatedAt++
|
||||
if err := c.Check(now, 24); err == nil {
|
||||
t.Error("altered envelope kept its proof-of-work")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSizeLimits(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
if _, err := SealToOwner(o.l, tk, hello(strings.Repeat("a", MaxText+1)), now, testDifficulty); err == nil {
|
||||
t.Error("oversized text accepted")
|
||||
}
|
||||
e, err := SealToOwner(o.l, tk, hello(strings.Repeat("ä", MaxText/2)), now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatalf("a full-size message failed: %v", err)
|
||||
}
|
||||
b, _ := e.Bytes()
|
||||
if len(b) > MaxSize {
|
||||
t.Fatalf("a full-size envelope is %d bytes, over the %d limit", len(b), MaxSize)
|
||||
}
|
||||
// The largest owner grant, with certificate and signature, still fits.
|
||||
grant := &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(),
|
||||
Address: strings.Repeat("ä", MaxAddress/2), Phone: strings.Repeat("1", MaxPhone),
|
||||
Email: strings.Repeat("e", MaxEmail), Note: strings.Repeat("ä", MaxNote/2),
|
||||
ValidUntil: now.Add(MaxGrantValidity).Unix()}
|
||||
e, err = SealToBuyer(o.dev, o.ref, grant, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatalf("a maximal grant does not fit: %v", err)
|
||||
}
|
||||
b, _ = e.Bytes()
|
||||
if len(b) > MaxSize {
|
||||
t.Fatalf("a maximal grant envelope is %d bytes, over the %d limit", len(b), MaxSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingHidesLength(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
size := func(text string) int {
|
||||
e, err := SealToOwner(o.l, thread(t), hello(text), now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return len(e.CT)
|
||||
}
|
||||
if a, b := size("hi"), size(strings.Repeat("x", 250)); a != b {
|
||||
t.Errorf("short messages differ in size: %d vs %d", a, b)
|
||||
}
|
||||
if a, b := size("hi"), size(strings.Repeat("x", 900)); a >= b {
|
||||
t.Errorf("a longer message should land in a larger bucket: %d vs %d", a, b)
|
||||
}
|
||||
for _, n := range []int{0, 1, 511, 512, 1023, 2047, 2048, MaxPlain} {
|
||||
got, err := pad(bytes.Repeat([]byte{'a'}, n))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 512 && len(got) != 1024 && len(got) != 2048 && len(got) != 4096 {
|
||||
t.Errorf("pad(%d) = %d bytes, not a bucket", n, len(got))
|
||||
}
|
||||
back, err := unpad(got)
|
||||
if err != nil || len(back) != n {
|
||||
t.Errorf("unpad(pad(%d)) = %d bytes, %v", n, len(back), err)
|
||||
}
|
||||
}
|
||||
if _, err := pad(make([]byte, MaxPlain+1)); err == nil {
|
||||
t.Error("oversized plaintext padded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLowOrderKeysAreRejected(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
e, _ := SealToOwner(o.l, thread(t), hello("hallo"), now, testDifficulty)
|
||||
c := *e
|
||||
c.EPK = strings.Repeat("00", 32) // a point of low order: shared secret would be all zero
|
||||
if _, err := c.OpenAsOwner(o.dev); err == nil {
|
||||
t.Error("low-order ephemeral key accepted")
|
||||
}
|
||||
p := &Plain{Type: TypeText, Thread: strings.Repeat("00", 32), N: 1, SentAt: now.Unix(), Text: "x"}
|
||||
if _, err := SealToBuyer(o.dev, o.ref, p, now, testDifficulty); err == nil {
|
||||
t.Error("sealing to a low-order thread key succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaintextRules(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
own := func(p *Plain) error {
|
||||
_, err := SealToBuyer(o.dev, o.ref, p, now, testDifficulty)
|
||||
return err
|
||||
}
|
||||
buyer := func(p *Plain) error {
|
||||
_, err := SealToOwner(o.l, tk, p, now, testDifficulty)
|
||||
return err
|
||||
}
|
||||
grant := func() *Plain {
|
||||
return &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(),
|
||||
Address: "Weg 1", ValidUntil: now.Add(time.Hour).Unix()}
|
||||
}
|
||||
if err := own(grant()); err != nil {
|
||||
t.Fatalf("valid grant: %v", err)
|
||||
}
|
||||
|
||||
bad := map[string]func() error{
|
||||
"buyers cannot grant": func() error {
|
||||
g := grant()
|
||||
g.Thread = ""
|
||||
return buyer(g)
|
||||
},
|
||||
"grant without address": func() error { g := grant(); g.Address = ""; return own(g) },
|
||||
"grant with text": func() error { g := grant(); g.Text = "hi"; return own(g) },
|
||||
"valid_until in the past": func() error {
|
||||
g := grant()
|
||||
g.ValidUntil = g.SentAt
|
||||
return own(g)
|
||||
},
|
||||
"valid_until too far": func() error {
|
||||
g := grant()
|
||||
g.ValidUntil = g.SentAt + int64(MaxGrantValidity/time.Second) + 1
|
||||
return own(g)
|
||||
},
|
||||
"text with grant fields": func() error {
|
||||
p := hello("hi")
|
||||
p.Address = "Weg 1"
|
||||
return buyer(p)
|
||||
},
|
||||
"empty text": func() error { return buyer(hello("")) },
|
||||
"control character": func() error { return buyer(hello("a\x07b")) },
|
||||
"unknown type": func() error { p := hello("x"); p.Type = "image"; return buyer(p) },
|
||||
"counter from zero": func() error { p := hello("x"); p.N = 0; return buyer(p) },
|
||||
"invalid utf-8": func() error { return buyer(hello("a\xffb")) },
|
||||
}
|
||||
for name, f := range bad {
|
||||
if err := f(); err == nil {
|
||||
t.Errorf("%s: accepted", name)
|
||||
}
|
||||
}
|
||||
if err := buyer(hello("Zeile 1\nZeile
2")); err != nil {
|
||||
t.Errorf("newlines and U+2028 should be fine: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaintextMustBeCanonical(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
// Valid content plus an unknown field, sealed correctly: the owner must refuse it.
|
||||
body := []byte(`{"n":1,"sent_at":1800000000,"t":"text","text":"hi","thread":"` + tk.PublicHex() + `","x":1}`)
|
||||
rpk, _ := ed25519PublicToX25519(ed25519.PublicKey(mustHex(t, o.l.Device)))
|
||||
e := &Envelope{Version: Version, Listing: o.ref, To: ToOwner, Rcpt: o.l.Device,
|
||||
CreatedAt: now.Unix(), ExpiresAt: now.Add(time.Hour).Unix()}
|
||||
epk, ct, err := seal(rpk, func(epk string) ([]byte, error) { e.EPK = epk; return e.headerBytes() }, body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e.EPK, e.CT = epk, hex.EncodeToString(ct)
|
||||
if _, err := e.OpenAsOwner(o.dev); err == nil || !strings.Contains(err.Error(), "canonical") {
|
||||
t.Fatalf("non-canonical plaintext accepted: %v", err)
|
||||
}
|
||||
if _, err := decodePlain([]byte(`{"t":"text"`)); err == nil {
|
||||
t.Fatal("broken JSON accepted")
|
||||
}
|
||||
b, _ := jcs.Marshal(hello("x"))
|
||||
if _, err := decodePlain(append([]byte(" "), b...)); err == nil {
|
||||
t.Fatal("whitespace-padded JSON accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailboxIsStableAndOpaque(t *testing.T) {
|
||||
k := thread(t)
|
||||
a, _ := k.Mailbox()
|
||||
b, _ := Mailbox(k.PublicHex())
|
||||
if a != b || len(a) != 32 || strings.Contains(a, k.PublicHex()[:8]) {
|
||||
t.Fatalf("mailbox %q", a)
|
||||
}
|
||||
if _, err := Mailbox("zz"); err == nil {
|
||||
t.Fatal("bad key accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestThreadKeyRoundTrip(t *testing.T) {
|
||||
k := thread(t)
|
||||
again, err := ThreadKeyFromBytes(k.Bytes())
|
||||
if err != nil || again.PublicHex() != k.PublicHex() {
|
||||
t.Fatalf("restoring a thread key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFirstMessageRules(t *testing.T) {
|
||||
ok := []string{
|
||||
"Guten Tag, ist die Wohnung noch frei?",
|
||||
"Ich komme z. B. am Samstag, ca. 10 Uhr.",
|
||||
"Preis 1.200 Euro, ok? Ja. Gut.",
|
||||
"Hallo, wir sind 2 Personen (u.a. Nichtraucher).",
|
||||
}
|
||||
links := []string{
|
||||
"schaut mal https://example.com/x",
|
||||
"http://evil",
|
||||
"ftp://x",
|
||||
"WWW.example",
|
||||
"auf beispiel.de gibt es mehr",
|
||||
"mail an max@example.com",
|
||||
"Hallo.Ich komme morgen",
|
||||
"Beispiel.DE",
|
||||
"bit.ly/abc",
|
||||
"auf straße-1.com",
|
||||
}
|
||||
for _, s := range ok {
|
||||
if ContainsLink(s) {
|
||||
t.Errorf("%q wrongly flagged as a link", s)
|
||||
}
|
||||
}
|
||||
for _, s := range links {
|
||||
if !ContainsLink(s) {
|
||||
t.Errorf("%q not flagged as a link", s)
|
||||
}
|
||||
}
|
||||
long := &Plain{Type: TypeText, Text: strings.Repeat("a", MaxFirstText+1)}
|
||||
if long.CheckBuyerFirst() == nil {
|
||||
t.Error("overlong first message accepted")
|
||||
}
|
||||
if (&Plain{Type: TypeText, Text: "gerne!"}).CheckBuyerFirst() != nil {
|
||||
t.Error("harmless first message rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func mustHex(t *testing.T, s string) []byte {
|
||||
t.Helper()
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
)
|
||||
|
||||
const (
|
||||
TypeText = "text"
|
||||
TypeGrant = "grant"
|
||||
|
||||
// Limits are in UTF-8 bytes.
|
||||
MaxFirstText = 1000
|
||||
MaxText = 2000
|
||||
MaxAddress = 300
|
||||
MaxPhone = 40
|
||||
MaxEmail = 120
|
||||
MaxNote = 1000
|
||||
// MaxGrantValidity bounds valid_until.
|
||||
MaxGrantValidity = 30 * 24 * time.Hour
|
||||
|
||||
replyContext = "allmende-reply-v1\n"
|
||||
)
|
||||
|
||||
// Plain is what an envelope carries inside its ciphertext.
|
||||
type Plain struct {
|
||||
Type string `json:"t"` // "text" or "grant"
|
||||
Thread string `json:"thread"` // thread public key, hex
|
||||
N int64 `json:"n"` // sender's counter in this thread, from 1
|
||||
SentAt int64 `json:"sent_at"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Address string `json:"address,omitempty"` // grant only
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
// ValidUntil is when a grant stops being shown (advisory).
|
||||
ValidUntil int64 `json:"valid_until,omitempty"`
|
||||
|
||||
// Owner replies are signed; buyer messages carry none of these.
|
||||
Listing *Ref `json:"listing,omitempty"`
|
||||
Device string `json:"device,omitempty"`
|
||||
Cert *identity.Cert `json:"cert,omitempty"`
|
||||
Sig string `json:"sig,omitempty"`
|
||||
}
|
||||
|
||||
func decodePlain(body []byte) (*Plain, error) {
|
||||
var p Plain
|
||||
if err := json.Unmarshal(body, &p); err != nil {
|
||||
return nil, errors.New("message: malformed plaintext")
|
||||
}
|
||||
// Re-encoding must reproduce the input exactly, so unknown fields,
|
||||
// non-canonical spelling and duplicates are all rejected.
|
||||
again, err := jcs.Marshal(&p)
|
||||
if err != nil || !bytes.Equal(again, body) {
|
||||
return nil, errors.New("message: plaintext is not canonical")
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func (p *Plain) unsignedBytes() ([]byte, error) {
|
||||
c := *p
|
||||
c.Sig = ""
|
||||
return jcs.Marshal(&c)
|
||||
}
|
||||
|
||||
func (p *Plain) signOwner(dev *identity.Device, ref Ref) {
|
||||
p.Listing = &Ref{Author: ref.Author, ID: ref.ID}
|
||||
p.Device = dev.Cert.Device
|
||||
p.Cert = dev.Cert
|
||||
p.Sig = ""
|
||||
b, _ := p.unsignedBytes() // cannot fail for the types in Plain
|
||||
p.Sig = hex.EncodeToString(dev.Key.Sign(append([]byte(replyContext), b...)))
|
||||
}
|
||||
|
||||
// verifyOwner checks that the reply was signed by a device certified by the
|
||||
// author of the listing it names. It cannot know about later revocations.
|
||||
func (p *Plain) verifyOwner() error {
|
||||
if p.Cert == nil || p.Listing == nil {
|
||||
return errors.New("message: reply is not signed")
|
||||
}
|
||||
if err := p.Cert.Check(); err != nil {
|
||||
return fmt.Errorf("message: %w", err)
|
||||
}
|
||||
if p.Cert.Author != p.Listing.Author || p.Cert.Device != p.Device {
|
||||
return errors.New("message: certificate does not match the listing's author and the device")
|
||||
}
|
||||
if !p.Cert.Covers(p.SentAt) {
|
||||
return errors.New("message: sent outside the certificate's validity")
|
||||
}
|
||||
b, err := p.unsignedBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sig, err := hex.DecodeString(p.Sig)
|
||||
if err != nil || len(sig) != 64 {
|
||||
return errors.New("message: malformed signature")
|
||||
}
|
||||
if !identity.Verify(p.Device, append([]byte(replyContext), b...), sig) {
|
||||
return errors.New("message: bad signature")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validate checks structure for a plaintext travelling in direction to.
|
||||
func (p *Plain) validate(to string) error {
|
||||
if !isHex(p.Thread, 64) {
|
||||
return errors.New("message: thread must be 64 hex characters")
|
||||
}
|
||||
if p.N < 1 || p.N > maxSafeInt || p.SentAt <= 0 || p.SentAt > maxSafeInt {
|
||||
return errors.New("message: n or sent_at out of range")
|
||||
}
|
||||
owner := to == ToBuyer
|
||||
if owner {
|
||||
if p.Listing == nil || !isHex(p.Listing.Author, 64) || !isHex(p.Listing.ID, 32) ||
|
||||
!isHex(p.Device, 64) || p.Cert == nil || !isHex(p.Sig, 128) {
|
||||
return errors.New("message: owner reply must be signed")
|
||||
}
|
||||
} else if p.Listing != nil || p.Device != "" || p.Cert != nil || p.Sig != "" {
|
||||
return errors.New("message: buyer messages are not signed")
|
||||
}
|
||||
switch p.Type {
|
||||
case TypeText:
|
||||
if p.Address != "" || p.Phone != "" || p.Email != "" || p.Note != "" || p.ValidUntil != 0 {
|
||||
return errors.New("message: text must not carry grant fields")
|
||||
}
|
||||
return checkText(p.Text, 1, MaxText, true)
|
||||
case TypeGrant:
|
||||
if !owner {
|
||||
return errors.New("message: only the owner can release an address")
|
||||
}
|
||||
if p.Text != "" {
|
||||
return errors.New("message: a grant carries its words in note")
|
||||
}
|
||||
if err := checkText(p.Address, 1, MaxAddress, true); err != nil {
|
||||
return fmt.Errorf("address: %w", err)
|
||||
}
|
||||
if err := checkText(p.Phone, 0, MaxPhone, false); err != nil {
|
||||
return fmt.Errorf("phone: %w", err)
|
||||
}
|
||||
if err := checkText(p.Email, 0, MaxEmail, false); err != nil {
|
||||
return fmt.Errorf("email: %w", err)
|
||||
}
|
||||
if err := checkText(p.Note, 0, MaxNote, true); err != nil {
|
||||
return fmt.Errorf("note: %w", err)
|
||||
}
|
||||
if p.ValidUntil <= p.SentAt || time.Duration(p.ValidUntil-p.SentAt)*time.Second > MaxGrantValidity {
|
||||
return errors.New("message: valid_until must be within 30 days after sent_at")
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("message: unknown type %q", p.Type)
|
||||
}
|
||||
}
|
||||
|
||||
// checkText limits s to maxBytes of UTF-8 and applies the listing text rules.
|
||||
// The rune limit passed on is maxBytes too: runes never outnumber bytes.
|
||||
func checkText(s string, min, maxBytes int, newlines bool) error {
|
||||
if len(s) > maxBytes {
|
||||
return fmt.Errorf("longer than %d bytes", maxBytes)
|
||||
}
|
||||
return listing.ValidText(s, min, maxBytes, newlines)
|
||||
}
|
||||
|
||||
// CheckBuyerFirst applies the extra rules for a buyer's messages before the
|
||||
// owner has replied: shorter, and no links. Relays cannot enforce this (the
|
||||
// text is encrypted), so the owner's node and the buyer's browser do.
|
||||
func (p *Plain) CheckBuyerFirst() error {
|
||||
if len(p.Text) > MaxFirstText {
|
||||
return fmt.Errorf("a first message may have at most %d bytes", MaxFirstText)
|
||||
}
|
||||
if ContainsLink(p.Text) {
|
||||
return errors.New("a first message must not contain links")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// hostname matches label.tld, in any script, so "example.com" and
|
||||
// "Beispiel.de" are caught but "z. B." and "etc." are not.
|
||||
var hostname = regexp.MustCompile(`[\p{L}\p{N}-]+\.\p{L}{2,}`)
|
||||
|
||||
// ContainsLink is a heuristic for URLs and addresses: a scheme separator,
|
||||
// "www.", or a hostname-like word. It also flags "Hallo.Ich" typed without a
|
||||
// space; the message is then hidden, not lost, and the browser asks the buyer
|
||||
// to fix it. It is a speed bump against scams, not a guarantee.
|
||||
func ContainsLink(s string) bool {
|
||||
l := strings.ToLower(s)
|
||||
return strings.Contains(l, "://") || strings.Contains(l, "www.") || hostname.MatchString(l)
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"now": 1800000000,
|
||||
"difficulty": 8,
|
||||
"listing": {
|
||||
"author": "381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803",
|
||||
"id": "00112233445566778899aabbccddeeff"
|
||||
},
|
||||
"device": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c",
|
||||
"device_seed": "0707070707070707070707070707070707070707070707070707070707070707",
|
||||
"thread_secret": "1111111111111111111111111111111111111111111111111111111111111111",
|
||||
"thread_public": "7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13",
|
||||
"mailbox": "1c5080388031861646a688822711548c",
|
||||
"to_owner": {
|
||||
"esk": "2222222222222222222222222222222222222222222222222222222222222222",
|
||||
"plain": {
|
||||
"t": "text",
|
||||
"thread": "7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13",
|
||||
"n": 1,
|
||||
"sent_at": 1800000000,
|
||||
"text": "Guten Tag, ist die Wohnung noch frei? Schöne Grüße 🏠\nZeile 2\u2028Zeile 3"
|
||||
},
|
||||
"plain_canonical": "{\"n\":1,\"sent_at\":1800000000,\"t\":\"text\",\"text\":\"Guten Tag, ist die Wohnung noch frei? Schöne Grüße 🏠\\nZeile 2\u2028Zeile 3\",\"thread\":\"7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13\"}",
|
||||
"padded_len": 512,
|
||||
"canonical": "{\"created_at\":1800000000,\"ct\":\"49dcc562f0a7ca98687ec373eb9b4528cafae1ccb46e9f9e8e746dd1c652124d5eb9ee8e63335a63c41148e59fa5cf8cd773309221668cda3d9d144e51285e99fe427ffe8ec65660c28eae5b10f61060864f5730d792859ce6a5baa3b9109b9398fb1e22dc4761b2c00af6f05b1ff386507bf1e407dfdcb81a467f9fe604dbbaf005db50387ad3fd1364e8f817d25d66e7a1c231c18460306c02bc5cc16725c9beb0ac9b1334a5f27be9b2f9d006524fd620f22b106a3a8dd4b82a5ee5a7a6f845b698c19d3035cfbf73f11346aa98b108aef1696e95637494b350993b71c981a13b192cb805f47917e8c073876a0116033cfa63a877bcd0604c0011f5c2197ba2fe384134c2cd2b55cac1b7cbe6997e11d9ceec3f71b1787a5721b3ccc082ef225f721c81884e89d37d0b7bbd48681d7e42d62cd5ca9dfab692d7f3a736a7f2d7db36f60c2b1aa5a4fb5fe39eb92cb01c24071eee6f515ff494f82ab303413275c4404e1d7775f7429306c948bfae6e659fea1be2b6948d00f4c8a022033f9ad040665e54ec9aeacd11d973dc6d32eb1535677cff8a9b248f688695b42e1608ff60c9ad0badce345a5828c21f4da49914ad4055b7df8dc06ea8976f24abc38b6fd7746ebecbcbde1ca9becce4dae99501819ffe4896319ee69151a4416ffc18aa56a0d481b4171789649cec9668c830fede417fe7b87fd09dcc441aff4eacc643c0e0fe21a773459e74e85b0ea592d3\",\"epk\":\"0faa684ed28867b97f4a6a2dee5df8ce974e76b7018e3f22a1c4cf2678570f20\",\"expires_at\":1801209600,\"listing\":{\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"id\":\"00112233445566778899aabbccddeeff\"},\"pow\":527,\"rcpt\":\"ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\",\"to\":\"owner\",\"v\":1}",
|
||||
"hash": "0034399737231f0ad0aef3caf03a682fdcc31fd79055e73f206f4a35da23334c",
|
||||
"work": 10
|
||||
},
|
||||
"to_buyer": {
|
||||
"esk": "3333333333333333333333333333333333333333333333333333333333333333",
|
||||
"plain": {
|
||||
"t": "grant",
|
||||
"thread": "7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13",
|
||||
"n": 1,
|
||||
"sent_at": 1800000000,
|
||||
"address": "Musterstraße 12, 20255 Hamburg",
|
||||
"phone": "+49 40 123456",
|
||||
"note": "Samstag 10 Uhr, bitte zweimal klingeln 🔔",
|
||||
"valid_until": 1800604800,
|
||||
"listing": {
|
||||
"author": "381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803",
|
||||
"id": "00112233445566778899aabbccddeeff"
|
||||
},
|
||||
"device": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c",
|
||||
"cert": {
|
||||
"v": 1,
|
||||
"author": "381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803",
|
||||
"device": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c",
|
||||
"issued_at": 1799996400,
|
||||
"expires_at": 1807776000,
|
||||
"sig": "dab8cef621f829c47eaf5bfea7fcaa3dad144b718d322b4c4989ecc33931c925afcfb50f642ce0c692bc53ceb57f67ddd3c347ff95a496e4f6413ecb5b32ac0e"
|
||||
},
|
||||
"sig": "4908dc2443f4436bca032583504b06e932c9acbf256814033e8b1982c7cb1e02a6a10999c3077e01606358c89461a711e27418d15dad53059f3ee347d960f408"
|
||||
},
|
||||
"plain_canonical": "{\"address\":\"Musterstraße 12, 20255 Hamburg\",\"cert\":{\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"device\":\"ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\",\"expires_at\":1807776000,\"issued_at\":1799996400,\"sig\":\"dab8cef621f829c47eaf5bfea7fcaa3dad144b718d322b4c4989ecc33931c925afcfb50f642ce0c692bc53ceb57f67ddd3c347ff95a496e4f6413ecb5b32ac0e\",\"v\":1},\"device\":\"ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\",\"listing\":{\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"id\":\"00112233445566778899aabbccddeeff\"},\"n\":1,\"note\":\"Samstag 10 Uhr, bitte zweimal klingeln 🔔\",\"phone\":\"+49 40 123456\",\"sent_at\":1800000000,\"sig\":\"4908dc2443f4436bca032583504b06e932c9acbf256814033e8b1982c7cb1e02a6a10999c3077e01606358c89461a711e27418d15dad53059f3ee347d960f408\",\"t\":\"grant\",\"thread\":\"7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13\",\"valid_until\":1800604800}",
|
||||
"padded_len": 1024,
|
||||
"canonical": "{\"created_at\":1800000000,\"ct\":\"8ab2fc4f4fadaa3c8dc5f439bf14bfb7a7bcbd87d4c86d55db264b14f4ff754e617444acbf11421d83bdb0d8b826cb2f1afde4898bb8b53ba9a3ece8cb3972fab5f777b9fbf3217588c802fc0d96abc0bd0e8367ad16ac7b81205b00e8e7885703228d813495208f42deeb0b7a3f104d605e77d83f191394156745b227a7dfd753243d768d49c37cd0e53e19c801fc6b45a7f1fd4cc0d5af37ca87a9e600ccbadec048ee71f482f526cec43ba5941210b4c28bc633b3f8373587f9be728bd90944ee4c81703fcd27eaa8d86a41a41d37e499d33e5d1024c1723d0d77d7a5a53012363446d80ca590b7bc34a9930cf1d2b1c6335e56c1eb22534875729e4f8de020bd2cd2993593550b384ff9601fd8d0a072b32e6a7a2e36c71f9259b78030170e9dfa74fe09ed774e08feca66b2b791545b592fa4b7502d5031456f5e55b1ecc6f928216f591f1c57ac0222a66ff7c5af2eeb1a30672a9be846ac9da682a4bb97cad9562f62b1928d9db8b7d27ef494b0372fc0279d6430ca8443f9e40bf2dd082bc79613696e36f81e6600d567f0580bf42713658f6bd92c3c6c18e63ead7e070da60f5470fbfc179e0e623f7cfaa6b82ed9f89495cacdfc86cc0c2ed119efd99a986af689b4ef62384f801da777d5fce0a7260ae00001d70a98a3cb8a6f93a7286f1f7915b4d2da0a7b6af304903061aa96657922a33d5048c2253a3524533f4ed14cae2e0f4cc65a110cf681176ab31510d3316b858af6caee2538e164a6e51095ad4b31aab8c14706f031ed0c8fff2d30110e224dfc3ab5ec07a01e9a5b5e754bb2b5060cad3b30361a80c08e136e59cc02ddf50444a8f67ee0f8d1704a1ee7f73e5a03774d28bf71393313cdad43a6e11d56f7b1125af733c7095fd4dca009ffd951d13b74bf286e0ca6c0ed11268d07b57d98ec27093fcaa08bf41929639edd8afe4b7bc6a8a0e0f22e70e7a72cfa1fa0888b52423447003732c38e667aa3a1616c84eee78066c73234c5550ea3a32cbd46c9a2ad99e02b94cf48abb6155cebc5d0f344150e4d439b468f02ab82fc5ec8c90c9cecb838fe86d1bbff101239c5ccf33b0d1298332f7150e6e46e49dd5c06212fd78ddc077b75368002b54c2098ae9e3ca33b239134c406c8adc4c3af9b96095293c8f852ff012d3a6c31cb3f6c7feac339cf4bb27eb2841849001c9c499f472d16ee7fe8184bb2dbe9fa93dbcf76dcc6c6b3c7827bf62090d59b77b5432e974d74fe8a2e7c5aee68b7a7fe96a530e03e62f694b0abd035f22f40d64da500a09d71d3488261b3cbff6d6a3fd422084602a3672b89490fd9c0932017f366223ae4fa132df2111b218e711020218f4378432ef97045de9be216124051b68f0a7fd0601a9b0da6fa22118ae2d6eae2c28106bc803b8732251219eb5891812c5b0ebfab504dc60d3f60993c0484b7813a40f5595969e8f40cb51b1167\",\"epk\":\"7b0d47d93427f8311160781c7c733fd89f88970aef490d8aa0ee19a4cb8a1b14\",\"expires_at\":1801209600,\"listing\":{\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"id\":\"00112233445566778899aabbccddeeff\"},\"pow\":79,\"rcpt\":\"1c5080388031861646a688822711548c\",\"to\":\"buyer\",\"v\":1}",
|
||||
"hash": "00453c5f05142dd4176db4381d30cf00079b847189aa60902d7bf9d9e4a5a3ee",
|
||||
"work": 9
|
||||
},
|
||||
"links": [
|
||||
{
|
||||
"text": "Guten Tag, ist die Wohnung noch frei?",
|
||||
"link": false
|
||||
},
|
||||
{
|
||||
"text": "Ich komme z. B. am Samstag, ca. 10 Uhr.",
|
||||
"link": false
|
||||
},
|
||||
{
|
||||
"text": "Preis 1.200 Euro, ok? Ja. Gut.",
|
||||
"link": false
|
||||
},
|
||||
{
|
||||
"text": "Hallo, wir sind 2 Personen (u.a. Nichtraucher).",
|
||||
"link": false
|
||||
},
|
||||
{
|
||||
"text": "schaut mal https://example.com/x",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "WWW.example",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "auf beispiel.de gibt es mehr",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "mail an max@example.com",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "Hallo.Ich komme morgen",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "Beispiel.DE",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "auf straße-1.com",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "bit.ly/abc",
|
||||
"link": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package p2p
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const msgRegion = "u1x"
|
||||
|
||||
func hello(t *testing.T, text string) *message.Plain {
|
||||
t.Helper()
|
||||
return &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: text}
|
||||
}
|
||||
|
||||
func TestMessagesTravelBetweenBuyerGatewayAndOwner(t *testing.T) {
|
||||
owner := startNode(t, nil, msgRegion)
|
||||
gateway := startNode(t, nil, msgRegion)
|
||||
connect(t, gateway, owner)
|
||||
|
||||
l := owner.listing(t, "u1xjhx")
|
||||
if err := owner.Publish(context.Background(), l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
eventually(t, "gateway learns the listing", func() bool {
|
||||
_, err := gateway.s.Get(context.Background(), l.Author, l.ID)
|
||||
return err == nil
|
||||
})
|
||||
|
||||
// The buyer's browser sends through the gateway.
|
||||
tk, err := message.NewThreadKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env, err := message.SealToOwner(l, tk, hello(t, "Ist die Wohnung noch frei?"), time.Now(), msgDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gateway.PublishMessage(context.Background(), msgRegion, env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var got []*message.Envelope
|
||||
eventually(t, "owner receives the message", func() bool {
|
||||
got, _ = owner.s.OwnerMessages(context.Background(), l.Author)
|
||||
return len(got) == 1
|
||||
})
|
||||
plain, err := got[0].OpenAsOwner(owner.dev)
|
||||
if err != nil || plain.Text != "Ist die Wohnung noch frei?" {
|
||||
t.Fatalf("owner could not read it: %v %+v", err, plain)
|
||||
}
|
||||
|
||||
// The owner answers; the reply waits in the gateway's mailbox.
|
||||
reply := &message.Plain{Type: message.TypeText, Thread: plain.Thread, N: 1, SentAt: time.Now().Unix(), Text: "Ja!"}
|
||||
renv, err := message.SealToBuyer(owner.dev, message.Ref{Author: l.Author, ID: l.ID}, reply, time.Now(), msgDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := owner.PublishMessage(context.Background(), msgRegion, renv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mailbox, _ := tk.Mailbox()
|
||||
var box []*message.Envelope
|
||||
eventually(t, "reply reaches the gateway's mailbox", func() bool {
|
||||
box, _ = gateway.s.Mailbox(context.Background(), mailbox, 0, 10)
|
||||
return len(box) == 1
|
||||
})
|
||||
back, err := box[0].OpenAsBuyer(tk)
|
||||
if err != nil || back.Text != "Ja!" {
|
||||
t.Fatalf("buyer could not read the reply: %v %+v", err, back)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLateJoinersSyncMessagesAfterListings(t *testing.T) {
|
||||
owner := startNode(t, nil, msgRegion)
|
||||
l := owner.listing(t, "u1xjhx")
|
||||
if err := owner.Publish(context.Background(), l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tk, _ := message.NewThreadKey()
|
||||
env, err := message.SealToOwner(l, tk, hello(t, "hallo"), time.Now(), msgDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := owner.PublishMessage(context.Background(), msgRegion, env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply := &message.Plain{Type: message.TypeText, Thread: tk.PublicHex(), N: 1, SentAt: time.Now().Unix(), Text: "ok"}
|
||||
renv, _ := message.SealToBuyer(owner.dev, message.Ref{Author: l.Author, ID: l.ID}, reply, time.Now(), msgDifficulty)
|
||||
if err := owner.PublishMessage(context.Background(), msgRegion, renv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Joins later, and in another region as well, which must stay empty.
|
||||
late := startNode(t, nil, msgRegion)
|
||||
other := startNode(t, nil, "u1y")
|
||||
connect(t, late, owner)
|
||||
connect(t, other, owner)
|
||||
|
||||
eventually(t, "late joiner has the owner-bound message", func() bool {
|
||||
got, _ := late.s.OwnerMessages(context.Background(), l.Author)
|
||||
return len(got) == 1
|
||||
})
|
||||
mailbox, _ := tk.Mailbox()
|
||||
eventually(t, "late joiner has the reply", func() bool {
|
||||
box, _ := late.s.Mailbox(context.Background(), mailbox, 0, 10)
|
||||
return len(box) == 1
|
||||
})
|
||||
if n, _ := other.s.MessageCount(context.Background()); n != 0 {
|
||||
t.Fatalf("a node in another region holds %d envelopes", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidMessagesAreNotAccepted(t *testing.T) {
|
||||
a := startNode(t, nil, msgRegion)
|
||||
l := a.listing(t, "u1xjhx")
|
||||
if err := a.Publish(context.Background(), l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tk, _ := message.NewThreadKey()
|
||||
|
||||
// No proof-of-work at this node's difficulty.
|
||||
var weak *message.Envelope
|
||||
for {
|
||||
e, err := message.SealToOwner(l, tk, hello(t, "x"), time.Now(), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, _ := e.Work(); w < msgDifficulty {
|
||||
weak = e
|
||||
break
|
||||
}
|
||||
}
|
||||
if err := a.PublishMessage(context.Background(), msgRegion, weak); !errors.Is(err, store.ErrInvalid) {
|
||||
t.Fatalf("weak message: %v, want ErrInvalid", err)
|
||||
}
|
||||
|
||||
// A listing this node does not hold.
|
||||
b := startNode(t, nil, msgRegion)
|
||||
foreign := b.listing(t, "u1xjhx")
|
||||
env, _ := message.SealToOwner(foreign, tk, hello(t, "x"), time.Now(), msgDifficulty)
|
||||
if err := a.PublishMessage(context.Background(), msgRegion, env); !errors.Is(err, store.ErrNoListing) {
|
||||
t.Fatalf("unknown listing: %v, want ErrNoListing", err)
|
||||
}
|
||||
if n, _ := a.s.MessageCount(context.Background()); n != 0 {
|
||||
t.Fatalf("rejected messages were stored (%d)", n)
|
||||
}
|
||||
}
|
||||
+112
-5
@@ -30,11 +30,15 @@ import (
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
listingTopicPrefix = "/allmende/1/listings/"
|
||||
// messageTopicPrefix carries encrypted message envelopes, one topic per
|
||||
// region next to the listing topic.
|
||||
messageTopicPrefix = "/allmende/1/messages/"
|
||||
// RevocationTopic carries identity revocations for the whole network.
|
||||
RevocationTopic = "/allmende/1/revocations"
|
||||
|
||||
@@ -52,11 +56,14 @@ type Config struct {
|
||||
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)
|
||||
RedialInterval time.Duration // how often lost bootstrap peers are redialed (default 20s)
|
||||
Clock func() time.Time // default time.Now
|
||||
Logger *slog.Logger
|
||||
Difficulty int // required proof-of-work bits
|
||||
// MessageDifficulty is the proof-of-work bits required of message
|
||||
// envelopes; it must match the store's.
|
||||
MessageDifficulty int
|
||||
SyncPageSize int // records per sync page (default 500)
|
||||
RedialInterval time.Duration // how often lost bootstrap peers are redialed (default 20s)
|
||||
Clock func() time.Time // default time.Now
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
// Node is a running participant.
|
||||
@@ -74,6 +81,7 @@ type Node struct {
|
||||
|
||||
mu sync.Mutex
|
||||
topics map[string]*pubsub.Topic
|
||||
msgTopics map[string]*pubsub.Topic
|
||||
subscribed []string
|
||||
bootstrap []peer.AddrInfo
|
||||
syncing map[peer.ID]bool
|
||||
@@ -126,6 +134,7 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
|
||||
ctx: nctx,
|
||||
cancel: cancel,
|
||||
topics: map[string]*pubsub.Topic{},
|
||||
msgTopics: map[string]*pubsub.Topic{},
|
||||
syncing: map[peer.ID]bool{},
|
||||
bootstrap: bootstrap,
|
||||
}
|
||||
@@ -226,6 +235,24 @@ func (n *Node) Publish(ctx context.Context, l *listing.Listing) error {
|
||||
return t.Publish(ctx, data)
|
||||
}
|
||||
|
||||
// PublishMessage stores an envelope locally (which verifies it) and gossips it
|
||||
// on the message topic of region. The node must replicate the region: owner-
|
||||
// bound envelopes are only accepted for listings it holds.
|
||||
func (n *Node) PublishMessage(ctx context.Context, region string, e *message.Envelope) error {
|
||||
if _, err := n.cfg.Store.PutMessage(ctx, region, e); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := e.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t, err := n.messageTopic(region)
|
||||
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 {
|
||||
@@ -307,9 +334,56 @@ func (n *Node) subscribeRegion(region string) error {
|
||||
}
|
||||
})
|
||||
}()
|
||||
|
||||
mt, err := n.messageTopic(region)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
msub, err := mt.Subscribe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n.wg.Add(1)
|
||||
go func() {
|
||||
defer n.wg.Done()
|
||||
n.consume(msub, func(msg *pubsub.Message) {
|
||||
e, ok := msg.ValidatorData.(*message.Envelope)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
switch _, err := n.cfg.Store.PutMessage(n.ctx, region, e); {
|
||||
case err == nil, errors.Is(err, store.ErrNoListing), errors.Is(err, store.ErrQueueFull):
|
||||
default:
|
||||
n.log.Warn("store message", "err", err)
|
||||
}
|
||||
})
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// messageTopic joins (once) the message topic for region.
|
||||
func (n *Node) messageTopic(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.msgTopics[region]; ok {
|
||||
return t, nil
|
||||
}
|
||||
name := messageTopicPrefix + region
|
||||
if err := n.ps.RegisterTopicValidator(name, n.messageValidator(region),
|
||||
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t, err := n.ps.Join(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n.msgTopics[region] = t
|
||||
return t, 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) {
|
||||
@@ -360,6 +434,39 @@ func (n *Node) listingValidator(region string) pubsub.ValidatorEx {
|
||||
}
|
||||
}
|
||||
|
||||
// messageValidator checks what a relay can see: the envelope's structure,
|
||||
// size and proof-of-work, and the listing it points to. It cannot read the
|
||||
// content. Invalid envelopes cost the relaying peer score; ones this node
|
||||
// cannot place (unknown listing, a device that changed) or whose clocks
|
||||
// disagree are ignored without penalty.
|
||||
func (n *Node) messageValidator(region string) pubsub.ValidatorEx {
|
||||
return func(ctx context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
|
||||
if len(msg.Data) > message.MaxSize {
|
||||
return pubsub.ValidationReject
|
||||
}
|
||||
var e message.Envelope
|
||||
if err := json.Unmarshal(msg.Data, &e); err != nil {
|
||||
return pubsub.ValidationReject
|
||||
}
|
||||
// Only the canonical encoding, so every node derives the same ID.
|
||||
if canon, err := e.Bytes(); err != nil || !bytes.Equal(canon, msg.Data) {
|
||||
return pubsub.ValidationReject
|
||||
}
|
||||
err := n.cfg.Store.CheckMessage(ctx, region, &e)
|
||||
switch {
|
||||
case err == nil:
|
||||
msg.ValidatorData = &e
|
||||
return pubsub.ValidationAccept
|
||||
case errors.Is(err, listing.ErrTimeWindow), errors.Is(err, store.ErrNoListing):
|
||||
return pubsub.ValidationIgnore
|
||||
case errors.Is(err, store.ErrInvalid):
|
||||
return pubsub.ValidationReject
|
||||
default:
|
||||
return pubsub.ValidationIgnore // a local failure is not the peer's fault
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Node) validateListing(ctx context.Context, data []byte) (*listing.Listing, pubsub.ValidationResult) {
|
||||
if len(data) > listing.MaxSize {
|
||||
return nil, pubsub.ValidationReject
|
||||
|
||||
+14
-10
@@ -18,7 +18,10 @@ import (
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const difficulty = 6
|
||||
const (
|
||||
difficulty = 6
|
||||
msgDifficulty = 4
|
||||
)
|
||||
|
||||
// testLogger is silent unless P2P_DEBUG is set.
|
||||
func testLogger() *slog.Logger {
|
||||
@@ -49,19 +52,20 @@ func startNodeWith(t *testing.T, root *identity.Identity, tweak func(*Config), r
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty})
|
||||
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty, MessageDifficulty: msgDifficulty})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := Config{
|
||||
Device: dev,
|
||||
Store: s,
|
||||
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
|
||||
Regions: regions,
|
||||
Difficulty: difficulty,
|
||||
SyncPageSize: 3,
|
||||
RedialInterval: 200 * time.Millisecond,
|
||||
Logger: testLogger(),
|
||||
Device: dev,
|
||||
Store: s,
|
||||
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
|
||||
Regions: regions,
|
||||
Difficulty: difficulty,
|
||||
MessageDifficulty: msgDifficulty,
|
||||
SyncPageSize: 3,
|
||||
RedialInterval: 200 * time.Millisecond,
|
||||
Logger: testLogger(),
|
||||
}
|
||||
if tweak != nil {
|
||||
tweak(&cfg)
|
||||
|
||||
+68
-3
@@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
@@ -30,11 +32,12 @@ const (
|
||||
)
|
||||
|
||||
type syncRequest struct {
|
||||
Kind string `json:"kind"` // "listings" or "revocations"
|
||||
Kind string `json:"kind"` // "listings", "messages" 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"`
|
||||
AfterAuthor string `json:"after_author,omitempty"` // listings
|
||||
AfterID string `json:"after_id,omitempty"` // listings
|
||||
AfterHash string `json:"after_hash,omitempty"` // messages
|
||||
Limit int `json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
@@ -81,6 +84,27 @@ func (n *Node) handleSync(s network.Stream) {
|
||||
return
|
||||
}
|
||||
}
|
||||
case "messages":
|
||||
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.MessagesSince(n.ctx, req.Region,
|
||||
store.MessageCursor{CreatedAt: req.AfterCreated, Hash: req.AfterHash}, limit)
|
||||
if err != nil {
|
||||
_ = s.Reset()
|
||||
return
|
||||
}
|
||||
for _, e := range items {
|
||||
if !write(e.Bytes()) {
|
||||
_ = s.Reset()
|
||||
return
|
||||
}
|
||||
}
|
||||
case "revocations":
|
||||
revs, err := n.cfg.Store.Revocations(n.ctx)
|
||||
if err != nil {
|
||||
@@ -147,6 +171,47 @@ func (n *Node) SyncFrom(ctx context.Context, p peer.ID) error {
|
||||
if err := n.syncRegion(ctx, p, region); err != nil {
|
||||
return err
|
||||
}
|
||||
// After the listings: owner-bound messages are only accepted for
|
||||
// listings we already hold.
|
||||
if err := n.syncMessages(ctx, p, region); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *Node) syncMessages(ctx context.Context, p peer.ID, region string) error {
|
||||
var cur store.MessageCursor
|
||||
for page := 0; page < maxSyncPages; page++ {
|
||||
var count int
|
||||
var last *message.Envelope
|
||||
err := n.request(ctx, p, syncRequest{
|
||||
Kind: "messages", Region: region, Limit: n.cfg.SyncPageSize,
|
||||
AfterCreated: cur.CreatedAt, AfterHash: cur.Hash,
|
||||
}, func(line []byte) {
|
||||
var e message.Envelope
|
||||
if json.Unmarshal(line, &e) != nil {
|
||||
return
|
||||
}
|
||||
count++
|
||||
last = &e
|
||||
switch _, err := n.cfg.Store.PutMessage(ctx, region, &e); {
|
||||
case err == nil, errors.Is(err, store.ErrNoListing), errors.Is(err, store.ErrQueueFull):
|
||||
default:
|
||||
n.log.Debug("sync: message rejected", "peer", p, "err", err)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count < n.cfg.SyncPageSize || last == nil {
|
||||
return nil
|
||||
}
|
||||
c, err := store.MessageCursorOf(last)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cur = c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
// Directions of an InboxMessage.
|
||||
const (
|
||||
InboxIn = "in" // from a buyer
|
||||
InboxOut = "out" // our reply
|
||||
)
|
||||
|
||||
// InboxMessage is one decrypted message in the owner's conversations.
|
||||
type InboxMessage struct {
|
||||
Hash string // hash of the envelope that carried it
|
||||
Listing message.Ref
|
||||
Thread string
|
||||
Dir string
|
||||
Plain *message.Plain
|
||||
Hidden bool // a buyer message that broke the first-message rules
|
||||
ReceivedAt int64
|
||||
}
|
||||
|
||||
// ThreadSummary describes one conversation.
|
||||
type ThreadSummary struct {
|
||||
Listing message.Ref
|
||||
Thread string
|
||||
Messages int
|
||||
Hidden int
|
||||
Replied bool // we have answered at least once
|
||||
FirstAt int64
|
||||
LastAt int64
|
||||
}
|
||||
|
||||
// Address is the exact location and contact data of a listing. It is stored
|
||||
// only here and used only to prefill an address grant.
|
||||
type Address struct {
|
||||
Address string `json:"address"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
}
|
||||
|
||||
// Region returns the gossip region of a listing, even if it is deleted or
|
||||
// expired but not yet purged, so replies can still be routed.
|
||||
func (s *Store) Region(ctx context.Context, author, id string) (string, error) {
|
||||
var geohash string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT geohash FROM listings WHERE author = ? AND id = ?`, author, id).Scan(&geohash)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return listing.Region(geohash), nil
|
||||
}
|
||||
|
||||
// SeenEnvelopes returns which of the given envelope hashes the owner's node
|
||||
// has already processed.
|
||||
func (s *Store) SeenEnvelopes(ctx context.Context, hashes []string) (map[string]bool, error) {
|
||||
seen := map[string]bool{}
|
||||
for _, h := range hashes {
|
||||
var n int
|
||||
if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM inbox_seen WHERE hash = ?`, h).Scan(&n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen[h] = n > 0
|
||||
}
|
||||
return seen, nil
|
||||
}
|
||||
|
||||
// MarkSeen records an envelope as processed until expiresAt.
|
||||
func (s *Store) MarkSeen(ctx context.Context, hash string, expiresAt int64) error {
|
||||
_, err := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`, hash, expiresAt)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddInbox stores a decrypted message and marks its envelope as seen, in one
|
||||
// transaction. Adding the same hash twice is a no-op.
|
||||
func (s *Store) AddInbox(ctx context.Context, m InboxMessage, seenUntil int64) error {
|
||||
data, err := jcs.Marshal(m.Plain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT OR IGNORE INTO inbox (hash, author, listing_id, thread, dir, n, sent_at, received_at, hidden, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
m.Hash, m.Listing.Author, m.Listing.ID, m.Thread, m.Dir, m.Plain.N, m.Plain.SentAt, m.ReceivedAt,
|
||||
boolInt(m.Hidden), data); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`,
|
||||
m.Hash, seenUntil); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// HasThread reports whether a conversation exists.
|
||||
func (s *Store) HasThread(ctx context.Context, ref message.Ref, thread string) (bool, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`,
|
||||
ref.Author, ref.ID, thread).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// Replied reports whether we have sent anything in the conversation.
|
||||
func (s *Store) Replied(ctx context.Context, ref message.Ref, thread string) (bool, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`,
|
||||
ref.Author, ref.ID, thread).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// NewThreadsSince counts conversations of a listing that began (were first
|
||||
// received) at or after since.
|
||||
func (s *Store) NewThreadsSince(ctx context.Context, ref message.Ref, since int64) (int, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM (
|
||||
SELECT MIN(received_at) AS first FROM inbox
|
||||
WHERE author = ? AND listing_id = ? GROUP BY thread
|
||||
) WHERE first >= ?`, ref.Author, ref.ID, since).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// NextOut returns the counter for our next message in a conversation.
|
||||
func (s *Store) NextOut(ctx context.Context, ref message.Ref, thread string) (int64, error) {
|
||||
var max sql.NullInt64
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT MAX(n) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`,
|
||||
ref.Author, ref.ID, thread).Scan(&max)
|
||||
return max.Int64 + 1, err
|
||||
}
|
||||
|
||||
// Threads lists the author's conversations, most recently active first.
|
||||
func (s *Store) Threads(ctx context.Context, author string) ([]ThreadSummary, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT listing_id, thread, COUNT(*), SUM(hidden), SUM(dir = 'out'), MIN(received_at), MAX(sent_at)
|
||||
FROM inbox WHERE author = ?
|
||||
GROUP BY listing_id, thread
|
||||
ORDER BY MAX(sent_at) DESC, thread`, author)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []ThreadSummary
|
||||
for rows.Next() {
|
||||
t := ThreadSummary{Listing: message.Ref{Author: author}}
|
||||
var replies int
|
||||
if err := rows.Scan(&t.Listing.ID, &t.Thread, &t.Messages, &t.Hidden, &replies, &t.FirstAt, &t.LastAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Replied = replies > 0
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ThreadMessages returns a conversation in order.
|
||||
func (s *Store) ThreadMessages(ctx context.Context, ref message.Ref, thread string) ([]InboxMessage, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT hash, dir, hidden, received_at, data FROM inbox
|
||||
WHERE author = ? AND listing_id = ? AND thread = ?
|
||||
ORDER BY sent_at, dir, n, hash`, ref.Author, ref.ID, thread)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []InboxMessage
|
||||
for rows.Next() {
|
||||
m := InboxMessage{Listing: ref, Thread: thread}
|
||||
var hidden int
|
||||
var data []byte
|
||||
if err := rows.Scan(&m.Hash, &m.Dir, &hidden, &m.ReceivedAt, &data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.Hidden = hidden != 0
|
||||
m.Plain = &message.Plain{}
|
||||
if err := json.Unmarshal(data, m.Plain); err != nil {
|
||||
return nil, fmt.Errorf("store: corrupt inbox row: %w", err)
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DeleteThread erases a conversation from this node.
|
||||
func (s *Store) DeleteThread(ctx context.Context, ref message.Ref, thread string) (bool, error) {
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`DELETE FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`, ref.Author, ref.ID, thread)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
// SetAddress stores the exact address of one of the author's listings.
|
||||
func (s *Store) SetAddress(ctx context.Context, ref message.Ref, a Address) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT OR REPLACE INTO addresses (author, listing_id, address, phone, email) VALUES (?, ?, ?, ?, ?)`,
|
||||
ref.Author, ref.ID, a.Address, a.Phone, a.Email)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetAddress returns the stored address, or ErrNotFound.
|
||||
func (s *Store) GetAddress(ctx context.Context, ref message.Ref) (Address, error) {
|
||||
var a Address
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT address, phone, email FROM addresses WHERE author = ? AND listing_id = ?`,
|
||||
ref.Author, ref.ID).Scan(&a.Address, &a.Phone, &a.Email)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return a, ErrNotFound
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
// DeleteAddress erases the stored address.
|
||||
func (s *Store) DeleteAddress(ctx context.Context, ref message.Ref) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`DELETE FROM addresses WHERE author = ? AND listing_id = ?`, ref.Author, ref.ID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
const (
|
||||
// MaxOwnerQueue is how many live envelopes one listing's owner queue holds.
|
||||
MaxOwnerQueue = 200
|
||||
// MaxMailboxQueue is how many live replies one mailbox holds.
|
||||
MaxMailboxQueue = 50
|
||||
|
||||
defaultMaxMessages = 20000
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNoListing means an owner-bound envelope refers to a listing this node
|
||||
// does not hold live, or to a device that no longer signs for it. This
|
||||
// is usually ordering or a device change, not misbehaviour, so the p2p
|
||||
// layer ignores such envelopes without penalizing the sender.
|
||||
ErrNoListing = errors.New("store: no such live listing")
|
||||
// ErrQueueFull means a queue was full of envelopes with at least as much
|
||||
// proof-of-work as the new one.
|
||||
ErrQueueFull = errors.New("store: message queue full")
|
||||
)
|
||||
|
||||
// PutMessage verifies an envelope as a relay can and stores it in region.
|
||||
// Conflict-free: an envelope's identity is its hash, so duplicates are no-ops.
|
||||
//
|
||||
// Queues are bounded (per listing, per mailbox and overall). When one is full
|
||||
// the envelope with the least proof-of-work is evicted, oldest first, so
|
||||
// filling a queue costs more work than the messages it displaces.
|
||||
func (s *Store) PutMessage(ctx context.Context, region string, e *message.Envelope) (Outcome, error) {
|
||||
now := s.clock()
|
||||
if err := e.Check(now, s.msgDifficulty); err != nil {
|
||||
return Ignored, fmt.Errorf("%w: %w", ErrInvalid, err)
|
||||
}
|
||||
if !listing.ValidRegion(region) {
|
||||
return Ignored, fmt.Errorf("%w: bad region %q", ErrInvalid, region)
|
||||
}
|
||||
hash, err := e.Hash()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
work, err := e.Work()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
data, err := e.Bytes()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM messages WHERE expires_at <= ?`, now.Unix()); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
if err := s.route(ctx, tx, now.Unix(), region, e); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
var dup int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM messages WHERE hash = ?`, hash).Scan(&dup); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if dup > 0 {
|
||||
return Ignored, nil
|
||||
}
|
||||
|
||||
// Make room: the queue's own cap first, then the overall cap.
|
||||
var victims []string
|
||||
if e.To == message.ToOwner {
|
||||
v, reject, err := victim(ctx, tx, `to_dir = 'owner' AND author = ? AND listing_id = ?`,
|
||||
[]any{e.Listing.Author, e.Listing.ID}, s.ownerQueue, work)
|
||||
if err != nil || reject {
|
||||
return Ignored, orFull(err)
|
||||
}
|
||||
if v != "" {
|
||||
victims = append(victims, v)
|
||||
}
|
||||
} else {
|
||||
v, reject, err := victim(ctx, tx, `to_dir = 'buyer' AND rcpt = ?`, []any{e.Rcpt}, s.mailboxQueue, work)
|
||||
if err != nil || reject {
|
||||
return Ignored, orFull(err)
|
||||
}
|
||||
if v != "" {
|
||||
victims = append(victims, v)
|
||||
}
|
||||
}
|
||||
// If the queue already frees a slot, count it before checking the total.
|
||||
limit := s.maxMessages + len(victims)
|
||||
v, reject, err := victim(ctx, tx, `1 = 1`, nil, limit, work)
|
||||
if err != nil || reject {
|
||||
return Ignored, orFull(err)
|
||||
}
|
||||
if v != "" {
|
||||
victims = append(victims, v)
|
||||
}
|
||||
for _, h := range victims {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM messages WHERE hash = ?`, h); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT INTO messages (hash, to_dir, author, listing_id, rcpt, region, created_at, expires_at, work, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
hash, e.To, e.Listing.Author, e.Listing.ID, e.Rcpt, region, e.CreatedAt, e.ExpiresAt, work, data)
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
return Inserted, nil
|
||||
}
|
||||
|
||||
type rowQuerier interface {
|
||||
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
|
||||
}
|
||||
|
||||
// route checks an envelope against the listing it refers to: the region must
|
||||
// match the listing's, and an owner-bound envelope needs a live listing whose
|
||||
// current device is the recipient. Replies to buyers need no listing (the
|
||||
// owner may have deleted it since), but if it is known the region still has
|
||||
// to match.
|
||||
func (s *Store) route(ctx context.Context, q rowQuerier, now int64, region string, e *message.Envelope) error {
|
||||
var geohash, device string
|
||||
var tombstone, expires int64
|
||||
err := q.QueryRowContext(ctx,
|
||||
`SELECT geohash, device, tombstone, expires_at FROM listings WHERE author = ? AND id = ?`,
|
||||
e.Listing.Author, e.Listing.ID).Scan(&geohash, &device, &tombstone, &expires)
|
||||
known := err == nil
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if known && listing.Region(geohash) != region {
|
||||
return fmt.Errorf("%w: wrong region for this listing", ErrInvalid)
|
||||
}
|
||||
if e.To == message.ToOwner && (!known || tombstone != 0 || expires <= now || device != e.Rcpt) {
|
||||
return ErrNoListing
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckMessage is the read-only part of PutMessage: what a relay verifies
|
||||
// before forwarding an envelope. It returns an error wrapping ErrInvalid for
|
||||
// envelopes that are wrong, and ErrNoListing for ones this node cannot place.
|
||||
func (s *Store) CheckMessage(ctx context.Context, region string, e *message.Envelope) error {
|
||||
now := s.clock()
|
||||
if err := e.Check(now, s.msgDifficulty); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrInvalid, err)
|
||||
}
|
||||
if !listing.ValidRegion(region) {
|
||||
return fmt.Errorf("%w: bad region %q", ErrInvalid, region)
|
||||
}
|
||||
return s.route(ctx, s.db, now.Unix(), region, e)
|
||||
}
|
||||
|
||||
// orFull turns "rejected, no error" into ErrQueueFull.
|
||||
func orFull(err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrQueueFull
|
||||
}
|
||||
|
||||
// victim looks at the rows matching where. If there are fewer than limit it
|
||||
// returns nothing. Otherwise it picks the row with the least work (oldest on
|
||||
// ties) to evict, or reject = true if the new envelope has even less work.
|
||||
// where is always a constant fragment from this file, never caller input.
|
||||
func victim(ctx context.Context, tx *sql.Tx, where string, args []any, limit, work int) (hash string, reject bool, err error) {
|
||||
var n int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM messages WHERE `+where, args...).Scan(&n); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if n < limit {
|
||||
return "", false, nil
|
||||
}
|
||||
var least int
|
||||
err = tx.QueryRowContext(ctx,
|
||||
`SELECT hash, work FROM messages WHERE `+where+` ORDER BY work, created_at LIMIT 1`, args...).
|
||||
Scan(&hash, &least)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if work < least {
|
||||
return "", true, nil
|
||||
}
|
||||
return hash, false, nil
|
||||
}
|
||||
|
||||
// OwnerMessages returns the live envelopes addressed to author's listings,
|
||||
// oldest first. The owner's node decrypts them with its device key.
|
||||
func (s *Store) OwnerMessages(ctx context.Context, author string) ([]*message.Envelope, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM messages
|
||||
WHERE to_dir = 'owner' AND author = ? AND expires_at > ?
|
||||
ORDER BY created_at, hash`, author, s.clock().Unix())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collectMessages(rows)
|
||||
}
|
||||
|
||||
// Mailbox returns up to limit live replies in a mailbox created at or after
|
||||
// since, oldest first. A browser polls it; it dedupes by hash.
|
||||
func (s *Store) Mailbox(ctx context.Context, tag string, since int64, limit int) ([]*message.Envelope, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM messages
|
||||
WHERE to_dir = 'buyer' AND rcpt = ? AND created_at >= ? AND expires_at > ?
|
||||
ORDER BY created_at, hash LIMIT ?`, tag, since, s.clock().Unix(), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collectMessages(rows)
|
||||
}
|
||||
|
||||
// MessageCursor is a keyset position in the (created_at, hash) order used to
|
||||
// page through envelopes during sync. The zero value is the beginning.
|
||||
type MessageCursor struct {
|
||||
CreatedAt int64
|
||||
Hash string
|
||||
}
|
||||
|
||||
// MessageCursorOf returns the cursor positioned at e.
|
||||
func MessageCursorOf(e *message.Envelope) (MessageCursor, error) {
|
||||
h, err := e.Hash()
|
||||
return MessageCursor{CreatedAt: e.CreatedAt, Hash: h}, err
|
||||
}
|
||||
|
||||
// MessagesSince returns up to limit live envelopes of a region after cur,
|
||||
// oldest first, for peers that are catching up.
|
||||
func (s *Store) MessagesSince(ctx context.Context, region string, cur MessageCursor, limit int) ([]*message.Envelope, error) {
|
||||
if !listing.ValidRegion(region) {
|
||||
return nil, fmt.Errorf("store: invalid region %q", region)
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM messages
|
||||
WHERE region = ? AND expires_at > ? AND (created_at, hash) > (?, ?)
|
||||
ORDER BY created_at, hash LIMIT ?`, region, s.clock().Unix(), cur.CreatedAt, cur.Hash, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collectMessages(rows)
|
||||
}
|
||||
|
||||
// MessageCount returns the number of live envelopes held.
|
||||
func (s *Store) MessageCount(ctx context.Context) (int, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM messages WHERE expires_at > ?`,
|
||||
s.clock().Unix()).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func collectMessages(rows *sql.Rows) ([]*message.Envelope, error) {
|
||||
defer rows.Close()
|
||||
var out []*message.Envelope
|
||||
for rows.Next() {
|
||||
var data []byte
|
||||
if err := rows.Scan(&data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var e message.Envelope
|
||||
if err := json.Unmarshal(data, &e); err != nil {
|
||||
return nil, fmt.Errorf("store: corrupt message row: %w", err)
|
||||
}
|
||||
out = append(out, &e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
const msgDifficulty = 4
|
||||
|
||||
const region = "u1x"
|
||||
|
||||
func newMsgEnv(t *testing.T, opt Options) *env {
|
||||
t.Helper()
|
||||
e := &env{now: t0}
|
||||
e.root, _, _ = identity.NewRoot()
|
||||
e.dev = newDevice(t, e.root)
|
||||
opt.Difficulty = difficulty
|
||||
opt.MessageDifficulty = msgDifficulty
|
||||
opt.Clock = func() time.Time { return e.now }
|
||||
s, err := Open(":memory:", opt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { s.Close() })
|
||||
e.s = s
|
||||
return e
|
||||
}
|
||||
|
||||
// toOwner makes a buyer's envelope whose work is exactly `work` bits, so
|
||||
// eviction order can be tested precisely.
|
||||
func toOwner(t *testing.T, l *listing.Listing, at time.Time, work int) *message.Envelope {
|
||||
t.Helper()
|
||||
for {
|
||||
tk, err := message.NewThreadKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := &message.Plain{Type: message.TypeText, N: 1, SentAt: at.Unix(), Text: "hi"}
|
||||
e, err := message.SealToOwner(l, tk, p, at, work)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, _ := e.Work(); w == work {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// toBuyer makes an owner reply to the given thread (a fresh one if tk is nil).
|
||||
func toBuyer(t *testing.T, e *env, l *listing.Listing, tk *message.ThreadKey, at time.Time, work int) *message.Envelope {
|
||||
t.Helper()
|
||||
for {
|
||||
k := tk
|
||||
if k == nil {
|
||||
var err error
|
||||
if k, err = message.NewThreadKey(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
p := &message.Plain{Type: message.TypeText, Thread: k.PublicHex(), N: 1, SentAt: at.Unix(), Text: "ok"}
|
||||
env, err := message.SealToBuyer(e.dev, message.Ref{Author: l.Author, ID: l.ID}, p, at, work)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, _ := env.Work(); w == work {
|
||||
return env
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (e *env) putMsg(t *testing.T, env *message.Envelope) Outcome {
|
||||
t.Helper()
|
||||
o, err := e.s.PutMessage(ctx, region, env)
|
||||
if err != nil {
|
||||
t.Fatalf("PutMessage: %v", err)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func TestMessagesRoundTrip(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
tk, _ := message.NewThreadKey()
|
||||
in := toOwner(t, l, e.now, msgDifficulty)
|
||||
if e.putMsg(t, in) != Inserted {
|
||||
t.Fatal("not inserted")
|
||||
}
|
||||
if e.putMsg(t, in) != Ignored {
|
||||
t.Fatal("a duplicate must be a no-op")
|
||||
}
|
||||
out := toBuyer(t, e, l, tk, e.now.Add(time.Second), msgDifficulty)
|
||||
e.putMsg(t, out)
|
||||
|
||||
got, err := e.s.OwnerMessages(ctx, l.Author)
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("OwnerMessages = %d, %v", len(got), err)
|
||||
}
|
||||
if h1, _ := got[0].Hash(); h1 != mustHash(t, in) {
|
||||
t.Fatal("stored envelope differs from what was put")
|
||||
}
|
||||
mb, _ := tk.Mailbox()
|
||||
box, err := e.s.Mailbox(ctx, mb, 0, 10)
|
||||
if err != nil || len(box) != 1 {
|
||||
t.Fatalf("Mailbox = %d, %v", len(box), err)
|
||||
}
|
||||
if _, err := box[0].OpenAsBuyer(tk); err != nil {
|
||||
t.Fatalf("a stored reply no longer opens: %v", err)
|
||||
}
|
||||
if other, _ := e.s.Mailbox(ctx, strings.Repeat("0", 32), 0, 10); len(other) != 0 {
|
||||
t.Fatal("another mailbox must be empty")
|
||||
}
|
||||
if later, _ := e.s.Mailbox(ctx, mb, out.CreatedAt+1, 10); len(later) != 0 {
|
||||
t.Fatal("since must exclude older envelopes")
|
||||
}
|
||||
|
||||
all, err := e.s.MessagesSince(ctx, region, MessageCursor{}, 10)
|
||||
if err != nil || len(all) != 2 {
|
||||
t.Fatalf("MessagesSince = %d, %v", len(all), err)
|
||||
}
|
||||
cur, _ := MessageCursorOf(all[0])
|
||||
rest, _ := e.s.MessagesSince(ctx, region, cur, 10)
|
||||
if len(rest) != 1 || mustHash(t, rest[0]) != mustHash(t, all[1]) {
|
||||
t.Fatal("cursor paging is wrong")
|
||||
}
|
||||
if n, _ := e.s.MessageCount(ctx); n != 2 {
|
||||
t.Fatalf("count = %d", n)
|
||||
}
|
||||
if other, _ := e.s.MessagesSince(ctx, "u1y", MessageCursor{}, 10); len(other) != 0 {
|
||||
t.Fatal("another region must be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func mustHash(t *testing.T, e *message.Envelope) string {
|
||||
t.Helper()
|
||||
h, err := e.Hash()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func TestOwnerMessagesNeedALiveListing(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil)
|
||||
env := toOwner(t, l, e.now, msgDifficulty)
|
||||
|
||||
if _, err := e.s.PutMessage(ctx, region, env); !errors.Is(err, ErrNoListing) {
|
||||
t.Fatalf("unknown listing: %v, want ErrNoListing", err)
|
||||
}
|
||||
e.put(t, l)
|
||||
if _, err := e.s.PutMessage(ctx, "u1y", env); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("wrong region: %v, want ErrInvalid", err)
|
||||
}
|
||||
e.putMsg(t, env)
|
||||
|
||||
// A message sealed to a device that no longer signs for the listing.
|
||||
old := toOwner(t, l, e.now.Add(time.Second), msgDifficulty)
|
||||
e.dev = newDevice(t, e.root) // the owner recovered onto a new device
|
||||
re := e.listing(t, func(x *listing.Listing) { x.ID = l.ID; x.Seq = 2 })
|
||||
e.put(t, re)
|
||||
if _, err := e.s.PutMessage(ctx, region, old); !errors.Is(err, ErrNoListing) {
|
||||
t.Fatalf("stale device: %v, want ErrNoListing", err)
|
||||
}
|
||||
|
||||
// Deleted listing.
|
||||
ts := e.listing(t, func(x *listing.Listing) {
|
||||
*x = listing.Listing{Version: listing.Version, ID: l.ID, Seq: 3, CreatedAt: e.now.Unix(),
|
||||
ExpiresAt: e.now.Add(24 * time.Hour).Unix(), Tombstone: true, Geohash: "u1xjhx"}
|
||||
})
|
||||
e.put(t, ts)
|
||||
fresh := toOwner(t, re, e.now.Add(2*time.Second), msgDifficulty)
|
||||
if _, err := e.s.PutMessage(ctx, region, fresh); !errors.Is(err, ErrNoListing) {
|
||||
t.Fatalf("deleted listing: %v, want ErrNoListing", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuyerRepliesDoNotNeedTheListing(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil) // never stored: the owner may have deleted it meanwhile
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, e.now, msgDifficulty))
|
||||
|
||||
// If the listing is known, the region must still match.
|
||||
e.put(t, l)
|
||||
if _, err := e.s.PutMessage(ctx, "u1y", toBuyer(t, e, l, nil, e.now, msgDifficulty)); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("wrong region for a known listing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidEnvelopesAreRejected(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
weak := toOwner(t, l, e.now, msgDifficulty)
|
||||
strict := newMsgEnv(t, Options{})
|
||||
strict.s.msgDifficulty = 30
|
||||
if _, err := strict.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("weak proof-of-work: %v", err)
|
||||
}
|
||||
|
||||
if _, err := e.s.PutMessage(ctx, "nope", weak); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("bad region: %v", err)
|
||||
}
|
||||
|
||||
// Clock failures stay recognisable so the p2p layer can ignore them.
|
||||
late := newMsgEnv(t, Options{})
|
||||
late.now = t0.Add(20 * 24 * time.Hour)
|
||||
_, err := late.s.PutMessage(ctx, region, weak)
|
||||
if !errors.Is(err, ErrInvalid) || !errors.Is(err, listing.ErrTimeWindow) {
|
||||
t.Fatalf("expired: %v, want ErrInvalid wrapping ErrTimeWindow", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagesExpire(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
tk, _ := message.NewThreadKey()
|
||||
e.putMsg(t, toOwner(t, l, e.now, msgDifficulty))
|
||||
e.putMsg(t, toBuyer(t, e, l, tk, e.now, msgDifficulty))
|
||||
|
||||
e.now = e.now.Add(message.MaxLifetime + time.Minute)
|
||||
mb, _ := tk.Mailbox()
|
||||
if box, _ := e.s.Mailbox(ctx, mb, 0, 10); len(box) != 0 {
|
||||
t.Fatal("expired reply still served")
|
||||
}
|
||||
if got, _ := e.s.OwnerMessages(ctx, l.Author); len(got) != 0 {
|
||||
t.Fatal("expired message still served")
|
||||
}
|
||||
if n, _ := e.s.MessageCount(ctx); n != 0 {
|
||||
t.Fatalf("count = %d", n)
|
||||
}
|
||||
if removed, err := e.s.Expire(ctx); err != nil || removed < 2 {
|
||||
t.Fatalf("Expire removed %d, %v", removed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueueEvictsTheLeastWorkOldestFirst(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{OwnerQueue: 3})
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
|
||||
a := toOwner(t, l, at(1), 4)
|
||||
b := toOwner(t, l, at(2), 4)
|
||||
c := toOwner(t, l, at(3), 4)
|
||||
for _, m := range []*message.Envelope{a, b, c} {
|
||||
e.putMsg(t, m)
|
||||
}
|
||||
|
||||
// More work than the least: evicts the oldest of the least-work ones.
|
||||
d := toOwner(t, l, at(4), 9)
|
||||
e.putMsg(t, d)
|
||||
has := func(m *message.Envelope) bool {
|
||||
all, _ := e.s.OwnerMessages(ctx, l.Author)
|
||||
for _, x := range all {
|
||||
if mustHash(t, x) == mustHash(t, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
if has(a) || !has(b) || !has(c) || !has(d) {
|
||||
t.Fatalf("after d: a=%v b=%v c=%v d=%v, want a evicted only", has(a), has(b), has(c), has(d))
|
||||
}
|
||||
|
||||
// Equal work: the newcomer displaces the oldest (spec: oldest first on ties).
|
||||
f := toOwner(t, l, at(5), 4)
|
||||
e.putMsg(t, f)
|
||||
if has(b) || !has(c) || !has(d) || !has(f) {
|
||||
t.Fatalf("after f: b=%v c=%v d=%v f=%v", has(b), has(c), has(d), has(f))
|
||||
}
|
||||
|
||||
// A queue full of strong envelopes refuses weaker ones and keeps them all.
|
||||
for i := 6; i < 9; i++ {
|
||||
e.putMsg(t, toOwner(t, l, at(i), 9))
|
||||
}
|
||||
weak := toOwner(t, l, at(10), 4)
|
||||
if _, err := e.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrQueueFull) {
|
||||
t.Fatalf("weak newcomer: %v, want ErrQueueFull", err)
|
||||
}
|
||||
if all, _ := e.s.OwnerMessages(ctx, l.Author); len(all) != 3 {
|
||||
t.Fatalf("queue holds %d, want 3", len(all))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailboxQueueIsBounded(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{MailboxQueue: 2})
|
||||
l := e.listing(t, nil)
|
||||
tk, _ := message.NewThreadKey()
|
||||
mb, _ := tk.Mailbox()
|
||||
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
|
||||
|
||||
e.putMsg(t, toBuyer(t, e, l, tk, at(1), 4))
|
||||
e.putMsg(t, toBuyer(t, e, l, tk, at(2), 4))
|
||||
e.putMsg(t, toBuyer(t, e, l, tk, at(3), 9))
|
||||
box, _ := e.s.Mailbox(ctx, mb, 0, 10)
|
||||
if len(box) != 2 {
|
||||
t.Fatalf("mailbox holds %d, want 2", len(box))
|
||||
}
|
||||
// Another mailbox is not affected.
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(4), 4))
|
||||
}
|
||||
|
||||
func TestOverallCapIsEnforced(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{MaxMessages: 2})
|
||||
l := e.listing(t, nil)
|
||||
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
|
||||
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(1), 4))
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(2), 4))
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(3), 9)) // evicts the oldest weak one
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(4), 9)) // evicts the other weak one
|
||||
if n, _ := e.s.MessageCount(ctx); n != 2 {
|
||||
t.Fatalf("count = %d, want 2", n)
|
||||
}
|
||||
weak := toBuyer(t, e, l, nil, at(5), 4)
|
||||
if _, err := e.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrQueueFull) {
|
||||
t.Fatalf("weak newcomer at the overall cap: %v", err)
|
||||
}
|
||||
if n, _ := e.s.MessageCount(ctx); n != 2 {
|
||||
t.Fatalf("count = %d after a rejection, want 2", n)
|
||||
}
|
||||
}
|
||||
+89
-6
@@ -43,14 +43,27 @@ func (o Outcome) String() string {
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Difficulty int // required proof-of-work bits
|
||||
Difficulty int // required proof-of-work bits for listings and revocations
|
||||
Clock func() time.Time // defaults to time.Now
|
||||
|
||||
// MessageDifficulty is the proof-of-work bits required of message
|
||||
// envelopes (message.DefaultDifficulty on a real node).
|
||||
MessageDifficulty int
|
||||
// MaxMessages caps the envelopes this node holds; 0 means 20000.
|
||||
MaxMessages int
|
||||
// OwnerQueue and MailboxQueue cap the envelopes per listing and per
|
||||
// mailbox; 0 means MaxOwnerQueue and MaxMailboxQueue.
|
||||
OwnerQueue, MailboxQueue int
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
difficulty int
|
||||
clock func() time.Time
|
||||
db *sql.DB
|
||||
difficulty int
|
||||
clock func() time.Time
|
||||
msgDifficulty int
|
||||
maxMessages int
|
||||
ownerQueue int
|
||||
mailboxQueue int
|
||||
}
|
||||
|
||||
const schema = `
|
||||
@@ -87,6 +100,56 @@ CREATE TABLE IF NOT EXISTS revocations (
|
||||
data BLOB NOT NULL,
|
||||
PRIMARY KEY (author, device)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
-- Encrypted message envelopes this node relays (see internal/message).
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
hash TEXT PRIMARY KEY,
|
||||
to_dir TEXT NOT NULL, -- 'owner' or 'buyer'
|
||||
author TEXT NOT NULL, -- listing reference
|
||||
listing_id TEXT NOT NULL,
|
||||
rcpt TEXT NOT NULL, -- owner: device key; buyer: mailbox tag
|
||||
region TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
work INTEGER NOT NULL, -- leading zero bits, decides what a full queue evicts
|
||||
data BLOB NOT NULL
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS messages_listing ON messages (to_dir, author, listing_id);
|
||||
CREATE INDEX IF NOT EXISTS messages_mailbox ON messages (to_dir, rcpt, created_at);
|
||||
CREATE INDEX IF NOT EXISTS messages_region ON messages (region, created_at, hash);
|
||||
CREATE INDEX IF NOT EXISTS messages_expires ON messages (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS messages_work ON messages (work, created_at);
|
||||
|
||||
-- The owner's decrypted conversations. These exist only on the owner's node:
|
||||
-- they are never gossiped.
|
||||
CREATE TABLE IF NOT EXISTS inbox (
|
||||
hash TEXT PRIMARY KEY, -- hash of the envelope that carried it
|
||||
author TEXT NOT NULL,
|
||||
listing_id TEXT NOT NULL,
|
||||
thread TEXT NOT NULL,
|
||||
dir TEXT NOT NULL, -- 'in' from a buyer, 'out' our reply
|
||||
n INTEGER NOT NULL,
|
||||
sent_at INTEGER NOT NULL,
|
||||
received_at INTEGER NOT NULL,
|
||||
hidden INTEGER NOT NULL, -- broke the first-message rules
|
||||
data BLOB NOT NULL -- canonical plaintext
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS inbox_thread ON inbox (author, listing_id, thread, sent_at);
|
||||
-- Envelopes the owner's node has already looked at (decrypted or not), so
|
||||
-- garbage is not decrypted again on every collection.
|
||||
CREATE TABLE IF NOT EXISTS inbox_seen (
|
||||
hash TEXT PRIMARY KEY,
|
||||
expires_at INTEGER NOT NULL
|
||||
) WITHOUT ROWID;
|
||||
-- The exact address of a listing, only ever read by its owner's node.
|
||||
CREATE TABLE IF NOT EXISTS addresses (
|
||||
author TEXT NOT NULL,
|
||||
listing_id TEXT NOT NULL,
|
||||
address TEXT NOT NULL,
|
||||
phone TEXT NOT NULL,
|
||||
email TEXT NOT NULL,
|
||||
PRIMARY KEY (author, listing_id)
|
||||
) WITHOUT ROWID;
|
||||
`
|
||||
|
||||
// Open opens (creating if needed) the database at path. Use ":memory:" for
|
||||
@@ -106,10 +169,21 @@ func Open(path string, opt Options) (*Store, error) {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock}
|
||||
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock,
|
||||
msgDifficulty: opt.MessageDifficulty, maxMessages: opt.MaxMessages,
|
||||
ownerQueue: opt.OwnerQueue, mailboxQueue: opt.MailboxQueue}
|
||||
if s.ownerQueue <= 0 {
|
||||
s.ownerQueue = MaxOwnerQueue
|
||||
}
|
||||
if s.mailboxQueue <= 0 {
|
||||
s.mailboxQueue = MaxMailboxQueue
|
||||
}
|
||||
if s.clock == nil {
|
||||
s.clock = time.Now
|
||||
}
|
||||
if s.maxMessages <= 0 {
|
||||
s.maxMessages = defaultMaxMessages
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -433,7 +507,16 @@ func (s *Store) Expire(ctx context.Context) (int64, error) {
|
||||
return n, err
|
||||
}
|
||||
m, _ := res.RowsAffected()
|
||||
return n + m, nil
|
||||
res, err = s.db.ExecContext(ctx, `DELETE FROM messages WHERE expires_at <= ?`, now)
|
||||
if err != nil {
|
||||
return n + m, err
|
||||
}
|
||||
k, _ := res.RowsAffected()
|
||||
// Not counted: housekeeping of the owner's "already seen" markers.
|
||||
if _, err := s.db.ExecContext(ctx, `DELETE FROM inbox_seen WHERE expires_at <= ?`, now); err != nil {
|
||||
return n + m + k, err
|
||||
}
|
||||
return n + m + k, nil
|
||||
}
|
||||
|
||||
// Count returns the number of live listings.
|
||||
|
||||
Reference in New Issue
Block a user