Skip to content

Commit

Permalink
feat: fix dns and add chain http api (#147)
Browse files Browse the repository at this point in the history
  • Loading branch information
stringhandler authored Nov 12, 2024
1 parent 37e0dd7 commit 01c97e9
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 36 deletions.
2 changes: 1 addition & 1 deletion src/cli/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub struct StartArgs {
///
/// e.g.:
/// /ip4/127.0.0.1/tcp/52313/p2p/12D3KooWCUNCvi7PBPymgsHx39JWErYdSoT3EFPrn3xoVff4CHFu
/// /dnsaddr/esmeralda.p2pool.tari.com
/// /dnsaddr/esmeralda.sha-p2pool.tari.com
#[arg(short, long, value_name = "seed-peers")]
pub seed_peers: Option<Vec<String>>,

Expand Down
2 changes: 1 addition & 1 deletion src/cli/commands/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub async fn server(
let mut seed_peers = vec![];
let network = Network::get_current_or_user_setting_or_default();
if network != Network::LocalNet && !args.no_default_seed_peers {
let default_seed_peer = format!("/dnsaddr/{}.p2pool.tari.com", network.as_key_str());
let default_seed_peer = format!("/dnsaddr/{}.sha-p2pool.tari.com", network.as_key_str());
seed_peers.push(default_seed_peer);
}
if let Some(cli_seed_peers) = args.seed_peers.clone() {
Expand Down
4 changes: 2 additions & 2 deletions src/server/http/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ pub struct HttpServer {
}

#[derive(Clone)]
pub struct AppState {
stats_client: StatsClient,
pub(crate) struct AppState {
pub stats_client: StatsClient,
pub squad: Squad,
pub p2p_service_client: Sender<P2pServiceQuery>,
}
Expand Down
34 changes: 23 additions & 11 deletions src/server/http/stats/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::server::{
http::{
server::AppState,
stats::models::{SquadDetails, Stats},
stats_collector::GetStatsResponse,
},
p2p::{ConnectedPeerInfo, P2pServiceQuery},
};
Expand Down Expand Up @@ -196,8 +197,7 @@ pub(crate) async fn handle_get_stats(State(state): State<AppState>) -> Result<Js
let timer = std::time::Instant::now();
info!(target: LOG_TARGET, "handle_get_stats");

let sha3x_stats = get_chain_stats(state.clone(), PowAlgorithm::Sha3x).await?;
let randomx_stats = get_chain_stats(state.clone(), PowAlgorithm::RandomX).await?;
let (rx_stats, sha3x_stats) = get_chain_stats(state.clone()).await?;
// let peer_count = state.peer_store.peer_count().await;
let peer_count = 0;
let connected = peer_count > 0;
Expand Down Expand Up @@ -232,11 +232,9 @@ pub(crate) async fn handle_get_stats(State(state): State<AppState>) -> Result<Js
// };

let stats = Stats {
connected,
peer_count,
connection_info,
connected_since,
randomx_stats,
randomx_stats: rx_stats,
sha3x_stats,
};
if timer.elapsed() > MAX_ACCEPTABLE_HTTP_TIMEOUT {
Expand All @@ -246,12 +244,26 @@ pub(crate) async fn handle_get_stats(State(state): State<AppState>) -> Result<Js
}

#[allow(clippy::too_many_lines)]
async fn get_chain_stats(state: AppState, _algo: PowAlgorithm) -> Result<ChainStats, StatusCode> {
Ok(ChainStats {
share_chain_height: 0,
share_chain_length: 0,
squad: SquadDetails::new(state.squad.to_string(), state.squad.formatted()),
})
async fn get_chain_stats(state: AppState) -> Result<(GetStatsResponse, GetStatsResponse), StatusCode> {
let stats_client = state.stats_client.clone();
let (rx_stats, sha3x_stats) = (
stats_client
.get_chain_stats(PowAlgorithm::RandomX)
.await
.map_err(|error| {
error!(target: LOG_TARGET, "Failed to get chain stats: {error:?}");
StatusCode::INTERNAL_SERVER_ERROR
})?,
stats_client
.get_chain_stats(PowAlgorithm::Sha3x)
.await
.map_err(|error| {
error!(target: LOG_TARGET, "Failed to get chain stats: {error:?}");
StatusCode::INTERNAL_SERVER_ERROR
})?,
);

Ok((rx_stats, sha3x_stats))
// return from cache if possible
// let stats_cache = state.stats_cache.clone();
// if let Some(stats) = stats_cache.stats(algo).await {
Expand Down
13 changes: 7 additions & 6 deletions src/server/http/stats/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ use tari_common_types::tari_address::TariAddress;
use tari_core::transactions::tari_amount::MicroMinotari;
use tari_utilities::{epoch_time::EpochTime, hex::Hex};

use crate::{server::p2p::ConnectionInfo, sharechain::p2block::P2Block};
use crate::{
server::{http::stats_collector::GetStatsResponse, p2p::ConnectionInfo},
sharechain::p2block::P2Block,
};

#[derive(Serialize, Deserialize, Clone)]
pub struct StatsBlock {
Expand Down Expand Up @@ -83,14 +86,12 @@ impl SquadDetails {
}
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Clone)]
pub struct Stats {
pub connected: bool,
pub peer_count: u64,
pub connection_info: ConnectionInfo,
pub connected_since: Option<EpochTime>,
pub randomx_stats: ChainStats,
pub sha3x_stats: ChainStats,
pub randomx_stats: GetStatsResponse,
pub sha3x_stats: GetStatsResponse,
}

#[derive(Serialize, Deserialize, Clone)]
Expand Down
32 changes: 28 additions & 4 deletions src/server/http/stats_collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::time::Duration;

use human_format::Formatter;
use log::{error, info};
use serde::Serialize;
use tari_core::proof_of_work::{Difficulty, PowAlgorithm};
use tari_shutdown::ShutdownSignal;
use tari_utilities::epoch_time::EpochTime;
Expand Down Expand Up @@ -168,9 +169,26 @@ impl StatsCollector {
},
res = self.request_rx.recv() => {
match res {
Some(StatsRequest::GetStats(_pow, _tx)) => {
todo!();
// let _ = tx.send(hashrate);
Some(StatsRequest::GetStats(pow, tx)) => {

match pow {
PowAlgorithm::Sha3x => {
let _ = tx.send(GetStatsResponse {
height: self.sha3x_chain_height,
last_block_time: EpochTime::now(),
num_my_shares: 0,
total_shares: 0,
}).inspect_err(|e| error!(target: LOG_TARGET, "Error sending stats response: {:?}", e));
},
PowAlgorithm::RandomX => {
let _ = tx.send(GetStatsResponse {
height: self.randomx_chain_height,
last_block_time: EpochTime::now(),
num_my_shares: 0,
total_shares: 0,
}).inspect_err(|e| error!(target: LOG_TARGET, "Error sending stats response: {:?}", e));
},
}
},
None => {
break;
Expand Down Expand Up @@ -207,7 +225,13 @@ pub(crate) enum StatsRequest {
GetStats(PowAlgorithm, tokio::sync::oneshot::Sender<GetStatsResponse>),
}

pub(crate) struct GetStatsResponse {}
#[derive(Serialize, Clone, Debug)]
pub(crate) struct GetStatsResponse {
height: u64,
last_block_time: EpochTime,
num_my_shares: u64,
total_shares: u64,
}

#[derive(Clone)]
pub(crate) struct ChainStats {
Expand Down
21 changes: 11 additions & 10 deletions src/server/p2p/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use libp2p::{
gossipsub::{self, IdentTopic, Message, MessageAcceptance, MessageId, PublishError},
identify::{self, Info},
identity::Keypair,
kad::{self, store::MemoryStore, Event},
kad::{self, store::MemoryStore, Event, Mode},
mdns::{self, tokio::Tokio},
multiaddr::Protocol,
noise,
Expand Down Expand Up @@ -428,7 +428,7 @@ where S: ShareChain

/// Creates a new swarm from the provided config
async fn new_swarm(config: &config::Config) -> Result<Swarm<ServerNetworkBehaviour>, Error> {
let swarm = libp2p::SwarmBuilder::with_existing_identity(Self::keypair(&config.p2p_service).await?)
let mut swarm = libp2p::SwarmBuilder::with_existing_identity(Self::keypair(&config.p2p_service).await?)
.with_tokio()
.with_tcp(tcp::Config::default(), noise::Config::new, yamux::Config::default)
.map_err(|error| Error::LibP2P(LibP2PError::Noise(error)))?
Expand Down Expand Up @@ -523,8 +523,8 @@ where S: ShareChain
// .with_swarm_config(|c| c.with_idle_connection_timeout(config.idle_connection_timeout))
.build();

dbg!("Check if we must set the kademlia mode");
// swarm.behaviour_mut().kademlia.set_mode(Some(Mode::Server));
// All nodes are servers
swarm.behaviour_mut().kademlia.set_mode(Some(Mode::Server));

Ok(swarm)
}
Expand Down Expand Up @@ -1111,10 +1111,10 @@ where S: ShareChain
established_in,
..
} => {
debug!(target: LOG_TARGET, squad = &self.config.squad; "Connection established: {peer_id:?} -> {endpoint:?} ({num_established:?}/{concurrent_dial_errors:?}/{established_in:?})");
info!(target: LOG_TARGET, squad = &self.config.squad; "Connection established: {peer_id:?} -> {endpoint:?} ({num_established:?}/{concurrent_dial_errors:?}/{established_in:?})");
},
SwarmEvent::Dialing { peer_id, .. } => {
debug!(target: LOG_TARGET, squad = &self.config.squad; "Dialing: {peer_id:?}");
info!(target: LOG_TARGET, squad = &self.config.squad; "Dialing: {peer_id:?}");
},
SwarmEvent::NewListenAddr { address, .. } => {
info!(target: LOG_TARGET, squad = &self.config.squad; "Listening on {address:?}");
Expand Down Expand Up @@ -1495,6 +1495,8 @@ where S: ShareChain
return;
}

dbg!(&info);

if self.swarm.external_addresses().count() > 0 {
debug!(target: LOG_TARGET, "No need to relay, we have an external address already. {}", self.swarm.external_addresses().map(|a| a.to_string()).collect::<Vec<String>>().join(", "));
// Check if we can relay
Expand All @@ -1517,10 +1519,8 @@ where S: ShareChain
.any(|p| *p == CATCH_UP_SYNC_REQUEST_RESPONSE_PROTOCOL)
{
warn!(target: LOG_TARGET, "Peer does not support current catchup sync protocol, will disconnect");
if !is_relay || self.relay_store.read().await.has_active_relay() {
self.swarm.behaviour_mut().kademlia.remove_peer(&peer_id);
let _res = self.swarm.disconnect_peer_id(peer_id);
}
self.swarm.behaviour_mut().kademlia.remove_peer(&peer_id);
let _res = self.swarm.disconnect_peer_id(peer_id);

// return;
}
Expand Down Expand Up @@ -2195,6 +2195,7 @@ where S: ShareChain
/// Adding all peer addresses to kademlia DHT and run bootstrap to get peers.
async fn join_seed_peers(&mut self, seed_peers: HashMap<PeerId, Multiaddr>) -> Result<(), Error> {
seed_peers.iter().for_each(|(peer_id, addr)| {
info!(target: LOG_TARGET, squad = &self.config.squad; "Adding seed peer: {:?} -> {:?}", peer_id, addr);
self.swarm.behaviour_mut().kademlia.add_address(peer_id, addr.clone());
});

Expand Down
5 changes: 4 additions & 1 deletion src/server/p2p/peer_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use log::warn;
use tari_core::proof_of_work::PowAlgorithm;
use tari_utilities::epoch_time::EpochTime;

use crate::server::{http::stats_collector::StatsBroadcastClient, p2p::messages::PeerInfo};
use crate::server::{http::stats_collector::StatsBroadcastClient, p2p::messages::PeerInfo, PROTOCOL_VERSION};

const LOG_TARGET: &str = "tari::p2pool::peer_store";
// const PEER_BAN_TIME: Duration = Duration::from_secs(60 * 5);
Expand Down Expand Up @@ -274,6 +274,9 @@ impl PeerStore {
.iter()
.filter_map(|(peer_id, peer_info)| {
if let Ok(p) = PeerId::from_str(peer_id) {
if peer_info.version < PROTOCOL_VERSION {
return None;
}
Some((
peer_id.clone(),
PeerStoreRecord::new(p, peer_info.clone()).with_timestamp(EpochTime::now().as_u64()),
Expand Down

0 comments on commit 01c97e9

Please sign in to comment.