// 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 }