From d6d27af140b0cbaf70af1acf2777c25c99e671ce Mon Sep 17 00:00:00 2001 From: Kriday Dave Date: Tue, 6 Oct 2026 03:26:57 +0530 Subject: [PATCH] refactor: persist state through the shared atomic writer StateEngine::save carried its own copy of the tempfile-persist-fsync sequence that util::atomic_write already implements, line for line. One implementation, one place to audit. --- src/engine.rs | 22 ++-------------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/src/engine.rs b/src/engine.rs index 9c66857..9066e4d 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -112,28 +112,10 @@ impl StateEngine { } } - /// Save signed state to file (pretty JSON) — atomic via tempfile in same dir + /// Save signed state to file (pretty JSON), atomically. pub fn save(path: &std::path::Path, signed: &SignedState) -> Result<(), TaprootError> { - use std::io::Write; let bytes = serde_json::to_vec_pretty(signed)?; - let parent = path - .parent() - .filter(|p| !p.as_os_str().is_empty()) - .unwrap_or_else(|| std::path::Path::new(".")); - if !parent.as_os_str().is_empty() && parent != std::path::Path::new(".") { - std::fs::create_dir_all(parent)?; - } - // Use tempfile with random suffix to avoid symlink races and collisions - let mut tmp = tempfile::NamedTempFile::new_in(parent)?; - tmp.write_all(&bytes)?; - tmp.flush()?; - tmp.as_file().sync_all()?; - tmp.persist(path).map_err(|e| TaprootError::Io(e.error))?; - // fsync parent dir for durability - if let Ok(dir) = std::fs::File::open(parent) { - let _ = dir.sync_all(); - } - Ok(()) + crate::util::atomic_write(path, &bytes) } /// Load signed state from file and verify