use std::collections::HashMap;
use std::path::Path;
use serde::Deserialize;
use starknet::core::types::Felt;
use tracing::{debug, warn};
use crate::decode::privacy_crypto::types::SecretFelt;
use crate::error::{Result, StarktopError};
#[derive(Debug, Default, Deserialize)]
pub struct ViewingKeysFile {
#[serde(default)]
pub keys: HashMap<String, String>,
}
#[derive(Debug, Clone)]
pub struct ViewingKey {
pub user: Felt,
pub private_key: SecretFelt,
}
pub fn load_viewing_keys(path: &Path) -> Result<(Vec<ViewingKey>, Option<String>)> {
if !path.exists() {
debug!(path = %path.display(), "Viewing keys file not found, using empty");
return Ok((Vec::new(), None));
}
if let Err(msg) = check_permissions(path) {
warn!("{}", msg);
}
let content = std::fs::read_to_string(path)
.map_err(|e| StarktopError::Config(format!("Failed to read viewing keys file: {e}")))?;
let file: ViewingKeysFile = match toml::from_str(&content) {
Ok(f) => f,
Err(e) => {
let msg = format!(
"viewing_keys.toml is corrupted (TOML parse error: {e}) — no viewing keys loaded"
);
warn!("{}", msg);
return Ok((Vec::new(), Some(msg)));
}
};
let mut keys = Vec::new();
for (user_hex, key_hex) in &file.keys {
let user = match Felt::from_hex(user_hex) {
Ok(f) => f,
Err(e) => {
warn!(address = user_hex, error = %e, "Invalid user address in viewing keys, skipping");
continue;
}
};
let private_felt = match Felt::from_hex(key_hex) {
Ok(f) => f,
Err(e) => {
warn!(address = user_hex, error = %e, "Invalid private viewing key, skipping");
continue;
}
};
keys.push(ViewingKey {
user,
private_key: SecretFelt::new(private_felt),
});
}
debug!(count = keys.len(), "Loaded viewing keys");
Ok((keys, None))
}
#[cfg(unix)]
fn check_permissions(path: &Path) -> std::result::Result<(), String> {
use std::os::unix::fs::PermissionsExt;
let meta =
std::fs::metadata(path).map_err(|e| format!("Cannot stat viewing keys file: {e}"))?;
let mode = meta.permissions().mode();
if mode & 0o077 != 0 {
return Err(format!(
"viewing_keys.toml at {} has loose permissions ({:o}) — \
chmod 600 to restrict to owner only",
path.display(),
mode & 0o777
));
}
Ok(())
}
#[cfg(not(unix))]
fn check_permissions(_path: &Path) -> std::result::Result<(), String> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_file_is_ok() {
let path = Path::new("/tmp/starktop-nonexistent-viewing-keys.toml");
let (keys, warn) = load_viewing_keys(path).unwrap();
assert!(keys.is_empty());
assert!(warn.is_none());
}
#[test]
fn parses_valid_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("vk.toml");
std::fs::write(
&path,
r#"
[keys]
"0xabcd" = "0xc0ffee"
"#,
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut p = std::fs::metadata(&path).unwrap().permissions();
p.set_mode(0o600);
std::fs::set_permissions(&path, p).unwrap();
}
let (keys, warn) = load_viewing_keys(&path).unwrap();
assert!(warn.is_none());
assert_eq!(keys.len(), 1);
assert_eq!(keys[0].user, Felt::from_hex("0xabcd").unwrap());
}
#[test]
fn corrupt_toml_yields_warning() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("vk.toml");
std::fs::write(&path, "this is { not valid").unwrap();
let (keys, warn) = load_viewing_keys(&path).unwrap();
assert!(keys.is_empty());
assert!(warn.is_some());
}
}