Skip to content

Commit f90823c

Browse files
browgeorge
andcommitted
perf(mobile): verify signatures with native libsecp256k1
Route the existing pure-Dart signature checks (NIP-OA profiles and owner attestations, Solo me_* records, pairing events) through verifiedNostrEventFromJson and verifySchnorrHex, and sign NIP-OA owner authorizations with signSchnorrHex. Incoming relay events are still not verified. Co-authored-by: george <973be878edd6d4f79692a3827f20a6f7fe0ed0362f269ff6b6ba8867033d7d8e@sprout-oss.stage.blox.sqprod.co> Signed-off-by: Tom Brow <[email protected]>
1 parent 3dbc95c commit f90823c

9 files changed

Lines changed: 179 additions & 13 deletions

File tree

‎mobile/lib/features/pairing/pairing_provider.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,7 @@ class PairingNotifier extends Notifier<PairingState> {
526526
// NIP-AB §Event Validation: verify event signature (NIP-01).
527527
// The nostr package's Event.fromJson verifies id + sig on construction.
528528
try {
529-
final event = nostr.Event.fromJson(jsonEncode(eventJson));
529+
final event = verifiedNostrEventFromJson(jsonEncode(eventJson));
530530
if (event.id != eventId) return; // id mismatch
531531
} catch (_) {
532532
return; // invalid signature or malformed event

‎mobile/lib/shared/agents/remote_agents.dart‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import 'dart:async';
22
import 'dart:convert';
33

4+
import 'package:buzz/shared/crypto/event_signing.dart';
45
import 'package:crypto/crypto.dart';
56
import 'package:flutter/foundation.dart';
67
import 'package:hooks_riverpod/hooks_riverpod.dart';
@@ -734,7 +735,7 @@ List<String> signOwnerAuthorization(nostr.Keys owner, String agent) {
734735
'auth',
735736
owner.public,
736737
'',
737-
nostr.Schnorr.sign(secretKey: owner.secret, message: digest),
738+
signSchnorrHex(secretKey: owner.secret, messageHex: digest),
738739
];
739740
}
740741

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

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,78 @@ nostr.Event signNostrEvent({
5454
);
5555
return unsigned.copyWith(sig: _encodeHex(signature));
5656
}
57+
58+
final _hex128 = RegExp(r'^[0-9a-fA-F]{128}$');
59+
60+
/// Verifies a BIP-340 Schnorr [signature] (128 hex) over the 32-byte
61+
/// [messageHex] digest for the x-only [publicKey] with libsecp256k1.
62+
///
63+
/// Returns false for malformed hex as well as for invalid signatures.
64+
bool verifySchnorrHex({
65+
required String publicKey,
66+
required String messageHex,
67+
required String signature,
68+
}) {
69+
if (!_hex64.hasMatch(publicKey) ||
70+
!_hex64.hasMatch(messageHex) ||
71+
!_hex128.hasMatch(signature)) {
72+
return false;
73+
}
74+
return secp256k1.schnorrVerify(
75+
signature: _decodeHex(signature),
76+
message: _decodeHex(messageHex),
77+
publicKey: _decodeHex(publicKey),
78+
);
79+
}
80+
81+
/// Signs a 32-byte [messageHex] digest with [secretKey] and returns the
82+
/// 128-hex BIP-340 signature, computed by libsecp256k1.
83+
String signSchnorrHex({required String secretKey, required String messageHex}) {
84+
if (!_hex64.hasMatch(messageHex)) {
85+
throw ArgumentError('Message must be 64 hex characters');
86+
}
87+
return _encodeHex(
88+
secp256k1.schnorrSign(
89+
message: _decodeHex(messageHex),
90+
secretKey: _decodeSecretKey(secretKey),
91+
),
92+
);
93+
}
94+
95+
/// Parses [payload] like `nostr.Event.fromJson` and verifies its timestamp,
96+
/// id and signature like `verify: true` does, with the signature check in
97+
/// libsecp256k1.
98+
///
99+
/// Throws the same `nostr` exception types as the pure-Dart path.
100+
nostr.Event verifiedNostrEventFromJson(String payload) {
101+
final event = nostr.Event.fromJson(payload, verify: false);
102+
if (event.createdAt <= 0 || event.createdAt >= 253402300800) {
103+
throw nostr.EventValidationException(
104+
'created_at ${event.createdAt} is not a valid Unix timestamp (seconds)',
105+
nostr.EventValidationReason.invalidTimestamp,
106+
);
107+
}
108+
if (event.id != event.getEventId()) {
109+
throw const nostr.EventValidationException(
110+
'event id mismatch',
111+
nostr.EventValidationReason.idMismatch,
112+
);
113+
}
114+
if (!_hex64.hasMatch(event.pubkey) || !_hex128.hasMatch(event.sig)) {
115+
throw const nostr.EventValidationException(
116+
'malformed pubkey or signature',
117+
nostr.EventValidationReason.malformedSignature,
118+
);
119+
}
120+
if (!verifySchnorrHex(
121+
publicKey: event.pubkey,
122+
messageHex: event.id,
123+
signature: event.sig,
124+
)) {
125+
throw const nostr.EventValidationException(
126+
'Schnorr signature invalid',
127+
nostr.EventValidationReason.invalidSignature,
128+
);
129+
}
130+
return event;
131+
}

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

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

4-
import 'package:nostr/nostr.dart' as nostr;
4+
import 'package:buzz/shared/crypto/event_signing.dart';
55
import 'package:pointycastle/digests/sha256.dart';
66
import '../relay/nostr_models.dart';
77

@@ -13,7 +13,7 @@ String? verifiedProfileOaOwnerPubkey(NostrEvent event) {
1313
.toList();
1414
if (tags.length != 1 || tags.single.length != 4) return null;
1515
try {
16-
nostr.Event.fromJson(jsonEncode(event.toJson()));
16+
verifiedNostrEventFromJson(jsonEncode(event.toJson()));
1717
} catch (_) {
1818
return null;
1919
}
@@ -76,9 +76,9 @@ String? verifiedOaOwnerPubkey(List<List<String>> tags, String agentPubkey) {
7676
.join();
7777

7878
try {
79-
if (nostr.Schnorr.verify(
79+
if (verifySchnorrHex(
8080
publicKey: owner,
81-
message: message,
81+
messageHex: message,
8282
signature: sig,
8383
)) {
8484
return owner;

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

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

4-
import 'package:nostr/nostr.dart' as nostr;
4+
import 'package:buzz/shared/crypto/event_signing.dart';
55

66
import '../relay/relay.dart';
77
import 'me_sync.dart';
@@ -64,7 +64,7 @@ Map<String, String> _inventoryNames(List<NostrEvent> events, String owner) {
6464
if (id == null || !RegExp(r'^[0-9a-f]{64}$').hasMatch(id)) continue;
6565
// Verify before allowing a newer tombstone or record to replace a head.
6666
try {
67-
nostr.Event.fromJson(jsonEncode(event.toJson()));
67+
verifiedNostrEventFromJson(jsonEncode(event.toJson()));
6868
} catch (_) {
6969
// A corrupt record must not hide unrelated verified agents.
7070
continue;

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ import 'dart:async';
22
import 'dart:convert';
33
import 'dart:isolate';
44

5+
import 'package:buzz/shared/crypto/event_signing.dart';
56
import 'package:hooks_riverpod/hooks_riverpod.dart';
67
import 'package:http/http.dart' as http;
7-
import 'package:nostr/nostr.dart' as nostr;
88

99
import '../relay/relay.dart';
1010
import 'me_sync.dart';
@@ -83,7 +83,7 @@ Set<String> _archived(List<NostrEvent> events, String authority) {
8383
}
8484
final encoded = jsonEncode(event.toJson());
8585
if (utf8.encode(encoded).length > 2 * 1024 * 1024) return {};
86-
nostr.Event.fromJson(encoded);
86+
verifiedNostrEventFromJson(encoded);
8787
return {
8888
for (final tag in event.tags)
8989
if (tag.length >= 2 &&

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

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

4-
import 'package:nostr/nostr.dart' as nostr;
4+
import 'package:buzz/shared/crypto/event_signing.dart';
55
import 'package:hooks_riverpod/hooks_riverpod.dart';
66

77
import '../crypto/nip_oa.dart';
@@ -105,7 +105,7 @@ List<AgentDirectoryEntry> _verifiedProfiles(
105105
final latest = <String, NostrEvent>{};
106106
for (final event in events) {
107107
try {
108-
nostr.Event.fromJson(jsonEncode(event.toJson()));
108+
verifiedNostrEventFromJson(jsonEncode(event.toJson()));
109109
} catch (_) {
110110
continue;
111111
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ class MeSync {
348348
)) {
349349
throw const FormatException('Invalid Solo record');
350350
}
351-
nostr.Event.fromJson(jsonEncode(event.toJson()));
351+
verifiedNostrEventFromJson(jsonEncode(event.toJson()));
352352
return MeGroups.decode(nip44Decrypt(key, event.content), community);
353353
}
354354

‎mobile/test/shared/crypto/event_signing_test.dart‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import 'dart:convert';
12
import 'dart:math';
23

34
import 'package:buzz/shared/crypto/event_signing.dart';
@@ -80,4 +81,93 @@ void main() {
8081
);
8182
}
8283
});
84+
85+
group('verifiedNostrEventFromJson', () {
86+
final secretKey = _randomSecretKey(Random(2));
87+
final event = nostr.Event.from(
88+
kind: 1,
89+
content: 'hello',
90+
secretKey: secretKey,
91+
createdAt: 1700000000,
92+
tags: [
93+
['t', 'x'],
94+
],
95+
);
96+
Map<String, dynamic> map() => Map<String, dynamic>.from(event.toMap());
97+
98+
test('accepts what the pure-Dart verifier accepts', () {
99+
final verified = verifiedNostrEventFromJson(jsonEncode(map()));
100+
expect(verified.id, event.id);
101+
expect(verified.sig, event.sig);
102+
});
103+
104+
test('rejects what the pure-Dart verifier rejects', () {
105+
final otherSig = signNostrEvent(
106+
kind: 1,
107+
content: 'other',
108+
secretKey: secretKey,
109+
).sig;
110+
final cases = <String, Map<String, dynamic>>{
111+
'tampered content': map()..['content'] = 'hellO',
112+
'wrong signature': map()..['sig'] = otherSig,
113+
'other pubkey': map()..['pubkey'] = 'a' * 64,
114+
'malformed sig': map()..['sig'] = 'zz' * 64,
115+
'short sig': map()..['sig'] = event.sig.substring(2),
116+
'zero timestamp': map()..['created_at'] = 0,
117+
};
118+
for (final MapEntry(key: reason, value: payload) in cases.entries) {
119+
final json = jsonEncode(payload);
120+
expect(
121+
() => nostr.Event.fromJson(json),
122+
throwsA(isA<nostr.NostrException>()),
123+
reason: '$reason (pure Dart)',
124+
);
125+
expect(
126+
() => verifiedNostrEventFromJson(json),
127+
throwsA(isA<nostr.NostrException>()),
128+
reason: reason,
129+
);
130+
}
131+
});
132+
});
133+
134+
test('Schnorr hex helpers interoperate with nostr.Schnorr', () {
135+
final secretKey = _randomSecretKey(Random(3));
136+
final publicKey = derivePublicKeyHex(secretKey);
137+
final digest = 'ab' * 32;
138+
final signature = signSchnorrHex(secretKey: secretKey, messageHex: digest);
139+
expect(
140+
nostr.Schnorr.verify(
141+
publicKey: publicKey,
142+
message: digest,
143+
signature: signature,
144+
),
145+
isTrue,
146+
);
147+
final reference = nostr.Schnorr.sign(secretKey: secretKey, message: digest);
148+
expect(
149+
verifySchnorrHex(
150+
publicKey: publicKey,
151+
messageHex: digest,
152+
signature: reference,
153+
),
154+
isTrue,
155+
);
156+
expect(
157+
verifySchnorrHex(
158+
publicKey: publicKey,
159+
messageHex: 'cd' * 32,
160+
signature: reference,
161+
),
162+
isFalse,
163+
);
164+
expect(
165+
verifySchnorrHex(
166+
publicKey: 'zz',
167+
messageHex: digest,
168+
signature: reference,
169+
),
170+
isFalse,
171+
);
172+
});
83173
}

0 commit comments

Comments
 (0)