stratum_node_cli/key.rs
1//! Operator key files: one `nsec1…` line in a `0600` file.
2
3use std::fmt::Write as _;
4use std::path::Path;
5
6use bech32::{Bech32, Hrp};
7use stratum_node_core::{NostrSecretKey, ParseKeyError};
8use zeroize::Zeroizing;
9
10use crate::private_file::{self, ModePolicy, PrivateFileError};
11
12/// The NIP-19 prefix of a secret key.
13const NSEC_HRP: &str = "nsec";
14
15/// The length of an `nsec1…` string over 32 bytes.
16const NSEC_LEN: usize = 63;
17
18/// The largest key file read: one `nsec` line with room for a CRLF.
19const KEY_FILE_LIMIT: usize = 128;
20
21/// How many times generation retries when the random bytes are not a valid
22/// secp256k1 scalar. The chance of even one retry is about 2^-128.
23const MAX_GENERATE_ATTEMPTS: usize = 8;
24
25/// Creates a new operator key file holding a freshly generated key.
26///
27/// The key is 32 bytes from the operating system's random source
28/// (`getrandom`), written as one NIP-19 `nsec1…` line followed by a newline.
29/// The file is created exclusively with mode `0600` set at creation, so an
30/// existing file, or a symbolic link at `path`, is never overwritten or
31/// followed. The returned key's [`public`](NostrSecretKey::public) principal
32/// is the operator's DID; the secret is never returned in text form.
33///
34/// # Examples
35///
36/// ```
37/// use stratum_node_cli::{generate_key_file, load_key_file};
38///
39/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
40/// let dir = std::env::temp_dir().join(format!("stratum-doc-{}", std::process::id()));
41/// std::fs::create_dir_all(&dir)?;
42/// let path = dir.join("operator.nsec");
43/// # let _ = std::fs::remove_file(&path);
44/// let key = generate_key_file(&path)?;
45/// assert_eq!(load_key_file(&path)?.public(), key.public());
46/// assert!(generate_key_file(&path).is_err(), "never overwrites");
47/// # std::fs::remove_file(&path)?;
48/// # Ok(())
49/// # }
50/// ```
51///
52/// # Errors
53///
54/// Returns [`KeyFileError::File`] with [`PrivateFileError::AlreadyExists`]
55/// when anything exists at `path`, another [`KeyFileError::File`] for an
56/// operating-system failure (nothing is left behind), and
57/// [`KeyFileError::RandomUnavailable`] when the random source fails.
58pub fn generate_key_file(path: &Path) -> Result<NostrSecretKey, KeyFileError> {
59 let mut bytes = Zeroizing::new([0u8; 32]);
60 let mut key = None;
61 for _ in 0..MAX_GENERATE_ATTEMPTS {
62 getrandom::fill(bytes.as_mut_slice()).map_err(|_| KeyFileError::RandomUnavailable)?;
63 if let Ok(candidate) = NostrSecretKey::from_bytes(&bytes) {
64 key = Some(candidate);
65 break;
66 }
67 }
68 let key = key.ok_or(KeyFileError::RandomUnavailable)?;
69 let mut line = Zeroizing::new(String::with_capacity(NSEC_LEN + 1));
70 let hrp = Hrp::parse_unchecked(NSEC_HRP);
71 bech32::encode_lower_to_fmt::<Bech32, _>(&mut *line, hrp, bytes.as_slice())
72 .map_err(|_| KeyFileError::Encoding)?;
73 line.write_char('\n').map_err(|_| KeyFileError::Encoding)?;
74 private_file::create(path, line.as_bytes()).map_err(KeyFileError::File)?;
75 Ok(key)
76}
77
78/// Loads an operator key file written by [`generate_key_file`].
79///
80/// The file must be a regular file (not a symbolic link) with a mode not
81/// open to group or others, holding one `nsec1…` string optionally followed by a
82/// newline. The contents are read into memory that is zeroised afterwards.
83///
84/// # Errors
85///
86/// Returns [`KeyFileError::File`] for a symbolic link, a non-regular file, a
87/// mode wider than `0600`, an over-long file or an operating-system
88/// failure, [`KeyFileError::NotOneLine`] when the file is not one line of
89/// text, and [`KeyFileError::InvalidKey`] when the line is not a valid
90/// `nsec`. No error carries any part of the file.
91pub fn load_key_file(path: &Path) -> Result<NostrSecretKey, KeyFileError> {
92 let contents = private_file::read(path, KEY_FILE_LIMIT, ModePolicy::OwnerOnly)
93 .map_err(KeyFileError::File)?;
94 let text = std::str::from_utf8(&contents).map_err(|_| KeyFileError::NotOneLine)?;
95 let line = text
96 .strip_suffix("\r\n")
97 .or_else(|| text.strip_suffix('\n'))
98 .unwrap_or(text);
99 if line.contains(['\n', '\r']) {
100 return Err(KeyFileError::NotOneLine);
101 }
102 NostrSecretKey::from_nsec(line).map_err(KeyFileError::InvalidKey)
103}
104
105/// Why an operator key file could not be created or loaded.
106///
107/// No variant carries any part of the key.
108#[derive(Debug, thiserror::Error)]
109#[non_exhaustive]
110pub enum KeyFileError {
111 /// The file could not be created, opened or read safely.
112 #[error(transparent)]
113 File(PrivateFileError),
114 /// The file is not a single line of UTF-8 text.
115 #[error("key file must hold exactly one nsec line")]
116 NotOneLine,
117 /// The line is not a valid NIP-19 secret key.
118 #[error("key file does not hold a valid nsec key")]
119 InvalidKey(#[source] ParseKeyError),
120 /// The operating system's random source failed.
121 #[error("the system random source is unavailable")]
122 RandomUnavailable,
123 /// The key could not be encoded as `nsec`.
124 #[error("the key could not be encoded as nsec")]
125 Encoding,
126}