weirdnet-contacts 0.1.0

A contact book for Weirdnet apps: trusted and blocked identities, presence with privacy rules (base to everyone, detail to trusted contacts), signed text direct messages with delivery state and an offline queue, and contact links, served over weirdnet-service.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! The live state: your book, conversations, outbox and presence behind one lock.
use crate::book::{Book, ContactState};
use crate::id::UserId;
use crate::message::{Body, Conversation, Delivery, Message, MessageId};
use crate::presence::{Audience, PresenceInfo, PresencePolicy, PresenceView, Viewer, view_for};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::sync::{Mutex, MutexGuard};
use weirdnet_net::Keypair;

/// Milliseconds since the Unix epoch.
pub fn now_ms() -> i64 {
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
}

/// What happened to a message that was received.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Receipt {
    /// Kept, from a trusted contact.
    Delivered,
    /// Kept as a message request: the sender is not trusted yet (trust or block them).
    Request,
    /// Already had it.
    Duplicate,
}

/// Why a received message was refused. The `code` goes back to the sender.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum Refusal {
    /// Addressed to someone else.
    #[error("not-for-me")]
    NotForMe,
    /// The signature does not hold.
    #[error("bad-signature")]
    BadSignature,
    /// Empty or over the size limits.
    #[error("too-large")]
    TooLarge,
    /// The sender is blocked or banned.
    #[error("blocked")]
    Blocked,
    /// The sender wrote too often, or too many unknown senders wrote.
    #[error("rate-limited")]
    RateLimited,
}

/// Why a message could not be written.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum SendError {
    /// You blocked the recipient.
    #[error("the recipient is blocked")]
    Blocked,
    /// Empty or over the size limits.
    #[error("empty or too large")]
    TooLarge,
    /// The key could not sign.
    #[error("cannot sign: {0}")]
    Sign(String),
}

/// Limits on what strangers can do to you.
#[derive(Clone, Copy, Debug)]
pub struct Limits {
    /// Messages accepted per sender per minute.
    pub per_minute: usize,
    /// Conversations that are message requests, at most.
    pub max_requests: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Limits { per_minute: 30, max_requests: 200 }
    }
}

/// What an app stores: plain serde data. Not the key, not presence (rebuilt on start).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Snapshot {
    /// The book.
    pub book: Book,
    /// Every conversation.
    pub conversations: Vec<Conversation>,
    /// The next message counter.
    pub seq: u64,
}

struct State {
    book: Book,
    convs: BTreeMap<UserId, Conversation>,
    presence: PresenceInfo,
    seq: u64,
    shared: BTreeSet<UserId>,
    hits: HashMap<UserId, VecDeque<i64>>,
}

/// Your contacts, conversations and presence.
pub struct Contacts {
    me: Keypair,
    id: UserId,
    limits: Limits,
    state: Mutex<State>,
}

impl Contacts {
    /// Fresh state for the identity `me`.
    pub fn new(me: Keypair) -> Self {
        Self::restore(me, Snapshot::default(), Limits::default())
    }

    /// State from a [`Snapshot`].
    pub fn restore(me: Keypair, s: Snapshot, limits: Limits) -> Self {
        let id = UserId::of_keypair(&me);
        let convs = s.conversations.into_iter().map(|c| (c.with.clone(), c)).collect();
        let state = State { book: s.book, convs, presence: PresenceInfo::default(), seq: s.seq, shared: BTreeSet::new(), hits: HashMap::new() };
        Contacts { me, id, limits, state: Mutex::new(state) }
    }

    /// What to store.
    pub fn snapshot(&self) -> Snapshot {
        let s = self.lock();
        Snapshot { book: s.book.clone(), conversations: s.convs.values().cloned().collect(), seq: s.seq }
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(|p| p.into_inner())
    }

    /// Your identity.
    pub fn id(&self) -> &UserId {
        &self.id
    }

    /// Your key, to sign other things (a contact link, a presence record).
    pub fn keypair(&self) -> &Keypair {
        &self.me
    }

    /// A copy of the book.
    pub fn book(&self) -> Book {
        self.lock().book.clone()
    }

    /// How `user` is treated.
    pub fn state_of(&self, user: &UserId) -> ContactState {
        self.lock().book.state_of(user)
    }

    /// Trust `user`: they leave the message requests and see your detail presence.
    pub fn trust(&self, user: &UserId, name: &str, now: i64) {
        let mut s = self.lock();
        s.book.trust(user, name, now);
        if let Some(c) = s.convs.get_mut(user) {
            c.request = false;
        }
    }

