Skip to content

Commit d08f598

Browse files
square-tombstudioclaude
committed
perf(mobile): derive keys natively and hash NIP-98 bodies faster
Public key derivation in AccountIdentityStore (publicKeyForNsec, which runs on every relay auth assertion, and the record read/create paths) now uses libsecp256k1 instead of pure-Dart nostr.Keys (~7 ms per call on an iPhone 12 mini). Default agent writes sign natively too. NIP-98 payload hashing, media upload hashing and NIP-OA preimage hashing use package:crypto instead of pointycastle SHA256Digest. AOT benchmark on Mac (pointycastle vs crypto): 1 KB 39.9 us vs 6.6 us (6.1x), 50 KB 1518 us vs 293 us (5.2x), 1 MB 29.6 ms vs 6.1 ms (4.9x), identical output. Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Tom Brow <[email protected]>
1 parent 009dc10 commit d08f598

8 files changed

Lines changed: 150 additions & 31 deletions

File tree

‎mobile/lib/shared/crypto/nip_oa.dart‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import 'dart:convert';
2-
import 'dart:typed_data';
32

43
import 'package:buzz/shared/crypto/event_signing.dart';
5-
import 'package:pointycastle/digests/sha256.dart';
4+
import 'package:crypto/crypto.dart' as crypto;
65
import '../relay/nostr_models.dart';
76

