From 739803896e1545758b2bad7ea4370f0eb9d0a29d Mon Sep 17 00:00:00 2001 From: foxy98pl Date: Sun, 18 Aug 2024 14:18:17 +0200 Subject: [PATCH] Add counter for terminal users --- src/main.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/main.rs b/src/main.rs index 2111cf8..af3701c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,7 @@ use rayon::ThreadPoolBuilder; use num_cpus; use std::thread; use std::time::{Duration, Instant}; +use std::path::Path; #[derive(Deserialize)] struct BlockRecord { @@ -35,6 +36,11 @@ struct Output { pubkey: String, } +#[derive(Serialize, Deserialize)] +struct Counter { + value: u32, +} + fn verify_hash(key: &[u8], hashed_password: &str) -> Result<(), String> { let parsed_hash = PasswordHash::new(hashed_password) .map_err(|e| format!("Failed to parse hashed password: {}", e))?; @@ -85,6 +91,11 @@ fn generate_keypair(file_path: &str) -> Result> { } fn main() -> Result<(), Box> { + //Creating counter + let counter_file_path = "counter.json" + let path = Path::new(counter_file_path); + create_counter_file(&path)?; + let mut counter = read_counter_file(&path)?; // Argument parsing let matches = Command::new("My App") .version("1.0") @@ -214,6 +225,7 @@ fn main() -> Result<(), Box> { if response.status().is_success() { println!("Data successfully sent to the server."); + increment_counter(&mut counter, &path)?; // Log the submitted data let mut log_file = OpenOptions::new() .append(true) @@ -231,3 +243,33 @@ fn main() -> Result<(), Box> { thread::sleep(Duration::from_secs(10)); } } + +fn create_counter_file(path: &Path) -> std::io::Result<()> { + if path.exists() { + println!("File '{}' already exists. Skipping creation.", path.display()); + return Ok(()); + } + let counter = Counter { value: 0 }; + let mut file = File::create(&path)?; + let json = serde_json::to_string_pretty(&counter)?; + file.write_all(json.as_bytes())?; + println!("Created '{}' with initial value of 0", path.display()); + Ok(()) +} + +fn read_counter_file(path: &Path) -> std::io::Result { + let mut file = File::open(&path)?; + let mut json = String::new(); + file.read_to_string(&mut json)?; + let counter: Counter = serde_json::from_str(&json)?; + Ok(counter) +} + +fn increment_counter(counter: &mut Counter, path: &Path) -> std::io::Result<()> { + counter.value += 1; + let json = serde_json::to_string_pretty(&counter)?; + let mut file = OpenOptions::new().write(true).truncate(true).open(path)?; + file.write_all(json.as_bytes())?; + println!("Total blocks verified: {}", counter.value * 100); + Ok(()) +} \ No newline at end of file