    /// Block `user`: their conversation, presence view and anything queued for them go, and
    /// everything they send is refused.
    pub fn block(&self, user: &UserId, now: i64) {
        let mut s = self.lock();
        s.book.block(user, now);
        s.convs.remove(user);
        s.hits.remove(user);
    }

    /// Lift a block (back to unknown; nothing returns).
    pub fn unblock(&self, user: &UserId, now: i64) {
        self.lock().book.unblock(user, now);
    }

    /// Remove a contact from the book (their conversation stays).
    pub fn remove(&self, user: &UserId) -> bool {
        self.lock().book.remove(user)
    }

    /// Ban `user` by identity (a host's or operator's ban): refused like a block, and the
    /// conversation goes too.
    pub fn ban(&self, user: &UserId) {
        let mut s = self.lock();
        s.book.ban(user);
        s.convs.remove(user);
    }

    /// Lift a ban.
    pub fn unban(&self, user: &UserId) {
        self.lock().book.unban(user);
    }

    /// Change your privacy settings.
    pub fn set_policy(&self, policy: PresencePolicy) {
        self.lock().book.policy = policy;
    }

    /// Set or clear the detail audience for one contact.
    pub fn set_audience(&self, user: &UserId, audience: Option<Audience>, now: i64) {
        self.lock().book.set_audience(user, audience, now);
    }

    /// Say whether `user` is in the project your session hint names, so they may see its name
    /// when the policy shares it.
    pub fn share_project_with(&self, user: &UserId, shares: bool) {
        let mut s = self.lock();
        if shares {
            s.shared.insert(user.clone());
        } else {
            s.shared.remove(user);
        }
    }

    /// Set what you show about yourself.
    pub fn set_presence(&self, info: PresenceInfo) {
        self.lock().presence = info;
    }

    /// What `peer` may see of you (`None` when you blocked them).
    pub fn presence_for(&self, peer: &UserId) -> Option<PresenceView> {
        let s = self.lock();
        let viewer =
            Viewer { state: s.book.state_of(peer), shares_project: s.shared.contains(peer), audience: s.book.get(peer).and_then(|c| c.audience) };
        view_for(&s.book.policy, &s.presence, viewer)
    }

    /// Write a message to `to`. It is queued; [`crate::client::flush`] sends it.
    pub fn compose(&self, to: &UserId, body: Body, now: i64) -> Result<MessageId, SendError> {
        let mut s = self.lock();
        if s.book.state_of(to) == ContactState::Blocked {
            return Err(SendError::Blocked);
        }
        s.seq += 1;
        let id = MessageId(format!("{}-{}-{}", self.id.short(), now, s.seq));
        let m = Message::sign(&self.me, to, id.clone(), body, now).map_err(SendError::Sign)?;
        if !m.within_limits() {
            s.seq -= 1;
            return Err(SendError::TooLarge);
        }
        s.convs.entry(to.clone()).or_insert_with(|| Conversation::new(to.clone())).insert(m, Delivery::Queued);
        Ok(id)
    }

    /// The messages to `to` that still need sending (queued; failed ones wait for
    /// [`Contacts::retry_failed`]), oldest first.
    pub fn outbox(&self, to: &UserId) -> Vec<Message> {
        let s = self.lock();
        s.convs
            .get(to)
            .map(|c| c.entries().iter().filter(|e| e.msg.from == self.id && e.delivery == Delivery::Queued).map(|e| e.msg.clone()).collect())
            .unwrap_or_default()
    }

    /// Put every failed message to `to` back in the outbox; returns how many.
    pub fn retry_failed(&self, to: &UserId) -> usize {
        let mut s = self.lock();
        let Some(c) = s.convs.get_mut(to) else { return 0 };
        let ids: Vec<MessageId> =
            c.entries().iter().filter(|e| e.msg.from == self.id && e.delivery == Delivery::Failed).map(|e| e.msg.id.clone()).collect();
        for id in &ids {
            c.advance(id, Delivery::Queued);
        }
        ids.len()
    }

    /// Identities that have something waiting to be sent.
    pub fn outbox_peers(&self) -> Vec<UserId> {
        let s = self.lock();
        s.convs
            .values()
            .filter(|c| c.entries().iter().any(|e| e.msg.from == self.id && e.delivery == Delivery::Queued))
            .map(|c| c.with.clone())
            .collect()
    }

