nym_api_requests/models/network_monitor.rs
1// Copyright 2025 - Nym Technologies SA <contact@nymtech.net>
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::pagination::PaginatedResponse;
5use nym_crypto::asymmetric::ed25519;
6use nym_crypto::asymmetric::ed25519::serde_helpers::bs58_ed25519_pubkey;
7use nym_mixnet_contract_common::NodeId;
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use std::collections::BTreeMap;
11use utoipa::ToSchema;
12
13#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, Default, ToSchema)]
14pub struct TestNode {
15 pub node_id: Option<u32>,
16 pub identity_key: Option<String>,
17}
18
19#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
20pub struct TestRoute {
21 pub gateway: TestNode,
22 pub layer1: TestNode,
23 pub layer2: TestNode,
24 pub layer3: TestNode,
25}
26
27#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
28pub struct PartialTestResult {
29 pub monitor_run_id: i64,
30 pub timestamp: i64,
31 pub overall_reliability_for_all_routes_in_monitor_run: Option<u8>,
32 pub test_routes: TestRoute,
33}
34
35pub type MixnodeTestResultResponse = PaginatedResponse<PartialTestResult>;
36pub type GatewayTestResultResponse = PaginatedResponse<PartialTestResult>;
37
38#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
39pub struct NetworkMonitorRunDetailsResponse {
40 pub monitor_run_id: i64,
41 pub network_reliability: f64,
42 pub total_sent: usize,
43 pub total_received: usize,
44
45 // integer score to number of nodes with that score
46 pub mixnode_results: BTreeMap<u8, usize>,
47 pub gateway_results: BTreeMap<u8, usize>,
48}
49
50#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)]
51#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
52#[cfg_attr(
53 feature = "generate-ts",
54 ts(
55 export,
56 export_to = "ts-packages/types/src/types/rust/MixnodeCoreStatusResponse.ts"
57 )
58)]
59pub struct MixnodeCoreStatusResponse {
60 pub mix_id: NodeId,
61 pub count: i64,
62}
63
64#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)]
65#[cfg_attr(feature = "generate-ts", derive(ts_rs::TS))]
66#[cfg_attr(
67 feature = "generate-ts",
68 ts(
69 export,
70 export_to = "ts-packages/types/src/types/rust/GatewayCoreStatusResponse.ts"
71 )
72)]
73pub struct GatewayCoreStatusResponse {
74 pub identity: String,
75 pub count: i64,
76}
77
78/// Request/response types for the v3 network-monitor flow, in which an orchestrator submits
79/// stress testing results to nym-api via signed batches.
80pub mod v3 {
81 use super::*;
82 use crate::models::described::v3::DeclaredRolesV3;
83 use crate::models::{DisplayRole, OffsetDateTimeJsonSchemaWrapper};
84 use crate::signable::SignedMessage;
85 use nym_mixnet_contract_common::EpochId;
86 use std::time::Duration;
87 use time::OffsetDateTime;
88
89 /// Signed envelope posted by a network monitor orchestrator to
90 /// `POST /v3/nym-nodes/stress-testing/batch-submit`.
91 ///
92 /// The signature is checked against the `signer` field of the inner
93 /// [`StressTestBatchSubmissionContent`], which must also match one of the orchestrators
94 /// registered in the network-monitors contract.
95 pub type StressTestBatchSubmission = SignedMessage<StressTestBatchSubmissionContent>;
96
97 /// Confirmation returned to an orchestrator after a successful submission, reporting what
98 /// became of the individual results. The three counts sum to the number of results submitted.
99 ///
100 /// Reporting these matters because an accepted batch can still store nothing: rows deduplicate
101 /// at the database with insert-or-ignore semantics, so without a count the submitter cannot
102 /// distinguish "stored" from "silently discarded" - both are a `200`.
103 ///
104 /// Every field is optional so that a newer orchestrator can still read the empty body returned
105 /// by a nym-api predating these counts. `None` therefore means "not reported", which is a
106 /// different signal from `Some(0)`.
107 #[derive(Clone, Debug, Default, Serialize, Deserialize, ToSchema)]
108 pub struct BatchSubmissionResponse {
109 /// Results newly stored by this submission.
110 #[serde(default)]
111 pub accepted: Option<usize>,
112
113 /// Results that were already stored, i.e. this submission re-sent a measurement nym-api had
114 /// seen before. Expected to be non-zero on the orchestrator's at-least-once retry path; a
115 /// persistently non-zero value means measurements are being discarded.
116 #[serde(default)]
117 pub duplicates: Option<usize>,
118
119 /// Results dropped by per-entry validation (an entry whose role the endpoint does not
120 /// accept, or a performance score outside `[0.0, 1.0]`).
121 #[serde(default)]
122 pub rejected: Option<usize>,
123 }
124
125 /// Both batch endpoints report the same three counts, so they share one body rather than
126 /// carrying two structurally identical types that could drift apart.
127 pub type StressTestBatchSubmissionResponse = BatchSubmissionResponse;
128 pub type LivenessTestBatchSubmissionResponse = BatchSubmissionResponse;
129
130 /// Single stress-test measurement for one node, produced by a network monitor orchestrator.
131 #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
132 pub struct StressTestResult {
133 /// Orchestrator-local id of the test run that produced this result. Combined with the
134 /// batch's `signer` it uniquely identifies the measurement, allowing nym-api to dedupe
135 /// retried submissions on the at-least-once delivery path.
136 pub testrun_id: i64,
137
138 /// Contract-assigned id of the node that was tested.
139 pub node_id: NodeId,
140
141 /// Whether the tested node was acting as a mixnode during the measurement.
142 ///
143 /// Included explicitly (rather than inferred from on-chain role) so the API can reject or
144 /// route entries that don't match the expected role without re-querying the contract.
145 pub is_mixnode: bool,
146
147 #[schema(value_type = String)]
148 #[serde(with = "time::serde::rfc3339")]
149 pub test_timestamp: OffsetDateTime,
150
151 /// Measured performance score in the `[0.0, 1.0]` range.
152 pub test_performance: f64,
153
154 /// Whether the node responded at all during testing.
155 ///
156 /// Recorded alongside `test_performance` so that a genuine 0.0 score (node responded but
157 /// dropped everything) can be distinguished from the node being offline entirely.
158 pub was_reachable: bool,
159 }
160
161 /// Body of a stress-test batch submission, signed by a network monitor orchestrator.
162 #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
163 pub struct StressTestBatchSubmissionContent {
164 /// ed25519 identity key of the submitting orchestrator. Must match an entry in the
165 /// network-monitors contract for the batch to be accepted.
166 #[schema(value_type = String)]
167 #[serde(with = "ed25519::bs58_ed25519_pubkey")]
168 pub signer: ed25519::PublicKey,
169
170 /// Time at which this batch was produced. Also used as a monotonic nonce for replay
171 /// protection: the API rejects submissions whose timestamp is not strictly greater than
172 /// the orchestrator's previous accepted submission.
173 #[schema(value_type = String)]
174 #[serde(with = "time::serde::rfc3339")]
175 pub timestamp: OffsetDateTime,
176
177 pub results: Vec<StressTestResult>,
178 }
179
180 impl StressTestBatchSubmissionContent {
181 /// Build a batch submission body stamped with the current UTC time.
182 pub fn new(signer: ed25519::PublicKey, results: Vec<StressTestResult>) -> Self {
183 StressTestBatchSubmissionContent {
184 signer,
185 timestamp: OffsetDateTime::now_utc(),
186 results,
187 }
188 }
189
190 /// Whether this submission is older than `max_age` relative to the current UTC time.
191 ///
192 /// Used server-side to reject submissions that have been sitting around too long, even if
193 /// they are otherwise well-formed and correctly signed.
194 pub fn is_stale(&self, max_age: Duration) -> bool {
195 self.timestamp + max_age < OffsetDateTime::now_utc()
196 }
197 }
198
199 /// Signed envelope posted by a network monitor orchestrator to
200 /// `POST /v3/nym-nodes/liveness-testing/batch-submit`.
201 ///
202 /// Liveness has its OWN endpoint rather than sharing the stress one because nym-api keeps a
203 /// per-signer replay high-water mark per endpoint: two streams signed by the same orchestrator
204 /// and validated against one shared mark would reject each other indefinitely.
205 pub type LivenessTestBatchSubmission = SignedMessage<LivenessTestBatchSubmissionContent>;
206
207 /// Single liveness measurement for one node, produced by a network monitor orchestrator.
208 #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
209 pub struct LivenessTestResult {
210 /// Orchestrator-local id of the test run that produced this result. Combined with the
211 /// batch's `signer` it uniquely identifies the measurement, allowing nym-api to dedupe
212 /// retried submissions on the at-least-once delivery path.
213 pub testrun_id: i64,
214
215 /// Contract-assigned id of the node that was tested.
216 pub node_id: NodeId,
217
218 #[schema(value_type = String)]
219 #[serde(with = "time::serde::rfc3339")]
220 pub test_timestamp: OffsetDateTime,
221
222 /// Score for the run: the average over the fixed set of interfaces its probe exercises,
223 /// with an interface that produced no measurement counted as zero. A mixnode probe
224 /// exercises one interface and a gateway probe two, so this single ratio is the whole
225 /// submission shape for both - identical for every role.
226 ///
227 /// The average is computed orchestrator-side and CANNOT be recomputed here: its
228 /// denominator is the set the run's (kind, role) pairing is expected to produce, which
229 /// this submission deliberately does not carry, so a run missing one of its interfaces
230 /// would average over the wrong denominator on this side. The orchestrator knows the
231 /// expected set from the row it stored, so it averages there.
232 ///
233 /// The per-interface breakdown behind this number stays on the orchestrator, which keeps
234 /// it under the run's row and serves it on its own read surface. It is deliberately NOT
235 /// submitted: nym-api scores on the average alone, and a submission shape carrying figures
236 /// nothing reads would have to be versioned before it could be trusted - the same reason
237 /// the latency distribution is not submitted either. Telling a gateway with a dead
238 /// delivery apart from a uniformly half-lossy one is therefore a lookup against the
239 /// orchestrator, not a question nym-api can answer.
240 pub test_performance: f64,
241
242 /// Whether the node responded at all during testing.
243 ///
244 /// Recorded alongside `test_performance` so that a genuine 0.0 score (node responded but
245 /// dropped everything) can be distinguished from the node being offline entirely.
246 pub was_reachable: bool,
247 }
248
249 /// Body of a liveness batch submission, signed by a network monitor orchestrator.
250 #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
251 pub struct LivenessTestBatchSubmissionContent {
252 /// ed25519 identity key of the submitting orchestrator. Must match an entry in the
253 /// network-monitors contract for the batch to be accepted.
254 #[schema(value_type = String)]
255 #[serde(with = "ed25519::bs58_ed25519_pubkey")]
256 pub signer: ed25519::PublicKey,
257
258 /// Time at which this batch was produced. Also used as a monotonic nonce for replay
259 /// protection: the API rejects submissions whose timestamp is not strictly greater than
260 /// the orchestrator's previous accepted submission ON THIS ENDPOINT.
261 #[schema(value_type = String)]
262 #[serde(with = "time::serde::rfc3339")]
263 pub timestamp: OffsetDateTime,
264
265 pub results: Vec<LivenessTestResult>,
266 }
267
268 impl LivenessTestBatchSubmissionContent {
269 /// Whether this submission is older than `max_age` relative to the current UTC time.
270 ///
271 /// Used server-side to reject submissions that have been sitting around too long, even if
272 /// they are otherwise well-formed and correctly signed.
273 pub fn is_stale(&self, max_age: Duration) -> bool {
274 self.timestamp + max_age < OffsetDateTime::now_utc()
275 }
276 }
277
278 /// Which role or roles a node declares, so a divergence row can be read against the probe
279 /// that produced it. The two liveness probes share no machinery, and a mixnode's divergence
280 /// has nothing in common with a gateway's.
281 ///
282 /// `Both` labels the NODE, not the measurement: a dual-role node's stored liveness score
283 /// already averages its mixnode and gateway runs together, so its divergence cannot be
284 /// attributed to one path or the other.
285 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
286 #[serde(rename_all = "snake_case")]
287 pub enum DivergenceNodeRole {
288 Mixnode,
289 Gateway,
290 Both,
291 }
292
293 /// One node's liveness score set against the v1 monitor's routing score for the same node.
294 #[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema, ToSchema)]
295 pub struct NodeLivenessDivergence {
296 #[schema(value_type = u32)]
297 pub node_id: NodeId,
298
299 /// Aggregated v3 liveness score over the configured window, in `[0.0, 1.0]`.
300 pub liveness_score: f64,
301
302 /// The v1 monitor's routing score for the same node, in `[0.0, 1.0]`.
303 pub routing_score: f64,
304
305 /// `liveness_score - routing_score`. NEGATIVE means liveness scores the node WORSE than
306 /// v1 routing does, which is the expected direction while the fleet is mid-upgrade: a node
307 /// that has not ingested its agents' on-chain authorisations, or a gateway not yet
308 /// carrying the monitor-session behaviour, scores zero on liveness for reasons unrelated
309 /// to its forwarding. Reading the sign the other way inverts the whole gauge.
310 pub divergence: f64,
311
312 /// Whether any liveness sample in the window reached the node at all. `false` with a
313 /// `liveness_score` of zero means never measured, which is a different finding from a node
314 /// that answered and delivered nothing.
315 pub was_reachable: bool,
316
317 pub role: DivergenceNodeRole,
318 }
319
320 /// Response body for the liveness divergence gauge.
321 ///
322 /// Every liveness-ELIGIBLE bonded node appears, including those with no sample yet, so that
323 /// coverage is readable off the same response as the comparison: deciding whether to give
324 /// liveness a non-zero weight needs both how much of the fleet has been measured and how the
325 /// measured part compares.
326 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)]
327 pub struct LivenessDivergenceResponse {
328 /// Oldest of the caches this was assembled from, so the figures' age is visible.
329 pub refreshed_at: OffsetDateTimeJsonSchemaWrapper,
330
331 pub nodes: Vec<NodeLivenessDivergence>,
332 }
333
334 /// Which way nym-api's figure and the performance contract's differ for a node, the first
335 /// that matches in declaration order.
336 #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema)]
337 #[serde(rename_all = "snake_case")]
338 pub enum ContractDivergenceCategory {
339 /// nym-api scores the node above zero; the contract has no source for it.
340 Missing,
341
342 /// nym-api has no annotation for the node; the contract scores it.
343 ContractOnly,
344
345 /// The contract has a source for the node but cannot score it.
346 Unscoreable,
347
348 /// The contract's figure comes from an epoch before the current one.
349 Fallback,
350
351 /// The two figures differ by at least the threshold.
352 Divergent,
353
354 Agree,
355 }
356
357 /// Nodes in one category, in total and per declared role. A node counts under every role it
358 /// declares, and one nym-api has not described counts in the total only.
359 #[derive(
360 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema,
361 )]
362 pub struct ContractDivergenceCounts {
363 pub total: usize,
364 pub mixnode: usize,
365 pub entry: usize,
366 pub exit: usize,
367 }
368
369 #[derive(
370 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, ToSchema,
371 )]
372 pub struct ContractDivergenceCategoryCounts {
373 pub missing: ContractDivergenceCounts,
374 pub contract_only: ContractDivergenceCounts,
375 pub unscoreable: ContractDivergenceCounts,
376 pub fallback: ContractDivergenceCounts,
377 pub divergent: ContractDivergenceCounts,
378 pub agree: ContractDivergenceCounts,
379 }
380
381 impl ContractDivergenceCounts {
382 /// Counts one node under every role it declares, and an undescribed one in the total only.
383 pub fn add(&mut self, declared_roles: Option<&DeclaredRolesV3>) {
384 self.total += 1;
385 let Some(roles) = declared_roles else {
386 return;
387 };
388 if roles.mixnode {
389 self.mixnode += 1;
390 }
391 if roles.entry {
392 self.entry += 1;
393 }
394 if roles.can_operate_exit_gateway() {
395 self.exit += 1;
396 }
397 }
398 }
399
400 impl ContractDivergenceCategoryCounts {
401 pub fn category_mut(
402 &mut self,
403 category: ContractDivergenceCategory,
404 ) -> &mut ContractDivergenceCounts {
405 match category {
406 ContractDivergenceCategory::Missing => &mut self.missing,
407 ContractDivergenceCategory::ContractOnly => &mut self.contract_only,
408 ContractDivergenceCategory::Unscoreable => &mut self.unscoreable,
409 ContractDivergenceCategory::Fallback => &mut self.fallback,
410 ContractDivergenceCategory::Divergent => &mut self.divergent,
411 ContractDivergenceCategory::Agree => &mut self.agree,
412 }
413 }
414 }
415
416 /// nym-api's own figure for a node, from its annotation.
417 #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema, ToSchema)]
418 pub struct NymApiFigure {
419 pub performance: f64,
420 pub routing_score: f64,
421 pub config_score: f64,
422 }
423
424 /// The performance contract's figure for a node at the current epoch, with the medians it
425 /// was scored from.
426 #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema, ToSchema)]
427 pub struct NodeContractFigure {
428 /// The epoch of the bundle the figure resolved to.
429 #[schema(value_type = u32)]
430 pub source_epoch: EpochId,
431
432 pub score: Option<f64>,
433 pub liveness: Option<f64>,
434 pub stress: Option<f64>,
435 pub config: Option<f64>,
436 }
437
438 /// What nym-api's describe cache says about a node, carried on `missing` rows to tell the
439 /// groups the orchestrator cannot describe apart.
440 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema, ToSchema)]
441 pub struct DescribedNodeDetails {
442 pub version: String,
443 pub mixnode: bool,
444 pub entry: bool,
445 pub exit: bool,
446 }
447
448 /// One node whose figures do not agree.
449 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)]
450 pub struct NodeContractDivergence {
451 #[schema(value_type = u32)]
452 pub node_id: NodeId,
453
454 pub category: ContractDivergenceCategory,
455
456 /// Absent when nym-api has no annotation for the node.
457 pub nym_api: Option<NymApiFigure>,
458
459 /// Absent when the contract has no source for the node.
460 pub contract: Option<NodeContractFigure>,
461
462 /// The node's role in the current rewarded set, if it has one.
463 pub rewarded_set_role: Option<DisplayRole>,
464
465 /// Present on `missing` rows only.
466 pub described: Option<DescribedNodeDetails>,
467 }
468
469 /// Response body for the contract divergence gauge.
470 ///
471 /// TEMPORARY: it exists for the shadow period before rewarding switches to the performance
472 /// contract, and is deleted afterwards.
473 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, ToSchema)]
474 pub struct ContractDivergenceResponse {
475 /// Oldest of the caches this was assembled from, so the figures' age is visible.
476 pub refreshed_at: OffsetDateTimeJsonSchemaWrapper,
477
478 /// The current epoch, at which the contract's figures are resolved.
479 #[schema(value_type = u32)]
480 pub epoch_id: EpochId,
481
482 /// The difference at which two figures count as divergent.
483 pub threshold: f64,
484
485 pub counts: ContractDivergenceCategoryCounts,
486
487 /// Every node not in agreement.
488 pub nodes: Vec<NodeContractDivergence>,
489 }
490
491 /// Response body for `GET /v3/nym-nodes/stress-testing/known-monitors/{identity_key}`,
492 /// used by orchestrators to check whether this nym-api currently recognises their key.
493 #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
494 pub struct KnownNetworkMonitorResponse {
495 /// The ed25519 identity key that was queried (base58-encoded on the wire).
496 #[serde(with = "bs58_ed25519_pubkey")]
497 #[schema(value_type = String)]
498 pub identity_key: ed25519::PublicKey,
499
500 /// Whether the queried identity key is currently recognised by this nym-api
501 /// as an authorised network monitor permitted to submit stress testing results.
502 pub authorised: bool,
503 }
504
505 #[cfg(test)]
506 mod tests {
507 use super::*;
508 use crate::signable::SignableMessageBody;
509 use nym_test_utils::helpers::deterministic_rng;
510 use time::macros::datetime;
511
512 fn dummy_liveness_results() -> Vec<LivenessTestResult> {
513 // Order-distinguishable entries, as in the stress body: `testrun_id` is the order
514 // witness, so a permuting deserialisation would break the signature check below.
515 vec![
516 // a gateway run, whose score averages its two interfaces - the shape is the same
517 // as a mixnode's, since the interfaces averaged over never reach the wire
518 LivenessTestResult {
519 testrun_id: 1,
520 node_id: 42,
521 test_timestamp: datetime!(2026-06-01 12:34:56.123456789 UTC),
522 test_performance: 0.5,
523 was_reachable: true,
524 },
525 // a mixnode run: one interface, so the score is that interface's ratio
526 LivenessTestResult {
527 testrun_id: 2,
528 node_id: 7,
529 test_timestamp: datetime!(2026-06-01 12:34:56 UTC),
530 test_performance: 0.97,
531 was_reachable: true,
532 },
533 ]
534 }
535
536 // Same hazard as the stress body: if JSON serialisation is not a byte-exact fixed point,
537 // no liveness batch could ever pass nym-api's signature check. Kept separate from the
538 // stress test because the two bodies are independent types on independent endpoints, and
539 // a float or timestamp encoding change would have to break both to be caught by one.
540 #[test]
541 fn signed_liveness_batch_roundtrips_and_is_a_byte_exact_fixed_point() {
542 let mut rng = deterministic_rng();
543 let keys = ed25519::KeyPair::new(&mut rng);
544
545 let body = LivenessTestBatchSubmissionContent {
546 signer: *keys.public_key(),
547 timestamp: datetime!(2026-06-01 12:34:56.123456789 UTC),
548 results: dummy_liveness_results(),
549 };
550
551 let signed_bytes = body.plaintext();
552 let signed = body.clone().sign(keys.private_key());
553
554 let bytes = serde_json::to_vec(&signed).unwrap();
555 let deserialised: LivenessTestBatchSubmission = serde_json::from_slice(&bytes).unwrap();
556 assert!(
557 deserialised.verify_signature(&deserialised.body.signer),
558 "signature failed to verify after a JSON round-trip"
559 );
560
561 // re-serialising the parsed body must reproduce the signed bytes verbatim
562 assert_eq!(signed_bytes, deserialised.body.plaintext());
563
564 // the results keep their order, so the scores stay attached to the right nodes
565 let ids: Vec<_> = deserialised
566 .body
567 .results
568 .iter()
569 .map(|result| (result.testrun_id, result.node_id))
570 .collect();
571 assert_eq!(ids, vec![(1, 42), (2, 7)]);
572 }
573
574 fn dummy_results() -> Vec<StressTestResult> {
575 // Order-distinguishable entries: if deserialisation ever permuted the array, the
576 // re-serialised body would no longer match the signed bytes, and `verify_signature`
577 // would return false. `testrun_id` is the order witness.
578 vec![
579 StressTestResult {
580 testrun_id: 1,
581 node_id: 42,
582 is_mixnode: true,
583 test_timestamp: datetime!(2026-06-01 12:34:56.123456789 UTC),
584 test_performance: 0.6666666666666666,
585 was_reachable: true,
586 },
587 StressTestResult {
588 testrun_id: 2,
589 node_id: 7,
590 is_mixnode: true,
591 test_timestamp: datetime!(2026-06-01 12:34:56 UTC),
592 test_performance: 0.0,
593 was_reachable: false,
594 },
595 StressTestResult {
596 testrun_id: 3,
597 node_id: u32::MAX,
598 is_mixnode: true,
599 test_timestamp: datetime!(2026-06-01 12:34:56.999999999 UTC),
600 test_performance: 1.0,
601 was_reachable: true,
602 },
603 ]
604 }
605
606 // Integrity check on the wire is `serde_json::to_vec(deserialize(serde_json::to_vec(body)))
607 // == serde_json::to_vec(body)`. If JSON serialisation isn't a fixed point, every batch
608 // submission would fail nym-api's signature verification. Cover the timestamp shapes the
609 // orchestrator actually produces, including the `+1ns` bump from the monotonicity safeguard.
610 #[test]
611 fn signed_batch_submission_roundtrips_through_json() {
612 let mut rng = deterministic_rng();
613 let keys = ed25519::KeyPair::new(&mut rng);
614
615 let timestamps = [
616 datetime!(2026-06-01 12:34:56 UTC),
617 datetime!(2026-06-01 12:34:56.000000001 UTC),
618 datetime!(2026-06-01 12:34:56.999999999 UTC),
619 datetime!(2026-06-01 12:34:56.123456789 UTC),
620 OffsetDateTime::now_utc(),
621 OffsetDateTime::now_utc() + time::Duration::NANOSECOND,
622 ];
623
624 for timestamp in timestamps {
625 let body = StressTestBatchSubmissionContent {
626 signer: *keys.public_key(),
627 timestamp,
628 results: dummy_results(),
629 };
630 let signed = body.clone().sign(keys.private_key());
631
632 let bytes = serde_json::to_vec(&signed).unwrap();
633 let deserialised: StressTestBatchSubmission =
634 serde_json::from_slice(&bytes).unwrap();
635
636 // The handler verifies against `body.body.signer` — match that exactly.
637 assert!(
638 deserialised.verify_signature(&deserialised.body.signer),
639 "signature failed to verify after JSON round-trip for timestamp {timestamp}",
640 );
641 assert_eq!(deserialised.body.timestamp, timestamp);
642 }
643 }
644
645 // Every f64 that the orchestrator's `received as f64 / sent as f64` formula can produce
646 // (storage/models.rs) must round-trip byte-exactly through JSON. Exhaustively cover the
647 // range and exercise sent values that produce non-terminating fractions (1/3, 1/7, ...).
648 #[test]
649 fn computed_test_performance_values_roundtrip() {
650 for sent in 1u64..=200 {
651 for received in 0u64..=(sent * 2) {
652 let perf = received as f64 / sent as f64;
653 let s = serde_json::to_string(&perf).unwrap();
654 let perf2: f64 = serde_json::from_str(&s).unwrap();
655 let s2 = serde_json::to_string(&perf2).unwrap();
656 assert_eq!(
657 s, s2,
658 "f64 round-trip mismatch for {received}/{sent} = {perf}: {s} -> {s2}",
659 );
660 }
661 }
662 }
663
664 // serde_json serialises non-finite f64 as `null`. Confirm what the deserialiser does with
665 // `null` for a struct field typed as f64 - if it succeeds with a default value (rather than
666 // erroring), a NaN/Infinity test_performance could silently break signature verification
667 // because the re-serialised body would no longer have `null` at that position.
668 #[test]
669 fn non_finite_test_performance_breaks_loudly_not_silently() {
670 let nan_result = StressTestResult {
671 testrun_id: 1,
672 node_id: 1,
673 is_mixnode: true,
674 test_timestamp: datetime!(2026-06-01 12:34:56 UTC),
675 test_performance: f64::NAN,
676 was_reachable: true,
677 };
678 let json = serde_json::to_string(&nan_result).unwrap();
679 // NaN serialises as `null` - this is the dangerous shape
680 assert!(
681 json.contains(r#""test_performance":null"#),
682 "expected NaN to serialise as null: {json}",
683 );
684 // ...and `null` MUST fail to deserialise rather than silently becoming 0.0 / default;
685 // if this ever changes, NaN would silently corrupt signature verification.
686 let deserialised: Result<StressTestResult, _> = serde_json::from_str(&json);
687 assert!(
688 deserialised.is_err(),
689 "deserialising null into f64 unexpectedly succeeded - signature verification \
690 would silently fail for any submission containing a non-finite test_performance",
691 );
692 }
693
694 // Specifically pin the two hypotheses we want to rule out:
695 // 1. Vec<StressTestResult> serialisation/deserialisation preserves order.
696 // 2. The body bytes serialised standalone (= what gets signed) are byte-identical to
697 // the body sub-object bytes embedded in the outer SignedMessage JSON (= what the
698 // server sees after parsing). Re-serialising the deserialised body must reproduce
699 // the signed bytes verbatim, otherwise no signature could ever verify.
700 #[test]
701 fn batch_body_serialisation_is_a_byte_exact_fixed_point() {
702 let mut rng = deterministic_rng();
703 let keys = ed25519::KeyPair::new(&mut rng);
704
705 let body = StressTestBatchSubmissionContent {
706 signer: *keys.public_key(),
707 timestamp: datetime!(2026-06-01 12:34:56.123456789 UTC),
708 results: dummy_results(),
709 };
710
711 let signed_bytes = body.plaintext();
712 let body_str = std::str::from_utf8(&signed_bytes).unwrap();
713
714 // (1) array order preserved on the wire
715 let pos1 = body_str.find(r#""testrun_id":1"#).unwrap();
716 let pos2 = body_str.find(r#""testrun_id":2"#).unwrap();
717 let pos3 = body_str.find(r#""testrun_id":3"#).unwrap();
718 assert!(pos1 < pos2 && pos2 < pos3, "JSON: {body_str}");
719
720 // (2) round-trip is byte-exact
721 let deserialised: StressTestBatchSubmissionContent =
722 serde_json::from_slice(&signed_bytes).unwrap();
723 let resigned_bytes = deserialised.plaintext();
724 assert_eq!(
725 signed_bytes, resigned_bytes,
726 "deserialise-then-re-serialise was not a fixed point"
727 );
728 }
729
730 // nym-api and the orchestrator are deployed independently, so an orchestrator carrying the
731 // submission counts may talk to a nym-api that predates them and answers a bare `{}`. That
732 // must deserialise rather than error - a hard failure here would break submissions outright,
733 // which is worse than the missing telemetry - and it must land as `None` rather than
734 // `Some(0)`, because the orchestrator warns on a non-zero duplicate count and "not reported"
735 // must not be mistaken for "nothing was stored".
736 #[test]
737 fn submission_response_tolerates_a_body_without_counts() {
738 let old: StressTestBatchSubmissionResponse = serde_json::from_str("{}")
739 .expect("a response body predating the counts must still deserialise");
740 assert_eq!(old.accepted, None);
741 assert_eq!(old.duplicates, None);
742 assert_eq!(old.rejected, None);
743
744 // and a populated body round-trips with its counts intact
745 let reported = StressTestBatchSubmissionResponse {
746 accepted: Some(48),
747 duplicates: Some(1),
748 rejected: Some(1),
749 };
750 let json = serde_json::to_string(&reported).unwrap();
751 let parsed: StressTestBatchSubmissionResponse = serde_json::from_str(&json).unwrap();
752 assert_eq!(parsed.accepted, Some(48));
753 assert_eq!(parsed.duplicates, Some(1));
754 assert_eq!(parsed.rejected, Some(1));
755 }
756
757 // The mirror of the above: a nym-api reporting the counts, answering an orchestrator that
758 // predates them and whose type carried no fields at all. Serde must ignore the unknown keys
759 // rather than error.
760 //
761 // This is the more dangerous of the two directions. The client parses with a plain
762 // `serde_json::from_slice`, so a decode failure surfaces as a failed POST, and the
763 // submission watermark is only advanced after a POST succeeds - an old orchestrator would
764 // therefore treat every batch as failed, resubmit the same rows forever and never make
765 // forward progress, while nym-api quietly stored them on the first attempt.
766 #[test]
767 fn submission_response_counts_are_ignored_by_a_reader_predating_them() {
768 // faithful copy of the previously deployed shape
769 #[derive(Deserialize)]
770 struct OldStressTestBatchSubmissionResponse {}
771
772 let json = serde_json::to_string(&StressTestBatchSubmissionResponse {
773 accepted: Some(48),
774 duplicates: Some(1),
775 rejected: Some(1),
776 })
777 .unwrap();
778
779 let parsed: Result<OldStressTestBatchSubmissionResponse, _> =
780 serde_json::from_str(&json);
781 assert!(
782 parsed.is_ok(),
783 "a reader predating the counts rejected {json}: {:?}",
784 parsed.err(),
785 );
786 }
787 }
788}