|
| 1 | +#![deny(missing_docs, rustdoc::broken_intra_doc_links)] |
| 2 | +//! Utilities for building iroh nodes. |
| 3 | +pub mod rpc; |
| 4 | + |
| 5 | +use std::path::PathBuf; |
| 6 | + |
| 7 | +use anyhow::Context; |
| 8 | +use iroh_net::key::SecretKey; |
| 9 | +use tokio::io::AsyncWriteExt; |
| 10 | + |
| 11 | +/// Loads a [`SecretKey`] from the provided file, or stores a newly generated one |
| 12 | +/// at the given location. |
| 13 | +pub async fn load_secret_key(key_path: PathBuf) -> anyhow::Result<SecretKey> { |
| 14 | + if key_path.exists() { |
| 15 | + let keystr = tokio::fs::read(key_path).await?; |
| 16 | + let secret_key = SecretKey::try_from_openssh(keystr).context("invalid keyfile")?; |
| 17 | + Ok(secret_key) |
| 18 | + } else { |
| 19 | + let secret_key = SecretKey::generate(); |
| 20 | + let ser_key = secret_key.to_openssh()?; |
| 21 | + |
| 22 | + // Try to canonicalize if possible |
| 23 | + let key_path = key_path.canonicalize().unwrap_or(key_path); |
| 24 | + let key_path_parent = key_path.parent().ok_or_else(|| { |
| 25 | + anyhow::anyhow!("no parent directory found for '{}'", key_path.display()) |
| 26 | + })?; |
| 27 | + tokio::fs::create_dir_all(&key_path_parent).await?; |
| 28 | + |
| 29 | + // write to tempfile |
| 30 | + let (file, temp_file_path) = tempfile::NamedTempFile::new_in(key_path_parent) |
| 31 | + .context("unable to create tempfile")? |
| 32 | + .into_parts(); |
| 33 | + let mut file = tokio::fs::File::from_std(file); |
| 34 | + file.write_all(ser_key.as_bytes()) |
| 35 | + .await |
| 36 | + .context("unable to write keyfile")?; |
| 37 | + file.flush().await?; |
| 38 | + drop(file); |
| 39 | + |
| 40 | + // move file |
| 41 | + tokio::fs::rename(temp_file_path, key_path) |
| 42 | + .await |
| 43 | + .context("failed to rename keyfile")?; |
| 44 | + |
| 45 | + Ok(secret_key) |
| 46 | + } |
| 47 | +} |
0 commit comments