tempo-x402 3.4.0

x402 payment protocol library for Tempo blockchain (EIP-712, TIP-20, wallet, client)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Replay protection via nonce tracking.
//!
//! Provides the [`NonceStore`] trait and two implementations:
//! - [`InMemoryNonceStore`] — fast, concurrent (DashMap-backed), lost on restart
//! - [`SqliteNonceStore`] — persistent, survives restarts, required for production
//!
//! Nonces are claimed atomically via [`NonceStore::try_use`] before settlement
//! and are **never released on failure** (the transaction may still mine).

use alloy::primitives::FixedBytes;
use dashmap::DashMap;
use std::sync::Mutex;
use std::time::Instant;
use tracing;

/// Trait for nonce storage backends.
///
/// Implementations must be thread-safe (`Send + Sync`).
pub trait NonceStore: Send + Sync {
    /// Check if a nonce has already been used.
    fn is_used(&self, nonce: &FixedBytes<32>) -> bool;

    /// Record a nonce as used.
    fn record(&self, nonce: FixedBytes<32>);

    /// Atomically check if nonce is unused and record it if so.
    /// Returns `true` if the nonce was successfully claimed (was not used before).
    /// Returns `false` if the nonce was already used (replay attempt).
    /// This is the preferred method for replay protection as it's atomic.
    fn try_use(&self, nonce: FixedBytes<32>) -> bool;

    /// Release a previously claimed nonce (e.g., when settlement fails after nonce claim).
    /// This allows the payer to retry with the same signed authorization.
    fn release(&self, nonce: &FixedBytes<32>);

    /// Purge nonces older than `max_age_secs`. Returns number purged.
    fn purge_expired(&self, max_age_secs: u64) -> usize;
}

/// In-memory nonce store backed by DashMap. Fast but lost on restart.
pub struct InMemoryNonceStore {
    nonces: DashMap<FixedBytes<32>, Instant>,
}

impl InMemoryNonceStore {
    pub fn new() -> Self {
        Self {
            nonces: DashMap::new(),
        }
    }
}

impl Default for InMemoryNonceStore {
    fn default() -> Self {
        Self::new()
    }
}

impl NonceStore for InMemoryNonceStore {
    fn is_used(&self, nonce: &FixedBytes<32>) -> bool {
        self.nonces.contains_key(nonce)
    }

    fn record(&self, nonce: FixedBytes<32>) {
        self.nonces.insert(nonce, Instant::now());
    }

    fn try_use(&self, nonce: FixedBytes<32>) -> bool {
        // DashMap's entry API provides atomicity within a single process
        use dashmap::mapref::entry::Entry;
        match self.nonces.entry(nonce) {
            Entry::Occupied(_) => false, // Already used
            Entry::Vacant(v) => {
                v.insert(Instant::now());
                true // Successfully claimed
            }
        }
    }

    fn release(&self, nonce: &FixedBytes<32>) {
        self.nonces.remove(nonce);
    }

    fn purge_expired(&self, max_age_secs: u64) -> usize {
        let before = self.nonces.len();
        self.nonces
            .retain(|_, inserted| inserted.elapsed().as_secs() < max_age_secs);
        before - self.nonces.len()
    }
}

/// Persistent nonce store backed by SQLite. Survives restarts.
pub struct SqliteNonceStore {
    conn: Mutex<rusqlite::Connection>,
}

impl SqliteNonceStore {
    /// Open (or create) a SQLite nonce database at the given path.
    ///
    /// On Unix systems, the database file permissions are restricted to 0600
    /// (owner read/write only) to prevent other users from reading nonce data.
    pub fn open(path: &str) -> Result<Self, rusqlite::Error> {
        let conn = rusqlite::Connection::open(path)?;
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS used_nonces (
                nonce BLOB PRIMARY KEY,
                recorded_at INTEGER NOT NULL
            );
            CREATE INDEX IF NOT EXISTS idx_nonces_recorded_at ON used_nonces(recorded_at);
            PRAGMA journal_mode=WAL;
            PRAGMA wal_autocheckpoint=1000;",
        )?;

        // Restrict file permissions on Unix to owner-only (0600).
        // This prevents other system users from reading the nonce database,
        // which could reveal payment timing information.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Err(e) = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) {
                tracing::warn!(
                    path = %path,
                    error = %e,
                    "failed to set nonce database file permissions to 0600"
                );
            }
        }

        Ok(Self {
            conn: Mutex::new(conn),
        })
    }
}