    /// Move one of your messages to `to`'s delivery state.
    pub fn mark(&self, peer: &UserId, id: &MessageId, d: Delivery) {
        if let Some(c) = self.lock().convs.get_mut(peer) {
            c.advance(id, d);
        }
    }

    /// Your messages to `peer` written after `since_ms`, for a pull by `peer`.
    pub fn messages_since(&self, peer: &UserId, since_ms: i64) -> Vec<Message> {
        let s = self.lock();
        s.convs
            .get(peer)
            .map(|c| c.entries().iter().filter(|e| e.msg.from == self.id && e.msg.sent_ms > since_ms).map(|e| e.msg.clone()).collect())
            .unwrap_or_default()
    }

    /// The newest message time from `peer` that you hold, to ask a pull from there.
    pub fn newest_from(&self, peer: &UserId) -> i64 {
        let s = self.lock();
        s.convs.get(peer).and_then(|c| c.entries().iter().filter(|e| &e.msg.from == peer).map(|e| e.msg.sent_ms).max()).unwrap_or(0)
    }

    /// Take in a message from `msg.from`. The checks, in order: addressed to you, size,
    /// signature, blocked or banned, repeat, rate limit, message-request cap.
    pub fn receive(&self, msg: Message, now: i64) -> Result<Receipt, Refusal> {
        if msg.to != self.id {
            return Err(Refusal::NotForMe);
        }
        if !msg.within_limits() {
            return Err(Refusal::TooLarge);
        }
        if !msg.verify() {
            return Err(Refusal::BadSignature);
        }
        let mut s = self.lock();
        let from = msg.from.clone();
        let state = s.book.state_of(&from);
        if state == ContactState::Blocked {
            return Err(Refusal::Blocked);
        }
        if let Some(c) = s.convs.get_mut(&from)
            && c.get(&msg.id).is_some()
        {
            c.insert(msg, Delivery::Delivered);
            return Ok(Receipt::Duplicate);
        }
        let hits = s.hits.entry(from.clone()).or_default();
        while hits.front().is_some_and(|t| now - t > 60_000) {
            hits.pop_front();
        }
        if hits.len() >= self.limits.per_minute {
            return Err(Refusal::RateLimited);
        }
        let request = state != ContactState::Trusted;
        if request {
            let already = s.convs.get(&from).is_some_and(|c| c.request);
            if !already && s.convs.values().filter(|c| c.request).count() >= self.limits.max_requests {
                return Err(Refusal::RateLimited);
            }
        }
        s.hits.entry(from.clone()).or_default().push_back(now);
        if request {
            s.book.note(&from, "", now);
        }
        let c = s.convs.entry(from.clone()).or_insert_with(|| Conversation::new(from.clone()));
        c.request = request;
        c.insert(msg, Delivery::Delivered);
        Ok(if request { Receipt::Request } else { Receipt::Delivered })
    }

    /// Mark everything from `peer` as read; returns the ids that were newly read, to tell them.
    pub fn mark_read(&self, peer: &UserId) -> Vec<MessageId> {
        let mut s = self.lock();
        let Some(c) = s.convs.get_mut(peer) else { return Vec::new() };
        let ids: Vec<MessageId> =
            c.entries().iter().filter(|e| &e.msg.from == peer && e.delivery != Delivery::Read).map(|e| e.msg.id.clone()).collect();
        for id in &ids {
            c.advance(id, Delivery::Read);
        }
        ids
    }

    /// `peer` says they read these: only your own messages to them move.
    pub fn read_by(&self, peer: &UserId, ids: &[MessageId]) -> usize {
        let mut s = self.lock();
        let Some(c) = s.convs.get_mut(peer) else { return 0 };
        let mine: Vec<MessageId> = ids.iter().filter(|i| c.get(i).is_some_and(|e| e.msg.from == self.id)).cloned().collect();
        for id in &mine {
            c.advance(id, Delivery::Read);
        }
        mine.len()
    }

    /// A copy of the conversation with `peer`.
    pub fn conversation(&self, peer: &UserId) -> Option<Conversation> {
        self.lock().convs.get(peer).cloned()
    }

