Skip to content

Commit e88bb81

Browse files
square-tombclaude
andcommitted
fix(mobile): bound verified-profile work and reconcile replays
Drop events that cannot be projections (non-empty content, more than eight tags, or oversized tag values) before buffering them, keep only the newest live event per subject awaiting proof, and treat a retried subscription's replay as a new snapshot instead of live updates. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Tom Brow <[email protected]>
1 parent 06d3718 commit e88bb81

3 files changed

Lines changed: 127 additions & 10 deletions

File tree

‎mobile/lib/shared/verified_profiles/verified_profile.dart‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,11 +176,26 @@ class VerifiedProfile {
176176
/// A newer signed event with a malformed profile still replaces the older one
177177
/// at this address, so a malformed projection clears the earlier verified name
178178
/// instead of preserving it. Callers must have verified id and signature.
179+
/// Longer than any valid tag name or value (64 scalar values is at most 128
180+
/// UTF-16 code units).
181+
const _maxTagValue = 256;
182+
179183
String? verifiedProfileSubject(
180184
NostrEvent event,
181185
VerifiedProfileAuthority authority,
182186
) {
183-
if (event.kind != verifiedProfileKind || event.pubkey != authority.pubkey) {
187+
if (event.kind != verifiedProfileKind ||
188+
event.pubkey != authority.pubkey ||
189+
// Bounded before any buffering or proof work: a projection or
190+
// retraction has empty content and at most eight short two-element tags.
191+
event.content.isNotEmpty ||
192+
event.tags.length > 8 ||
193+
event.tags.any(
194+
(tag) =>
195+
tag.length != 2 ||
196+
tag[0].length > _maxTagValue ||
197+
tag[1].length > _maxTagValue,
198+
)) {
184199
return null;
185200
}
186201
for (final tag in event.tags) {

‎mobile/lib/shared/verified_profiles/verified_profile_directory.dart‎

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,15 @@ class _Batch {
2020
_Batch(this.subjects);
2121
final List<String> subjects;
2222
final List<NostrEvent> early = [];
23+
24+
/// Live events awaiting proof, newest per subject, so a fast stream cannot
25+
/// queue unbounded work.
26+
final Map<String, NostrEvent> pending = {};
2327
Future<void> tail = Future.value();
28+
29+
/// Bumped when the relay replays the subscription, so work from the
30+
/// previous snapshot is dropped.
31+
int epoch = 0;
2432
void Function()? unsubscribe;
2533

2634
/// Retires this batch so the next sync can reopen it.
@@ -248,10 +256,13 @@ class VerifiedProfilesNotifier extends Notifier<Map<String, VerifiedProfile>> {
248256
limit: chunk.length,
249257
),
250258
(event) => _onEvent(batch, event, authority, generation),
251-
onStatusChanged: (status) {
252-
if (status == RelaySubscriptionStatus.ready) {
253-
_onEose(batch, authority, generation);
254-
}
259+
onStatusChanged: (status) => switch (status) {
260+
RelaySubscriptionStatus.ready => _onEose(
261+
batch,
262+
authority,
263+
generation,
264+
),
265+
RelaySubscriptionStatus.retrying => _onRetry(batch, fail),
255266
},
256267
onClosed: (_) => fail(),
257268
);
@@ -285,15 +296,38 @@ class VerifiedProfilesNotifier extends Notifier<Map<String, VerifiedProfile>> {
285296
batch.early.add(event);
286297
return;
287298
}
299+
final queued = batch.pending.isNotEmpty;
300+
if (supersedes(event, batch.pending[subject])) {
301+
batch.pending[subject] = event;
302+
}
303+
if (queued) return;
304+
final epoch = batch.epoch;
288305
_enqueue(batch, generation, () async {
289-
final proven = await _prove([event]);
290-
if (_live(batch, generation)) {
306+
final events = batch.pending.values.toList();
307+
batch.pending.clear();
308+
final proven = await _prove(events);
309+
if (_current(batch, generation, epoch)) {
291310
_accept(proven, authority);
292311
_publish();
293312
}
294313
});
295314
}
296315

316+
/// The relay closed and is replaying the subscription: reconcile the replay
317+
/// as a new snapshot rather than as live updates.
318+
void _onRetry(_Batch batch, void Function() fail) {
319+
if (!batch.active) return;
320+
batch.epoch++;
321+
batch.ready = false;
322+
batch.candidates = 0;
323+
batch.early.clear();
324+
batch.pending.clear();
325+
batch.timeout?.cancel();
326+
batch.timeout = Timer(_eoseTimeout, fail);
327+
_checked.removeAll(batch.subjects);
328+
_publish();
329+
}
330+
297331
void _onEose(
298332
_Batch batch,
299333
VerifiedProfileAuthority authority,
@@ -305,17 +339,19 @@ class VerifiedProfilesNotifier extends Notifier<Map<String, VerifiedProfile>> {
305339
batch.timeout = null;
306340
final early = List.of(batch.early);
307341
batch.early.clear();
342+
final epoch = batch.epoch;
343+
final candidates = batch.candidates;
308344
_enqueue(batch, generation, () async {
309345
final proven = await _prove(early);
310-
if (!_live(batch, generation)) return;
346+
if (!_current(batch, generation, epoch)) return;
311347
_accept(proven, authority);
312348
final seen = {
313349
for (final event in proven) verifiedProfileSubject(event, authority)!,
314350
};
315351
// A full response that omits subjects may be truncated: only a short
316352
// response proves absence.
317353
final complete =
318-
batch.candidates < batch.subjects.length ||
354+
candidates < batch.subjects.length ||
319355
seen.length == batch.subjects.length;
320356
for (final subject in batch.subjects) {
321357
if (!complete && !seen.contains(subject)) continue;
@@ -329,9 +365,13 @@ class VerifiedProfilesNotifier extends Notifier<Map<String, VerifiedProfile>> {
329365
bool _live(_Batch batch, int generation) =>
330366
batch.active && generation == _generation && ref.mounted;
331367

368+
bool _current(_Batch batch, int generation, int epoch) =>
369+
_live(batch, generation) && batch.epoch == epoch;
370+
332371
void _enqueue(_Batch batch, int generation, Future<void> Function() job) {
372+
final epoch = batch.epoch;
333373
batch.tail = batch.tail.then((_) async {
334-
if (!_live(batch, generation)) return;
374+
if (!_live(batch, generation) || batch.epoch != epoch) return;
335375
try {
336376
await job();
337377
} catch (error) {

‎mobile/test/shared/verified_profiles/verified_profile_directory_failures_test.dart‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ class _ScriptedSession extends RelaySessionNotifier {
1616
List<NostrEvent> history = const [];
1717
int subscriptions = 0;
1818
int unsubscribed = 0;
19+
void Function(NostrEvent)? emit;
20+
void Function(RelaySubscriptionStatus)? status;
1921

2022
@override
2123
SessionState build() => const SessionState(status: SessionStatus.connected);
@@ -28,6 +30,8 @@ class _ScriptedSession extends RelaySessionNotifier {
2830
required void Function(RelaySubscriptionStatus status) onStatusChanged,
2931
}) async {
3032
subscriptions++;
33+
emit = onEvent;
34+
status = onStatusChanged;
3135
final events = history;
3236
Future.microtask(() {
3337
for (final event in events) {
@@ -43,11 +47,13 @@ void main() {
4347
late _ScriptedSession session;
4448
late ProviderContainer container;
4549
late int proofCalls;
50+
late int provenEvents;
4651
late bool proofThrows;
4752

4853
void setUpContainer() {
4954
session = _ScriptedSession();
5055
proofCalls = 0;
56+
provenEvents = 0;
5157
proofThrows = false;
5258
container = ProviderContainer(
5359
overrides: [
@@ -60,6 +66,7 @@ void main() {
6066
),
6167
verifiedProfileProofCheckerProvider.overrideWithValue((events) async {
6268
proofCalls++;
69+
provenEvents += events.length;
6370
if (proofThrows) throw StateError('isolate failed');
6471
return [for (final e in events) hasVerifiedEventProof(e)];
6572
}),
@@ -105,4 +112,59 @@ void main() {
105112
expect(profile?.checked, isTrue);
106113
});
107114
});
115+
116+
test('an oversized event is dropped before buffering or proof', () {
117+
fakeAsync((async) {
118+
setUpContainer();
119+
final oversized = signedProjection(profileTags(subjectA));
120+
session.history = [
121+
NostrEvent(
122+
id: oversized.id,
123+
pubkey: oversized.pubkey,
124+
createdAt: oversized.createdAt,
125+
kind: oversized.kind,
126+
tags: oversized.tags,
127+
content: 'x' * 100000,
128+
sig: oversized.sig,
129+
),
130+
];
131+
expect(start(async), isEmpty);
132+
expect(provenEvents, 0);
133+
expect(session.unsubscribed, 0);
134+
});
135+
});
136+
137+
test('live events are coalesced to the newest per subject', () {
138+
fakeAsync((async) {
139+
setUpContainer();
140+
expect(start(async), isEmpty);
141+
for (var i = 0; i < 50; i++) {
142+
session.emit!(
143+
signedProjection(profileTags(subjectA), createdAt: 3000 + i),
144+
);
145+
}
146+
async.elapse(const Duration(milliseconds: 100));
147+
expect(provenEvents, 1);
148+
expect(container.read(verifiedProfilesProvider)[subjectA], isNotNull);
149+
});
150+
});
151+
152+
test('a replayed subscription is reconciled as a new snapshot', () {
153+
fakeAsync((async) {
154+
setUpContainer();
155+
session.history = [signedProjection(profileTags(subjectA))];
156+
expect(start(async)[subjectA]?.checked, isTrue);
157+
158+
// The relay closes and replays the subscription without the record.
159+
session.status!(RelaySubscriptionStatus.retrying);
160+
async.elapse(const Duration(milliseconds: 10));
161+
expect(
162+
container.read(verifiedProfilesProvider)[subjectA]?.checked,
163+
isFalse,
164+
);
165+
session.status!(RelaySubscriptionStatus.ready);
166+
async.elapse(const Duration(milliseconds: 100));
167+
expect(container.read(verifiedProfilesProvider), isEmpty);
168+
});
169+
});
108170
}

0 commit comments

Comments
 (0)