nostr tools added
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import 'dart:convert';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:nostr_tools/nostr_tools.dart';
|
||||
|
||||
/// Represents a Nostr event.
|
||||
class NostrEvent {
|
||||
@@ -24,6 +23,10 @@ class NostrEvent {
|
||||
/// Event signature (64-byte hex string).
|
||||
final String sig;
|
||||
|
||||
/// Event API instance for event operations.
|
||||
static final _eventApi = EventApi();
|
||||
static final _keyApi = KeyApi();
|
||||
|
||||
/// Creates a [NostrEvent] with the provided values.
|
||||
NostrEvent({
|
||||
required this.id,
|
||||
@@ -50,6 +53,33 @@ class NostrEvent {
|
||||
);
|
||||
}
|
||||
|
||||
/// Creates a [NostrEvent] from a nostr_tools Event object.
|
||||
factory NostrEvent.fromNostrToolsEvent(Event event) {
|
||||
return NostrEvent(
|
||||
id: event.id,
|
||||
pubkey: event.pubkey,
|
||||
createdAt: event.created_at,
|
||||
kind: event.kind,
|
||||
tags: event.tags,
|
||||
content: event.content,
|
||||
sig: event.sig,
|
||||
);
|
||||
}
|
||||
|
||||
/// Converts this [NostrEvent] to a nostr_tools Event object.
|
||||
Event toNostrToolsEvent() {
|
||||
return Event(
|
||||
id: id,
|
||||
pubkey: pubkey,
|
||||
created_at: createdAt,
|
||||
kind: kind,
|
||||
tags: tags,
|
||||
content: content,
|
||||
sig: sig,
|
||||
verify: false, // Already verified if coming from our model
|
||||
);
|
||||
}
|
||||
|
||||
/// Converts the [NostrEvent] to a JSON array (Nostr event format).
|
||||
List<dynamic> toJson() {
|
||||
return [
|
||||
@@ -63,7 +93,7 @@ class NostrEvent {
|
||||
];
|
||||
}
|
||||
|
||||
/// Creates an event from content and signs it with a private key.
|
||||
/// Creates an event from content and signs it with a private key using nostr_tools.
|
||||
///
|
||||
/// [content] - Event content.
|
||||
/// [kind] - Event kind (default: 1 for text note).
|
||||
@@ -75,51 +105,42 @@ class NostrEvent {
|
||||
required String privateKey,
|
||||
List<List<String>>? tags,
|
||||
}) {
|
||||
// Derive public key from private key (simplified)
|
||||
final privateKeyBytes = _hexToBytes(privateKey);
|
||||
final publicKeyBytes = sha256.convert(privateKeyBytes).bytes.sublist(0, 32);
|
||||
final pubkey = publicKeyBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
// Get public key from private key using nostr_tools
|
||||
final pubkey = _keyApi.getPublicKey(privateKey);
|
||||
|
||||
final createdAt = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
final eventTags = tags ?? [];
|
||||
|
||||
// Create event data for signing
|
||||
final eventData = [
|
||||
0,
|
||||
pubkey,
|
||||
createdAt,
|
||||
kind,
|
||||
eventTags,
|
||||
content,
|
||||
];
|
||||
|
||||
// Generate event ID (hash of event data)
|
||||
final eventJson = jsonEncode(eventData);
|
||||
final idBytes = sha256.convert(utf8.encode(eventJson)).bytes.sublist(0, 32);
|
||||
final id = idBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
// Generate signature (simplified - in real Nostr, use secp256k1)
|
||||
final sigBytes = sha256.convert(utf8.encode(id + privateKey)).bytes.sublist(0, 32);
|
||||
final sig = sigBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
return NostrEvent(
|
||||
id: id,
|
||||
pubkey: pubkey,
|
||||
createdAt: createdAt,
|
||||
// Create event using nostr_tools Event model
|
||||
final event = Event(
|
||||
kind: kind,
|
||||
tags: eventTags,
|
||||
content: content,
|
||||
sig: sig,
|
||||
created_at: createdAt,
|
||||
pubkey: pubkey,
|
||||
verify: false, // We'll sign it next
|
||||
);
|
||||
|
||||
// Get event hash (ID) using nostr_tools
|
||||
event.id = _eventApi.getEventHash(event);
|
||||
|
||||
// Sign the event using nostr_tools
|
||||
event.sig = _eventApi.signEvent(event, privateKey);
|
||||
|
||||
// Convert to our NostrEvent model
|
||||
return NostrEvent.fromNostrToolsEvent(event);
|
||||
}
|
||||
|
||||
/// Converts hex string to bytes.
|
||||
static List<int> _hexToBytes(String hex) {
|
||||
final result = <int>[];
|
||||
for (int i = 0; i < hex.length; i += 2) {
|
||||
result.add(int.parse(hex.substring(i, i + 2), radix: 16));
|
||||
/// Verifies the event signature using nostr_tools.
|
||||
///
|
||||
/// Returns true if the signature is valid, false otherwise.
|
||||
bool verifySignature() {
|
||||
try {
|
||||
final event = toNostrToolsEvent();
|
||||
return _eventApi.verifySignature(event);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -127,4 +148,3 @@ class NostrEvent {
|
||||
return 'NostrEvent(id: ${id.substring(0, 8)}..., kind: $kind, content: ${content.substring(0, content.length > 20 ? 20 : content.length)}...)';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import 'dart:convert';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:nostr_tools/nostr_tools.dart';
|
||||
|
||||
/// Represents a Nostr keypair (private and public keys).
|
||||
class NostrKeyPair {
|
||||
@@ -9,6 +8,12 @@ class NostrKeyPair {
|
||||
/// Public key in hex format (32 bytes, 64 hex characters).
|
||||
final String publicKey;
|
||||
|
||||
/// Key API instance for key operations.
|
||||
static final _keyApi = KeyApi();
|
||||
|
||||
/// NIP-19 API instance for bech32 encoding/decoding.
|
||||
static final _nip19 = Nip19();
|
||||
|
||||
/// Creates a [NostrKeyPair] with the provided keys.
|
||||
///
|
||||
/// [privateKey] - Private key in hex format.
|
||||
@@ -18,25 +23,91 @@ class NostrKeyPair {
|
||||
required this.publicKey,
|
||||
});
|
||||
|
||||
/// Generates a new Nostr keypair.
|
||||
/// Generates a new Nostr keypair using nostr_tools.
|
||||
///
|
||||
/// Returns a new [NostrKeyPair] with random private and public keys.
|
||||
factory NostrKeyPair.generate() {
|
||||
// Generate random 32-byte private key
|
||||
final random = List<int>.generate(32, (i) => DateTime.now().microsecondsSinceEpoch % 256);
|
||||
final privateKeyBytes = sha256.convert(utf8.encode(DateTime.now().toString() + random.toString())).bytes.sublist(0, 32);
|
||||
final privateKey = privateKeyBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
// Derive public key from private key (simplified - in real Nostr, use secp256k1)
|
||||
final publicKeyBytes = sha256.convert(privateKeyBytes).bytes.sublist(0, 32);
|
||||
final publicKey = publicKeyBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
final privateKey = _keyApi.generatePrivateKey();
|
||||
final publicKey = _keyApi.getPublicKey(privateKey);
|
||||
|
||||
return NostrKeyPair(
|
||||
privateKey: privateKey,
|
||||
publicKey: publicKey,
|
||||
);
|
||||
}
|
||||
|
||||
/// Creates a [NostrKeyPair] from nsec (private key in bech32 format).
|
||||
///
|
||||
/// [nsec] - Private key in nsec format (e.g., 'nsec1...').
|
||||
///
|
||||
/// Returns a [NostrKeyPair] with the decoded private key and derived public key.
|
||||
///
|
||||
/// Throws [FormatException] if nsec is invalid.
|
||||
factory NostrKeyPair.fromNsec(String nsec) {
|
||||
try {
|
||||
final decoded = _nip19.decode(nsec);
|
||||
if (decoded['type'] != 'nsec') {
|
||||
throw FormatException('Invalid nsec format: expected "nsec" type');
|
||||
}
|
||||
|
||||
final privateKey = decoded['data'] as String;
|
||||
final publicKey = _keyApi.getPublicKey(privateKey);
|
||||
|
||||
return NostrKeyPair(
|
||||
privateKey: privateKey,
|
||||
publicKey: publicKey,
|
||||
);
|
||||
} catch (e) {
|
||||
throw FormatException('Failed to parse nsec: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [NostrKeyPair] from npub (public key in bech32 format).
|
||||
///
|
||||
/// Note: This creates a keypair with only the public key. Private key operations won't work.
|
||||
///
|
||||
/// [npub] - Public key in npub format (e.g., 'npub1...').
|
||||
///
|
||||
/// Returns a [NostrKeyPair] with the decoded public key and empty private key.
|
||||
///
|
||||
/// Throws [FormatException] if npub is invalid.
|
||||
factory NostrKeyPair.fromNpub(String npub) {
|
||||
try {
|
||||
final decoded = _nip19.decode(npub);
|
||||
if (decoded['type'] != 'npub') {
|
||||
throw FormatException('Invalid npub format: expected "npub" type');
|
||||
}
|
||||
|
||||
final publicKey = decoded['data'] as String;
|
||||
|
||||
// No private key available when importing from npub
|
||||
return NostrKeyPair(
|
||||
privateKey: '', // Empty private key - can't sign events
|
||||
publicKey: publicKey,
|
||||
);
|
||||
} catch (e) {
|
||||
throw FormatException('Failed to parse npub: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [NostrKeyPair] from a hex private key.
|
||||
///
|
||||
/// [hexPrivateKey] - Private key in hex format (64 hex characters).
|
||||
///
|
||||
/// Returns a [NostrKeyPair] with the provided private key and derived public key.
|
||||
factory NostrKeyPair.fromHexPrivateKey(String hexPrivateKey) {
|
||||
if (hexPrivateKey.length != 64) {
|
||||
throw FormatException('Invalid hex private key: expected 64 hex characters');
|
||||
}
|
||||
|
||||
final publicKey = _keyApi.getPublicKey(hexPrivateKey);
|
||||
|
||||
return NostrKeyPair(
|
||||
privateKey: hexPrivateKey,
|
||||
publicKey: publicKey,
|
||||
);
|
||||
}
|
||||
|
||||
/// Creates a [NostrKeyPair] from a JSON map.
|
||||
factory NostrKeyPair.fromJson(Map<String, dynamic> json) {
|
||||
return NostrKeyPair(
|
||||
@@ -53,9 +124,21 @@ class NostrKeyPair {
|
||||
};
|
||||
}
|
||||
|
||||
/// Encodes the private key to nsec format.
|
||||
String toNsec() {
|
||||
if (privateKey.isEmpty) {
|
||||
throw StateError('Cannot encode empty private key to nsec');
|
||||
}
|
||||
return _nip19.nsecEncode(privateKey);
|
||||
}
|
||||
|
||||
/// Encodes the public key to npub format.
|
||||
String toNpub() {
|
||||
return _nip19.npubEncode(publicKey);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'NostrKeyPair(publicKey: ${publicKey.substring(0, 8)}...)';
|
||||
return 'NostrKeyPair(publicKey: $publicKey)';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import 'dart:convert';
|
||||
|
||||
/// Represents a Nostr user profile (metadata from kind 0 events).
|
||||
class NostrProfile {
|
||||
/// Public key (npub or hex).
|
||||
final String publicKey;
|
||||
|
||||
/// Display name or username.
|
||||
final String? name;
|
||||
|
||||
/// About/bio text.
|
||||
final String? about;
|
||||
|
||||
/// Profile picture URL.
|
||||
final String? picture;
|
||||
|
||||
/// Website URL.
|
||||
final String? website;
|
||||
|
||||
/// NIP-05 identifier (e.g., [email protected]).
|
||||
final String? nip05;
|
||||
|
||||
/// Banner image URL.
|
||||
final String? banner;
|
||||
|
||||
/// LUD16 (Lightning address).
|
||||
final String? lud16;
|
||||
|
||||
/// Raw metadata JSON for additional fields.
|
||||
final Map<String, dynamic> rawMetadata;
|
||||
|
||||
/// Timestamp when profile was last updated.
|
||||
final DateTime? updatedAt;
|
||||
|
||||
/// Creates a [NostrProfile] instance.
|
||||
NostrProfile({
|
||||
required this.publicKey,
|
||||
this.name,
|
||||
this.about,
|
||||
this.picture,
|
||||
this.website,
|
||||
this.nip05,
|
||||
this.banner,
|
||||
this.lud16,
|
||||
Map<String, dynamic>? rawMetadata,
|
||||
this.updatedAt,
|
||||
}) : rawMetadata = rawMetadata ?? {};
|
||||
|
||||
/// Creates a [NostrProfile] from Nostr metadata event content (JSON string).
|
||||
///
|
||||
/// [publicKey] - The public key of the profile owner.
|
||||
/// [content] - JSON string from kind 0 event content.
|
||||
/// [updatedAt] - Optional timestamp when profile was updated.
|
||||
factory NostrProfile.fromEventContent({
|
||||
required String publicKey,
|
||||
required String content,
|
||||
DateTime? updatedAt,
|
||||
}) {
|
||||
try {
|
||||
final metadata = jsonDecode(content) as Map<String, dynamic>;
|
||||
|
||||
return NostrProfile(
|
||||
publicKey: publicKey,
|
||||
name: metadata['name'] as String?,
|
||||
about: metadata['about'] as String?,
|
||||
picture: metadata['picture'] as String?,
|
||||
website: metadata['website'] as String?,
|
||||
nip05: metadata['nip05'] as String?,
|
||||
banner: metadata['banner'] as String?,
|
||||
lud16: metadata['lud16'] as String?,
|
||||
rawMetadata: metadata,
|
||||
updatedAt: updatedAt ?? DateTime.now(),
|
||||
);
|
||||
} catch (e) {
|
||||
// Return minimal profile if parsing fails
|
||||
return NostrProfile(
|
||||
publicKey: publicKey,
|
||||
rawMetadata: {},
|
||||
updatedAt: updatedAt ?? DateTime.now(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [NostrProfile] from a JSON map.
|
||||
factory NostrProfile.fromJson(Map<String, dynamic> json) {
|
||||
return NostrProfile(
|
||||
publicKey: json['publicKey'] as String,
|
||||
name: json['name'] as String?,
|
||||
about: json['about'] as String?,
|
||||
picture: json['picture'] as String?,
|
||||
website: json['website'] as String?,
|
||||
nip05: json['nip05'] as String?,
|
||||
banner: json['banner'] as String?,
|
||||
lud16: json['lud16'] as String?,
|
||||
rawMetadata: json['rawMetadata'] as Map<String, dynamic>? ?? {},
|
||||
updatedAt: json['updatedAt'] != null
|
||||
? DateTime.parse(json['updatedAt'] as String)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
/// Converts [NostrProfile] to JSON.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'publicKey': publicKey,
|
||||
'name': name,
|
||||
'about': about,
|
||||
'picture': picture,
|
||||
'website': website,
|
||||
'nip05': nip05,
|
||||
'banner': banner,
|
||||
'lud16': lud16,
|
||||
'rawMetadata': rawMetadata,
|
||||
'updatedAt': updatedAt?.toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
/// Gets display name (name, nip05, or public key prefix).
|
||||
String get displayName {
|
||||
if (name != null && name!.isNotEmpty) return name!;
|
||||
if (nip05 != null && nip05!.isNotEmpty) return nip05!;
|
||||
return publicKey.length > 16
|
||||
? '${publicKey.substring(0, 8)}...${publicKey.substring(publicKey.length - 8)}'
|
||||
: publicKey;
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'NostrProfile(publicKey: ${publicKey.substring(0, 8)}..., name: $name)';
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user