Skip to main content

nym_api_requests/
nym_nodes.rs

1// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::models::described::type_translation::{DeclaredRolesV1, LewesProtocolDetailsV1};
5use crate::models::described::v1::NymNodeDataV1;
6use crate::models::OffsetDateTimeJsonSchemaWrapper;
7use crate::pagination::{PaginatedResponse, Pagination};
8use nym_crypto::asymmetric::ed25519::serde_helpers::bs58_ed25519_pubkey;
9use nym_crypto::asymmetric::x25519::serde_helpers::bs58_x25519_pubkey;
10use nym_crypto::asymmetric::{ed25519, x25519};
11use nym_mixnet_contract_common::nym_node::Role;
12use nym_mixnet_contract_common::reward_params::Performance;
13use nym_mixnet_contract_common::{EpochId, Interval, NodeId};
14use nym_noise_keys::VersionedNoiseKeyV1;
15use serde::{Deserialize, Serialize};
16use std::collections::HashMap;
17use std::net::IpAddr;
18use time::OffsetDateTime;
19use utoipa::ToSchema;
20
21#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, utoipa::ToSchema)]
22pub struct SkimmedNodesWithMetadata {
23    pub nodes: Vec<SkimmedNodeV1>,
24    pub metadata: NodesResponseMetadata,
25}
26
27impl SkimmedNodesWithMetadata {
28    pub fn new(nodes: Vec<SkimmedNodeV1>, metadata: NodesResponseMetadata) -> Self {
29        SkimmedNodesWithMetadata { nodes, metadata }
30    }
31}
32
33/// The same, for the listing that carries LP details.
34///
35/// A separate type rather than a generic parameter: the two feeds describe different networks - a
36/// node that published no LP details is absent from this one - and keeping them apart is what stops
37/// a route being built from the wrong one.
38#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, utoipa::ToSchema)]
39pub struct LpSkimmedNodesWithMetadata {
40    pub nodes: Vec<SkimmedNodeV2>,
41    pub metadata: NodesResponseMetadata,
42}
43
44impl LpSkimmedNodesWithMetadata {
45    pub fn new(nodes: Vec<SkimmedNodeV2>, metadata: NodesResponseMetadata) -> Self {
46        LpSkimmedNodesWithMetadata { nodes, metadata }
47    }
48}
49
50#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, utoipa::ToSchema)]
51pub struct SemiSkimmedNodesWithMetadata {
52    pub nodes: Vec<SemiSkimmedNodeV1>,
53    pub metadata: NodesResponseMetadata,
54}
55
56impl SemiSkimmedNodesWithMetadata {
57    pub fn new(nodes: Vec<SemiSkimmedNodeV1>, metadata: NodesResponseMetadata) -> Self {
58        SemiSkimmedNodesWithMetadata { nodes, metadata }
59    }
60}
61
62#[derive(
63    Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, utoipa::ToSchema, PartialEq,
64)]
65#[serde(rename_all = "kebab-case")]
66pub enum TopologyRequestStatus {
67    NoUpdates,
68    Fresh(Interval),
69}
70
71#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
72pub struct CachedNodesResponse<T: ToSchema> {
73    pub refreshed_at: OffsetDateTimeJsonSchemaWrapper,
74    pub nodes: Vec<T>,
75}
76
77impl<T: ToSchema> From<Vec<T>> for CachedNodesResponse<T> {
78    fn from(nodes: Vec<T>) -> Self {
79        CachedNodesResponse::new(nodes)
80    }
81}
82
83impl<T: ToSchema> CachedNodesResponse<T> {
84    pub fn new(nodes: Vec<T>) -> Self {
85        CachedNodesResponse {
86            refreshed_at: OffsetDateTime::now_utc().into(),
87            nodes,
88        }
89    }
90}
91
92#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, utoipa::ToSchema)]
93pub struct NodesResponseMetadata {
94    pub status: Option<TopologyRequestStatus>,
95    #[schema(value_type = u32)]
96    pub absolute_epoch_id: EpochId,
97    pub rotation_id: u32,
98    pub refreshed_at: OffsetDateTimeJsonSchemaWrapper,
99}
100
101impl NodesResponseMetadata {
102    pub fn consistency_check(&self, other: &NodesResponseMetadata) -> bool {
103        self.status == other.status
104            && self.absolute_epoch_id == other.absolute_epoch_id
105            && self.rotation_id == other.rotation_id
106    }
107
108    pub fn refreshed_at(&self) -> OffsetDateTime {
109        self.refreshed_at.into()
110    }
111}
112
113#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema)]
114// can't add any new fields here, even with #[serde(default)] and whatnot,
115// because it will break all clients using bincode : (
116pub struct PaginatedCachedNodesResponseV1<T> {
117    pub status: Option<TopologyRequestStatus>,
118    pub refreshed_at: OffsetDateTimeJsonSchemaWrapper,
119    pub nodes: PaginatedResponse<T>,
120}
121
122#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema)]
123pub struct PaginatedCachedNodesResponseV2<T> {
124    pub metadata: NodesResponseMetadata,
125    pub nodes: PaginatedResponse<T>,
126}
127
128impl<T> From<PaginatedCachedNodesResponseV2<T>> for PaginatedCachedNodesResponseV1<T> {
129    fn from(res: PaginatedCachedNodesResponseV2<T>) -> Self {
130        PaginatedCachedNodesResponseV1 {
131            status: res.metadata.status,
132            refreshed_at: res.metadata.refreshed_at,
133            nodes: res.nodes,
134        }
135    }
136}
137
138impl<T> PaginatedCachedNodesResponseV2<T> {
139    pub fn new_full(
140        absolute_epoch_id: EpochId,
141        rotation_id: u32,
142        refreshed_at: impl Into<OffsetDateTimeJsonSchemaWrapper>,
143        nodes: Vec<T>,
144    ) -> Self {
145        PaginatedCachedNodesResponseV2 {
146            nodes: PaginatedResponse {
147                pagination: Pagination {
148                    total: nodes.len(),
149                    page: 0,
150                    size: nodes.len(),
151                },
152                data: nodes,
153            },
154            metadata: NodesResponseMetadata {
155                refreshed_at: refreshed_at.into(),
156                status: None,
157                absolute_epoch_id,
158                rotation_id,
159            },
160        }
161    }
162
163    pub fn fresh(mut self, interval: Interval) -> Self {
164        self.metadata.status = Some(TopologyRequestStatus::Fresh(interval));
165        self
166    }
167
168    pub fn no_updates(absolute_epoch_id: EpochId, rotation_id: u32) -> Self {
169        PaginatedCachedNodesResponseV2 {
170            nodes: PaginatedResponse {
171                pagination: Pagination {
172                    total: 0,
173                    page: 0,
174                    size: 0,
175                },
176                data: Vec::new(),
177            },
178            metadata: NodesResponseMetadata {
179                refreshed_at: OffsetDateTime::now_utc().into(),
180                status: Some(TopologyRequestStatus::NoUpdates),
181                absolute_epoch_id,
182                rotation_id,
183            },
184        }
185    }
186}
187
188#[derive(Clone, Copy, Debug, Serialize, Deserialize, schemars::JsonSchema, utoipa::ToSchema)]
189#[serde(rename_all = "kebab-case")]
190pub enum NodeRoleQueryParam {
191    ActiveMixnode,
192
193    #[serde(alias = "entry", alias = "gateway")]
194    EntryGateway,
195
196    #[serde(alias = "exit")]
197    ExitGateway,
198}
199
200#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema, Default)]
201pub enum NodeRole {
202    // a properly active mixnode
203    Mixnode {
204        layer: u8,
205    },
206
207    #[serde(alias = "entry", alias = "gateway")]
208    EntryGateway,
209
210    #[serde(alias = "exit")]
211    ExitGateway,
212
213    // equivalent of node that's in rewarded set but not in the inactive set
214    Standby,
215
216    #[default]
217    Inactive,
218}
219
220impl NodeRole {
221    pub fn is_inactive(&self) -> bool {
222        matches!(self, NodeRole::Inactive)
223    }
224}
225
226impl From<Option<Role>> for NodeRole {
227    fn from(role: Option<Role>) -> Self {
228        match role {
229            Some(Role::EntryGateway) => NodeRole::EntryGateway,
230            Some(Role::Layer1) => NodeRole::Mixnode { layer: 1 },
231            Some(Role::Layer2) => NodeRole::Mixnode { layer: 2 },
232            Some(Role::Layer3) => NodeRole::Mixnode { layer: 3 },
233            Some(Role::ExitGateway) => NodeRole::ExitGateway,
234            Some(Role::Standby) => NodeRole::Standby,
235            None => NodeRole::Inactive,
236        }
237    }
238}
239
240#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
241pub struct BasicEntryInformation {
242    pub hostname: Option<String>,
243
244    pub ws_port: u16,
245    pub wss_port: Option<u16>,
246}
247
248// the bare minimum information needed to construct sphinx packets
249#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
250pub struct SkimmedNodeV1 {
251    #[schema(value_type = u32)]
252    pub node_id: NodeId,
253
254    #[serde(with = "bs58_ed25519_pubkey")]
255    #[schemars(with = "String")]
256    #[schema(value_type = String)]
257    pub ed25519_identity_pubkey: ed25519::PublicKey,
258
259    #[schema(value_type = Vec<String>)]
260    pub ip_addresses: Vec<IpAddr>,
261
262    pub mix_port: u16,
263
264    #[serde(with = "bs58_x25519_pubkey")]
265    #[schemars(with = "String")]
266    #[schema(value_type = String)]
267    pub x25519_sphinx_pubkey: x25519::PublicKey,
268
269    #[serde(alias = "epoch_role")]
270    pub role: NodeRole,
271
272    // needed for the purposes of sending appropriate test packets
273    #[serde(default)]
274    pub supported_roles: DeclaredRolesV1,
275
276    pub entry: Option<BasicEntryInformation>,
277
278    /// Average node performance in last 24h period
279    #[schema(value_type = String)]
280    pub performance: Performance,
281}
282
283impl SkimmedNodeV1 {
284    pub fn get_mix_layer(&self) -> Option<u8> {
285        match self.role {
286            NodeRole::Mixnode { layer } => Some(layer),
287            _ => None,
288        }
289    }
290}
291
292// everything needed to route a sphinx packet to this node and to reach it on either transport
293#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
294pub struct SkimmedNodeV2 {
295    #[schema(value_type = u32)]
296    pub node_id: NodeId,
297
298    #[serde(with = "bs58_ed25519_pubkey")]
299    #[schemars(with = "String")]
300    #[schema(value_type = String)]
301    pub ed25519_identity_pubkey: ed25519::PublicKey,
302
303    #[schema(value_type = Vec<String>)]
304    pub ip_addresses: Vec<IpAddr>,
305
306    pub mix_port: u16,
307
308    #[serde(with = "bs58_x25519_pubkey")]
309    #[schemars(with = "String")]
310    #[schema(value_type = String)]
311    pub x25519_sphinx_pubkey: x25519::PublicKey,
312
313    #[serde(alias = "epoch_role")]
314    pub role: NodeRole,
315
316    // needed for the purposes of sending appropriate test packets
317    #[serde(default)]
318    pub supported_roles: DeclaredRolesV1,
319
320    pub entry: Option<BasicEntryInformation>,
321
322    /// Average node performance in last 24h period
323    #[schema(value_type = String)]
324    pub performance: Performance,
325
326    /// Everything needed to route to this node over LP and to establish a session with it.
327    ///
328    /// `content.data_port` paired with one of `ip_addresses` is this node's address on an LP
329    /// route, the way `mix_port` is its address on a legacy one.
330    pub lp: LewesProtocolDetailsV1,
331
332    /// Build version of this node used as a hint in inferring the Ciphersuite compatibility
333    pub build_version: String,
334}
335
336impl SkimmedNodeV2 {
337    pub fn get_mix_layer(&self) -> Option<u8> {
338        match self.role {
339            NodeRole::Mixnode { layer } => Some(layer),
340            _ => None,
341        }
342    }
343}
344
345// an intermediate variant that exposes additional data such as noise keys but without
346// the full fat of the self-described data
347#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
348pub struct SemiSkimmedNodeV1 {
349    pub basic: SkimmedNodeV1,
350
351    pub x25519_noise_versioned_key: Option<VersionedNoiseKeyV1>,
352    // pub location:
353}
354
355#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
356pub struct FullFatNode {
357    pub expanded: SemiSkimmedNodeV1,
358
359    // kinda temporary for now to make as few changes as possible for now
360    pub self_described: Option<NymNodeDataV1>,
361}
362
363#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, ToSchema)]
364pub struct NodesByAddressesRequestBody {
365    #[schema(value_type = Vec<String>)]
366    pub addresses: Vec<IpAddr>,
367}
368
369#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, ToSchema)]
370pub struct NodesByAddressesResponse {
371    #[schema(value_type = HashMap<String, Option<u32>>)]
372    pub existence: HashMap<IpAddr, Option<NodeId>>,
373}
374
375/// All the information required for sending packets between nodes (sphinx, noise, LP)
376#[derive(Clone, Debug, Serialize, Deserialize, schemars::JsonSchema, ToSchema)]
377pub struct SemiSkimmedNodeV3 {
378    /// Basic node information required for mixnet routing
379    pub basic: SkimmedNodeV1,
380
381    /// Noise key of the node
382    pub noise_key: Option<VersionedNoiseKeyV1>,
383
384    /// Build version of this node used as a hint in inferring the Ciphersuite compatibility
385    pub build_version: String,
386
387    /// Information required for establishing an LP connection
388    pub lp: Option<LewesProtocolDetailsV1>,
389}