mirror of
https://github.com/block/buzz.git
synced 2026-10-30 22:11:36 +00:00
Follows #8654. Deriving an x-only public key from a secret key with `nostr.Keys(secret).public` costs about 5.6 ms in pure Dart on an iPhone SE (2nd gen, Profile). The app does it in 10 places, including relay config, the signed-event relay's `pubkey` getter, push lease checks, status updates, and the settings identity row's `build` method. This routes all of them through `derivePublicKeyHex` from #8654, which takes 16.5 µs on the same device. Behavior is unchanged for valid keys: output is the same lowercase hex. For a malformed or out-of-range key the thrown type changes from nostr's `InvalidKeyException` to `ArgumentError`; every affected site either catches all errors or rethrows its own `FormatException`/`StateError`, and nothing in `lib` or `test` matches on the old type. Sites that need a full `nostr.Keys` object (key generation, `AccountIdentityStore`) are unchanged. ### Validation - `derivePublicKeyHex` is checked against `nostr.Keys` for 64 random keys in #8654's `event_signing_test.dart`. - Full mobile analyze and test suite pass on this branch after rebasing onto main, including the package's own tests. - iPhone 12 mini, Profile build of this stack (with #8656 and #8657 on top): paired to the internal Buzz community through Desktop; relay auth, identity row, avatar, and channel/DM/inbox loading all worked under the derived key. buzz-review-completed (agent review, Codex and security review clean; device validation above; human app test not applicable under the mobile testing exception) 🤖 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> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
177 lines
5.1 KiB
Dart
177 lines
5.1 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
import 'package:nostr/nostr.dart' as nostr;
|
|
|
|
import '../../shared/relay/relay.dart';
|
|
import 'user_status.dart';
|
|
import 'user_status_cache_provider.dart';
|
|
import 'package:buzz/shared/crypto/event_signing.dart';
|
|
|
|
/// Manages the current user's own NIP-38 status (kind:30315, d=general).
|
|
///
|
|
/// Fetches the existing status on build and provides [setStatus] / [clearStatus]
|
|
/// for publishing. Publishes via WebSocket (triggers fan-out). No heartbeat
|
|
/// needed — user status events are parameterised replaceable, not ephemeral.
|
|
class UserStatusNotifier extends AsyncNotifier<UserStatus?> {
|
|
Timer? _expirationTimer;
|
|
|
|
@override
|
|
Future<UserStatus?> build() async {
|
|
ref.watch(relayClientProvider);
|
|
ref.watch(relaySessionProvider);
|
|
ref.onDispose(() {
|
|
_expirationTimer?.cancel();
|
|
_expirationTimer = null;
|
|
});
|
|
|
|
final status = await _fetch();
|
|
_scheduleExpiration(status);
|
|
return status;
|
|
}
|
|
|
|
Future<UserStatus?> _fetch() async {
|
|
final config = ref.read(relayConfigProvider);
|
|
final nsec = config.nsec;
|
|
if (nsec == null || nsec.isEmpty) return null;
|
|
|
|
String pubkey;
|
|
try {
|
|
final privkeyHex = nostr.Nip19.decode(payload: nsec).data;
|
|
pubkey = derivePublicKeyHex(privkeyHex);
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
|
|
final sessionState = ref.read(relaySessionProvider);
|
|
if (sessionState.status != SessionStatus.connected) return null;
|
|
|
|
try {
|
|
final session = ref.read(relaySessionProvider.notifier);
|
|
final events = await session.fetchHistory(
|
|
NostrFilter(
|
|
kinds: const [EventKind.userStatus],
|
|
authors: [pubkey],
|
|
tags: const {
|
|
'#d': ['general'],
|
|
},
|
|
limit: 1,
|
|
),
|
|
);
|
|
|
|
if (events.isEmpty) return null;
|
|
|
|
// Pick the most recent event.
|
|
final latest = events.reduce(
|
|
(a, b) => a.createdAt >= b.createdAt ? a : b,
|
|
);
|
|
final status = UserStatus.fromEvent(latest);
|
|
final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
|
return status.isEmpty || status.isExpiredAt(now) ? null : status;
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Future<void> setStatus(
|
|
String text,
|
|
String emoji, {
|
|
DateTime? expiresAt,
|
|
}) async {
|
|
final trimmed = text.trim();
|
|
final config = ref.read(relayConfigProvider);
|
|
final nsec = config.nsec;
|
|
if (nsec == null || nsec.isEmpty) return;
|
|
|
|
final tags = <List<String>>[
|
|
['d', 'general'],
|
|
];
|
|
if (emoji.isNotEmpty) {
|
|
tags.add(['emoji', emoji]);
|
|
}
|
|
if (expiresAt != null) {
|
|
tags.add(['expiration', '${expiresAt.millisecondsSinceEpoch ~/ 1000}']);
|
|
}
|
|
|
|
final privkeyHex = nostr.Nip19.decode(payload: nsec).data;
|
|
final event = signNostrEvent(
|
|
kind: EventKind.userStatus,
|
|
content: trimmed,
|
|
tags: tags,
|
|
secretKey: privkeyHex,
|
|
);
|
|
|
|
final session = ref.read(relaySessionProvider.notifier);
|
|
await session.publish(NostrEvent.fromJson(event.toMap()));
|
|
|
|
// Optimistic update: update own state immediately.
|
|
final newStatus = (trimmed.isNotEmpty || emoji.isNotEmpty)
|
|
? UserStatus(
|
|
text: trimmed,
|
|
emoji: emoji,
|
|
updatedAt: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
|
expiresAt: expiresAt == null
|
|
? null
|
|
: expiresAt.millisecondsSinceEpoch ~/ 1000,
|
|
)
|
|
: null;
|
|
state = AsyncValue.data(newStatus);
|
|
_scheduleExpiration(newStatus);
|
|
|
|
// Also update the shared cache so other UI reads stay consistent.
|
|
final pubkey = derivePublicKeyHex(privkeyHex);
|
|
ref.read(userStatusCacheProvider.notifier).updateStatus(pubkey, newStatus);
|
|
}
|
|
|
|
Future<void> clearStatus() => setStatus('', '');
|
|
|
|
void _scheduleExpiration(UserStatus? status) {
|
|
_expirationTimer?.cancel();
|
|
_expirationTimer = null;
|
|
final deadline = status?.expirationDateTime;
|
|
if (deadline == null) return;
|
|
|
|
final remaining = deadline.difference(DateTime.now());
|
|
_expirationTimer = Timer(
|
|
remaining.isNegative ? Duration.zero : remaining,
|
|
_expireCurrentStatus,
|
|
);
|
|
}
|
|
|
|
void _expireCurrentStatus() {
|
|
final current = state.asData?.value;
|
|
if (current == null) return;
|
|
final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
|
if (!current.isExpiredAt(now)) {
|
|
// Timer callbacks can land just before the Unix-second boundary.
|
|
_expirationTimer = Timer(
|
|
const Duration(milliseconds: 50),
|
|
_expireCurrentStatus,
|
|
);
|
|
return;
|
|
}
|
|
|
|
state = const AsyncValue.data(null);
|
|
final pubkey = _currentPubkey();
|
|
if (pubkey != null) {
|
|
ref.read(userStatusCacheProvider.notifier).updateStatus(pubkey, null);
|
|
}
|
|
}
|
|
|
|
String? _currentPubkey() {
|
|
final nsec = ref.read(relayConfigProvider).nsec;
|
|
if (nsec == null || nsec.isEmpty) return null;
|
|
try {
|
|
final privkeyHex = nostr.Nip19.decode(payload: nsec).data;
|
|
return derivePublicKeyHex(privkeyHex);
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
|
|
final userStatusProvider =
|
|
AsyncNotifierProvider<UserStatusNotifier, UserStatus?>(
|
|
UserStatusNotifier.new,
|
|
);
|