Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add converts for pub key #7

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions lib/src/utils.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'dart:math';
import 'dart:typed_data';

import 'package:convert/convert.dart';
import 'package:dart_bech32/dart_bech32.dart';

/// generates 32 random bytes converted in hex
String generate64RandomHexChars() {
Expand All @@ -13,3 +15,34 @@ String generate64RandomHexChars() {
int currentUnixTimestampSeconds() {
return DateTime.now().millisecondsSinceEpoch ~/ 1000;
}

/// takes an npub key and converts it to hex key
String? npubKeyToHex(String npub) {
try {
final decoded = bech32.decode(npub);
if (decoded.prefix == 'npub') {
final bytes = bech32.fromWords(decoded.words).sublist(0, 32);
final pubkey = hex.encode(bytes);
return pubkey;
}
return null;
} catch (e) {
return null;
}
}

/// takes an hex key and converts it to npub key
String? hexKeyToNub(String hexkey) {
try {
final derivedNPub = bech32.encode(
Decoded(
prefix: 'npub',
words: bech32.toWords(Uint8List.fromList(hex.decode(hexkey))),
),
);

return derivedNPub;
} catch (e) {
return null;
}
}
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ dependencies:
bip340: ^0.0.4
convert: ^3.1.1
crypto: ^3.0.2
dart_bech32: ^2.0.0
40 changes: 40 additions & 0 deletions test/utils_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import 'package:nostr/nostr.dart';
import 'package:test/test.dart';

void main() {
const npubValid =
'npub1eqmj85el4pkg7qdj2jcae24qykev5evnyz2s6pzdytzpkhga4u5sdmhexk';
const hexValid =
'c83723d33fa86c8f01b254b1dcaaa025b2ca659320950d044d22c41b5d1daf29';

const npubInvalid =
'nrub1eqmj85el4pkg7qdj2jcae24qykev5evnyz2s6pzdytzpkhga4u5sdmhexk';
const hexInvalid =
'_pub1eqmj85el4pkg7qdj2jcae24qykevdcaaa025b2ca6d22c41b5d1daf29';

group('Convert', () {
test('Npub to hex valid', () {
final hex = npubKeyToHex(npubValid);

expect(hex, hexValid);
});

test('Hex to npub valid', () {
final npub = hexKeyToNub(hexValid);

expect(npub, npub);
});

test('Npub to hex invalid', () {
final hex = npubKeyToHex(npubInvalid);

expect(hex, null);
});

test('Hex to npub invalid', () {
final npub = hexKeyToNub(hexInvalid);

expect(npub, null);
});
});
}