87
/// Verify the signed profile and all owner-attestation conditions against it.
@@ -70,10 +69,7 @@ String? verifiedOaOwnerPubkey(List<List<String>> tags, String agentPubkey) {
7069
if (!_validConditions(conditions)) continue;
7170

7271
final preimage = utf8.encode('nostr:agent-auth:$agent:$conditions');
73-
final digest = SHA256Digest().process(Uint8List.fromList(preimage));
74-
final message = digest
75-
.map((b) => b.toRadixString(16).padLeft(2, '0'))
76-
.join();
72+
final message = crypto.sha256.convert(preimage).toString();
7773

7874
try {
7975
if (verifySchnorrHex(

‎mobile/lib/shared/hosted/account_identity_store.dart‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart';
66

77
import 'package:nostr/nostr.dart' as nostr;
88

9+
import '../crypto/event_signing.dart';
910
import '../storage/secure_storage.dart';
1011

1112
import 'hosted_environment.dart';
@@ -140,9 +141,9 @@ class AccountIdentityStore {
140141
checkCurrent?.call();
141142
// Read before parsing/generating any candidate: corrupt != absent.
142143
final existing = await _read();
143-
final keys = _keys(nsec);
144+
final pubkey = publicKeyForNsec(nsec);
144145
if (existing != null) {
145-
if (existing.pubkey != keys.public) throw AccountIdentityFailure.occupied;
146+
if (existing.pubkey != pubkey) throw AccountIdentityFailure.occupied;
146147
if (recoveredBackup == null) return existing.snapshot;
147148
if (existing.backup != null) {
148149
if (jsonEncode(existing.backup!._json()) !=
@@ -152,11 +153,11 @@ class AccountIdentityStore {
152153
return existing.snapshot;
153154
}
154155
}
155-
if (recoveredBackup != null && recoveredBackup.pubkey != keys.public) {
156+
if (recoveredBackup != null && recoveredBackup.pubkey != pubkey) {
156157
throw AccountIdentityFailure.mismatch;
157158
}
158159
checkCurrent?.call();
159-
final record = _Record(nsec, keys.public, recoveredBackup);
160+
final record = _Record(nsec, pubkey, recoveredBackup);
160161
await _write(record);
161162
return record.snapshot;
162163
});
@@ -268,7 +269,7 @@ class AccountIdentityStore {
268269
_serialized(() async {
269270
final record = await _read();
270271
if (record == null) throw AccountIdentityFailure.absent;
271-
return operation(_keys(record.nsec));
272+
return operation(keysForHex(_nsecHex(record.nsec)));
272273
});
273274

274275
Future<_Record?> _read() async {
@@ -288,7 +289,7 @@ class AccountIdentityStore {
288289
final value = jsonDecode(raw) as Map<String, dynamic>;
289290
if (value['version'] != 1) throw AccountIdentityFailure.unreadable;
290291
final nsec = value['nsec'] as String;
291-
final pubkey = _keys(nsec).public;
292+
final pubkey = publicKeyForNsec(nsec);
292293
if (value['pubkey'] != pubkey ||
293294
(_pairingPubkey != null && _pairingPubkey != pubkey)) {
294295
throw AccountIdentityFailure.unreadable;
@@ -332,10 +333,20 @@ class AccountIdentityStore {
332333
}
333334

334335
/// Validate a candidate without exposing signing material to the UI.
335-
static String publicKeyForNsec(String nsec) => _keys(nsec).public;
336+
///
337+
/// Derives the public key with libsecp256k1. This runs on every relay auth
338+
/// assertion, where the pure-Dart derivation in `nostr.Keys` cost ~7 ms.
339+
static String publicKeyForNsec(String nsec) =>
340+
derivePublicKeyHex(_validSecretHex(_nsecHex(nsec)));
336341

337342
/// Rejects invalid secp256k1 scalars before constructing a signing key.
338-
static nostr.Keys keysForHex(String hex) {
343+
///
344+
/// `nostr.Keys` always derives the public key in pure Dart and cannot take
345+
/// a precomputed one, so this stays for the rare callers that need a
346+
/// `nostr.Keys` object.
347+
static nostr.Keys keysForHex(String hex) => nostr.Keys(_validSecretHex(hex));
348+
349+
static String _validSecretHex(String hex) {
339350
if (!RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(hex)) {
340351
throw AccountIdentityFailure.invalidKey;
341352
}
@@ -347,17 +358,17 @@ class AccountIdentityStore {
347358
if (scalar <= BigInt.zero || scalar >= order) {
348359
throw AccountIdentityFailure.invalidKey;
349360
}
350-
return nostr.Keys(hex);
361+
return hex;
351362
}
352363

353-
static nostr.Keys _keys(String nsec) {
364+
static String _nsecHex(String nsec) {
354365
try {
355366
final decoded = nostr.Nip19.decode(payload: nsec);
356367
if (decoded.prefix != nostr.Nip19Prefix.nsec ||
357368
!RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(decoded.data)) {
358369
throw AccountIdentityFailure.invalidKey;
359370
}
360-
return keysForHex(decoded.data);
371+
return decoded.data;
361372
} catch (_) {
362373
throw AccountIdentityFailure.invalidKey;
363374
}

‎mobile/lib/shared/me/default_agent_writer.dart‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import 'dart:convert';
22

3-
import 'package:nostr/nostr.dart' as nostr;
4-
3+
import '../crypto/event_signing.dart';
54
import '../crypto/nip44.dart';
65
import '../relay/relay.dart';
76
import 'default_agent.dart';
@@ -32,19 +31,19 @@ Future<void> saveDefaultAgent(MeSync sync, String? pubkey) async {
3231
}
3332
}
3433
final event = NostrEvent.fromJson(
35-
nostr.Event.from(
34+
signNostrEvent(
3635
kind: 30078,
3736
content: nip44Encrypt(
3837
sync.key,
3938
jsonEncode({'version': 1, 'agent': pubkey}),
4039
),
4140
secretKey: sync.privateHex,
41+
pubkey: sync.pubkey,
4242
createdAt: now,
4343
tags: [
4444
['d', defaultAgentCoordinate(sync.community)],
4545
['t', defaultAgentTag],
4646
],
47-
verify: false,
4847
).toMap(),
4948
);
5049
await sync.session.publish(event);

‎mobile/lib/shared/relay/media_upload.dart‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
1010
import 'package:http/http.dart' as http;
1111
import 'package:image_picker/image_picker.dart';
1212
import 'package:nostr/nostr.dart' as nostr;
13-
import 'package:pointycastle/digests/sha256.dart';
13+
import 'package:crypto/crypto.dart' as crypto;
1414

1515
import 'animated_image_sanitizer.dart';
1616
import 'media_auth.dart';
@@ -790,10 +790,7 @@ Stream<List<int>> _uploadByteStream(
790790
}
791791
}
792792

793-
String _sha256Hex(Uint8List bytes) {
794-
final digest = SHA256Digest().process(bytes);
795-
return digest.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
796-
}
793+
String _sha256Hex(Uint8List bytes) => crypto.sha256.convert(bytes).toString();
797794

798795
String? _tryDetectImageMimeType(Uint8List bytes) {
799796
try {

‎mobile/lib/shared/relay/relay_session.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ import 'dart:async';
22
import 'dart:convert';
33
import 'dart:math';
44

5+
import 'package:crypto/crypto.dart' as crypto;
56
import 'package:http/http.dart' as http;
67
import 'package:nostr/nostr.dart' as nostr;
7-
import 'package:pointycastle/digests/sha256.dart';
88
import 'package:uuid/uuid.dart';
99

1010
import 'package:flutter/foundation.dart';

‎mobile/lib/shared/relay/relay_session_auth.dart‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@ String buildNip98AuthHeader({
1616
if (privkeyHex.isEmpty) {
1717
throw Exception('Invalid nsec');
1818
}
19-
final payloadHash = SHA256Digest()
20-
.process(Uint8List.fromList(bodyBytes))
21-
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
22-
.join();
19+
final payloadHash = crypto.sha256.convert(bodyBytes).toString();
2320
final event = signNostrEvent(
2421
kind: 27235,
2522
content: '',

‎mobile/test/shared/hosted/account_identity_store_test.dart‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,55 @@ void main() {
1111
);
1212
setUp(() => FlutterSecureStorage.setMockInitialValues({}));
1313

14+
group('publicKeyForNsec', () {
15+
test('matches known vectors and the pure-Dart derivation', () {
16+
const one =
17+
'0000000000000000000000000000000000000000000000000000000000000001';
18+
// secp256k1 generator point x coordinate for secret key 1.
19+
expect(
20+
AccountIdentityStore.publicKeyForNsec(
21+
nostr.Bech32Entity.encode(prefix: nostr.Nip19Prefix.nsec, data: one),
22+
),
23+
'79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
24+
);
25+
for (final hex in [
26+
'b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfef',
27+
'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140',
28+
]) {
29+
final keys = nostr.Keys(hex);
30+
expect(AccountIdentityStore.publicKeyForNsec(keys.nsec), keys.public);
31+
}
32+
});
33+
34+
test('rejects invalid keys with invalidKey', () {
35+
final invalid = [
36+
'not an nsec',
37+
'',
38+
nostr.Keys(
39+
'0000000000000000000000000000000000000000000000000000000000000001',
40+
).npub,
41+
// Scalar zero and the curve order are not valid secret keys.
42+
nostr.Bech32Entity.encode(
43+
prefix: nostr.Nip19Prefix.nsec,
44+
data:
45+
'0000000000000000000000000000000000000000000000000000000000000000',
46+
),
47+
nostr.Bech32Entity.encode(
48+
prefix: nostr.Nip19Prefix.nsec,
49+
data:
50+
'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141',
51+
),
52+
];
53+
for (final value in invalid) {
54+
expect(
55+
() => AccountIdentityStore.publicKeyForNsec(value),
56+
throwsA(AccountIdentityFailure.invalidKey),
57+
reason: value,
58+
);
59+
}
60+
});
61+
});
62+
1463
for (final simulated in [false, true]) {
1564
test(
1665
'recovery retains scoped receipt; simulated=$simulated cannot authorize',
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import 'dart:convert';
2+
3+
import 'package:buzz/shared/crypto/event_signing.dart';
4+
import 'package:buzz/shared/relay/relay_session.dart';
5+
import 'package:flutter_test/flutter_test.dart';
6+
import 'package:nostr/nostr.dart' as nostr;
7+
8+
void main() {
9+
final keys = nostr.Keys(
10+
'b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfef',
11+
);
12+
13+
Map<String, dynamic> decode(String header) {
14+
expect(header, startsWith('Nostr '));
15+
return jsonDecode(utf8.decode(base64.decode(header.substring(6))))
16+
as Map<String, dynamic>;
17+
}
18+
19+
String payloadTag(Map<String, dynamic> event) =>
20+
(event['tags'] as List).firstWhere((t) => t[0] == 'payload')[1] as String;
21+
22+
test(
23+
'payload tag is the lowercase SHA-256 hex of the body (known vectors)',
24+
() {
25+
final vectors = {
26+
'': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
27+
'abc':
28+
'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
29+
};
30+
for (final entry in vectors.entries) {
31+
final header = buildNip98AuthHeader(
32+
method: 'post',
33+
url: 'https://relay.example/query',
34+
bodyBytes: utf8.encode(entry.key),
35+
nsec: keys.nsec,
36+
);
37+
final event = decode(header);
38+
expect(payloadTag(event), entry.value);
39+
expect(event['kind'], 27235);
40+
expect(event['pubkey'], keys.public);
41+
expect(
42+
(event['tags'] as List).firstWhere((t) => t[0] == 'method')[1],
43+
'POST',
44+
);
45+
expect(
46+
verifySchnorrHex(
47+
publicKey: event['pubkey'] as String,
48+
messageHex: event['id'] as String,
49+
signature: event['sig'] as String,
50+
),
51+
isTrue,
52+
);
53+
}
54+
},
55+
);
56+
57+
test('hashes bodies longer than one SHA-256 block identically', () {
58+
// 1,000,000 repetitions of "a" (FIPS 180 test vector).
59+
final header = buildNip98AuthHeader(
60+
method: 'POST',
61+
url: 'https://relay.example/query',
62+
bodyBytes: List.filled(1000000, 0x61),
63+
nsec: keys.nsec,
64+
);
65+
expect(
66+
payloadTag(decode(header)),
67+
'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0',
68+
);
69+
});
70+
}

0 commit comments

Comments
 (0)