UNPKG

snstr

Version:

Secure Nostr Software Toolkit for Renegades - A comprehensive TypeScript library for Nostr protocol implementation

66 lines (65 loc) 2.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.signEvent = signEvent; exports.verifySignature = verifySignature; exports.generateKeypair = generateKeypair; exports.getPublicKey = getPublicKey; exports.sha256Hex = sha256Hex; const secp256k1_1 = require("@noble/curves/secp256k1"); const utils_1 = require("@noble/hashes/utils"); const sha2_1 = require("@noble/hashes/sha2"); /** * Sign an event with the given private key */ async function signEvent(eventId, privateKey) { const privateKeyBytes = (0, utils_1.hexToBytes)(privateKey); const eventIdBytes = (0, utils_1.hexToBytes)(eventId); const signatureBytes = await secp256k1_1.schnorr.sign(eventIdBytes, privateKeyBytes); return (0, utils_1.bytesToHex)(signatureBytes); } /** * Verify the signature of an event */ async function verifySignature(eventId, signature, publicKey) { try { const eventIdBytes = (0, utils_1.hexToBytes)(eventId); const signatureBytes = (0, utils_1.hexToBytes)(signature); const publicKeyBytes = (0, utils_1.hexToBytes)(publicKey); return await secp256k1_1.schnorr.verify(signatureBytes, eventIdBytes, publicKeyBytes); } catch (error) { console.error("Failed to verify signature:", error); return false; } } /** * Generate a keypair for Nostr */ async function generateKeypair() { // Use the library's built-in private key generation // This ensures the private key is in the valid range (1 <= privateKey < curve order) const privateKey = (0, utils_1.bytesToHex)(secp256k1_1.schnorr.utils.randomPrivateKey()); const publicKey = getPublicKey(privateKey); return { privateKey, publicKey }; } /** * Get the public key from a private key */ function getPublicKey(privateKey) { const privateKeyBytes = (0, utils_1.hexToBytes)(privateKey); const publicKeyBytes = secp256k1_1.schnorr.getPublicKey(privateKeyBytes); return (0, utils_1.bytesToHex)(publicKeyBytes); } // NIP-04 functions have been moved to the dedicated module at src/nip04/index.ts // For NIP-04 encryption/decryption, please import from '../nip04' instead /** * Compute SHA-256 hash of data * @param data The data to hash (string or Uint8Array) * @returns The hash as a Uint8Array */ function sha256Hex(data) { if (typeof data === "string") { data = new TextEncoder().encode(data); } return (0, utils_1.bytesToHex)((0, sha2_1.sha256)(data)); }