/// Helper to get current unix timestamp safely.
/// On clock error, returns i64::MAX to ensure nonces are never prematurely purged
/// (fail-secure: nonces recorded with max timestamp will survive any purge cutoff).
fn unix_now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
        .unwrap_or_else(|_| {
            tracing::error!(
                "system clock before UNIX epoch — using max timestamp for nonce safety"
            );
            i64::MAX
        })
}

impl NonceStore for SqliteNonceStore {
    fn is_used(&self, nonce: &FixedBytes<32>) -> bool {
        // Fail-secure: if mutex is poisoned or query fails, assume nonce IS used
        let conn = match self.conn.lock() {
            Ok(c) => c,
            Err(poisoned) => {
                tracing::error!("nonce store mutex poisoned, recovering");
                poisoned.into_inner()
            }
        };
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM used_nonces WHERE nonce = ?1",
                [nonce.as_slice()],
                |row| row.get(0),
            )
            .unwrap_or(1); // Fail-secure: database error = assume nonce is used
        count > 0
    }

    fn record(&self, nonce: FixedBytes<32>) {
        let conn = match self.conn.lock() {
            Ok(c) => c,
            Err(poisoned) => {
                tracing::error!("nonce store mutex poisoned, recovering");
                poisoned.into_inner()
            }
        };
        let now = unix_now();
        if let Err(e) = conn.execute(
            "INSERT OR IGNORE INTO used_nonces (nonce, recorded_at) VALUES (?1, ?2)",
            rusqlite::params![nonce.as_slice(), now],
        ) {
            tracing::warn!(error = %e, "failed to record nonce - may allow replay if try_use also fails");
        }
    }

    fn try_use(&self, nonce: FixedBytes<32>) -> bool {
        // Fail-secure: if mutex is poisoned, reject (return false = nonce "already used")
        let conn = match self.conn.lock() {
            Ok(c) => c,
            Err(poisoned) => {
                tracing::error!("nonce store mutex poisoned, recovering");
                poisoned.into_inner()
            }
        };
        let now = unix_now();
        // INSERT will fail on PRIMARY KEY constraint if nonce exists.
        // This is atomic at the database level, safe across processes.
        match conn.execute(
            "INSERT INTO used_nonces (nonce, recorded_at) VALUES (?1, ?2)",
            rusqlite::params![nonce.as_slice(), now],
        ) {
            Ok(_) => true, // Successfully claimed
            Err(rusqlite::Error::SqliteFailure(err, _))
                if err.code == rusqlite::ffi::ErrorCode::ConstraintViolation =>
            {
                false // Actual duplicate nonce — reject
            }
            Err(e) => {
                // Infrastructure error (disk full, etc.) — log but allow the payment.
                // Better to risk a theoretical replay than to block ALL payments.
                tracing::error!(error = %e, "Nonce store write failed — allowing payment to proceed");
                true
            }
        }
    }

    fn release(&self, nonce: &FixedBytes<32>) {
        let conn = match self.conn.lock() {
            Ok(c) => c,
            Err(poisoned) => {
                tracing::error!("nonce store mutex poisoned, recovering");
                poisoned.into_inner()
            }
        };
        if let Err(e) = conn.execute(
            "DELETE FROM used_nonces WHERE nonce = ?1",
            rusqlite::params![nonce.as_slice()],
        ) {
            tracing::error!(error = %e, "failed to release nonce — it will remain consumed");
        }
    }

    fn purge_expired(&self, max_age_secs: u64) -> usize {
        let conn = match self.conn.lock() {
            Ok(c) => c,
            Err(poisoned) => {
                tracing::error!("nonce store mutex poisoned, recovering");
                poisoned.into_inner()
            }
        };
        let now = unix_now();

        // Guard against backward clock jumps: if now is before the earliest recorded
        // nonce, the system clock has jumped backward. Skip purge to avoid accidentally
        // removing valid nonces.
        let min_recorded: i64 = conn
            .query_row(
                "SELECT COALESCE(MIN(recorded_at), 0) FROM used_nonces",
                [],
                |row| row.get(0),
            )
            .unwrap_or(0);
        if min_recorded > 0 && now < min_recorded {
            tracing::warn!(
                now = now,
                min_recorded = min_recorded,
                "clock appears to have jumped backward — skipping nonce purge"
            );
            return 0;
        }

        // Guard against forward clock jumps: if the newest nonce was recorded recently
        // (within 2x the purge window) but now thinks it's very old, something is wrong.
        // We only check when max_recorded is "recent enough" to indicate active operation
        // — if all entries are genuinely ancient, normal purging should proceed.
        let max_recorded: i64 = conn
            .query_row(
                "SELECT COALESCE(MAX(recorded_at), 0) FROM used_nonces",
                [],
                |row| row.get(0),
            )
            .unwrap_or(0);
        // min_recorded already computed above for backward clock jump check.
        // If there's a wide spread between min and max recorded timestamps AND now is
        // far ahead, a clock jump may have occurred between recording and purging.
        if min_recorded > 0
            && max_recorded > 0
            && max_recorded > min_recorded
            && now.saturating_sub(max_recorded) > (max_age_secs as i64) * 2
        {
            tracing::warn!(
                now = now,
                max_recorded = max_recorded,
                min_recorded = min_recorded,
                "clock appears to have jumped forward — skipping nonce purge"
            );
            return 0;
        }

        // Saturating subtraction: if now is i64::MAX (clock error) or max_age_secs is
        // very large, cutoff saturates instead of wrapping, preventing accidental purge.
        let cutoff = now.saturating_sub(max_age_secs as i64);
        conn.execute(
            "DELETE FROM used_nonces WHERE recorded_at < ?1",
            rusqlite::params![cutoff],
        )
        .unwrap_or(0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy::primitives::FixedBytes;

    #[test]
    fn test_in_memory_store_basic() {
        let store = InMemoryNonceStore::new();
        let nonce = FixedBytes::new([0x42; 32]);

        assert!(!store.is_used(&nonce));
        store.record(nonce);
        assert!(store.is_used(&nonce));
    }

    #[test]
    fn test_sqlite_store_basic() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.db");
        let store = SqliteNonceStore::open(path.to_str().unwrap()).unwrap();
        let nonce = FixedBytes::new([0x42; 32]);

        assert!(!store.is_used(&nonce));
        store.record(nonce);
        assert!(store.is_used(&nonce));
    }

    #[test]
    fn test_sqlite_store_persists() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.db");
        let nonce = FixedBytes::new([0xaa; 32]);

        // Write with one instance
        {
            let store = SqliteNonceStore::open(path.to_str().unwrap()).unwrap();
            store.record(nonce);
            assert!(store.is_used(&nonce));
        }

        // Read with a new instance — must still be there
        {
            let store = SqliteNonceStore::open(path.to_str().unwrap()).unwrap();
            assert!(store.is_used(&nonce));
        }
    }

    #[test]
    fn test_sqlite_store_purge() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.db");
        let store = SqliteNonceStore::open(path.to_str().unwrap()).unwrap();
        let nonce = FixedBytes::new([0xbb; 32]);

        // Manually insert with a very old timestamp
        {
            let conn = store.conn.lock().unwrap();
            conn.execute(
                "INSERT INTO used_nonces (nonce, recorded_at) VALUES (?1, ?2)",
                rusqlite::params![nonce.as_slice(), 1000i64],
            )
            .unwrap();
        }

        assert!(store.is_used(&nonce));
        let purged = store.purge_expired(60);
        assert_eq!(purged, 1);
        assert!(!store.is_used(&nonce));
    }

    #[test]
    fn test_in_memory_store_independent_nonces() {
        let store = InMemoryNonceStore::new();
        let a = FixedBytes::new([0x01; 32]);
        let b = FixedBytes::new([0x02; 32]);

        store.record(a);
        assert!(store.is_used(&a));
        assert!(!store.is_used(&b));
    }

    #[test]
    fn test_sqlite_store_independent_nonces() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.db");
        let store = SqliteNonceStore::open(path.to_str().unwrap()).unwrap();

        let a = FixedBytes::new([0x01; 32]);
        let b = FixedBytes::new([0x02; 32]);

        store.record(a);
        assert!(store.is_used(&a));
        assert!(!store.is_used(&b));
    }

    #[test]
    fn test_in_memory_try_use_atomic() {
        let store = InMemoryNonceStore::new();
        let nonce = FixedBytes::new([0x99; 32]);

        // First try_use should succeed
        assert!(store.try_use(nonce));
        // Second try_use should fail (already used)
        assert!(!store.try_use(nonce));
        // Should be marked as used
        assert!(store.is_used(&nonce));
    }

    #[test]
    fn test_sqlite_try_use_atomic() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.db");
        let store = SqliteNonceStore::open(path.to_str().unwrap()).unwrap();

        let nonce = FixedBytes::new([0x99; 32]);

        // First try_use should succeed
        assert!(store.try_use(nonce));
        // Second try_use should fail (already used)
        assert!(!store.try_use(nonce));
        // Should be marked as used
        assert!(store.is_used(&nonce));
    }
}