Files
buzz/mobile/lib/features/settings/settings_page/connection_section.dart
Tom Brow 8161a7cad0 perf(mobile): derive public keys with native libsecp256k1 (#8655)
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>
2026-10-29 08:53:58 -07:00

158 lines
4.7 KiB
Dart

part of '../settings_page.dart';
class _ConnectionSection extends ConsumerWidget {
const _ConnectionSection({required this.identityRecoveryPageBuilder});
final WidgetBuilder identityRecoveryPageBuilder;
@override
Widget build(BuildContext context, WidgetRef ref) {
final config = ref.watch(relayConfigProvider);
final authState = ref.watch(authProvider).value;
final nsec = config.nsec;
final community = authState?.community;
if (nsec == null || nsec.isEmpty || community == null) {
return const SizedBox.shrink();
}
return AppListCard(
verticalPadding: Grid.twelve,
children: [
AppListRow(
title: 'Export private key',
subtitle: 'Save an nsec backup of this community identity',
trailing: const _RowChevron(),
onTap: () => showNsecExportSheet(
context,
community: community,
isCurrent: () {
if (!context.mounted) return false;
final current = ref.read(authProvider).value?.community;
return current?.id == community.id &&
current?.nsec == community.nsec &&
current?.sensitiveActionPolicy ==
community.sensitiveActionPolicy;
},
),
),
AppListRow(
title: 'Send identity to desktop',
subtitle: 'Scan a recovery code shown by Buzz Desktop',
trailing: const _RowChevron(),
onTap: () async {
final pairing = ref.read(pairingProvider.notifier);
final authorized = await pairing.authorizeIdentityExport(
community: community,
);
if (!authorized) {
if (!context.mounted) return;
final message = ref.read(pairingProvider).errorMessage;
if (message != null) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(message)));
}
return;
}
try {
if (!context.mounted) return;
final resumed = await _waitForResumedFrame();
if (!resumed) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Buzz did not return to the foreground. Try again.',
),
),
);
}
return;
}
if (!context.mounted) return;
await Navigator.of(context).push(
MaterialPageRoute<void>(builder: identityRecoveryPageBuilder),
);
} finally {
pairing.reset();
}
},
),
],
);
}
}
const _resumeWaitTimeout = Duration(seconds: 5);
Future<bool> _waitForResumedFrame() async {
final binding = WidgetsBinding.instance;
if (binding.lifecycleState != AppLifecycleState.resumed) {
final resumed = Completer<void>();
final listener = AppLifecycleListener(
onResume: () {
if (!resumed.isCompleted) resumed.complete();
},
);
try {
await resumed.future.timeout(_resumeWaitTimeout);
} on TimeoutException {
return false;
} finally {
listener.dispose();
}
}
await binding.endOfFrame;
return true;
}
/// The full npub for [privHex], or null when it holds no usable key. A
/// well-formed nsec can still hold a scalar outside the curve order.
String? _npubFor(String privHex) {
if (privHex.isEmpty) return null;
try {
return fullNpub(derivePublicKeyHex(privHex));
} on ArgumentError {
return null;
}
}
class _IdentityRow extends StatelessWidget {
const _IdentityRow({required this.nsec});
final String nsec;
@override
Widget build(BuildContext context) {
final npub = _npubFor(nostr.Nip19.decode(payload: nsec).data);
// The full npub is the canonical copy/share form (never raw hex); an
// invalid identity is surfaced as unavailable and never copied.
return Semantics(
button: true,
label: 'Copy identity public key',
value: npub ?? 'Identity unavailable',
child: AppListRow(
title: 'Copy public key (npub)',
trailing: Icon(
BuzzIcons.copy,
size: 18,
color: context.colors.onSurfaceVariant,
),
onTap: npub == null
? null
: () async {
await copyToClipboard(
context,
npub,
message: 'Public key (npub) copied',
);
await successHaptic();
},
),
);
}
}