-
Notifications
You must be signed in to change notification settings - Fork 57
js-peer: add ability to connect via peerID #210
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
Open
Nkovaturient
wants to merge
22
commits into
libp2p:main
Choose a base branch
from
Nkovaturient:connect-via-peerId
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
162a99c
added-multiaddrs
Nkovaturient 7b7c596
connectPeerByID-initial-fix
Nkovaturient 0b97a97
modified-kadDHT-with-peerRouting-method
Nkovaturient 322e072
Merge branch 'main' into connect-via-peerId
Nkovaturient 6aef49c
prettier-code-styling
Nkovaturient ae5b517
add-peer-connectivity&validity
Nkovaturient 3c20c29
Merge remote-tracking branch 'origin/main' into connect-via-peerId
2color e82651d
chore: normalize linebreaks
2color 99b9826
chore:improve-peerID-connection-logic
Nkovaturient 2ff31ee
Merge branch 'libp2p:main' into connect-via-peerId
Nkovaturient 3dc0459
Merge branch 'main' of https://github.com/Nkovaturient/universal-conn…
Nkovaturient a0d5c28
Merge branch 'connect-via-peerId' of https://github.com/Nkovaturient/…
Nkovaturient 18a31fb
Merge branch 'main' into connect-via-peerId
Nkovaturient c459ded
Refactor: Unify multiaddr and PeerID connection in index.tsx & run fo…
Nkovaturient a2cda72
Merge branch 'main' of https://github.com/Nkovaturient/universal-conn…
Nkovaturient eb137d3
resolve-merge-conflicts
Nkovaturient b5a69c3
removed-setConn-ctx+apt-peer-list-style
Nkovaturient 94b2ed6
remove-setConn-ctx+revert-peer-list-styling
Nkovaturient 1acb6a4
Merge branch 'libp2p:main' into connect-via-peerId
Nkovaturient d8c5d07
afresh-dial-peerID-ability
Nkovaturient ddc386d
Merge branch 'main' of https://github.com/Nkovaturient/universal-conn…
Nkovaturient a0314d8
Merge branch 'connect-via-peerId' of https://github.com/Nkovaturient/…
Nkovaturient File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| import { useLibp2pContext } from '@/context/ctx' | ||
| import { multiaddr } from '@multiformats/multiaddr' | ||
| import { useState } from 'react' | ||
| import Spinner from '@/components/spinner' | ||
| import { connectToMultiaddr } from '../lib/libp2p' | ||
| import type { PeerId } from '@libp2p/interface' | ||
|
|
||
| interface PeerMaddrListProps { | ||
| resolvedMultiaddrs: string[] | ||
| setResolvedMultiaddrs: (addrs: string[]) => void | ||
| setError: (error: string | null) => void | ||
| } | ||
|
|
||
| export default function PeerMaddrList({ resolvedMultiaddrs, setResolvedMultiaddrs, setError }: PeerMaddrListProps) { | ||
| if (resolvedMultiaddrs.length === 0) return null | ||
|
|
||
| return ( | ||
| <div className="mt-6 w-full"> | ||
| <h4 className="text-lg font-semibold text-gray-900 mb-3">Found {resolvedMultiaddrs.length} addresses:</h4> | ||
| <ul className="p-4 border rounded-lg bg-gray-50 shadow-sm space-y-3"> | ||
| {resolvedMultiaddrs.map((addr, index) => ( | ||
| <MaddrItem key={index} addr={addr} setResolvedMultiaddrs={setResolvedMultiaddrs} setError={setError} /> | ||
| ))} | ||
| </ul> | ||
| </div> | ||
| ) | ||
| } | ||
|
|
||
| interface MaddrItemProps { | ||
| addr: string | ||
| setResolvedMultiaddrs: (addrs: string[]) => void | ||
| setError: (error: string | null) => void | ||
| } | ||
|
|
||
| function MaddrItem({ addr, setResolvedMultiaddrs, setError }: MaddrItemProps) { | ||
Nkovaturient marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| const [loading, setLoading] = useState(false) | ||
| const { libp2p, connections, setConnections } = useLibp2pContext() | ||
|
|
||
| // Helper to check if address is external | ||
| const isExternalAddress = (addr: string) => { | ||
| return !addr.includes('127.0.0.1') && !addr.includes('localhost') && !addr.includes('::1') | ||
| } | ||
|
|
||
| // Helper to validate transport stack | ||
| const hasValidTransportStack = (addr: string) => { | ||
| const hasWebTransport = addr.includes('webtransport') && addr.includes('certhash') | ||
| const hasWebRTC = addr.includes('webrtc') && addr.includes('certhash') | ||
| const hasQuic = addr.includes('quic-v1') | ||
|
|
||
| return hasWebTransport || (hasWebRTC && hasQuic) | ||
| } | ||
|
|
||
| const handleConnect = async () => { | ||
| setLoading(true) | ||
| try { | ||
| const maddr = multiaddr(addr) | ||
| const peerId = maddr.getPeerId() | ||
|
|
||
| if (!peerId) { | ||
| throw new Error('No peer ID found in multiaddr') | ||
| } | ||
|
|
||
| if (!isExternalAddress(addr)) { | ||
| console.warn('⚠️ Attempting to connect to local address, this might fail:', addr) | ||
| } | ||
|
|
||
| if (!hasValidTransportStack(addr)) { | ||
| throw new Error('Invalid or incomplete transport protocol stack') | ||
| } | ||
| console.log(`🔌 Attempting to connect to ${addr}`) | ||
|
|
||
| // Ensure the multiaddr includes the peer ID | ||
| const fullAddr = addr.includes(`/p2p/${peerId}`) ? addr : `${addr}/p2p/${peerId}` | ||
| const fullMaddr = multiaddr(fullAddr) | ||
| // Attempt connection | ||
| await connectToMultiaddr(libp2p)(fullMaddr) | ||
| console.log('✅ Successfully connected via:', fullAddr) | ||
|
|
||
| if (connections && !connections.find((conn) => conn.remotePeer.toString() === peerId)) { | ||
| const newConnections = [...connections] | ||
| const peerConnections = libp2p.getConnections(peerId as unknown as PeerId) | ||
| if (peerConnections.length > 0) { | ||
| newConnections.push(peerConnections[0]) | ||
| setConnections(newConnections) | ||
| } | ||
| } | ||
|
|
||
| setError('✅ Successfully connected to peer!') | ||
| setResolvedMultiaddrs([]) | ||
| } catch (err: unknown) { | ||
| const errorMessage = err instanceof Error ? err.message : String(err) | ||
| console.error('❌ Connection failed:', errorMessage) | ||
| setError(`❌ Failed to connect: ${errorMessage}`) | ||
| } finally { | ||
| setLoading(false) | ||
| } | ||
| } | ||
|
|
||
| // Only show valid multiaddrs that can be used for connection | ||
| const isValidMultiaddr = () => { | ||
| try { | ||
| const maddr = multiaddr(addr) | ||
| return !!maddr.getPeerId() // Only show if it has a peer ID | ||
| } catch { | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| // Only show promising connection candidates | ||
| const getConnectionPriority = () => { | ||
| if (!isValidMultiaddr()) return 0 | ||
| let priority = 1 | ||
| if (isExternalAddress(addr)) priority += 2 | ||
| if (addr.includes('webtransport')) priority += 3 | ||
| if (addr.includes('webrtc')) priority += 2 | ||
| return priority | ||
| } | ||
|
|
||
| // Don't render if priority is 0 (invalid) | ||
| if (getConnectionPriority() === 0) { | ||
| return null | ||
| } | ||
|
|
||
| return ( | ||
| <li className="flex justify-between gap-x-6 py-3"> | ||
| <div className="flex min-w-0 gap-x-4"> | ||
| <div className="min-w-0 flex-auto"> | ||
| <p className="text-sm font-semibold leading-6 text-gray-900 break-all"> | ||
| <span | ||
| className={`inline-block px-2 py-1 text-xs rounded-full mr-2 | ||
| ${ | ||
| addr.includes('webtransport') | ||
| ? 'bg-green-100 text-green-800' | ||
| : addr.includes('webrtc') | ||
| ? 'bg-blue-100 text-blue-800' | ||
| : 'bg-purple-100 text-purple-800' | ||
| }`} | ||
| > | ||
| {addr.includes('webtransport') ? '🌐 WebTransport' : addr.includes('webrtc') ? '🔌 WebRTC' : '🚀 QUIC'} | ||
| {!isExternalAddress(addr) && ' (Local)'} | ||
| </span> | ||
| {addr} | ||
| </p> | ||
| </div> | ||
| </div> | ||
|
|
||
| <div className="hidden sm:flex sm:flex-col sm:items-end"> | ||
| <button | ||
| onClick={handleConnect} | ||
| className={`font-bold py-2 px-4 rounded flex flex-row items-center | ||
| ${ | ||
| loading | ||
| ? 'bg-gray-400 cursor-not-allowed' | ||
| : getConnectionPriority() > 3 | ||
| ? 'bg-green-600 hover:bg-green-700' | ||
| : 'bg-yellow-600 hover:bg-yellow-700' | ||
| } | ||
| text-white disabled:opacity-70`} | ||
| disabled={loading} | ||
| > | ||
| {loading && <Spinner />} | ||
| <span className="pl-1"> | ||
| {loading ? 'Connecting...' : getConnectionPriority() > 3 ? 'Connect (Recommended)' : 'Connect'} | ||
| </span> | ||
| </button> | ||
| </div> | ||
| </li> | ||
| ) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.