Skip to main content

NostrSecretKey

Struct NostrSecretKey 

Source
pub struct NostrSecretKey { /* private fields */ }
Expand description

A secp256k1 secret key used to sign Nostr events with BIP-340.

The key is zeroised when dropped. It does not implement Clone, Serialize or Display, and its Debug output shows only the public principal. This crate offers no way to export the secret again. Zeroising is best effort: temporary copies made on the stack while parsing are not all reachable, and memory dumps and swap are outside what it can promise.

§Examples

use stratum_node_core::NostrSecretKey;

let key = NostrSecretKey::from_hex(&"03".repeat(32))?;
let debug = format!("{key:?}");
assert!(!debug.contains(&"03".repeat(32)));
assert!(debug.contains(&key.public().to_string()));

It cannot be cloned or serialised:

ⓘ
fn needs_clone<T: Clone>() {}
needs_clone::<stratum_node_core::NostrSecretKey>();
ⓘ
fn needs_serialize<T: serde::Serialize>() {}
needs_serialize::<stratum_node_core::NostrSecretKey>();

Implementations§

Source§

impl NostrSecretKey

Source

pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, ParseKeyError>

Builds a key from its 32 big-endian bytes.

The caller remains responsible for zeroising its own copy.

§Errors

Returns ParseKeyError::OutOfRange when the value is zero or not below the secp256k1 group order.

Source

pub fn from_hex(hex: &str) -> Result<Self, ParseKeyError>

Parses a key from 64 lowercase hexadecimal digits.

§Errors

Returns ParseKeyError::InvalidHex for anything other than 64 lowercase hex digits, and ParseKeyError::OutOfRange as for from_bytes.

Source

pub fn from_nsec(nsec: &str) -> Result<Self, ParseKeyError>

Parses a NIP-19 nsec1… bech32 secret key.

§Errors

Returns ParseKeyError::InvalidBech32 for a malformed string, a bech32m checksum or non-zero padding bits (so each key has exactly one accepted encoding, up to letter case), ParseKeyError::WrongBech32Prefix for a prefix other than nsec, ParseKeyError::InvalidLength when the payload is not 32 bytes, and ParseKeyError::OutOfRange as for from_bytes.

Source

pub fn public(&self) -> DidNostr

Returns the public principal for this key.

Source

pub fn sign_event( &self, event: &UnsignedEvent, aux_rand: &[u8; 32], ) -> Result<SignedEvent, SignError>

Signs an event.

aux_rand is the 32 bytes of BIP-340 auxiliary randomness. It should come from a secure random source; BIP-340 signatures stay secure with fixed auxiliary data, but fresh randomness hardens against side-channel and fault attacks.

§Errors

Returns SignError::EmptyTag when a tag has no elements, SignError::UnsupportedCharacter when the content or a tag holds a control character this crate cannot serialise as NIP-01 requires (see SignedEvent), SignError::ZeroNonce in the negligible case that the derived nonce is zero, and SignError::AuxRandNotUsed if the BIP-340 backend did not take aux_rand as its single 32-byte auxiliary input. No signature is ever made with auxiliary data other than aux_rand.

Source

pub fn sign_request( &self, request: &ExpectedRequest<'_>, created_at: UnixTime, aux_rand: &[u8; 32], ) -> Result<String, SignError>

Builds and signs a kind-27235 request event and returns the complete Authorization header value, Nostr <base64 of event JSON>.

The event carries a u tag with request.url, a method tag with request.method exactly as given (no case folding: HTTP methods are case-sensitive, and the verifier compares them byte for byte) and, when request.body is Some (even if empty), a payload tag with the lowercase hex SHA-256 of the body. Content is empty. The result passes verify_request for the same request within the clock-skew window around created_at.

§Examples
use stratum_node_core::{verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime};

let key = NostrSecretKey::from_hex(&"04".repeat(32))?;
let request = ExpectedRequest::new("POST", "http://127.0.0.1:7070/api/v1/config/apply", Some(b"{}"));
let now = UnixTime::from_secs(1_700_000_000);
let header = key.sign_request(&request, now, &[0u8; 32])?;
let verified = verify_request(&header, &request, now, &RequestPolicy::new())?;
assert_eq!(verified.signer(), key.public());
§Errors

As for sign_event; a URL containing an unsupported control character gives SignError::UnsupportedCharacter.

Trait Implementations§

Source§

impl Debug for NostrSecretKey

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.