darkfi/rpc/
p2p_method.rs

1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2025 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use async_trait::async_trait;
20
21use super::{
22    jsonrpc::{JsonResponse, JsonResult},
23    util::*,
24};
25use crate::net;
26
27#[async_trait]
28pub trait HandlerP2p: Sync + Send {
29    async fn p2p_get_info(&self, id: u16, _params: JsonValue) -> JsonResult {
30        let mut channels = Vec::new();
31        for channel in self.p2p().hosts().channels() {
32            let session = match channel.session_type_id() {
33                net::session::SESSION_INBOUND => "inbound",
34                net::session::SESSION_OUTBOUND => "outbound",
35                net::session::SESSION_MANUAL => "manual",
36                net::session::SESSION_REFINE => "refine",
37                net::session::SESSION_SEED => "seed",
38                net::session::SESSION_DIRECT => "direct",
39                _ => panic!("invalid result from channel.session_type_id()"),
40            };
41
42            // For transport mixed connections send the mixed url to aid in debugging
43            channels.push(json_map([
44                ("url", JsonStr(channel.display_address().to_string())),
45                ("session", json_str(session)),
46                ("id", JsonNum(channel.info.id.into())),
47            ]));
48        }
49
50        let mut slots = Vec::new();
51        for channel_id in self.p2p().session_outbound().slot_info().await {
52            slots.push(JsonNum(channel_id.into()));
53        }
54
55        let result =
56            json_map([("channels", JsonArray(channels)), ("outbound_slots", JsonArray(slots))]);
57        JsonResponse::new(result, id).into()
58    }
59
60    fn p2p(&self) -> net::P2pPtr;
61}