Skip to main content

taskfast_cli/
wallet_lock.rs

1// SPDX-License-Identifier: MIT
2//! F9: exclusive file-lock guarding wallet-signing operations against
3//! concurrent `taskfast post` invocations sharing the same keystore.
4//!
5//! # What this prevents
6//!
7//! Tempo (like any EVM network) uses a monotonic per-address nonce. If
8//! two processes both call `eth_getTransactionCount(addr, "latest")` at
9//! the same moment, both get the same value, both sign a tx with that
10//! nonce, and the RPC drops whichever arrives second. The scenario is
11//! realistic for a multi-worker agent farm pointed at one wallet.
12//!
13//! # Scope
14//!
15//! Advisory, best-effort. We hold an OS-level exclusive lock on a file
16//! adjacent to the keystore from just before `eth_getTransactionCount`
17//! until after the raw tx has been submitted. A crash between those
18//! points releases the lock cleanly (the kernel drops it on fd close),
19//! so there's no stale-lock problem. The lock does **not** serialize
20//! wallets across different hosts — operators with multi-host setups
21//! must still keep per-host nonce coordination in mind.
22
23use std::fs::{File, OpenOptions};
24use std::path::{Path, PathBuf};
25
26use fs4::FileExt;
27
28use crate::cmd::CmdError;
29
30/// RAII handle releasing the lock on drop. Held for the entire
31/// sign+broadcast critical section.
32pub struct WalletGuard(#[allow(dead_code)] File);
33
34/// Acquire an exclusive file-lock keyed off the keystore path.
35///
36/// Blocks until the lock is available. The lock file lives at
37/// `<keystore_dir>/.taskfast-wallet.lock`; same-directory placement
38/// means two processes with different `--keystore` inputs that resolve
39/// to the same canonical path end up on the same lock.
40pub fn acquire(keystore_path: &Path) -> Result<WalletGuard, CmdError> {
41    let lock_path = lock_path_for(keystore_path);
42    let f = OpenOptions::new()
43        .read(true)
44        .write(true)
45        .create(true)
46        .truncate(false)
47        .open(&lock_path)
48        .map_err(|e| CmdError::Usage(format!("open wallet lock {}: {e}", lock_path.display())))?;
49    // fs4 1.0 renamed `lock_exclusive` -> `lock` to mirror std's stabilized
50    // file-locking API; semantics are identical (blocking exclusive lock).
51    // UFCS keeps this on fs4's trait rather than std's inherent `File::lock`.
52    FileExt::lock(&f).map_err(|e| {
53        CmdError::Usage(format!("acquire wallet lock {}: {e}", lock_path.display()))
54    })?;
55    Ok(WalletGuard(f))
56}
57
58fn lock_path_for(keystore_path: &Path) -> PathBuf {
59    let parent = keystore_path.parent().unwrap_or_else(|| Path::new("."));
60    parent.join(".taskfast-wallet.lock")
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use std::sync::mpsc;
67    use std::thread;
68    use std::time::Duration;
69    use tempfile::TempDir;
70
71    #[test]
72    fn lock_is_exclusive_across_threads() {
73        let tmp = TempDir::new().unwrap();
74        let keystore = tmp.path().join("keystore.json");
75        std::fs::write(&keystore, "{}").unwrap();
76
77        let first = acquire(&keystore).expect("first acquire");
78
79        let (tx, rx) = mpsc::channel();
80        let ks = keystore.clone();
81        let joiner = thread::spawn(move || {
82            // Should block until main releases. We signal when it
83            // finally returns so the assertion below can ordering-check.
84            let _g = acquire(&ks).expect("second acquire");
85            tx.send(()).unwrap();
86        });
87
88        // Prove the second thread is blocked: no signal for 100 ms.
89        assert!(
90            rx.recv_timeout(Duration::from_millis(100)).is_err(),
91            "second acquire must block while first holds the lock"
92        );
93        drop(first);
94        rx.recv_timeout(Duration::from_secs(2))
95            .expect("second acquire must unblock after first drops");
96        joiner.join().unwrap();
97    }
98
99    #[test]
100    fn lock_path_sits_beside_keystore() {
101        let p = Path::new("/some/dir/agent.keystore.json");
102        assert_eq!(
103            lock_path_for(p),
104            PathBuf::from("/some/dir/.taskfast-wallet.lock")
105        );
106    }
107}