diff --git a/packages/frontend/src/lib/constants.ts b/packages/frontend/src/lib/constants.ts index 128e66a6..f691e843 100644 --- a/packages/frontend/src/lib/constants.ts +++ b/packages/frontend/src/lib/constants.ts @@ -1,7 +1,6 @@ export const CHAT_TOPIC = "universal-connectivity" -// export const DEFAULT_APP_PEER = '12D3KooWBdmLJjhpgJ9KZgLM3f894ff9xyBfPvPjFNn7MKJpyrC2' -export const DEFAULT_APP_PEER = '12D3KooWRBy97UB99e3J6hiPesre1MZeuNQvfan4gBziswrRJsNK' +export const CIRCUIT_RELAY_CODE = 290 -export const CIRCUIT_RELAY_CODE = 290 +export const BOOTSTRAP_NODE = "/ip4/18.195.246.16/udp/9090/webrtc-direct/certhash/uEiBy_U1UNQ0IDvot_PKlQM_QeU3yx-zCAVaMxxVm2JxWBg/p2p/12D3KooWGTDZj1zAjMCJ8XXx9Z88zAAd6vn3krQYLwZ67S4vMUxz" \ No newline at end of file diff --git a/packages/frontend/src/lib/libp2p.ts b/packages/frontend/src/lib/libp2p.ts index 43e4d14d..089644ed 100644 --- a/packages/frontend/src/lib/libp2p.ts +++ b/packages/frontend/src/lib/libp2p.ts @@ -55,11 +55,19 @@ export async function startLibp2p(options: {} = {}) { discoverRelays: 1, }),], connectionEncryption: [noise()], + connectionManager: { + maxConnections: 10, + minConnections: 1, + }, streamMuxers: [yamux()], peerDiscovery: [ bootstrap({ + // #TODO: change to remote address + // list: [ + // '/ip4/18.195.246.16/udp/9090/webrtc-direct/certhash/uEiBy_U1UNQ0IDvot_PKlQM_QeU3yx-zCAVaMxxVm2JxWBg/p2p/12D3KooWGTDZj1zAjMCJ8XXx9Z88zAAd6vn3krQYLwZ67S4vMUxz', + // ], list: [ - '/ip4/18.195.246.16/udp/9090/webrtc-direct/certhash/uEiBy_U1UNQ0IDvot_PKlQM_QeU3yx-zCAVaMxxVm2JxWBg/p2p/12D3KooWGTDZj1zAjMCJ8XXx9Z88zAAd6vn3krQYLwZ67S4vMUxz', + '/ip4/127.0.0.1/udp/9090/webrtc-direct/certhash/uEiBy_U1UNQ0IDvot_PKlQM_QeU3yx-zCAVaMxxVm2JxWBg/p2p/12D3KooWA3nM2DyNTTJSPVdPzz7gvg8PHNNHPdNHxQm7KmvMbywM' ], }), ], diff --git a/packages/frontend/src/pages/index.tsx b/packages/frontend/src/pages/index.tsx index a4c3076b..ecdbc86c 100644 --- a/packages/frontend/src/pages/index.tsx +++ b/packages/frontend/src/pages/index.tsx @@ -2,33 +2,21 @@ import Head from 'next/head' import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/20/solid' import Nav from '@/components/nav' import { useLibp2pContext } from '@/context/ctx' -import { useCallback, useState } from 'react' +import { useState } from 'react' import { useInterval } from 'usehooks-ts' -import { - connectToMultiaddr, - connectToMultiaddrs, - filterPublicMultiaddrs, - getPeerMultiaddrs, - Libp2pDialError, -} from '@/lib/libp2p' -import type { Multiaddr } from '@multiformats/multiaddr' import { multiaddr } from '@multiformats/multiaddr' -import { peerIdFromString } from '@libp2p/peer-id' import { PeerId } from '@libp2p/interface-peer-id' import type { Connection } from '@libp2p/interface-connection' -import { DEFAULT_APP_PEER } from '../lib/constants' export default function Home() { const { libp2p } = useLibp2pContext() const [isConnected, setIsConnected] = useState(false) - const [peerID, setPeerID] = useState(DEFAULT_APP_PEER) const [maddr, setMultiaddr] = useState('') const [peers, setPeers] = useState([]) const [connections, setConnections] = useState([]) const [latency, setLatency] = useState() - const [multiaddrs, setMultiaddrs] = useState() useInterval(() => { const getConnectedPeers = async () => { @@ -38,25 +26,22 @@ export default function Home() { return await libp2p.getConnections() } - // const ping = async () => { - // if (maddr) { - // return libp2p.ping(multiaddr(maddr)) - // } - // } + const ping = async () => { + if (maddr) { + return libp2p.ping(multiaddr(maddr)) + } + } - // ping() - // .then((lat) => { - // setLatency(lat) - // }) - // .catch((e) => { - // console.error(e, e?.error) - // }) + ping() + .then((lat) => { + setLatency(lat) + }) + .catch((e) => { + console.error(e, e?.error) + }) getConnectedPeers().then((peers) => { - // If one of the connected peers matches the one in input we're connected - if (peers.some((pID) => multiaddr(maddr).getPeerId() === pID.toString())) { - setIsConnected(true) - } + setIsConnected(true) setPeers(peers) }) getConnections().then((conns) => { @@ -65,109 +50,6 @@ export default function Home() { }) }, 10000) - // Effect hook to connect to a specific peer when the page loads - // useEffect(() => { - // const connect = async () => { - // await connectToMultiaddrs(libp2p)([ - // multiaddr( - // '/dns4/ny5.bootstrap.libp2p.io/tcp/443/wss/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa', - // ), - // ]) - // } - - // connect() - // .then(() => { - // setIsConnected(true) - // }) - // .catch((e) => { - // console.error(e, e?.error) - // setIsConnected(false) - // }) - // }, [setIsConnected, setMultiaddrs, libp2p]) - - const handleGetMultiaddrs = useCallback( - async (e: React.MouseEvent) => { - try { - // 👇 Peer routing (DHT/DELEGATED) - setMultiaddrs(undefined) - const addrs = await getPeerMultiaddrs(libp2p)(peerID) - - setMultiaddrs(addrs) - - } catch (e) { - console.error(e) - } - }, - [libp2p, setMultiaddrs, peerID], - ) - - const handleFilterMultiaddrs = useCallback( - (e: React.MouseEvent) => { - if (multiaddrs) { - setMultiaddrs(filterPublicMultiaddrs(multiaddrs)) - } - }, - [setMultiaddrs, multiaddrs], - ) - - const handleConnectToMultiaddrs = useCallback( - async (e: React.MouseEvent) => { - try { - if (multiaddrs) { - const connections = await connectToMultiaddrs(libp2p)( - multiaddrs, - peerID, - ) - console.log('connections: ', connections) - - if ( - connections.find((conn) => { - return conn.remotePeer.toString() === peerID - }) - ) { - setIsConnected(true) - } - } - } catch (e) { - console.error(e) - } - }, - [libp2p, multiaddrs, peerID], - ) - - const handleConnectToMultiaddr = useCallback( - async (e: React.MouseEvent) => { - if (!maddr) { - return - } - - try { - const connection = await connectToMultiaddr(libp2p)(multiaddr(maddr)) - console.log('connection: ', connection) - - return connection - } catch (e) { - console.error(e) - } - }, - [libp2p, maddr], - ) - - // handleConnectToMultiaddr - - const handleMultiaddrChange = useCallback( - (e: React.ChangeEvent) => { - setMultiaddr(e.target.value) - }, - [setMultiaddr], - ) - - const handlePeerIdChange = useCallback( - (e: React.ChangeEvent) => { - setPeerID(e.target.value) - }, - [setPeerID], - ) return ( <> @@ -193,89 +75,7 @@ export default function Home() {
  • This PeerID: {libp2p.peerId.toString()}
  • -
    - -
    - -
    - {/*

    */} - -
    -
    - {multiaddrs && multiaddrs.length > 0 ? ( - <> -

    Multiaddrs for {peerID} 👇

    -
    -                      {multiaddrs.map((peer) => peer.toString()).join('\n')}
    -                    
    - - - - ) : null} -
    -
    - -
    - -
    - -

    Connected:{' '} {isConnected ? ( diff --git a/rust-peer/src/main.rs b/rust-peer/src/main.rs index d5856f79..b675f1f5 100644 --- a/rust-peer/src/main.rs +++ b/rust-peer/src/main.rs @@ -21,7 +21,7 @@ use std::{ fs::File, hash::{Hash, Hasher}, io::{BufReader, Read}, - time::{Duration, Instant}, + time::Duration, }; const TICK_INTERVAL: Duration = Duration::from_secs(15); @@ -77,6 +77,10 @@ struct Opt { /// Address of a remote peer to connect to. #[clap(long)] remote_address: Option, + + // use certificate path + #[clap(long)] + use_cert: Option, } /// An example WebRTC peer that will accept connections @@ -103,7 +107,6 @@ 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() { @@ -223,18 +226,26 @@ struct Behaviour { identify: identify::Behaviour, kademlia: Kademlia, keep_alive: keep_alive::Behaviour, - // ping: ping::Behaviour, + ping: ping::Behaviour, relay: relay::Behaviour, } fn create_swarm() -> Result> { - let f = File::open("/home/ec2-user/private_key")?; - let mut reader = BufReader::new(f); - let mut buffer = Vec::new(); + let local_key; + + let opt = Opt::parse(); + + if let Some(use_cert) = opt.use_cert { + let f = File::open(use_cert)?; + let mut reader = BufReader::new(f); + let mut buffer = Vec::new(); - reader.read_to_end(&mut buffer)?; + reader.read_to_end(&mut buffer)?; - let local_key = identity::Keypair::ed25519_from_bytes(&mut buffer)?; + local_key = identity::Keypair::ed25519_from_bytes(&mut buffer)?; + } else { + local_key = identity::Keypair::generate_ed25519(); + } let local_peer_id = PeerId::from(local_key.public()); debug!("Local peer id: {local_peer_id}"); @@ -294,7 +305,7 @@ fn create_swarm() -> Result> { identify: identify_config, kademlia: kad_behaviour, keep_alive: keep_alive::Behaviour::default(), - // ping: ping::Behaviour::default(), + ping: ping::Behaviour::default(), relay: relay::Behaviour::new(local_peer_id, Default::default()), }; Ok(SwarmBuilder::with_tokio_executor(transport, behaviour, local_peer_id).build())