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 /// The event ID covers `created_at` in whole seconds and these tags, not
161 /// the signature, so two identical requests signed in the same second
162 /// are the same event, and a server that keeps event IDs against replay
163 /// refuses the second. A client that may repeat a request within a second
164 /// should use [`sign_request_with_nonce`](Self::sign_request_with_nonce).
165 ///
166 /// [`verify_request`]: crate::verify_request
167 ///
168 /// # Examples
169 ///
170 /// ```
171 /// use stratum_node_core::{verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime};
172 ///
173 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
174 /// let key = NostrSecretKey::from_hex(&"04".repeat(32))?;
175 /// let request = ExpectedRequest::new("POST", "http://127.0.0.1:7070/api/v1/config/apply", Some(b"{}"));
176 /// let now = UnixTime::from_secs(1_700_000_000);
177 /// let header = key.sign_request(&request, now, &[0u8; 32])?;
178 /// let verified = verify_request(&header, &request, now, &RequestPolicy::new())?;
179 /// assert_eq!(verified.signer(), key.public());
180 /// # Ok(())
181 /// # }
182 /// ```
183 ///
184 /// # Errors
185 ///
186 /// As for [`sign_event`](Self::sign_event); a URL containing an
187 /// unsupported control character gives [`SignError::UnsupportedCharacter`].
188 pub fn sign_request(
189 &self,
190 request: &ExpectedRequest<'_>,
191 created_at: UnixTime,
192 aux_rand: &[u8; 32],
193 ) -> Result<String, SignError> {
194 self.sign_request_tagged(request, created_at, None, aux_rand)
195 }
196
197 /// As [`sign_request`](Self::sign_request), with one more tag,
198 /// `["nonce", <32 lowercase hex digits of nonce>]`, after the others
199 /// (after `payload` when there is a body, otherwise after `method`).
200 ///
201 /// A request event's ID covers the whole-second `created_at`, the URL,
202 /// the method and the body digest, but not the signature. Without a
203 /// nonce, two identical requests signed in one second are one event,
204 /// and a server that keeps event IDs for replay protection refuses the
205 /// second. A distinct nonce makes each signing a distinct event, so a
206 /// client need not wait for the clock to move on.
207 ///
208 /// `nonce` should be 16 fresh bytes from the operating system's random
209 /// source for every request; this crate never reads a random source
210 /// itself, so it is a parameter. It is not secret: it travels in the
211 /// clear inside the header and only has to differ between requests.
212 /// [`verify_request`] and [`verify_request_without_body`] ignore tags
213 /// outside the profile, so they accept the result exactly as they accept
214 /// one from [`sign_request`](Self::sign_request).
215 ///
216 /// [`verify_request`]: crate::verify_request
217 /// [`verify_request_without_body`]: crate::verify_request_without_body
218 ///
219 /// # Examples
220 ///
221 /// ```
222 /// use stratum_node_core::{verify_request, ExpectedRequest, NostrSecretKey, RequestPolicy, UnixTime};
223 ///
224 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
225 /// let key = NostrSecretKey::from_hex(&"04".repeat(32))?;
226 /// let request = ExpectedRequest::new("GET", "http://127.0.0.1:7070/api/v1/status", None);
227 /// let now = UnixTime::from_secs(1_700_000_000);
228 /// // In real use each nonce comes from the OS random source.
229 /// let first = key.sign_request_with_nonce(&request, now, &[1; 16], &[0; 32])?;
230 /// let second = key.sign_request_with_nonce(&request, now, &[2; 16], &[0; 32])?;
231 /// let policy = RequestPolicy::new();
232 /// let first = verify_request(&first, &request, now, &policy)?;
233 /// let second = verify_request(&second, &request, now, &policy)?;
234 /// assert_ne!(first.event_id(), second.event_id(), "same second, two events");
235 /// # Ok(())
236 /// # }
237 /// ```
238 ///
239 /// # Errors
240 ///
241 /// As for [`sign_request`](Self::sign_request).
242 pub fn sign_request_with_nonce(
243 &self,
244 request: &ExpectedRequest<'_>,
245 created_at: UnixTime,
246 nonce: &[u8; 16],
247 aux_rand: &[u8; 32],
248 ) -> Result<String, SignError> {
249 self.sign_request_tagged(request, created_at, Some(nonce), aux_rand)
250 }
251
252 /// The body of [`sign_request`](Self::sign_request) and
253 /// [`sign_request_with_nonce`](Self::sign_request_with_nonce).
254 fn sign_request_tagged(
255 &self,
256 request: &ExpectedRequest<'_>,
257 created_at: UnixTime,
258 nonce: Option<&[u8; 16]>,
259 aux_rand: &[u8; 32],
260 ) -> Result<String, SignError> {
261 let mut event = UnsignedEvent::new(HTTP_AUTH_KIND, created_at)
262 .with_tag(["u", request.url])
263 .with_tag(["method", request.method]);
264 if let Some(body) = request.body {
265 event = event.with_tag(["payload".to_owned(), Sha256Digest::of(body).to_hex()]);
266 }
267 if let Some(nonce) = nonce {
268 event = event.with_tag(["nonce".to_owned(), hex::encode(nonce)]);
269 }
270 let signed = self.sign_event(&event, aux_rand)?;
271 let token = base64::engine::general_purpose::STANDARD.encode(signed.to_json());
272 Ok(format!("{AUTHORIZATION_SCHEME} {token}"))
273 }
274}
275
276impl fmt::Debug for NostrSecretKey {
277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278 f.debug_struct("NostrSecretKey")
279 .field("public", &self.public)
280 .finish_non_exhaustive()
281 }
282}
283
284/// The reasons a secret key can fail to parse.
285///
286/// No variant carries any part of the input.
287#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
288#[non_exhaustive]
289pub enum ParseKeyError {
290 /// The text is not exactly 64 lowercase hexadecimal digits.
291 #[error("secret key is not 64 lowercase hex digits")]
292 InvalidHex,
293 /// The string is not valid bech32 with a bech32 (not bech32m) checksum
294 /// and zero padding bits.
295 #[error("invalid bech32 secret key")]
296 InvalidBech32,
297 /// The bech32 prefix is not `nsec`.
298 #[error("bech32 prefix is not nsec")]
299 WrongBech32Prefix,
300 /// The decoded payload is not 32 bytes.
301 #[error("secret key is not 32 bytes")]
302 InvalidLength,
303 /// The value is zero or not below the secp256k1 group order.
304 #[error("secret key is out of range")]
305 OutOfRange,
306}
307
308/// The reasons signing can fail.
309#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
310#[non_exhaustive]
311pub enum SignError {
312 /// The content or a tag contains a control character outside the set
313 /// NIP-01 escapes by name; see
314 /// [`SignedEvent`](crate::SignedEvent#character-restriction).
315 #[error("event text contains an unsupported control character")]
316 UnsupportedCharacter,
317 /// A tag has no elements; NIP-01 requires at least one.
318 #[error("event has an empty tag")]
319 EmptyTag,
320 /// The BIP-340 nonce derived from this key, message and auxiliary
321 /// randomness is zero. The probability is negligible; retry with fresh
322 /// auxiliary randomness.
323 #[error("derived signing nonce is zero; retry with fresh auxiliary randomness")]
324 ZeroNonce,
325 /// The BIP-340 backend did not take the auxiliary randomness as exactly
326 /// one 32-byte draw, so no signature is returned rather than one made
327 /// with substitute auxiliary data. This points at an incompatible
328 /// dependency version, not at the input; retrying does not help.
329 #[error("signing backend did not take the auxiliary randomness as one 32-byte draw")]
330 AuxRandNotUsed,
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336 use crate::request::{RequestPolicy, RequestTarget};
337 use crate::{verify_request, verify_request_without_body};
338
339 const URL: &str = "http://127.0.0.1:7070/api/v1/config/apply";
340 const AT: UnixTime = UnixTime::from_secs(1_700_000_000);
341
342 fn key() -> NostrSecretKey {
343 NostrSecretKey::from_hex(&"05".repeat(32)).expect("key")
344 }
345
346 /// The verified event inside an `Authorization` value.
347 fn event(header: &str) -> SignedEvent {
348 let token = header.strip_prefix("Nostr ").expect("scheme");
349 let json = base64::engine::general_purpose::STANDARD
350 .decode(token)
351 .expect("base64");
352 SignedEvent::from_json(&json).expect("valid event")
353 }
354
355 #[test]
356 fn different_nonces_in_one_second_are_different_events() {
357 let request = ExpectedRequest::new("POST", URL, Some(b"{}"));
358 let a = key()
359 .sign_request_with_nonce(&request, AT, &[1; 16], &[0; 32])
360 .expect("signs");
361 let b = key()
362 .sign_request_with_nonce(&request, AT, &[2; 16], &[0; 32])
363 .expect("signs");
364 assert_ne!(event(&a).id(), event(&b).id());
365 }
366
367 #[test]
368 fn the_same_nonce_is_the_same_event_whatever_the_aux_rand() {
369 let request = ExpectedRequest::new("POST", URL, Some(b"{}"));
370 let a = key()
371 .sign_request_with_nonce(&request, AT, &[7; 16], &[0; 32])
372 .expect("signs");
373 let b = key()
374 .sign_request_with_nonce(&request, AT, &[7; 16], &[9; 32])
375 .expect("signs");
376 assert_ne!(a, b, "the signatures differ");
377 assert_eq!(event(&a).id(), event(&b).id());
378 }
379
380 #[test]
381 fn a_nonce_signed_request_verifies_with_and_without_the_body() {
382 let policy = RequestPolicy::new();
383 for (method, body) in [("PUT", Some(&b"hello"[..])), ("GET", None)] {
384 let request = ExpectedRequest::new(method, URL, body);
385 let header = key()
386 .sign_request_with_nonce(&request, AT, &[3; 16], &[0; 32])
387 .expect("signs");
388 let full = verify_request(&header, &request, AT, &policy).expect("verifies");
389 assert_eq!(full.signer(), key().public());
390 let unchecked =
391 verify_request_without_body(&header, &RequestTarget::new(method, URL), AT, &policy)
392 .expect("verifies without body");
393 assert_eq!(unchecked.event_id(), full.event_id());
394 }
395 }
396
397 #[test]
398 fn the_nonce_tag_comes_last() {
399 let nonce = [0xab; 16];
400 let post = key()
401 .sign_request_with_nonce(
402 &ExpectedRequest::new("POST", URL, Some(b"{}")),
403 AT,
404 &nonce,
405 &[0; 32],
406 )
407 .expect("signs");
408 let tags = event(&post).tags().to_vec();
409 assert_eq!(tags.len(), 4, "{tags:?}");
410 assert_eq!(tags[0], ["u", URL]);
411 assert_eq!(tags[1], ["method", "POST"]);
412 assert_eq!(tags[2][0], "payload");
413 assert_eq!(tags[3], ["nonce", "ab".repeat(16).as_str()]);
414
415 let get = key()
416 .sign_request_with_nonce(
417 &ExpectedRequest::new("GET", URL, None),
418 AT,
419 &nonce,
420 &[0; 32],
421 )
422 .expect("signs");
423 let tags = event(&get).tags().to_vec();
424 assert_eq!(tags.len(), 3, "{tags:?}");
425 assert_eq!(tags[2], ["nonce", "ab".repeat(16).as_str()]);
426 }
427
428 #[test]
429 fn sign_request_carries_no_nonce() {
430 let header = key()
431 .sign_request(&ExpectedRequest::new("GET", URL, None), AT, &[0; 32])
432 .expect("signs");
433 let tags = event(&header).tags().to_vec();
434 assert_eq!(tags.len(), 2, "{tags:?}");
435 assert!(tags.iter().all(|tag| tag[0] != "nonce"));
436 }
437}