rspow 0.5.0

A multi-algorithm proof-of-work library in rust
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use crate::error::Error;
use crate::error::VerifyError;
use crate::near_stateless::cache::ReplayCache;
use crate::near_stateless::prf::DeterministicNonceProvider;
use crate::near_stateless::time::TimeProvider;
use crate::near_stateless::types::{SolveParams, Submission, VerifierConfig};
use crate::near_stateless::{cache::ReplayCacheError, client::derive_master_challenge};
use left_right::{Absorb, ReadHandle, WriteHandle};
use std::sync::{Arc, Mutex};

#[derive(Debug, thiserror::Error)]
pub enum NsError {
    #[error("timestamp too old")]
    StaleTimestamp,
    #[error("timestamp is in the future")]
    FutureTimestamp,
    #[error("replay detected")]
    Replay,
    #[error("master challenge mismatch")]
    MasterChallengeMismatch,
    #[error("verification failed: {0}")]
    Verify(#[from] VerifyError),
    #[error("invalid config: {0}")]
    InvalidConfig(String),
    #[error("replay cache error: {0}")]
    Cache(#[from] ReplayCacheError),
}

/// Update messages for left-right config.
enum ConfigUpdate {
    Set(VerifierConfig),
}

impl Absorb<ConfigUpdate> for VerifierConfig {
    fn absorb_first(&mut self, update: &mut ConfigUpdate, _first: &Self) {
        match update {
            ConfigUpdate::Set(cfg) => *self = cfg.clone(),
        }
    }

    fn sync_with(&mut self, first: &Self) {
        *self = first.clone();
    }
}

/// Server-side verifier helper for near-stateless PoW submissions.
pub struct NearStatelessVerifier<P: DeterministicNonceProvider, C: ReplayCache, T: TimeProvider> {
    config_r: ReadHandle<VerifierConfig>,
    config_w: Mutex<WriteHandle<VerifierConfig, ConfigUpdate>>,
    nonce_provider: Arc<P>,
    replay_cache: Arc<C>,
    time_provider: Arc<T>,
    server_secret: [u8; 32],
}

impl<P, C, T> NearStatelessVerifier<P, C, T>
where
    P: DeterministicNonceProvider + 'static,
    C: ReplayCache + 'static,
    T: TimeProvider + 'static,
{
    pub fn new(
        config: VerifierConfig,
        server_secret: [u8; 32],
        nonce_provider: Arc<P>,
        replay_cache: Arc<C>,
        time_provider: Arc<T>,
    ) -> Result<Self, Error> {
        config.validate()?;
        let (mut config_w, config_r) = left_right::new::<VerifierConfig, ConfigUpdate>();
        config_w.append(ConfigUpdate::Set(config));
        config_w.publish();
        Ok(Self {
            config_r,
            config_w: Mutex::new(config_w),
            nonce_provider,
            replay_cache,
            time_provider,
            server_secret,
        })
    }

    /// Update verifier configuration at runtime.
    pub fn set_config(&self, new_config: VerifierConfig) -> Result<(), Error> {
        new_config.validate()?;
        let mut wh = self.config_w.lock().expect("config writer poisoned");
        wh.append(ConfigUpdate::Set(new_config));
        wh.publish();
        Ok(())
    }

    /// Create parameters to send to a client: timestamp, deterministic nonce, and current config.
    pub fn issue_params(&self) -> SolveParams {
        let ts = self.time_provider.now_seconds();
        let det = self.nonce_provider.derive(self.server_secret, ts);
        let cfg = self
            .config_r
            .enter()
            .map(|g| g.clone())
            .expect("config read handle closed");
        SolveParams {
            timestamp: ts,
            deterministic_nonce: det,
            config: cfg,
        }
    }

    /// Verify a submission against server policy using the provided secret.
    pub fn verify_submission(&self, submission: &Submission) -> Result<(), NsError> {
        let cfg = self
            .config_r
            .enter()
            .map(|g| g.clone())
            .expect("config read handle closed");

        let now = self.time_provider.now_seconds();
        let ts = submission.timestamp;

        if ts > now {
            return Err(NsError::FutureTimestamp);
        }
        let age = std::time::Duration::from_secs(now.saturating_sub(ts));
        if age > cfg.time_window {
            return Err(NsError::StaleTimestamp);
        }

        // Compute expiry for replay cache: ts + window
        let expires_at = ts.saturating_add(cfg.time_window.as_secs());

        // Recompute deterministic nonce and master challenge
        let det_nonce = self.nonce_provider.derive(self.server_secret, ts);
        let master_challenge = derive_master_challenge(det_nonce, submission.client_nonce);

        if submission.proof_bundle.master_challenge != master_challenge {
            return Err(NsError::MasterChallengeMismatch);
        }

        submission
            .proof_bundle
            .verify_strict(cfg.min_difficulty, cfg.min_required_proofs)?;

        let inserted =
            self.replay_cache
                .insert_if_absent(submission.client_nonce, expires_at, now)?;
        if !inserted {
            return Err(NsError::Replay);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::equix::engine::EquixEngineBuilder;
    use crate::near_stateless::client::{
        build_submission, solve_submission, solve_submission_from_params,
    };
    use crate::near_stateless::prf::DeterministicNonceProvider;
    use crate::near_stateless::time::TimeProvider;
    use crate::pow::PowEngine;
    use std::collections::HashMap;
    use std::sync::atomic::AtomicU64;

    #[derive(Default, Clone)]
    struct MapReplayCache {
        map: Arc<Mutex<HashMap<[u8; 32], u64>>>,
    }

    impl ReplayCache for MapReplayCache {
        fn insert_if_absent(
            &self,
            client_nonce: [u8; 32],
            expires_at: u64,
            now: u64,
        ) -> Result<bool, ReplayCacheError> {
            let mut map = self.map.lock().unwrap();
            if let Some(exp) = map.get(&client_nonce) {
                if *exp > now {
                    return Ok(false);
                }
            }
            map.insert(client_nonce, expires_at);
            Ok(true)
        }
    }

    #[derive(Clone, Copy, Default)]
    struct TestNonceProvider;

    impl DeterministicNonceProvider for TestNonceProvider {
        fn derive(&self, secret: [u8; 32], ts: u64) -> [u8; 32] {
            let mut out = secret;
            out[..8].copy_from_slice(&ts.to_le_bytes());
            out
        }
    }

    #[derive(Clone, Copy)]
    struct FixedTimeProvider {
        now: u64,
    }

    impl TimeProvider for FixedTimeProvider {
        fn now_seconds(&self) -> u64 {
            self.now
        }
    }

    fn make_engine(bits: u32, required: usize) -> EquixEngineBuilder {
        EquixEngineBuilder::default()
            .bits(bits)
            .threads(1)
            .required_proofs(required)
            .progress(Arc::new(AtomicU64::new(0)))
    }

    fn solve_one(
        engine: &mut crate::equix::engine::EquixEngine,
        det: [u8; 32],
        client_nonce: [u8; 32],
        ts: u64,
    ) -> Submission {
        solve_submission(engine, ts, det, client_nonce).expect("solve should succeed")
    }

    fn verifier_with(
        cfg: VerifierConfig,
        time: impl TimeProvider + 'static,
        replay: impl ReplayCache + 'static,
    ) -> NearStatelessVerifier<TestNonceProvider, impl ReplayCache, impl TimeProvider> {
        NearStatelessVerifier::new(
            cfg,
            [42u8; 32],
            Arc::new(TestNonceProvider),
            Arc::new(replay),
            Arc::new(time),
        )
        .expect("config should be valid")
    }

    #[test]
    fn config_rejects_subsecond_window() {
        let cfg = VerifierConfig {
            time_window: std::time::Duration::from_millis(900),
            min_difficulty: 1,
            min_required_proofs: 1,
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn config_rejects_non_integer_seconds() {
        let cfg = VerifierConfig {
            time_window: std::time::Duration::from_millis(1_500),
            ..Default::default()
        };
        assert!(cfg.validate().is_err());
    }

    #[test]
    fn verify_submission_happy_path() {
        let mut engine = make_engine(1, 1).build_validated().unwrap();
        let cfg = VerifierConfig {
            time_window: std::time::Duration::from_secs(10),
            ..Default::default()
        };
        let ts = 1_000;
        let now = 1_004;
        let det = TestNonceProvider.derive([42u8; 32], ts);
        let client_nonce = [7u8; 32];
        let submission = solve_one(&mut engine, det, client_nonce, ts);

        let verifier = verifier_with(cfg, FixedTimeProvider { now }, MapReplayCache::default());

        assert!(verifier.verify_submission(&submission).is_ok());
    }

    #[test]
    fn rejects_future_timestamp() {
        let mut engine = make_engine(1, 1).build_validated().unwrap();
        let ts = 10;
        let det = TestNonceProvider.derive([1u8; 32], ts);
        let submission = solve_one(&mut engine, det, [2u8; 32], ts);
        let verifier = verifier_with(
            VerifierConfig::default(),
            FixedTimeProvider { now: 5 },
            MapReplayCache::default(),
        );

        match verifier.verify_submission(&submission) {
            Err(NsError::FutureTimestamp) => {}
            other => panic!("expected future timestamp, got {:?}", other),
        }
    }

    #[test]
    fn rejects_stale_timestamp() {
        let mut engine = make_engine(1, 1).build_validated().unwrap();
        let cfg = VerifierConfig {
            time_window: std::time::Duration::from_secs(5),
            ..Default::default()
        };
        let ts = 10;
        let det = TestNonceProvider.derive([3u8; 32], ts);
        let submission = solve_one(&mut engine, det, [4u8; 32], ts);
        let verifier = verifier_with(
            cfg,
            FixedTimeProvider { now: 16 },
            MapReplayCache::default(),
        );

        match verifier.verify_submission(&submission) {
            Err(NsError::StaleTimestamp) => {}
            other => panic!("expected stale, got {:?}", other),
        }
    }

    #[test]
    fn accepts_window_lower_bound_inclusively() {
        let mut engine = make_engine(1, 1).build_validated().unwrap();
        let cfg = VerifierConfig {
            time_window: std::time::Duration::from_secs(5),
            ..Default::default()
        };
        // ts exactly at now - window
        let ts = 10;
        let det = TestNonceProvider.derive([42u8; 32], ts);
        let submission = solve_one(&mut engine, det, [41u8; 32], ts);
        let verifier = verifier_with(
            cfg,
            FixedTimeProvider { now: 15 },
            MapReplayCache::default(),
        );

        assert!(verifier.verify_submission(&submission).is_ok());
    }

    #[test]
    fn detects_replay() {
        let mut engine = make_engine(1, 1).build_validated().unwrap();
        let cfg = VerifierConfig {
            time_window: std::time::Duration::from_secs(10),
            ..Default::default()
        };
        let ts = 100;
        let det = TestNonceProvider.derive([42u8; 32], ts);
        let submission = solve_one(&mut engine, det, [6u8; 32], ts);
        let verifier = verifier_with(
            cfg,
            FixedTimeProvider { now: 103 },
            MapReplayCache::default(),
        );

        verifier
            .verify_submission(&submission)
            .expect("first verify should succeed");

        match verifier.verify_submission(&submission) {
            Err(NsError::Replay) => {}
            other => panic!("expected replay, got {:?}", other),
        }
    }

    #[test]
    fn config_update_applies_to_verification() {
        let mut engine = make_engine(1, 1).build_validated().unwrap();
        let ts = 200;
        let det = TestNonceProvider.derive([42u8; 32], ts);
        let submission = solve_one(&mut engine, det, [9u8; 32], ts);
        let verifier = verifier_with(
            VerifierConfig {
                time_window: std::time::Duration::from_secs(10),
                ..Default::default()
            },
            FixedTimeProvider { now: 205 },
            MapReplayCache::default(),
        );

        let new_cfg = VerifierConfig {
            time_window: std::time::Duration::from_secs(10),
            min_required_proofs: 2,
            ..Default::default()
        };
        verifier.set_config(new_cfg).unwrap();

        match verifier.verify_submission(&submission) {
            Err(NsError::Verify(VerifyError::InvalidDifficulty)) => {}
            other => panic!("expected difficulty error, got {:?}", other),
        }
    }

    #[test]
    fn master_challenge_mismatch_is_rejected() {
        let mut engine = make_engine(1, 1).build_validated().unwrap();
        let ts = 50;
        let det = TestNonceProvider.derive([11u8; 32], ts);
        let submission = solve_one(&mut engine, det, [12u8; 32], ts);
        let verifier = verifier_with(
            VerifierConfig {
                time_window: std::time::Duration::from_secs(10),
                ..Default::default()
            },
            FixedTimeProvider { now: 55 },
            MapReplayCache::default(),
        );

        match verifier.verify_submission(&submission) {
            Err(NsError::MasterChallengeMismatch) => {}
            other => panic!("expected mismatch, got {:?}", other),
        }
    }

    #[test]
    fn build_submission_is_equivalent_to_struct_literal() {
        let mut engine = make_engine(1, 1).build_validated().unwrap();
        let ts = 70;
        let det = TestNonceProvider.derive([13u8; 32], ts);
        let client_nonce = [14u8; 32];
        let master = derive_master_challenge(det, client_nonce);
        let bundle = engine.solve_bundle(master).expect("solve should succeed");

        let via_helper = build_submission(ts, client_nonce, bundle.clone());
        let direct = Submission {
            timestamp: ts,
            client_nonce,
            proof_bundle: bundle,
        };

        assert_eq!(via_helper.timestamp, direct.timestamp);
        assert_eq!(via_helper.client_nonce, direct.client_nonce);
        assert_eq!(
            via_helper.proof_bundle.proofs.len(),
            direct.proof_bundle.proofs.len()
        );
    }

    #[test]
    fn issue_params_and_solve_round_trip() {
        let cfg = VerifierConfig {
            time_window: std::time::Duration::from_secs(10),
            min_difficulty: 1,
            min_required_proofs: 1,
        };
        let mut engine = make_engine(1, 1).build_validated().unwrap();
        let verifier = verifier_with(
            cfg.clone(),
            FixedTimeProvider { now: 1_000 },
            MapReplayCache::default(),
        );

        let params = verifier.issue_params();
        assert_eq!(params.config, cfg);
        assert_eq!(params.timestamp, 1_000);

        let client_nonce = [77u8; 32];
        let submission = solve_submission_from_params(&mut engine, &params, client_nonce)
            .expect("solve from params");

        assert_eq!(submission.timestamp, params.timestamp);
        assert_eq!(submission.client_nonce, client_nonce);

        verifier
            .verify_submission(&submission)
            .expect("round-trip verify");
    }
}