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:
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user