util.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. use std::path::PathBuf;
  2. use fxhash::FxHashMap;
  3. use log::info;
  4. use darkfi::Result;
  5. #[derive(Clone)]
  6. pub struct Workspace {
  7. pub encryption: Option<crypto_box::Box>,
  8. }
  9. impl Workspace {
  10. pub fn new() -> Result<Self> {
  11. Ok(Self { encryption: None })
  12. }
  13. }
  14. /// Parse the configuration file for any configured workspaces and return
  15. /// a map containing said configurations.
  16. pub fn parse_workspaces(config_file: &PathBuf) -> Result<FxHashMap<String, Workspace>> {
  17. let toml_contents = std::fs::read_to_string(config_file)?;
  18. let mut ret = FxHashMap::default();
  19. if let toml::Value::Table(map) = toml::from_str(&toml_contents)? {
  20. if map.contains_key("workspace") && map["workspace"].is_table() {
  21. for ws in map["workspace"].as_table().unwrap() {
  22. info!("Found configuration for workspace {}", ws.0);
  23. let mut workspace_info = Workspace::new()?;
  24. if ws.1.as_table().unwrap().contains_key("secret") {
  25. // Build the NaCl box
  26. let s = ws.1["secret"].as_str().unwrap();
  27. let bytes: [u8; 32] = bs58::decode(s).into_vec()?.try_into().unwrap();
  28. let secret = crypto_box::SecretKey::from(bytes);
  29. let public = secret.public_key();
  30. let msg_box = crypto_box::Box::new(&public, &secret);
  31. workspace_info.encryption = Some(msg_box);
  32. info!("Instantiated NaCl box for workspace {}", ws.0);
  33. }
  34. ret.insert(ws.0.to_string(), workspace_info);
  35. }
  36. }
  37. };
  38. Ok(ret)
  39. }
  40. pub fn find_free_id(task_ids: &[u32]) -> u32 {
  41. for i in 1.. {
  42. if !task_ids.contains(&i) {
  43. return i
  44. }
  45. }
  46. 1
  47. }
  48. #[cfg(test)]
  49. mod tests {
  50. use super::*;
  51. #[test]
  52. fn find_free_id_test() -> Result<()> {
  53. let mut ids: Vec<u32> = vec![1, 3, 8, 9, 10, 3];
  54. let ids_empty: Vec<u32> = vec![];
  55. let ids_duplicate: Vec<u32> = vec![1; 100];
  56. let find_id = find_free_id(&ids);
  57. assert_eq!(find_id, 2);
  58. ids.push(find_id);
  59. assert_eq!(find_free_id(&ids), 4);
  60. assert_eq!(find_free_id(&ids_empty), 1);
  61. assert_eq!(find_free_id(&ids_duplicate), 2);
  62. Ok(())
  63. }
  64. }