Files
nilsandClaude Sonnet 5.5 253eb6e75c messaging: the price of writing to a listing rises as its queue fills
Flooding a listing's inbox now gets dearer with every envelope. Relays ask
more proof-of-work from half full on, the node tells browsers the current
price, and the browser mines to it (or says the listing is too busy).

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

382 lines
12 KiB
Go

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) }
// Two thirds full already costs a bit more, hence 5 for the third.
a := toOwner(t, l, at(1), 4)
b := toOwner(t, l, at(2), 4)
c := toOwner(t, l, at(3), 5)
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))
}
// A full queue wants one bit more than its weakest envelope; that newcomer
// displaces the oldest of the weakest.
if _, err := e.s.PutMessage(ctx, region, toOwner(t, l, at(5), 4)); !errors.Is(err, ErrQueueFull) {
t.Fatalf("a newcomer only as strong as the weakest: %v, want ErrQueueFull", err)
}
f := toOwner(t, l, at(5), 5)
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, w := range []int{9, 9, 10} { // each must beat the weakest it displaces
e.putMsg(t, toOwner(t, l, at(6+i), w))
}
weak := toOwner(t, l, at(10), 4)
_, err := e.s.PutMessage(ctx, region, weak)
var we *WorkError
if !errors.Is(err, ErrQueueFull) || !errors.As(err, &we) || we.Required != 10 {
t.Fatalf("weak newcomer: %v, want a WorkError asking for 10 bits", 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)
}
}
func TestRequiredWorkRisesAsTheQueueFills(t *testing.T) {
e := newMsgEnv(t, Options{OwnerQueue: 8})
l := e.listing(t, nil)
e.put(t, l)
ref := message.Ref{Author: l.Author, ID: l.ID}
need := func() int {
n, err := e.s.RequiredWork(ctx, ref)
if err != nil {
t.Fatal(err)
}
return n
}
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
// A quiet queue costs the node's difficulty (4 in these tests).
want := []int{4, 4, 4, 4, 5, 5, 6, 6} // by the number of envelopes waiting, 0..7
work := 4
for i := 0; i < 8; i++ {
if got := need(); got != want[i] {
t.Fatalf("with %d waiting the price is %d bits, want %d", i, got, want[i])
}
if i == 7 {
work = 9
}
w := want[i]
if i == 7 {
w = work
}
e.putMsg(t, toOwner(t, l, at(i+1), w))
}
// Full: one bit more than the weakest waiting.
least := 4
if got := need(); got != least+1 {
t.Fatalf("a full queue asks %d bits, want %d", got, least+1)
}
// What the price says is accepted, one bit less is not.
if _, err := e.s.PutMessage(ctx, region, toOwner(t, l, at(20), need()-1)); !errors.Is(err, ErrQueueFull) {
t.Fatalf("one bit short: %v", err)
}
e.putMsg(t, toOwner(t, l, at(21), need()))
}