Skip to main content

stratum_node_core/
secret.rs

1//! Nostr secret keys and signing.
2
3use std::fmt;
4
5use base64::Engine as _;
6use k256::schnorr::SigningKey;
7use zeroize::Zeroizing;
8
9use crate::did::DidNostr;
10use crate::encoding::{self, Bech32Error};
11use crate::event::{SignedEvent, UnsignedEvent};
12use crate::id::{Sha256Digest, UnixTime};
13use crate::request::{ExpectedRequest, AUTHORIZATION_SCHEME, HTTP_AUTH_KIND};
14use crate::schnorr::SchnorrSignError;
15
16/// The NIP-19 human-readable prefix for secret keys.
17const NSEC_HRP: &str = "nsec";
18
19/// A secp256k1 secret key used to sign Nostr events with BIP-340.
20///
21/// The key is zeroised when dropped. It does not implement `Clone`,
22/// `Serialize` or `Display`, and its `Debug` output shows only the public
23/// principal. This crate offers no way to export the secret again. Zeroising
24/// is best effort: temporary copies made on the stack while parsing are not
25/// all reachable, and memory dumps and swap are outside what it can promise.
26///
27/// # Examples
28///
29/// ```
30/// use stratum_node_core::NostrSecretKey;
31///
32/// # fn main() -> Result<(), stratum_node_core::ParseKeyError> {
33/// let key = NostrSecretKey::from_hex(&"03".repeat(32))?;
34/// let debug = format!("{key:?}");
35/// assert!(!debug.contains(&"03".repeat(32)));
36/// assert!(debug.contains(&key.public().to_string()));
37/// # Ok(())
38/// # }
39/// ```
40///
41/// It cannot be cloned or serialised:
42///
43/// ```compile_fail
44/// fn needs_clone<T: Clone>() {}
45/// needs_clone::<stratum_node_core::NostrSecretKey>();
46/// ```
47///
48/// ```compile_fail
49/// fn needs_serialize<T: serde::Serialize>() {}
50/// needs_serialize::<stratum_node_core::NostrSecretKey>();
51/// ```
52pub struct NostrSecretKey {
53    key: SigningKey,
54    public: DidNostr,
55}
56
57impl NostrSecretKey {
58    /// Builds a key from its 32 big-endian bytes.
59    ///
60    /// The caller remains responsible for zeroising its own copy.
61    ///
62    /// # Errors
63    ///
64    /// Returns [`ParseKeyError::OutOfRange`] when the value is zero or not
65    /// below the secp256k1 group order.
66    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, ParseKeyError> {
67        let key = SigningKey::from_slice(bytes).map_err(|_| ParseKeyError::OutOfRange)?;
68        let public_bytes: [u8; 32] = key.verifying_key().to_bytes().into();
69        let public = DidNostr::from_bytes(public_bytes).map_err(|_| ParseKeyError::OutOfRange)?;
70        Ok(Self { key, public })
71    }
72
73    /// Parses a key from 64 lowercase hexadecimal digits.
74    ///
75    /// # Errors
76    ///
77    /// Returns [`ParseKeyError::InvalidHex`] for anything other than 64
78    /// lowercase hex digits, and [`ParseKeyError::OutOfRange`] as for
79    /// [`from_bytes`](Self::from_bytes).
80    pub fn from_hex(hex: &str) -> Result<Self, ParseKeyError> {
81        let mut bytes = Zeroizing::new([0u8; 32]);
82        if !encoding::decode_lower_hex_into(hex, bytes.as_mut_slice()) {
83            return Err(ParseKeyError::InvalidHex);
84        }
85        Self::from_bytes(&bytes)
86    }
87
88    /// Parses a NIP-19 `nsec1…` bech32 secret key.
89    ///
90    /// # Errors
91    ///
92    /// Returns [`ParseKeyError::InvalidBech32`] for a malformed string, a
93    /// bech32m checksum or non-zero padding bits (so each key has exactly
94    /// one accepted encoding, up to letter case), [`ParseKeyError::WrongBech32Prefix`] for a prefix
95    /// other than `nsec`, [`ParseKeyError::InvalidLength`] when the payload
96    /// is not 32 bytes, and [`ParseKeyError::OutOfRange`] as for
97    /// [`from_bytes`](Self::from_bytes).
98    pub fn from_nsec(nsec: &str) -> Result<Self, ParseKeyError> {
99        let mut bytes = Zeroizing::new([0u8; 32]);
100        encoding::decode_bech32(nsec, NSEC_HRP, &mut bytes).map_err(|err| match err {
101            Bech32Error::Invalid => ParseKeyError::InvalidBech32,
102            Bech32Error::WrongPrefix => ParseKeyError::WrongBech32Prefix,
103            Bech32Error::WrongLength => ParseKeyError::InvalidLength,
104        })?;
105        Self::from_bytes(&bytes)
106    }
107
108    /// Returns the public principal for this key.
109    pub fn public(&self) -> DidNostr {
110        self.public
111    }
112
113    /// Signs an event.
114    ///
115    /// `aux_rand` is the 32 bytes of BIP-340 auxiliary randomness. It should
116    /// come from a secure random source; BIP-340 signatures stay secure with
117    /// fixed auxiliary data, but fresh randomness hardens against
118    /// side-channel and fault attacks.
119    ///
120    /// # Errors
121    ///
122    /// Returns [`SignError::EmptyTag`] when a tag has no elements,
123    /// [`SignError::UnsupportedCharacter`] when the content or a tag holds a
124    /// control character this crate cannot serialise as NIP-01 requires (see
125    /// [`SignedEvent`](crate::SignedEvent#character-restriction)),
126    /// [`SignError::ZeroNonce`] in the negligible case that the derived nonce
127    /// is zero, and [`SignError::AuxRandNotUsed`] if the BIP-340 backend did
128    /// not take `aux_rand` as its single 32-byte auxiliary input. No
129    /// signature is ever made with auxiliary data other than `aux_rand`.
130    pub fn sign_event(
131        &self,
132        event: &UnsignedEvent,
133        aux_rand: &[u8; 32],
134    ) -> Result<SignedEvent, SignError> {
135        if event.has_empty_tag() {
136            return Err(SignError::EmptyTag);
137        }
138        if !event.is_supported_text() {
139            return Err(SignError::UnsupportedCharacter);
140        }
141        let id = event.id_for(&self.public);
142        let sig =
143            crate::schnorr::sign(&self.key, id.as_bytes(), aux_rand).map_err(|err| match err {
144                SchnorrSignError::ZeroNonce => SignError::ZeroNonce,
145                SchnorrSignError::AuxRandNotUsed => SignError::AuxRandNotUsed,
146            })?;
147        Ok(event.clone().into_signed(id, self.public, sig))
148    }
149
150    /// Builds and signs a kind-27235 request event and returns the complete
151    /// `Authorization` header value, `Nostr <base64 of event JSON>`.
152    ///
153    /// The event carries a `u` tag with `request.url`, a `method` tag with
154    /// `request.method` exactly as given (no case folding: HTTP methods are
155    /// case-sensitive, and the verifier compares them byte for byte) and, when `request.body` is `Some`
156    /// (even if empty), a `payload` tag with the lowercase hex SHA-256 of the
157    /// body. Content is empty. The result passes [`verify_request`] for the
158    /// same request within the clock-skew window around `created_at`.
159    ///
160    /// [`verify_request`]: crate::verify_request
161    ///
162    /// # Examples
163    ///
164    /// ```
165    /// use stratum_node_core::{verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime};
166    ///
167    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
168    /// let key = NostrSecretKey::from_hex(&"04".repeat(32))?;
169    /// let request = ExpectedRequest::new("POST", "http://127.0.0.1:7070/api/v1/config/apply", Some(b"{}"));
170    /// let now = UnixTime::from_secs(1_700_000_000);
171    /// let header = key.sign_request(&request, now, &[0u8; 32])?;
172    /// let verified = verify_request(&header, &request, now, &RequestPolicy::new())?;
173    /// assert_eq!(verified.signer(), key.public());
174    /// # Ok(())
175    /// # }
176    /// ```
177    ///
178    /// # Errors
179    ///
180    /// As for [`sign_event`](Self::sign_event); a URL containing an
181    /// unsupported control character gives [`SignError::UnsupportedCharacter`].
182    pub fn sign_request(
183        &self,
184        request: &ExpectedRequest<'_>,
185        created_at: UnixTime,
186        aux_rand: &[u8; 32],
187    ) -> Result<String, SignError> {
188        let mut event = UnsignedEvent::new(HTTP_AUTH_KIND, created_at)
189            .with_tag(["u", request.url])
190            .with_tag(["method", request.method]);
191        if let Some(body) = request.body {
192            event = event.with_tag(["payload".to_owned(), Sha256Digest::of(body).to_hex()]);
193        }
194        let signed = self.sign_event(&event, aux_rand)?;
195        let token = base64::engine::general_purpose::STANDARD.encode(signed.to_json());
196        Ok(format!("{AUTHORIZATION_SCHEME} {token}"))
197    }
198}
199
200impl fmt::Debug for NostrSecretKey {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        f.debug_struct("NostrSecretKey")
203            .field("public", &self.public)
204            .finish_non_exhaustive()
205    }
206}
207
208/// The reasons a secret key can fail to parse.
209///
210/// No variant carries any part of the input.
211#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
212#[non_exhaustive]
213pub enum ParseKeyError {
214    /// The text is not exactly 64 lowercase hexadecimal digits.
215    #[error("secret key is not 64 lowercase hex digits")]
216    InvalidHex,
217    /// The string is not valid bech32 with a bech32 (not bech32m) checksum
218    /// and zero padding bits.
219    #[error("invalid bech32 secret key")]
220    InvalidBech32,
221    /// The bech32 prefix is not `nsec`.
222    #[error("bech32 prefix is not nsec")]
223    WrongBech32Prefix,
224    /// The decoded payload is not 32 bytes.
225    #[error("secret key is not 32 bytes")]
226    InvalidLength,
227    /// The value is zero or not below the secp256k1 group order.
228    #[error("secret key is out of range")]
229    OutOfRange,
230}
231
232/// The reasons signing can fail.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
234#[non_exhaustive]
235pub enum SignError {
236    /// The content or a tag contains a control character outside the set
237    /// NIP-01 escapes by name; see
238    /// [`SignedEvent`](crate::SignedEvent#character-restriction).
239    #[error("event text contains an unsupported control character")]
240    UnsupportedCharacter,
241    /// A tag has no elements; NIP-01 requires at least one.
242    #[error("event has an empty tag")]
243    EmptyTag,
244    /// The BIP-340 nonce derived from this key, message and auxiliary
245    /// randomness is zero. The probability is negligible; retry with fresh
246    /// auxiliary randomness.
247    #[error("derived signing nonce is zero; retry with fresh auxiliary randomness")]
248    ZeroNonce,
249    /// The BIP-340 backend did not take the auxiliary randomness as exactly
250    /// one 32-byte draw, so no signature is returned rather than one made
251    /// with substitute auxiliary data. This points at an incompatible
252    /// dependency version, not at the input; retrying does not help.
253    #[error("signing backend did not take the auxiliary randomness as one 32-byte draw")]
254    AuxRandNotUsed,
255}