Skip to content

Commit

Permalink
fix: Remove ping + updated UI to filter protocols (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
maschad committed Apr 14, 2023
1 parent c718f2e commit 185c80f
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 24 deletions.
7 changes: 5 additions & 2 deletions packages/frontend/src/lib/libp2p.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { webSockets } from '@libp2p/websockets'
import { webTransport } from '@libp2p/webtransport'
import { webRTC, webRTCDirect } from '@libp2p/webrtc'
import { BOOTSTRAP_NODE, CHAT_TOPIC, CIRCUIT_RELAY_CODE } from './constants'
import * as filters from "@libp2p/websockets/filters"

// @ts-ignore
import { circuitRelayTransport } from 'libp2p/circuit-relay'
Expand All @@ -26,7 +27,9 @@ export async function startLibp2p() {
// libp2p is the networking layer that underpins Helia
const libp2p = await createLibp2p({
dht: kadDHT({protocolPrefix: "/universal-connectivity"}),
transports: [webTransport(), webSockets(), webRTC({
transports: [webTransport(), webSockets({
filter: filters.all,
}), webRTC({
rtcConfiguration: {
iceServers:[
{
Expand All @@ -50,7 +53,7 @@ export async function startLibp2p() {
bootstrap({
list: [
// BOOTSTRAP_NODE,
'/ip4/127.0.0.1/udp/9090/webrtc-direct/certhash/uEiA2twAWww-g6fXsJe6JPlROwCHbRj6fNgr_WHxiQGEK3g/p2p/12D3KooWLTB1SrjyF8R5Z1MKErcV8abs26eo4LpadQKWsxMUcDBJ',
'/ip4/127.0.0.1/udp/9090/webrtc-direct/certhash/uEiA2twAWww-g6fXsJe6JPlROwCHbRj6fNgr_WHxiQGEK3g/p2p/12D3KooWLTB1SrjyF8R5Z1MKErcV8abs26eo4LpadQKWsxMUcDBJ'
],
}),
],
Expand Down
40 changes: 28 additions & 12 deletions packages/frontend/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,35 @@ export default function Home() {
}
}, [libp2p, peerStats, setPeerStats])

const getUniqueConnections = (connections: Connection[]) => {
const uniqueConnections: Connection[] = []
type PeerProtoTuple = {
peerId: string
protocols: string[]
}

const getFormattedConnections = (connections: Connection[]): PeerProtoTuple[] => {
const protoNames: Map<string, string[]> = new Map()

connections.forEach((conn) => {
const exists = uniqueConnections.find(
(c) => c.remotePeer.toString() === conn.remotePeer.toString(),
)
if (!exists) {
uniqueConnections.push(conn)
const exists = protoNames.get(conn.remotePeer.toString())

if (exists) {
const namesToAdd = exists.filter(
(name) => !conn.remoteAddr.protoNames().includes(name),
)
protoNames.set(conn.remotePeer.toString(), [...exists, ...namesToAdd])
} else {
protoNames.set(conn.remotePeer.toString(), conn.remoteAddr.protoNames())
}
})
return uniqueConnections

return [...protoNames.entries()].map(([peerId, protocols]) => ({
peerId,
protocols,
}))

}


return (
<>
<Head>
Expand Down Expand Up @@ -77,13 +93,13 @@ export default function Home() {
<>
<h3 className="text-xl">
{' '}
Connected peers ({getUniqueConnections(peerStats.connections).length}) 👇
Connected peers ({getFormattedConnections(peerStats.connections).length}) 👇
</h3>
<pre className="px-2">
{getUniqueConnections(peerStats.connections)
{getFormattedConnections(peerStats.connections)
.map(
(conn) =>
`${conn.remotePeer.toString()} (${conn.remoteAddr.protoNames()})`,
(pair) =>
`${pair.peerId} (${pair.protocols.join(', ')})`,
)
.join('\n')}
</pre>
Expand Down
17 changes: 7 additions & 10 deletions rust-peer/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use libp2p::{
kad::record::store::MemoryStore,
kad::{Kademlia, KademliaConfig},
multiaddr::Protocol,
ping, relay,
relay,
swarm::{
keep_alive, AddressRecord, AddressScore, NetworkBehaviour, Swarm, SwarmBuilder, SwarmEvent,
},
Expand All @@ -22,7 +22,7 @@ use std::{
borrow::Cow,
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
time::Duration,
time::{Duration, Instant},
};
use tokio::fs;

Expand All @@ -39,10 +39,6 @@ struct Opt {
/// Address of a remote peer to connect to.
#[clap(long)]
remote_address: Option<Multiaddr>,

// use certificate path
#[clap(long)]
use_cert: Option<String>,
}

/// An example WebRTC peer that will accept connections
Expand Down Expand Up @@ -76,6 +72,7 @@ async fn main() -> Result<()> {

let mut tick = futures_timer::Delay::new(TICK_INTERVAL);

let now = Instant::now();
loop {
match futures::future::select(swarm.next(), &mut tick).await {
futures::future::Either::Left((event, _)) => match event.unwrap() {
Expand Down Expand Up @@ -176,7 +173,10 @@ async fn main() -> Result<()> {
debug!("Failed to run Kademlia bootstrap: {e:?}");
}

let message = format!("My social skills are a little rusty...");
let message = format!(
"Hello world! Sent from the rust-peer at: {:4}s",
now.elapsed().as_secs_f64()
);

if let Err(err) = swarm.behaviour_mut().gossipsub.publish(
gossipsub::IdentTopic::new("universal-connectivity"),
Expand All @@ -195,7 +195,6 @@ struct Behaviour {
identify: identify::Behaviour,
kademlia: Kademlia<MemoryStore>,
keep_alive: keep_alive::Behaviour,
ping: ping::Behaviour,
relay: relay::Behaviour,
}

Expand Down Expand Up @@ -270,12 +269,10 @@ fn create_swarm(
identify: identify_config,
kademlia: kad_behaviour,
keep_alive: keep_alive::Behaviour::default(),
ping: ping::Behaviour::default(),
relay: relay::Behaviour::new(
local_peer_id,
relay::Config {
max_reservations: 400,
max_circuit_duration: Duration::from_secs(100 * 100),
max_reservations_per_peer: 10,
..Default::default()
},
Expand Down

0 comments on commit 185c80f

Please sign in to comment.