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
This commit is contained in:
@@ -105,6 +105,7 @@ func New(cfg Config) http.Handler {
|
||||
// Messaging: public relay endpoints for buyers' browsers...
|
||||
mux.HandleFunc("POST /api/v1/messages", s.postMessage)
|
||||
mux.HandleFunc("GET /api/v1/messages", s.getMailbox)
|
||||
mux.HandleFunc("GET /api/v1/messages/required", s.getRequiredWork)
|
||||
// ...and the owner's inbox and private address, behind the admin token.
|
||||
if cfg.Inbox != nil {
|
||||
mux.HandleFunc("GET /api/v1/mine", s.admin(s.mine))
|
||||
|
||||
@@ -68,6 +68,15 @@ func (s *server) postMessage(w http.ResponseWriter, r *http.Request) {
|
||||
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):
|
||||
var we *store.WorkError
|
||||
if errors.As(err, &we) {
|
||||
// The price of this listing's queue has risen: say what it is now.
|
||||
writeJSON(w, http.StatusTooManyRequests, map[string]any{
|
||||
"error": "this listing is receiving many messages; it now needs more proof-of-work",
|
||||
"required_bits": we.Required,
|
||||
})
|
||||
return
|
||||
}
|
||||
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")
|
||||
@@ -78,6 +87,26 @@ func (s *server) postMessage(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"hash": h})
|
||||
}
|
||||
|
||||
// getRequiredWork tells a buyer's browser how much proof-of-work a message to
|
||||
// a listing needs right now. The price rises while the listing's queue fills,
|
||||
// so the browser asks before it mines.
|
||||
func (s *server) getRequiredWork(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
author, id := q.Get("author"), q.Get("id")
|
||||
if len(author) != 64 || !isLowerHex(author) || len(id) != 32 || !isLowerHex(id) {
|
||||
fail(w, http.StatusBadRequest, "author must be 64 and id 32 hex characters")
|
||||
return
|
||||
}
|
||||
bits, err := s.Store.RequiredWork(r.Context(), message.Ref{Author: author, ID: id})
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "internal error")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
noStore(w)
|
||||
writeJSON(w, http.StatusOK, map[string]int{"bits": bits})
|
||||
}
|
||||
|
||||
func (s *server) getMailbox(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
tag := q.Get("mailbox")
|
||||
|
||||
@@ -429,6 +429,53 @@ func TestStatusReportsMessageDifficulty(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheMessagePriceRisesWithTheQueueAndBuyersCanAskForIt(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
required := func() int {
|
||||
code, body := f.do(t, "GET", "/api/v1/messages/required?author="+l.Author+"&id="+l.ID, "", false)
|
||||
var r struct {
|
||||
Bits int `json:"bits"`
|
||||
}
|
||||
if code != 200 || json.Unmarshal(body, &r) != nil {
|
||||
t.Fatalf("required: %d %s", code, body)
|
||||
}
|
||||
return r.Bits
|
||||
}
|
||||
if got := required(); got != msgDifficulty {
|
||||
t.Fatalf("a quiet listing asks %d bits, want %d", got, msgDifficulty)
|
||||
}
|
||||
if code, _ := f.do(t, "GET", "/api/v1/messages/required?author=zz&id=1", "", false); code != 400 {
|
||||
t.Fatalf("bad parameters: %d", code)
|
||||
}
|
||||
|
||||
// Half of the 200-envelope queue costs one bit more.
|
||||
for i := 0; i < 100; i++ {
|
||||
if _, err := f.s.PutMessage(t.Context(), listing.Region(l.Geohash), buyerHello(t, l, newThread(t), "Hallo")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if got := required(); got != msgDifficulty+1 {
|
||||
t.Fatalf("a half-full queue asks %d bits, want %d", got, msgDifficulty+1)
|
||||
}
|
||||
|
||||
// A message at the old price is refused, and the answer names the new one.
|
||||
var weak *message.Envelope
|
||||
for {
|
||||
weak = buyerHello(t, l, newThread(t), "Hallo")
|
||||
if w, _ := weak.Work(); w == msgDifficulty {
|
||||
break
|
||||
}
|
||||
}
|
||||
code, body := f.send(t, weak)
|
||||
var refusal struct {
|
||||
Required int `json:"required_bits"`
|
||||
}
|
||||
if code != 429 || json.Unmarshal(body, &refusal) != nil || refusal.Required != msgDifficulty+1 {
|
||||
t.Fatalf("a message at the old price: %d %s", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlockingAConversationOverTheAPI(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
|
||||
@@ -31,6 +31,51 @@ var (
|
||||
ErrQueueFull = errors.New("store: message queue full")
|
||||
)
|
||||
|
||||
// WorkError means an owner-bound envelope did not carry enough proof-of-work
|
||||
// for the queue it is going into right now. It is not misbehaviour: the price
|
||||
// rises as a listing's queue fills, so the sender just has to mine more.
|
||||
// errors.Is(err, ErrQueueFull) is true for it.
|
||||
type WorkError struct{ Required int }
|
||||
|
||||
func (e *WorkError) Error() string {
|
||||
return fmt.Sprintf("store: this listing's queue needs %d bits of proof-of-work right now", e.Required)
|
||||
}
|
||||
func (e *WorkError) Is(target error) bool { return target == ErrQueueFull }
|
||||
|
||||
// RequiredWork is the proof-of-work, in bits, an envelope to the owner of ref
|
||||
// needs right now. It is the node's message difficulty while the queue is
|
||||
// quiet and rises with it: one bit more from half full, two from three
|
||||
// quarters. Once the queue is full it is one bit more than the weakest
|
||||
// envelope waiting, since a newcomer must beat what it would displace.
|
||||
// Flooding a listing therefore costs more with every envelope, instead of
|
||||
// locking honest senders out at a price they cannot see.
|
||||
func (s *Store) RequiredWork(ctx context.Context, ref message.Ref) (int, error) {
|
||||
return s.requiredWork(ctx, s.db, ref)
|
||||
}
|
||||
|
||||
func (s *Store) requiredWork(ctx context.Context, q rowQuerier, ref message.Ref) (int, error) {
|
||||
var n, least int
|
||||
err := q.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*), COALESCE(MIN(work), 0) FROM messages
|
||||
WHERE to_dir = 'owner' AND author = ? AND listing_id = ? AND expires_at > ?`,
|
||||
ref.Author, ref.ID, s.clock().Unix()).Scan(&n, &least)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
need := s.msgDifficulty
|
||||
switch {
|
||||
case n >= s.ownerQueue:
|
||||
if least+1 > need {
|
||||
need = least + 1
|
||||
}
|
||||
case 4*n >= 3*s.ownerQueue:
|
||||
need += 2
|
||||
case 2*n >= s.ownerQueue:
|
||||
need++
|
||||
}
|
||||
return need, nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
//
|
||||
@@ -153,6 +198,17 @@ func (s *Store) route(ctx context.Context, q rowQuerier, now int64, region strin
|
||||
if e.To == message.ToOwner && (!known || tombstone != 0 || expires <= now || device != e.Rcpt) {
|
||||
return ErrNoListing
|
||||
}
|
||||
if e.To == message.ToOwner {
|
||||
need, err := s.requiredWork(ctx, q, e.Listing)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if work, err := e.Work(); err != nil {
|
||||
return err
|
||||
} else if work < need {
|
||||
return &WorkError{Required: need}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -249,9 +249,10 @@ func TestQueueEvictsTheLeastWorkOldestFirst(t *testing.T) {
|
||||
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), 4)
|
||||
c := toOwner(t, l, at(3), 5)
|
||||
for _, m := range []*message.Envelope{a, b, c} {
|
||||
e.putMsg(t, m)
|
||||
}
|
||||
@@ -272,20 +273,26 @@ func TestQueueEvictsTheLeastWorkOldestFirst(t *testing.T) {
|
||||
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)
|
||||
// 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 := 6; i < 9; i++ {
|
||||
e.putMsg(t, toOwner(t, l, at(i), 9))
|
||||
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)
|
||||
if _, err := e.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrQueueFull) {
|
||||
t.Fatalf("weak newcomer: %v, want ErrQueueFull", err)
|
||||
_, 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))
|
||||
@@ -330,3 +337,45 @@ func TestOverallCapIsEnforced(t *testing.T) {
|
||||
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()))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user