    /// Identities you have a conversation with that are message requests.
    pub fn requests(&self) -> Vec<UserId> {
        self.lock().convs.values().filter(|c| c.request).map(|c| c.with.clone()).collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const T: i64 = 1_800_000_000_000;

    fn pair() -> (Contacts, Contacts) {
        (Contacts::new(Keypair::generate_ed25519()), Contacts::new(Keypair::generate_ed25519()))
    }

    fn text(s: &str) -> Body {
        Body::Text(s.into())
    }

    /// Deliver everything queued from `a` to `b`, as the service would.
    fn ship(a: &Contacts, b: &Contacts, now: i64) -> Vec<Result<Receipt, Refusal>> {
        let out = a.outbox(b.id());
        out.into_iter()
            .map(|m| {
                let id = m.id.clone();
                let r = b.receive(m, now);
                a.mark(b.id(), &id, if r.is_ok() { Delivery::Delivered } else { Delivery::Failed });
                r
            })
            .collect()
    }

    #[test]
    fn an_unknown_sender_is_a_request_until_trusted() {
        let (a, b) = pair();
        a.compose(b.id(), text("hi"), T).unwrap();
        assert_eq!(ship(&a, &b, T), [Ok(Receipt::Request)]);
        assert_eq!(b.requests(), [a.id().clone()]);
        b.trust(a.id(), "Ana", T + 1);
        assert!(b.requests().is_empty());
        a.compose(b.id(), text("again"), T + 2).unwrap();
        assert_eq!(ship(&a, &b, T + 2), [Ok(Receipt::Delivered)]);
        assert_eq!(b.conversation(a.id()).unwrap().entries().len(), 2);
    }

    #[test]
    fn blocking_removes_the_conversation_and_refuses_more() {
        let (a, b) = pair();
        a.compose(b.id(), text("hi"), T).unwrap();
        ship(&a, &b, T);
        b.block(a.id(), T + 1);
        assert!(b.conversation(a.id()).is_none());
        assert!(b.requests().is_empty());
        a.compose(b.id(), text("please"), T + 2).unwrap();
        assert_eq!(ship(&a, &b, T + 2), [Err(Refusal::Blocked)]);
        assert_eq!(b.presence_for(a.id()), None);
        assert_eq!(b.compose(a.id(), text("hello?"), T + 3), Err(SendError::Blocked));
    }

    #[test]
    fn a_banned_identity_is_refused_like_a_block_and_trust_does_not_lift_it() {
        let (a, b) = pair();
        b.ban(a.id());
        b.trust(a.id(), "Ana", T);
        a.compose(b.id(), text("hi"), T).unwrap();
        assert_eq!(ship(&a, &b, T), [Err(Refusal::Blocked)]);
        b.unban(a.id());
        a.retry_failed(b.id());
        assert_eq!(ship(&a, &b, T + 1), [Ok(Receipt::Delivered)]);
    }

    #[test]
    fn receive_checks_recipient_signature_size_and_repeats() {
        let (a, b) = pair();
        let c = Contacts::new(Keypair::generate_ed25519());
        a.compose(b.id(), text("hi"), T).unwrap();
        let m = a.outbox(b.id()).remove(0);
        assert_eq!(c.receive(m.clone(), T), Err(Refusal::NotForMe));
        let mut bad = m.clone();
        bad.body = text("tampered");
        assert_eq!(b.receive(bad, T), Err(Refusal::BadSignature));
        assert_eq!(b.receive(m.clone(), T), Ok(Receipt::Request));
        assert_eq!(b.receive(m, T), Ok(Receipt::Duplicate));
        assert_eq!(b.conversation(a.id()).unwrap().entries().len(), 1);
        assert_eq!(a.compose(b.id(), text(&"x".repeat(5000)), T), Err(SendError::TooLarge));
        assert_eq!(a.compose(b.id(), text(""), T), Err(SendError::TooLarge));
    }

    #[test]
    fn senders_are_rate_limited_and_requests_are_capped() {
        let a = Contacts::new(Keypair::generate_ed25519());
        let b = Contacts::restore(Keypair::generate_ed25519(), Snapshot::default(), Limits { per_minute: 3, max_requests: 2 });
        for i in 0..5 {
            a.compose(b.id(), text(&format!("m{i}")), T + i).unwrap();
        }
        let r = ship(&a, &b, T + 10);
        assert_eq!(r.iter().filter(|r| r.is_ok()).count(), 3);
        assert_eq!(r.iter().filter(|r| **r == Err(Refusal::RateLimited)).count(), 2);
        assert!(ship(&a, &b, T + 61_000).is_empty());
        a.retry_failed(b.id());
        assert!(ship(&a, &b, T + 62_000).iter().all(|r| r.is_ok()), "the minute passed");
        let strangers: Vec<_> = (0..3).map(|_| Contacts::new(Keypair::generate_ed25519())).collect();
        let mut kept = 0;
        for s in &strangers {
            s.compose(b.id(), text("hello"), T + 70_000).unwrap();
            kept += ship(s, &b, T + 70_000).iter().filter(|r| r.is_ok()).count();
        }
        assert_eq!(kept, 1, "a is already one request; the cap is two");
    }

    #[test]
    fn offline_messages_queue_and_a_pull_fills_the_gap() {
        let (a, b) = pair();
        b.trust(a.id(), "Ana", T);
        a.trust(b.id(), "Ben", T);
        a.compose(b.id(), text("one"), T + 1).unwrap();
        a.compose(b.id(), text("two"), T + 2).unwrap();
        assert_eq!(a.outbox(b.id()).len(), 2);
        assert_eq!(a.outbox_peers(), [b.id().clone()]);
        // b was away: it asks a for what it missed instead
        let since = b.newest_from(a.id());
        let got: Vec<_> = a.messages_since(b.id(), since);
        assert_eq!(got.len(), 2);
        for m in got {
            assert_eq!(b.receive(m, T + 5), Ok(Receipt::Delivered));
        }
        assert_eq!(b.newest_from(a.id()), T + 2);
        // the sender's queue still holds them until it hears; a repeat is harmless
        assert_eq!(ship(&a, &b, T + 6), [Ok(Receipt::Duplicate), Ok(Receipt::Duplicate)]);
        assert!(a.outbox(b.id()).is_empty());
    }

    #[test]
    fn read_receipts_move_only_your_own_messages() {
        let (a, b) = pair();
        b.trust(a.id(), "Ana", T);
        a.compose(b.id(), text("hi"), T).unwrap();
        ship(&a, &b, T);
        b.compose(a.id(), text("yo"), T + 1).unwrap();
        ship(&b, &a, T + 1);
        let ids = b.mark_read(a.id());
        assert_eq!(ids.len(), 1, "only a's message to b");
        assert!(b.mark_read(a.id()).is_empty());
        assert_eq!(a.read_by(b.id(), &ids), 1);
        let mine = a.conversation(b.id()).unwrap();
        assert_eq!(mine.entries().iter().find(|e| e.msg.from == *a.id()).unwrap().delivery, Delivery::Read);
        assert_eq!(
            mine.entries().iter().find(|e| e.msg.from == *b.id()).unwrap().delivery,
            Delivery::Delivered,
            "b cannot mark b's own message read for a"
        );
        let b_msg = mine.entries().iter().find(|e| e.msg.from == *b.id()).unwrap().msg.id.clone();
        assert_eq!(a.read_by(b.id(), &[b_msg]), 0);
    }

    #[test]
    fn presence_follows_the_policy_for_each_viewer() {
        use crate::presence::{InSession, Presence, SessionHint};
        let (a, b) = pair();
        let stranger = Contacts::new(Keypair::generate_ed25519());
        a.trust(b.id(), "Ben", T);
        a.set_presence(PresenceInfo {
            state: Presence::Online,
            status: Some("mixing".into()),
            in_session: SessionHint::Named("EP".into()),
            updated_ms: T,
        });
        let friend = a.presence_for(b.id()).unwrap();
        assert_eq!(friend.detail.unwrap().in_session, Some(InSession::Anonymous));
        assert_eq!(a.presence_for(stranger.id()).unwrap().detail, None);
        a.set_policy(PresencePolicy { share_project_name: true, ..Default::default() });
        a.share_project_with(b.id(), true);
        assert_eq!(a.presence_for(b.id()).unwrap().detail.unwrap().in_session, Some(InSession::Project("EP".into())));
        a.set_audience(b.id(), Some(Audience::Nobody), T);
        assert_eq!(a.presence_for(b.id()).unwrap().detail, None);
    }

    #[test]
    fn a_snapshot_restores_everything_but_the_key() {
        let (a, b) = pair();
        a.trust(b.id(), "Ben", T);
        a.compose(b.id(), text("hi"), T).unwrap();
        let json = serde_json::to_string(&a.snapshot()).unwrap();
        let again = Contacts::restore(Keypair::generate_ed25519(), serde_json::from_str(&json).unwrap(), Limits::default());
        assert_eq!(again.state_of(b.id()), ContactState::Trusted);
        assert_eq!(again.conversation(b.id()).unwrap().entries().len(), 1);
        again.compose(b.id(), text("more"), T + 1).unwrap();
        let ids: Vec<_> = again.conversation(b.id()).unwrap().entries().iter().map(|e| e.msg.id.clone()).collect();
        assert_eq!(ids.len(), 2);
        assert_ne!(ids[0], ids[1], "the counter continues");
    }
}