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};
9use hopr_lib::{Address, AsUnixTimestamp, Health, Multiaddr};
10use serde::{Deserialize, Serialize};
11use serde_with::{DisplayFromStr, serde_as};
12
13use crate::{
14    ApiError, ApiErrorStatus, BASE_PATH, InternalState, checksum_address_serializer, option_checksum_address_serializer,
15};
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    quality: 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#[serde_as]
101#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
102#[serde(rename_all = "camelCase")]
103#[schema(example = json!({
104    "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
105    "multiaddr": "/ip4/178.12.1.9/tcp/19092",
106    "heartbeats": {
107        "sent": 10,
108        "success": 10
109    },
110    "lastSeen": 1690000000,
111    "lastSeenLatency": 100,
112    "quality": 0.7,
113    "backoff": 0.5,
114    "isNew": true,
115}))]
116/// All information about a known peer.
117pub(crate) struct PeerInfo {
118    #[serde(serialize_with = "option_checksum_address_serializer")]
119    #[schema(value_type = Option<String>, example = "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe")]
120    address: Option<Address>,
121    #[serde_as(as = "Option<DisplayFromStr>")]
122    #[schema(value_type = Option<String>, example = "/ip4/178.12.1.9/tcp/19092")]
123    multiaddr: Option<Multiaddr>,
124    #[schema(example = json!({
125        "sent": 10,
126        "success": 10
127    }))]
128    heartbeats: HeartbeatInfo,
129    #[schema(example = 1690000000)]
130    last_seen: u128,
131    #[schema(example = 100)]
132    last_seen_latency: u128,
133    #[schema(example = 0.7)]
134    quality: f64,
135    #[schema(example = 0.5)]
136    backoff: f64,
137    #[schema(example = true)]
138    is_new: bool,
139}
140
141#[serde_as]
142#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
143#[schema(example = json!({
144    "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
145    "multiaddrs": "[/ip4/178.12.1.9/tcp/19092]"
146}))]
147#[serde(rename_all = "camelCase")]
148/// Represents a peer that has been announced on-chain.
149pub(crate) struct AnnouncedPeer {
150    #[serde(serialize_with = "checksum_address_serializer")]
151    #[schema(value_type = String, example = "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe")]
152    address: Address,
153    #[serde_as(as = "Vec<DisplayFromStr>")]
154    #[schema(value_type = Vec<String>, example = "[/ip4/178.12.1.9/tcp/19092]")]
155    multiaddrs: Vec<Multiaddr>,
156}
157
158#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
159#[serde(rename_all = "camelCase")]
160#[schema(example = json!({
161    "connected": [{
162        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
163        "multiaddr": "/ip4/178.12.1.9/tcp/19092",
164        "heartbeats": {
165            "sent": 10,
166            "success": 10
167        },
168        "lastSeen": 1690000000,
169        "lastSeenLatency": 100,
170        "quality": 0.7,
171        "backoff": 0.5,
172        "isNew": true,
173    }],
174    "announced": [{
175        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
176        "multiaddr": "/ip4/178.12.1.9/tcp/19092"
177    }]
178}))]
179/// All connected and announced peers.
180pub(crate) struct NodePeersResponse {
181    #[schema(example = json!([{
182        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
183        "multiaddr": "/ip4/178.12.1.9/tcp/19092",
184        "heartbeats": {
185            "sent": 10,
186            "success": 10
187        },
188        "lastSeen": 1690000000,
189        "lastSeenLatency": 100,
190        "quality": 0.7,
191        "backoff": 0.5,
192        "isNew": true,
193    }]))]
194    connected: Vec<PeerInfo>,
195    #[schema(example = json!([{
196        "address": "0xb4ce7e6e36ac8b01a974725d5ba730af2b156fbe",
197        "multiaddr": "/ip4/178.12.1.9/tcp/19092"
198    }]))]
199    announced: Vec<AnnouncedPeer>,
200}
201
202/// Lists information for `connected peers` and `announced peers`.
203///
204/// Connected peers are nodes which are connected to the node while announced peers are
205/// nodes which have announced to the network.
206///
207/// Optionally pass `quality` parameter to get only peers with higher or equal quality
208/// to the specified value.
209#[utoipa::path(
210        get,
211        path = const_format::formatcp!("{BASE_PATH}/node/peers"),
212        description = "Lists information for connected and announced peers",
213        params(NodePeersQueryRequest),
214        responses(
215            (status = 200, description = "Successfully returned observed peers", body = NodePeersResponse),
216            (status = 400, description = "Failed to extract a valid quality parameter", body = ApiError),
217            (status = 401, description = "Invalid authorization token.", body = ApiError),
218        ),
219        security(
220            ("api_token" = []),
221            ("bearer_token" = [])
222        ),
223        tag = "Node"
224    )]
225pub(super) async fn peers(
226    Query(NodePeersQueryRequest { quality }): Query<NodePeersQueryRequest>,
227    State(state): State<Arc<InternalState>>,
228) -> Result<impl IntoResponse, ApiError> {
229    if !(0.0f64..=1.0f64).contains(&quality) {
230        return Ok((StatusCode::BAD_REQUEST, ApiErrorStatus::InvalidQuality).into_response());
231    }
232
233    let hopr = state.hopr.clone();
234
235    let all_network_peers = futures::stream::iter(hopr.network_connected_peers().await?)
236        .filter_map(|peer| {
237            let hopr = hopr.clone();
238
239            async move {
240                if let Ok(Some(info)) = hopr.network_peer_info(&peer).await {
241                    let avg_quality = info.get_average_quality();
242                    if avg_quality >= quality {
243                        Some((peer, info))
244                    } else {
245                        None
246                    }
247                } else {
248                    None
249                }
250            }
251        })
252        .filter_map(|(peer_id, info)| {
253            let hopr = hopr.clone();
254
255            async move {
256                let address = hopr.peerid_to_chain_key(&peer_id).await.ok().flatten();
257
258                // WARNING: Only in Providence and Saint-Louis are all peers public
259                let multiaddresses = hopr.network_observed_multiaddresses(&peer_id).await;
260
261                Some((address, multiaddresses, info))
262            }
263        })
264        .map(|(address, mas, info)| PeerInfo {
265            address,
266            multiaddr: mas.first().cloned(),
267            heartbeats: HeartbeatInfo {
268                sent: info.heartbeats_sent,
269                success: info.heartbeats_succeeded,
270            },
271            last_seen: info.last_seen.as_unix_timestamp().as_millis(),
272            last_seen_latency: info.last_seen_latency.as_millis() / 2,
273            quality: info.get_average_quality(),
274            backoff: info.backoff,
275            is_new: info.heartbeats_sent == 0u64,
276        })
277        .collect::<Vec<_>>()
278        .await;
279
280    let announced_peers = hopr
281        .accounts_announced_on_chain()
282        .await?
283        .into_iter()
284        .map(|announced| async move {
285            AnnouncedPeer {
286                address: announced.chain_addr,
287                multiaddrs: announced.get_multiaddrs().to_vec(),
288            }
289        })
290        .collect::<FuturesUnordered<_>>()
291        .collect()
292        .await;
293
294    let body = NodePeersResponse {
295        connected: all_network_peers,
296        announced: announced_peers,
297    };
298
299    Ok((StatusCode::OK, Json(body)).into_response())
300}
301
302#[serde_as]
303#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
304#[schema(example = json!({
305        "announcedAddress": [
306            "/ip4/10.0.2.100/tcp/19092"
307        ],
308        "chain": "anvil-localhost",
309        "provider": "http://127.0.0.1:8545",
310        "channelClosurePeriod": 15,
311        "connectivityStatus": "Green",
312        "hoprChannels": "0x9a9f2ccfde556a7e9ff0848998aa4a0cfd8863ae",
313        "hoprManagementModule": "0xa51c1fc2f0d1a1b8494ed1fe312d7c3a78ed91c0",
314        "hoprNetworkRegistry": "0x3aa5ebb10dc797cac828524e59a333d0a371443c",
315        "hoprNodeSafe": "0x42bc901b1d040f984ed626eff550718498a6798a",
316        "hoprNodeSafeRegistry": "0x0dcd1bf9a1b36ce34237eeafef220932846bcd82",
317        "hoprToken": "0x9a676e781a523b5d0c0e43731313a708cb607508",
318        "isEligible": true,
319        "listeningAddress": [
320            "/ip4/10.0.2.100/tcp/19092"
321        ],
322        "network": "anvil-localhost",
323        "indexerBlock": 123456,
324        "indexerChecksum": "0000000000000000000000000000000000000000000000000000000000000000",
325        "indexBlockPrevChecksum": 0,
326        "indexerLastLogBlock": 123450,
327        "indexerLastLogChecksum": "cfde556a7e9ff0848998aa4a9a9f2ccfde556a7e9ff0848998aa4a0cfd8863ae",
328        "isIndexerCorrupted": false,
329    }))]
330#[serde(rename_all = "camelCase")]
331/// Information about the current node. Covers network, addresses, eligibility, connectivity status, contracts addresses
332/// and indexer state.
333pub(crate) struct NodeInfoResponse {
334    #[serde_as(as = "Vec<DisplayFromStr>")]
335    #[schema(value_type = Vec<String>, example = json!(["/ip4/10.0.2.100/tcp/19092"]))]
336    announced_address: Vec<Multiaddr>,
337    #[serde_as(as = "Vec<DisplayFromStr>")]
338    #[schema(value_type = Vec<String>, example = json!(["/ip4/10.0.2.100/tcp/19092"]))]
339    listening_address: Vec<Multiaddr>,
340    #[schema(example = "anvil-localhost")]
341    chain: String,
342    #[serde(serialize_with = "checksum_address_serializer")]
343    #[schema(value_type = String, example = "0x9a676e781a523b5d0c0e43731313a708cb607508")]
344    hopr_token: Address,
345    #[serde(serialize_with = "checksum_address_serializer")]
346    #[schema(value_type = String, example = "0x9a9f2ccfde556a7e9ff0848998aa4a0cfd8863ae")]
347    hopr_channels: Address,
348    #[serde(serialize_with = "checksum_address_serializer")]
349    #[schema(value_type = String, example = "0x0dcd1bf9a1b36ce34237eeafef220932846bcd82")]
350    hopr_node_safe_registry: Address,
351    #[serde(serialize_with = "checksum_address_serializer")]
352    #[schema(value_type = String, example = "0xa51c1fc2f0d1a1b8494ed1fe312d7c3a78ed91c0")]
353    hopr_management_module: Address,
354    #[serde(serialize_with = "checksum_address_serializer")]
355    #[schema(value_type = String, example = "0x42bc901b1d040f984ed626eff550718498a6798a")]
356    hopr_node_safe: Address,
357    #[serde_as(as = "DisplayFromStr")]
358    #[schema(value_type = String, example = "Green")]
359    connectivity_status: Health,
360    /// Channel closure period in seconds
361    #[schema(example = 15)]
362    channel_closure_period: u64,
363}
364
365/// Get information about this HOPR Node.
366#[utoipa::path(
367        get,
368        path = const_format::formatcp!("{BASE_PATH}/node/info"),
369        description = "Get information about this HOPR Node",
370        responses(
371            (status = 200, description = "Fetched node informations", body = NodeInfoResponse),
372            (status = 422, description = "Unknown failure", body = ApiError)
373        ),
374        security(
375            ("api_token" = []),
376            ("bearer_token" = [])
377        ),
378        tag = "Node"
379    )]
380pub(super) async fn info(State(state): State<Arc<InternalState>>) -> Result<impl IntoResponse, ApiError> {
381    let hopr = state.hopr.clone();
382
383    let safe_config = hopr.get_safe_config();
384
385    let chain_data = futures::try_join!(hopr.get_channel_closure_notice_period(), hopr.chain_info());
386
387    match chain_data {
388        Ok((channel_closure_notice_period, chain_info)) => {
389            let body = NodeInfoResponse {
390                announced_address: hopr.local_multiaddresses(),
391                listening_address: hopr.local_multiaddresses(),
392                chain: chain_info.chain_id.to_string(),
393                hopr_token: chain_info.contract_addresses.token,
394                hopr_channels: chain_info.contract_addresses.channels,
395                hopr_node_safe_registry: chain_info.contract_addresses.node_safe_registry,
396                hopr_management_module: chain_info.contract_addresses.module_implementation,
397                hopr_node_safe: safe_config.safe_address,
398                connectivity_status: hopr.network_health().await,
399                channel_closure_period: channel_closure_notice_period.as_secs(),
400            };
401
402            Ok((StatusCode::OK, Json(body)).into_response())
403        }
404        Err(error) => Ok((StatusCode::UNPROCESSABLE_ENTITY, ApiErrorStatus::from(error)).into_response()),
405    }
406}
407
408#[serde_as]
409#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
410#[serde(rename_all = "camelCase")]
411#[schema(example = json!({
412        "isEligible": true,
413        "multiaddrs": ["/ip4/10.0.2.100/tcp/19091"]
414}))]
415/// Reachable entry node information
416pub(crate) struct EntryNode {
417    #[serde_as(as = "Vec<DisplayFromStr>")]
418    #[schema(value_type = Vec<String>, example = json!(["/ip4/10.0.2.100/tcp/19091"]))]
419    multiaddrs: Vec<Multiaddr>,
420    #[schema(example = true)]
421    is_eligible: bool,
422}
423
424/// List all known entry nodes with multiaddrs and eligibility.
425#[utoipa::path(
426        get,
427        path = const_format::formatcp!("{BASE_PATH}/node/entry-nodes"),
428        description = "List all known entry nodes with multiaddrs and eligibility",
429        responses(
430            (status = 200, description = "Fetched public nodes' information", body = HashMap<String, EntryNode>, example = json!({
431                "0x188c4462b75e46f0c7262d7f48d182447b93a93c": {
432                    "isEligible": true,
433                    "multiaddrs": ["/ip4/10.0.2.100/tcp/19091"]
434                }
435            })),
436            (status = 401, description = "Invalid authorization token.", body = ApiError),
437            (status = 422, description = "Unknown failure", body = ApiError)
438        ),
439        security(
440            ("api_token" = []),
441            ("bearer_token" = [])
442        ),
443        tag = "Node"
444    )]
445pub(super) async fn entry_nodes(State(state): State<Arc<InternalState>>) -> Result<impl IntoResponse, ApiError> {
446    let hopr = state.hopr.clone();
447
448    match hopr.get_public_nodes().await {
449        Ok(nodes) => {
450            let mut body = HashMap::new();
451            for (_, address, mas) in nodes.into_iter() {
452                body.insert(
453                    address.to_string(),
454                    EntryNode {
455                        multiaddrs: mas,
456                        is_eligible: true,
457                    },
458                );
459            }
460
461            Ok((StatusCode::OK, Json(body)).into_response())
462        }
463        Err(error) => Ok((StatusCode::UNPROCESSABLE_ENTITY, ApiErrorStatus::from(error)).into_response()),
464    }
465}