Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: added multiaddr dial box + UI fixes (#49) #52

Merged
merged 4 commits into from
Apr 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions go-peer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import (
discovery "github.com/libp2p/go-libp2p/p2p/discovery/util"
quicTransport "github.com/libp2p/go-libp2p/p2p/transport/quic"
tcpTransport "github.com/libp2p/go-libp2p/p2p/transport/tcp"
webtransport "github.com/libp2p/go-libp2p/p2p/transport/webtransport"
ws "github.com/libp2p/go-libp2p/p2p/transport/websocket"
webtransport "github.com/libp2p/go-libp2p/p2p/transport/webtransport"
"github.com/multiformats/go-multiaddr"
)

Expand Down Expand Up @@ -188,7 +188,6 @@ func main() {
libp2p.Transport(tcpTransport.NewTCPTransport),
libp2p.Transport(webtransport.New),
libp2p.ListenAddrStrings("/ip4/0.0.0.0/udp/9091/quic-v1", "/ip4/0.0.0.0/udp/9092/quic-v1/webtransport", "/ip4/0.0.0.0/tcp/9090"),
),
)

// create a new libp2p Host with lots of options
Expand Down
139 changes: 139 additions & 0 deletions packages/frontend/public/libp2p-hero.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion packages/frontend/src/components/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export default function ChatContainer() {
alt="username"
/>
<span className="absolute w-3 h-3 bg-green-600 rounded-full left-10 top-3"></span> */}
<span className="text-3xl">💁‍♀️💁</span>
<span className="text-3xl">💁🏽‍♀️💁🏿‍♂️</span>
<span className="block ml-2 font-bold text-gray-600">
Public Chat
</span>
Expand Down
27 changes: 22 additions & 5 deletions packages/frontend/src/lib/libp2p.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createLibp2p } from 'libp2p'
import { createLibp2p, Libp2p } from 'libp2p'
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { bootstrap } from '@libp2p/bootstrap'
Expand All @@ -17,7 +17,7 @@ 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'
import { circuitRelayTransport, circuitRelayServer } from 'libp2p/circuit-relay'


export async function startLibp2p() {
Expand Down Expand Up @@ -45,14 +45,16 @@ export async function startLibp2p() {
}),],
connectionEncryption: [noise()],
connectionManager: {
maxConnections: 100,
maxConnections: 200,
minConnections: 1,
},
streamMuxers: [yamux()],
peerDiscovery: [
bootstrap({
list: [
BOOTSTRAP_NODE,
// BOOTSTRAP_NODE,
// Local Rust Peer Bootstrap node
"/ip4/127.0.0.1/udp/9090/webrtc-direct/certhash/uEiA2twAWww-g6fXsJe6JPlROwCHbRj6fNgr_WHxiQGEK3g/p2p/12D3KooWLTB1SrjyF8R5Z1MKErcV8abs26eo4LpadQKWsxMUcDBJ"
],
}),
],
Expand All @@ -62,7 +64,9 @@ export async function startLibp2p() {
ignoreDuplicatePublishError: true,
}),
identify: {
maxPushOutgoingStreams: 2,
maxPushOutgoingStreams: 100,
maxInboundStreams: 100,
maxOutboundStreams: 100,
},
autonat: {
startupDelay: 60 * 60 *24 * 1000,
Expand Down Expand Up @@ -103,3 +107,16 @@ export const setWebRTCRelayAddress = (maddrs: Multiaddr[], peerId: string) => {
})
}

export const connectToMultiaddr =
(libp2p: Libp2p) => async (multiaddr: Multiaddr) => {
console.log(`dialling: ${multiaddr.toString()}`)
try {
const conn = await libp2p.dial(multiaddr)
console.info('connected to', conn.remotePeer, 'on', conn.remoteAddr)
return conn
} catch (e) {
console.error(e)
throw e
}
}

86 changes: 74 additions & 12 deletions packages/frontend/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@ import Head from 'next/head'
import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/20/solid'
import Nav from '@/components/nav'
import { useLibp2pContext } from '@/context/ctx'
import { useInterval } from 'usehooks-ts'
import type { PeerId } from '@libp2p/interface-peer-id'
import type { Connection } from '@libp2p/interface-connection'
import { usePeerContext } from '../context/peer-ctx'
import { useEffect } from 'react'
import { useCallback, useEffect, useState } from 'react'
import Image from 'next/image'
import { multiaddr } from '@multiformats/multiaddr'
import { connectToMultiaddr } from '../lib/libp2p'


export default function Home() {
const { libp2p } = useLibp2pContext()
const { peerStats, setPeerStats } = usePeerContext()
const [maddr, setMultiaddr] = useState('')

useEffect(() => {
const peerConnectedCB = (evt: CustomEvent<Connection>) => {
Expand All @@ -36,14 +38,15 @@ export default function Home() {

connections.forEach((conn) => {
const exists = protoNames.get(conn.remotePeer.toString())
const dedupedProtonames = [...new Set(conn.remoteAddr.protoNames())]

if (exists) {
const namesToAdd = exists.filter(
(name) => !conn.remoteAddr.protoNames().includes(name),
)
if (exists?.length) {
const namesToAdd = dedupedProtonames.filter((name) => !exists.includes(name))
console.log('namesToAdd: ', namesToAdd)
protoNames.set(conn.remotePeer.toString(), [...exists, ...namesToAdd])

} else {
protoNames.set(conn.remotePeer.toString(), conn.remoteAddr.protoNames())
protoNames.set(conn.remotePeer.toString(), dedupedProtonames)
}
})

Expand All @@ -54,12 +57,38 @@ export default function Home() {

}

const handleConnectToMultiaddr = useCallback(
async (e: React.MouseEvent<HTMLButtonElement>) => {
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<HTMLInputElement>) => {
setMultiaddr(e.target.value)
},
[setMultiaddr],
)

return (
<>
<Head>
<title>js-libp2p-nextjs-example</title>
<meta name="description" content="js-libp2p-nextjs-example" />
<title>Universal Connectivity</title>
<meta name="description" content="universal connectivity" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
Expand All @@ -68,8 +97,14 @@ export default function Home() {
<div className="py-10">
<header>
<div className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8">
<h1 className="text-3xl font-bold leading-tight tracking-tight text-gray-900">
Libp2p WebTransport Example
<h1 className="text-3xl font-bold leading-tight tracking-tight text-gray-900 flex flex-row">
<p className="mr-4">Universal Connectivity</p>
<Image
src="/libp2p-hero.svg"
alt="libp2p logo"
height="46"
width="46"
/>
</h1>
</div>
</header>
Expand All @@ -78,6 +113,33 @@ export default function Home() {
<ul className="my-2 space-y-2 break-all">
<li className="">This PeerID: {libp2p.peerId.toString()}</li>
</ul>
<div className="my-6 w-1/2">
<label
htmlFor="peer-id"
className="block text-sm font-medium leading-6 text-gray-900"
>
multiaddr to connect to
</label>
<div className="mt-2">
<input
value={maddr}
type="text"
name="peer-id"
id="peer-id"
className="block w-full rounded-md border-0 py-1.5 px-3 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
placeholder="12D3Koo..."
aria-describedby="multiaddr-id-description"
onChange={handleMultiaddrChange}
/>
</div>
<button
type="button"
className="rounded-md bg-indigo-600 my-2 py-2 px-3 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
onClick={handleConnectToMultiaddr}
>
Connect to multiaddr
</button>
</div>


<div className="my-4 inline-flex items-center text-xl">
Expand Down