reth_cli_util/
load_secret_key.rsuse reth_fs_util::{self as fs, FsPathError};
use secp256k1::{Error as SecretKeyBaseError, SecretKey};
use std::{
io,
path::{Path, PathBuf},
};
use thiserror::Error;
pub fn rng_secret_key() -> SecretKey {
SecretKey::new(&mut rand::thread_rng())
}
#[derive(Error, Debug)]
pub enum SecretKeyError {
#[error(transparent)]
SecretKeyDecodeError(#[from] SecretKeyBaseError),
#[error(transparent)]
SecretKeyFsPathError(#[from] FsPathError),
#[error("failed to access key file {secret_file:?}: {error}")]
FailedToAccessKeyFile {
error: io::Error,
secret_file: PathBuf,
},
}
pub fn get_secret_key(secret_key_path: &Path) -> Result<SecretKey, SecretKeyError> {
let exists = secret_key_path.try_exists();
match exists {
Ok(true) => {
let contents = fs::read_to_string(secret_key_path)?;
Ok(contents.as_str().parse().map_err(SecretKeyError::SecretKeyDecodeError)?)
}
Ok(false) => {
if let Some(dir) = secret_key_path.parent() {
fs::create_dir_all(dir)?;
}
let secret = rng_secret_key();
let hex = alloy_primitives::hex::encode(secret.as_ref());
fs::write(secret_key_path, hex)?;
Ok(secret)
}
Err(error) => Err(SecretKeyError::FailedToAccessKeyFile {
error,
secret_file: secret_key_path.to_path_buf(),
}),
}
}