Files
buzz/mobile/lib/shared/me/me_archived_agents.dart
Tom Brow ccfc1490e4 perf(mobile): verify signatures with native libsecp256k1 (#8657)
The app already verifies signatures in a few places: NIP-OA agent
profiles and owner attestations, Solo `me_*` records (agent inventory,
archived agents, assistants, sync), and pairing events. Each used
`nostr.Event.fromJson`'s pure-Dart BIP-340 verify, about 11.2 ms per
event on an iPhone SE (2nd gen, Profile). This routes them through
`verifiedNostrEventFromJson` and `verifySchnorrHex`, which keep the same
checks (timestamp range, canonical id, Schnorr signature) and the same
`nostr` exception types, with the signature check in libsecp256k1 (40
µs). NIP-OA owner authorizations are now signed with `signSchnorrHex`,
which removes the last pure-Dart Schnorr call in `lib`.

Incoming relay events are still not verified; that stays a separate
decision.

A native trace showed pure-Dart Schnorr verify in `me_sync` and `nip_oa`
costs 100-125 ms per foreground. This PR moves exactly those sites.

### Validation

- Added tests: the native verifier accepts a valid event and rejects
tampered content, a wrong signature, a different pubkey, malformed and
short signatures, and a zero timestamp, each also rejected by the
pure-Dart verifier. Hex Schnorr helpers are checked in both directions
against `nostr.Schnorr`.
- Focused existing validation: crypto, NIP-OA, Solo/me, pairing and
agent tests pass. `just mobile-install mobile-check mobile-test` passes
at f90823cd1.
- Device: a Profile build of the full native stack ran on an iPhone 12
mini against the internal relay.

buzz-review-completed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: george <973be878edd6d4f79692a3827f20a6f7fe0ed0362f269ff6b6ba8867033d7d8e@sprout-oss.stage.blox.sqprod.co>
2026-10-29 12:50:19 -07:00

95 lines
3.0 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'package:buzz/shared/crypto/event_signing.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:http/http.dart' as http;
import '../relay/relay.dart';
import 'me_sync.dart';
final meRelayInformationClientProvider = Provider<http.Client>((ref) {
final client = http.Client();
ref.onDispose(client.close);
return client;
});
/// Matches desktop's known-archived filtering. Unknown archive evidence does
/// not hide identities; this is presentation, never ownership or admission.
final meArchivedAgentsProvider = FutureProvider<Set<String>>((ref) async {
final sync = ref.watch(meSyncProvider);
final client = ref.watch(meRelayInformationClientProvider);
try {
final uri = Uri.parse(sync.community);
final response = await client
.send(
http.Request('GET', uri)
..headers['Accept'] = 'application/nostr+json',
)
.timeout(const Duration(seconds: 3));
if (response.statusCode != 200) return {};
final chunks = StreamIterator(
response.stream.timeout(const Duration(seconds: 3)),
);
final bytes = <int>[];
try {
await (() async {
while (await chunks.moveNext()) {
final chunk = chunks.current;
if (bytes.length + chunk.length > 256 * 1024) {
throw const FormatException(
'Relay information exceeds size limit.',
);
}
bytes.addAll(chunk);
}
})().timeout(const Duration(seconds: 3));
} finally {
await chunks.cancel();
}
sync.check();
final info = jsonDecode(utf8.decode(bytes));
// NIP-11 self is the signing authority; pubkey is only a contact key.
final authority = info is Map<String, dynamic> ? info['self'] : null;
if (authority is! String ||
!RegExp(r'^[0-9a-f]{64}$').hasMatch(authority)) {
return {};
}
final events = await sync.session.fetchHistory(
NostrFilter(kinds: const [13535], authors: [authority], limit: 1),
timeout: const Duration(seconds: 3),
);
sync.check();
return await _parseArchives(events, authority);
} catch (_) {
return {};
}
});
Future<Set<String>> _parseArchives(List<NostrEvent> events, String authority) =>
Isolate.run(() => _archived(events, authority));
Set<String> _archived(List<NostrEvent> events, String authority) {
if (events.length != 1) return {};
final event = events.single;
final markers = event.tags.where((tag) => tag.isNotEmpty && tag.first == '-');
if (event.kind != 13535 ||
event.pubkey != authority ||
event.content.isNotEmpty ||
markers.length != 1 ||
markers.single.length != 1) {
return {};
}
final encoded = jsonEncode(event.toJson());
if (utf8.encode(encoded).length > 2 * 1024 * 1024) return {};
verifiedNostrEventFromJson(encoded);
return {
for (final tag in event.tags)
if (tag.length >= 2 &&
tag[0] == 'p' &&
RegExp(r'^[0-9a-f]{64}$').hasMatch(tag[1]))
tag[1],
};
}