Files
buzz/mobile/test/shared/hosted/account_identity_store_test.dart
Tom Brow 9c5032b63b perf(mobile): derive keys natively and hash NIP-98 bodies faster (#8965)
## Summary

Two pure-Dart crypto paths that run on the UI isolate during normal use:

- **NIP-98 body hashes.** Every relay HTTP query
(`RelaySessionNotifier._postForEvents`) hashes its request body for the
NIP-98 auth header with pointycastle's `SHA256Digest`. This switches
that hash, the media upload hash and the NIP-OA preimage hash to
`package:crypto`'s `sha256`, which is already a dependency. The output
is identical.
- **Public key derivation.** `AccountIdentityStore.publicKeyForNsec`
runs on every relay auth assertion and derived the key with the `nostr`
package's pure-Dart curve math. It now uses the native
`derivePublicKeyHex` (libsecp256k1) with the same validation. The
default-agent writer now signs with the native `signNostrEvent` instead
of `nostr.Event.from`.

Left as they were: `nostr.Keys` construction for signing keys (nostr
2.0.0 always derives in Dart, with no way to pass a known public key),
and `nostr.Keys.generate()` on the rare key-creation paths.

## Measurements

- **Device** (iPhone 12 mini, Profile build, #4things captures): NIP-98
hashing took 17 to 24 ms of UI CPU per 10 to 20 s capture, mostly from
channel notices queries. `publicKeyForNsec` took about 7 ms per relay
auth assertion.
- **Synthetic** (Mac, AOT, same output): SHA-256 of a 1 KB body takes
39.9 µs with pointycastle and 6.6 µs with `package:crypto`. 50 KB: 1,518
µs vs 293 µs. 1 MB: 29.6 ms vs 6.1 ms.

- **Device A/B after the change** (iPhone 12 mini, Profile/AOT, Tom's
Block community, two app resumes per build from the home screen, 15 s
windows; A is `origin/main` 3d26ed7, B is A plus this PR and
[#8966](https://github.com/block/buzz/pull/8966)): NIP-98 signing per
resume went from 42 / 50 ms to 9 / 13 ms of UI CPU, and all SHA-256 work
per resume from 74 / 73 ms to 33 / 33 ms. Dart public-key derivation
through `nostr.Keys` (left as is, see above) still takes 15 to 23 ms per
resume.
- **Same A/B on current `main`** (14037e3): pointycastle SHA-256 per
resume went from 39 / 45 ms to 7 / 0 ms, and NIP-98 header building from
4 / 5 ms to 2 / 0 ms. `nostr.Keys` derivation: 12 to 17 ms per resume on
both builds.

## Testing

- New known-vector tests for the NIP-98 header hash: an empty body,
`abc`, and the one-million-`a` FIPS vector. They also check the event's
kind, method, signature and pubkey.
- New `publicKeyForNsec` tests: the generator-point vector, matching the
pure-Dart derivation, and rejecting invalid keys (scalar 0 and n,
garbage, an npub).
- These are correctness tests only. A timing test would be flaky, so
none would fail if the old pure-Dart code came back.
- `just mobile-check mobile-test` passes (pre-push hook).
- Automated device run in place of manual testing: the B build above on
the 12 mini, launched and resumed twice into a signed-in Block
community, loading the channel list, channel notices and read state over
authenticated relay queries (NIP-98 headers and relay auth assertions on
every request). Not exercised on the device: media upload and the
default-agent writer.

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

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 16:23:47 -08:00

319 lines
10 KiB
Dart

import 'dart:async';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:buzz/shared/hosted/account_identity_store.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final key = nostr.Keys(
'0000000000000000000000000000000000000000000000000000000000000001',
);
setUp(() => FlutterSecureStorage.setMockInitialValues({}));
group('publicKeyForNsec', () {
test('matches known vectors and the pure-Dart derivation', () {
const one =
'0000000000000000000000000000000000000000000000000000000000000001';
// secp256k1 generator point x coordinate for secret key 1.
expect(
AccountIdentityStore.publicKeyForNsec(
nostr.Bech32Entity.encode(prefix: nostr.Nip19Prefix.nsec, data: one),
),
'79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
);
for (final hex in [
'b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfef',
'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140',
]) {
final keys = nostr.Keys(hex);
expect(AccountIdentityStore.publicKeyForNsec(keys.nsec), keys.public);
}
});
test('rejects invalid keys with invalidKey', () {
final invalid = [
'not an nsec',
'',
nostr.Keys(
'0000000000000000000000000000000000000000000000000000000000000001',
).npub,
// Scalar zero and the curve order are not valid secret keys.
nostr.Bech32Entity.encode(
prefix: nostr.Nip19Prefix.nsec,
data:
'0000000000000000000000000000000000000000000000000000000000000000',
),
nostr.Bech32Entity.encode(
prefix: nostr.Nip19Prefix.nsec,
data:
'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141',
),
];
for (final value in invalid) {
expect(
() => AccountIdentityStore.publicKeyForNsec(value),
throwsA(AccountIdentityFailure.invalidKey),
reason: value,
);
}
});
});
for (final simulated in [false, true]) {
test(
'recovery retains scoped receipt; simulated=$simulated cannot authorize',
() async {
final receipt = BackupReceipt(
backend: 'https://app.builderlab.xyz',
subject: 'account-a',
pubkey: key.public,
backupId: simulated ? 'debug-simulated-backup:old' : 'backup-1',
);
final store = AccountIdentityStore();
expect(await store.read(), isNull);
await store.create(key.nsec, recoveredBackup: receipt);
final restored = (await AccountIdentityStore().read())!;
expect(
restored.hasBackupFor(
backend: receipt.backend,
subject: receipt.subject,
),
!simulated,
);
expect(
restored.hasBackupFor(backend: receipt.backend, subject: 'account-b'),
isFalse,
);
expect(await store.withKeys((keys) async => keys.public), key.public);
expect((await store.create(key.nsec)).pubkey, key.public);
// Existing receipt migrates only to its owner; another account has
// an independent create-only slot and cannot replace the first key.
final owner = store.forSubject('account-a');
final otherAccount = store.forSubject('account-b');
expect((await owner.read())!.pubkey, key.public);
expect(await otherAccount.read(), isNull);
final otherKey = nostr.Keys('2'.padLeft(64, '0'));
await otherAccount.create(otherKey.nsec);
expect((await owner.read())!.pubkey, key.public);
expect((await store.read())!.pubkey, key.public);
expect((await otherAccount.read())!.pubkey, otherKey.public);
await store.forPairing(key.public).create(key.nsec);
await store.forPairing(otherKey.public).create(otherKey.nsec);
expect((await store.identities()).map((item) => item.pubkey).toSet(), {
key.public,
otherKey.public,
});
},
);
}
test(
'unrelated enumeration failure preserves known-slot access and errors',
() async {
final storage = EnumerationFailureStorage();
final legacy = AccountIdentityStore(storage: storage);
await legacy.create(key.nsec);
final scoped = legacy.forSubject('b');
final other = nostr.Keys('2'.padLeft(64, '0'));
await scoped.create(other.nsec);
await expectLater(
scoped.identities(),
throwsA(AccountIdentityFailure.unreadable),
);
expect((await scoped.read())!.pubkey, other.public);
expect(
await scoped.withSavedIdentity(key.public, (value) async => value),
key.nsec,
);
await storage.write(
key: AccountIdentityStore.storageKey,
value: 'broken',
);
await expectLater(
scoped.identities(),
throwsA(AccountIdentityFailure.unreadable),
);
},
);
test(
'unreadable storage never allows creation or touches legacy keys',
() async {
FlutterSecureStorage.setMockInitialValues({
AccountIdentityStore.storageKey: 'broken',
'buzz_communities': 'legacy',
});
final store = AccountIdentityStore();
await expectLater(
store.read(),
throwsA(AccountIdentityFailure.unreadable),
);
await expectLater(
store.create(key.nsec),
throwsA(AccountIdentityFailure.unreadable),
);
expect(
await const FlutterSecureStorage().read(key: 'buzz_communities'),
'legacy',
);
},
);
test('invalid candidate and wrong-key receipt never write', () async {
final store = AccountIdentityStore();
await expectLater(
store.create('not-a-key'),
throwsA(AccountIdentityFailure.invalidKey),
);
final other = nostr.Keys(
'0000000000000000000000000000000000000000000000000000000000000002',
);
await expectLater(
store.create(
key.nsec,
recoveredBackup: BackupReceipt(
backend: 'https://app.builderlab.xyz',
subject: 'a',
pubkey: other.public,
backupId: 'b',
),
),
throwsA(AccountIdentityFailure.mismatch),
);
expect(await store.read(), isNull);
await store.create(key.nsec);
await expectLater(
store.confirmBackup(
BackupReceipt(
backend: 'https://app.builderlab.xyz',
subject: 'a',
pubkey: other.public,
backupId: 'b',
),
),
throwsA(AccountIdentityFailure.mismatch),
);
expect((await store.read())!.backup, isNull);
});
for (final generate in [false, true]) {
test(
'uncertain ${generate ? "generated" : "recovered"} write retries exact identity once',
() async {
final storage = UncertainStorage();
final store = AccountIdentityStore(storage: storage);
var authorizations = 0;
final receipt = BackupReceipt(
backend: 'https://app.builderlab.xyz',
subject: 'a',
pubkey: key.public,
backupId: 'one',
);
Future<AccountIdentitySnapshot?> write() => generate
? store.generateIfAbsent(
authorize: () async {
authorizations++;
return true;
},
)
: store.create(key.nsec, recoveredBackup: receipt);
await expectLater(write(), throwsA(AccountIdentityFailure.unreadable));
final persisted = (await store.read())!;
final retried = (await write())!;
expect(retried.pubkey, persisted.pubkey);
expect(authorizations, generate ? 1 : 0);
if (!generate) {
expect(retried.backup?.backupId, 'one');
final other = nostr.Keys('2'.padLeft(64, '0'));
await expectLater(
store.create(other.nsec),
throwsA(AccountIdentityFailure.occupied),
);
await expectLater(
store.create(
key.nsec,
recoveredBackup: BackupReceipt(
backend: receipt.backend,
subject: 'b',
pubkey: key.public,
backupId: 'two',
),
),
throwsA(AccountIdentityFailure.mismatch),
);
}
expect(storage.writes, 1);
},
);
}
test(
'late durable write blocks second instance create until settled',
() async {
final storage = DelayedStorage();
final first = AccountIdentityStore(storage: storage).create(key.nsec);
await storage.started.future;
final second = AccountIdentityStore(storage: storage).create(key.nsec);
final retried = second;
storage.release.complete();
await first;
await retried;
expect(storage.writes, 1);
},
);
}
class DelayedStorage extends FlutterSecureStorage {
final started = Completer<void>();
final release = Completer<void>();
int writes = 0;
@override
Future<void> write({
required String key,
required String? value,
AppleOptions? iOptions,
AndroidOptions? aOptions,
LinuxOptions? lOptions,
WebOptions? webOptions,
AppleOptions? mOptions,
WindowsOptions? wOptions,
}) async {
writes++;
started.complete();
await release.future;
return super.write(key: key, value: value);
}
}
class UncertainStorage extends FlutterSecureStorage {
int writes = 0;
@override
Future<void> write({
required String key,
required String? value,
AppleOptions? iOptions,
AndroidOptions? aOptions,
LinuxOptions? lOptions,
WebOptions? webOptions,
AppleOptions? mOptions,
WindowsOptions? wOptions,
}) async {
writes++;
await super.write(key: key, value: value);
throw StateError('plugin response lost');
}
}
class EnumerationFailureStorage extends FlutterSecureStorage {
@override
Future<Map<String, String>> readAll({
AppleOptions? iOptions,
AndroidOptions? aOptions,
LinuxOptions? lOptions,
WebOptions? webOptions,
AppleOptions? mOptions,
WindowsOptions? wOptions,
}) async => throw StateError('unrelated entry cannot decrypt');
}