Skip to main content

hoprd_api/
node.rs

1use std::{collections::HashMap, sync::Arc};
2
3use axum::{
4    extract::{Json, Query, State},
5    http::status::StatusCode,
6    response::IntoResponse,
7};
8use futures::{StreamExt, stream::FuturesUnordered};
9#[cfg(feature = "telemetry")]
10use hopr_lib::PeerPacketStatsSnapshot;
11use hopr_lib::{Address, Health, Multiaddr, api::network::Observable};
12use serde::{Deserialize, Serialize};
13use serde_with::{DisplayFromStr, serde_as};
14
15use crate::{ApiError, ApiErrorStatus, BASE_PATH, InternalState, checksum_address_serializer};
16
17#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
18#[schema(example = json!({
19        "version": "2.1.0",
20    }))]
21#[serde(rename_all = "camelCase")]
22/// Running node version.
23pub(crate) struct NodeVersionResponse {
24    #[schema(example = "2.1.0")]
25    version: String,
26}
27
28/// Get the release version of the running node.
29#[utoipa::path(
30        get,
31        path = const_format::formatcp!("{BASE_PATH}/node/version"),
32        description = "Get the release version of the running node",
33        responses(
34            (status = 200, description = "Fetched node version", body = NodeVersionResponse),
35            (status = 401, description = "Invalid authorization token.", body = ApiError),
36        ),
37        security(
38            ("api_token" = []),
39            ("bearer_token" = [])
40        ),
41        tag = "Node"
42    )]
43pub(super) async fn version() -> impl IntoResponse {
44    let version = hopr_lib::constants::APP_VERSION.to_string();
45    (StatusCode::OK, Json(NodeVersionResponse { version })).into_response()
46}
47
48/// Get the configuration of the running node.
49#[utoipa::path(
50    get,
51    path = const_format::formatcp!("{BASE_PATH}/node/configuration"),
52    description = "Get the configuration of the running node",
53    responses(
54        (status = 200, description = "Fetched node configuration", body = HashMap<String, String>, example = json!({
55        "network": "anvil-localhost",
56        "provider": "http://127.0.0.1:8545",
57        "hoprToken": "0x9a676e781a523b5d0c0e43731313a708cb607508",
58        "hoprChannels": "0x9a9f2ccfde556a7e9ff0848998aa4a0cfd8863ae",
59        "...": "..."
60        })),
61        (status = 401, description = "Invalid authorization token.", body = ApiError),
62    ),
63    security(
64        ("api_token" = []),
65        ("bearer_token" = [])
66    ),
67    tag = "Configuration"
68    )]
69pub(super) async fn configuration(State(state): State<Arc<InternalState>>) -> impl IntoResponse {
70    (StatusCode::OK, Json(state.hoprd_cfg.clone())).into_response()
71}
72
73#[derive(Debug, Clone, Deserialize, utoipa::ToSchema, utoipa::IntoParams)]
74#[into_params(parameter_in = Query)]
75#[schema(example = json!({
76        "quality": 0.7
77    }))]
78/// Quality information for a peer.
79pub(crate) struct NodePeersQueryRequest {
80    #[serde(default)]
81    #[schema(required = false, example = 0.7)]
82    /// Minimum peer quality to be included in the response.
83    score: f64,
84}
85
86#[derive(Debug, Default, Clone, Serialize, utoipa::ToSchema)]
87#[schema(example = json!({
88    "sent": 10,
89    "success": 10
90}))]
91#[serde(rename_all = "camelCase")]
92/// Heartbeat information for a peer.
93pub(crate) struct HeartbeatInfo {
94    #[schema(example = 10)]
95    sent: u64,
96    #[schema(example = 10)]
97    success: u64,
98}
99
100#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
101#[schema(example = json!({
102    "packetsOut": 100,
103    "packetsIn": 50,
104    "bytesOut": 102400,
105    "bytesIn": 51200
106}))]
107#[serde(rename_all = "camelCase")]
108/// Packet statistics for a peer.
109pub(crate) struct PeerPacketStatsResponse {
110    #[schema(example = 100)]
111    pub packets_out: u64,
112    #[schema(example = 50)]
113    pub packets_in: u64,
114    #[schema(example = 102400)]
115    pub bytes_out: u64,
116    #[schema(example = 51200)]
117    pub bytes_in: u64,
118}
119
120#[cfg(feature = "telemetry")]
121impl From<PeerPacketStatsSnapshot> for PeerPacketStatsResponse {
122    fn from(snapshot: PeerPacketStatsSnapshot) -> Self {
123        Self {
124            packets_out: snapshot.packets_out,
125            packets_in: snapshot.packets_in,
126            bytes_out: snapshot.bytes_out,
127            bytes_in: snapshot.bytes_in,
128        }
129    }
130}
131
132#[serde_as]
133#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
134#[serde(rename_all = "camelCase")]
135#[schema(example = json!({
136    "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
137    "multiaddr": "/ip4/178.12.1.9/tcp/19092",
138    "probeRate": 0.476,
139    "lastSeen": 1690000000,
140    "averageLatency": 100,
141    "score": 0.7,
142    "packetStats": {
143        "packetsOut": 100,
144        "packetsIn": 50,
145        "bytesOut": 102400,
146        "bytesIn": 51200
147    }
148}))]
149/// All information about a known peer.
150pub(crate) struct PeerObservations {
151    #[serde(serialize_with = "checksum_address_serializer")]
152    #[schema(value_type = String, example = "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe")]
153    address: Address,
154    #[serde_as(as = "Option<DisplayFromStr>")]
155    #[schema(value_type = Option<String>, example = "/ip4/178.12.1.9/tcp/19092")]
156    multiaddr: Option<Multiaddr>,
157    #[schema(example = 0.476)]
158    probe_rate: f64,
159    #[schema(example = 1690000000)]
160    last_update: u128,
161    #[schema(example = 100)]
162    average_latency: u128,
163    #[schema(example = 0.7)]
164    score: f64,
165    /// Packet statistics for this peer (if available).
166    #[cfg(feature = "telemetry")]
167    #[serde(skip_serializing_if = "Option::is_none")]
168    packet_stats: Option<PeerPacketStatsResponse>,
169}
170
171#[serde_as]
172#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
173#[schema(example = json!({
174    "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
175    "multiaddrs": "[/ip4/178.12.1.9/tcp/19092]"
176}))]
177#[serde(rename_all = "camelCase")]
178/// Represents a peer that has been announced on-chain.
179pub(crate) struct AnnouncedPeer {
180    #[serde(serialize_with = "checksum_address_serializer")]
181    #[schema(value_type = String, example = "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe")]
182    address: Address,
183    #[serde_as(as = "Vec<DisplayFromStr>")]
184    #[schema(value_type = Vec<String>, example = "[/ip4/178.12.1.9/tcp/19092]")]
185    multiaddrs: Vec<Multiaddr>,
186}
187
188#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
189#[serde(rename_all = "camelCase")]
190#[schema(example = json!({
191    "connected": [{
192        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
193        "multiaddr": "/ip4/178.12.1.9/tcp/19092",
194        "heartbeats": {
195            "sent": 10,
196            "success": 10
197        },
198        "lastSeen": 1690000000,
199        "lastSeenLatency": 100,
200        "quality": 0.7,
201        "backoff": 0.5,
202        "isNew": true,
203    }],
204    "announced": [{
205        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
206        "multiaddr": "/ip4/178.12.1.9/tcp/19092"
207    }]
208}))]
209/// All connected and announced peers.
210pub(crate) struct NodePeersResponse {
211    #[schema(example = json!([{
212        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
213        "multiaddr": "/ip4/178.12.1.9/tcp/19092",
214        "heartbeats": {
215            "sent": 10,
216            "success": 10
217        },
218        "lastSeen": 1690000000,
219        "lastSeenLatency": 100,
220        "quality": 0.7,
221        "backoff": 0.5,
222        "isNew": true,
223    }]))]
224    connected: Vec<PeerObservations>,
225    #[schema(example = json!([{
226        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
227        "multiaddr": "/ip4/178.12.1.9/tcp/19092"
228    }]))]
229    announced: Vec<AnnouncedPeer>,
230}
231
232/// Lists information for `connected peers` and `announced peers`.
233///
234/// Connected peers are nodes which are connected to the node while announced peers are
235/// nodes which have announced to the network.
236///
237/// Optionally pass `quality` parameter to get only peers with higher or equal quality
238/// to the specified value.
239#[utoipa::path(
240        get,
241        path = const_format::formatcp!("{BASE_PATH}/node/peers"),
242        description = "Lists information for connected and announced peers",
243        params(NodePeersQueryRequest),
244        responses(
245            (status = 200, description = "Successfully returned observed peers", body = NodePeersResponse),
246            (status = 400, description = "Failed to extract a valid quality parameter", body = ApiError),
247            (status = 401, description = "Invalid authorization token.", body = ApiError),
248        ),
249        security(
250            ("api_token" = []),
251            ("bearer_token" = [])
252        ),
253        tag = "Node"
254    )]
255pub(super) async fn peers(
256    Query(NodePeersQueryRequest { score }): Query<NodePeersQueryRequest>,
257    State(state): State<Arc<InternalState>>,
258) -> Result<impl IntoResponse, ApiError> {
259    if !(0.0f64..=1.0f64).contains(&score) {
260        return Ok((StatusCode::BAD_REQUEST, ApiErrorStatus::InvalidQuality).into_response());
261    }
262
263    let hopr = state.hopr.clone();
264
265    let all_network_peers = futures::stream::iter(hopr.network_connected_peers().await?)
266        .filter_map(|peer| {
267            let hopr = hopr.clone();
268
269            async move {
270                if let Ok(Some(info)) = hopr.network_peer_info(&peer).await {
271                    if info.score() >= score {
272                        Some((peer, info))
273                    } else {
274                        None
275                    }
276                } else {
277                    None
278                }
279            }
280        })
281        .filter_map(|(peer_id, info)| {
282            let hopr = hopr.clone();
283
284            async move {
285                let Some(address) = hopr.peerid_to_chain_key(&peer_id).await.ok().flatten() else {
286                    // Filter out peers without a known chain address
287                    return None;
288                };
289
290                // WARNING: Only in Providence and Saint-Louis are all peers public
291                let multiaddresses = hopr.network_observed_multiaddresses(&peer_id).await;
292
293                Some(PeerObservations {
294                    address,
295                    multiaddr: multiaddresses.first().cloned(),
296                    last_update: info.last_update().as_millis(),
297                    average_latency: info.average_latency().map_or(0, |d| d.as_millis()),
298                    probe_rate: info.average_probe_rate(),
299                    score: info.score(),
300                    #[cfg(feature = "telemetry")]
301                    packet_stats: hopr
302                        .network_peer_packet_stats(&peer_id)
303                        .await
304                        .ok()
305                        .flatten()
306                        .map(PeerPacketStatsResponse::from),
307                })
308            }
309        })
310        .collect::<Vec<_>>()
311        .await;
312
313    let announced_peers = hopr
314        .accounts_announced_on_chain()
315        .await?
316        .into_iter()
317        .map(|announced| async move {
318            AnnouncedPeer {
319                address: announced.chain_addr,
320                multiaddrs: announced.get_multiaddrs().to_vec(),
321            }
322        })
323        .collect::<FuturesUnordered<_>>()
324        .collect()
325        .await;
326
327    let body = NodePeersResponse {
328        connected: all_network_peers,
329        announced: announced_peers,
330    };
331
332    Ok((StatusCode::OK, Json(body)).into_response())
333}
334
335#[serde_as]
336#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
337#[schema(example = json!({
338        "announcedAddress": [
339            "/ip4/10.0.2.100/tcp/19092"
340        ],
341        "providerUrl": "https://staging.blokli.hoprnet.link",
342        "hoprNetworkName": "rotsee",
343        "channelClosurePeriod": 15,
344        "connectivityStatus": "Green",
345        "hoprNodeSafe": "0x42bc901b1d040f984ed626eff550718498a6798a",
346        "listeningAddress": [
347            "/ip4/10.0.2.100/tcp/19092"
348        ],
349    }))]
350#[serde(rename_all = "camelCase")]
351/// Information about the current node. Covers network, addresses, eligibility, connectivity status, contracts addresses
352/// and indexer state.
353pub(crate) struct NodeInfoResponse {
354    #[serde_as(as = "Vec<DisplayFromStr>")]
355    #[schema(value_type = Vec<String>, example = json!(["/ip4/10.0.2.100/tcp/19092"]))]
356    announced_address: Vec<Multiaddr>,
357    #[serde_as(as = "Vec<DisplayFromStr>")]
358    #[schema(value_type = Vec<String>, example = json!(["/ip4/10.0.2.100/tcp/19092"]))]
359    listening_address: Vec<Multiaddr>,
360    #[schema(value_type = String, example = "https://staging.blokli.hoprnet.link")]
361    provider_url: String,
362    #[schema(value_type = String, example = "rotsee")]
363    hopr_network_name: String,
364    #[serde(serialize_with = "checksum_address_serializer")]
365    #[schema(value_type = String, example = "0x42bc901b1d040f984ed626eff550718498a6798a")]
366    hopr_node_safe: Address,
367    #[serde_as(as = "DisplayFromStr")]
368    #[schema(value_type = String, example = "Green")]
369    connectivity_status: Health,
370    /// Channel closure period in seconds
371    #[schema(example = 15)]
372    channel_closure_period: u64,
373}
374
375/// Get information about this HOPR Node.
376#[utoipa::path(
377        get,
378        path = const_format::formatcp!("{BASE_PATH}/node/info"),
379        description = "Get information about this HOPR Node",
380        responses(
381            (status = 200, description = "Fetched node informations", body = NodeInfoResponse),
382            (status = 422, description = "Unknown failure", body = ApiError)
383        ),
384        security(
385            ("api_token" = []),
386            ("bearer_token" = [])
387        ),
388        tag = "Node"
389    )]
390pub(super) async fn info(State(state): State<Arc<InternalState>>) -> Result<impl IntoResponse, ApiError> {
391    let hopr = state.hopr.clone();
392
393    let safe_config = hopr.get_safe_config();
394
395    let provider_url = state
396        .hoprd_cfg
397        .as_object()
398        .and_then(|cfg| cfg.get("blokli_url"))
399        .and_then(|v| v.as_str());
400
401    match futures::try_join!(hopr.chain_info(), hopr.get_channel_closure_notice_period()) {
402        Ok((info, channel_closure_notice_period)) => {
403            let body = NodeInfoResponse {
404                announced_address: hopr.local_multiaddresses(),
405                listening_address: hopr.local_multiaddresses(),
406                provider_url: provider_url.unwrap_or("n/a").to_owned(),
407                hopr_network_name: info.hopr_network_name,
408                hopr_node_safe: safe_config.safe_address,
409                connectivity_status: hopr.network_health().await,
410                channel_closure_period: channel_closure_notice_period.as_secs(),
411            };
412
413            Ok((StatusCode::OK, Json(body)).into_response())
414        }
415        Err(error) => Ok((StatusCode::UNPROCESSABLE_ENTITY, ApiErrorStatus::from(error)).into_response()),
416    }
417}
418
419#[serde_as]
420#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
421#[serde(rename_all = "camelCase")]
422#[schema(example = json!({
423        "isEligible": true,
424        "multiaddrs": ["/ip4/10.0.2.100/tcp/19091"]
425}))]
426/// Reachable entry node information
427pub(crate) struct EntryNode {
428    #[serde_as(as = "Vec<DisplayFromStr>")]
429    #[schema(value_type = Vec<String>, example = json!(["/ip4/10.0.2.100/tcp/19091"]))]
430    multiaddrs: Vec<Multiaddr>,
431    #[schema(example = true)]
432    is_eligible: bool,
433}
434
435/// List all known entry nodes with multiaddrs and eligibility.
436#[utoipa::path(
437        get,
438        path = const_format::formatcp!("{BASE_PATH}/node/entry-nodes"),
439        description = "List all known entry nodes with multiaddrs and eligibility",
440        responses(
441            (status = 200, description = "Fetched public nodes' information", body = HashMap<String, EntryNode>, example = json!({
442                "0x188c4462b75e46f0c7262d7f48d182447b93a93c": {
443                    "isEligible": true,
444                    "multiaddrs": ["/ip4/10.0.2.100/tcp/19091"]
445                }
446            })),
447            (status = 401, description = "Invalid authorization token.", body = ApiError),
448            (status = 422, description = "Unknown failure", body = ApiError)
449        ),
450        security(
451            ("api_token" = []),
452            ("bearer_token" = [])
453        ),
454        tag = "Node"
455    )]
456pub(super) async fn entry_nodes(State(state): State<Arc<InternalState>>) -> Result<impl IntoResponse, ApiError> {
457    let hopr = state.hopr.clone();
458
459    match hopr.get_public_nodes().await {
460        Ok(nodes) => {
461            let mut body = HashMap::new();
462            for (_, address, mas) in nodes.into_iter() {
463                body.insert(
464                    address.to_string(),
465                    EntryNode {
466                        multiaddrs: mas,
467                        is_eligible: true,
468                    },
469                );
470            }
471
472            Ok((StatusCode::OK, Json(body)).into_response())
473        }
474        Err(error) => Ok((StatusCode::UNPROCESSABLE_ENTITY, ApiErrorStatus::from(error)).into_response()),
475    }
476}