Skip to content

Commit

Permalink
bumping libp2p by libp2p#73
Browse files Browse the repository at this point in the history
  • Loading branch information
DrHongos committed Jun 6, 2023
1 parent 710a551 commit 8f332cb
Show file tree
Hide file tree
Showing 10 changed files with 654 additions and 1,393 deletions.
13 changes: 0 additions & 13 deletions improvements_dforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,6 @@
- validar en server:
Public Message: At [datetime] the node [peerId] was validated as [account]

bumped libp2p and other dependencies
- no hay relayer activado, FIXME
- needs to ts-ignore a lot of conditioned stuff in components

BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG
helia uses ipfs-bitswap that inside implements
"@libp2p/interface-libp2p": "^3.1.0",
helia uses "^3.2.0"
that changes considerable the Libp2p type !
- try to check if it works (it breaks)
- bump ipfs-bitswap dependency (locally (try again))
BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG


- firmar el nodo libp2p para verificar en server
https://wagmi.sh/react/hooks/useSignMessage
Expand Down
1,810 changes: 504 additions & 1,306 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions packages/frontend/next.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
productionBrowserSourceMaps: true,
}

module.exports = nextConfig
9 changes: 5 additions & 4 deletions packages/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@
"@headlessui/react": "^1.7.13",
"@heroicons/react": "^2.0.16",
"@libp2p/bootstrap": "^8.0.0",
"@libp2p/kad-dht": "^8.0.6",
"@libp2p/webrtc": "^1.1.2",
"@libp2p/websockets": "^5.0.3",
"@libp2p/webtransport": "^1.0.7",
"@libp2p/interface-pubsub": "^4.0.0",
"@libp2p/kad-dht": "^9.1.0",
"@libp2p/webrtc": "^2.0.4",
"@libp2p/websockets": "^6.0.1",
"@libp2p/webtransport": "^2.0.1",
"@multiformats/mafmt": "^12.1.0",
"@multiformats/multiaddr": "^12.1.1",
"@types/node": "18.14.6",
Expand Down
11 changes: 7 additions & 4 deletions packages/frontend/src/components/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,14 @@ export default function ChatContainer({topic}: ChatProps) {
setMessageHistory([...messageHistory, { msg, from: 'other', peerId: evt.detail.from.toString(), topic: evt.detail.topic }])
}
}

//@ts-ignore: conditionally rendered
libp2p.services.pubsub.addEventListener('message', messageCB)

return () => {
// Cleanup handlers 👇
// libp2p.services.pubsub.unsubscribe(CHAT_TOPIC)
libp2p.services.pubsub.removeEventListener('message', messageCB)
//@ts-ignore: conditionally rendered
libp2p.services.pubsub.removeEventListener('message', messageCB)
}
}, [libp2p, messageHistory, setMessageHistory])

Expand All @@ -80,16 +81,18 @@ export default function ChatContainer({topic}: ChatProps) {

console.log(
'peers in gossip:',
libp2p.services.pubsub.getSubscribers(topic).toString(),
//@ts-ignore: conditionally rendered
libp2p.services.pubsub.getSubscribers(topic).toString(),
)

//@ts-ignore: conditionally rendered
const res = await libp2p.services.pubsub.publish(
topic,
new TextEncoder().encode(input),
)
console.log(
'sent message to: ',
res.recipients.map((peerId) => peerId.toString()),
res.recipients.map((peerId: any) => peerId.toString()),
)

const myPeerId = libp2p.peerId.toString()
Expand Down
60 changes: 45 additions & 15 deletions packages/frontend/src/components/peerControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,31 @@ import { multiaddr } from '@multiformats/multiaddr'
import { connectToMultiaddr } from '../lib/libp2p'
import PeerInfo from "./peerInfo"
import type { Connection } from '@libp2p/interface-connection'
import { useListenAddressesContext } from '@/context/listen-addresses-ctx'

function PeerControl() {
const { libp2p } = useLibp2pContext()
const { peerStats, setPeerStats } = usePeerContext()
const { listenAddresses, setListenAddresses } = useListenAddressesContext()
const [maddr, setMultiaddr] = useState('')
const [peersListOpen, setPeersListOpen] = useState<boolean>(false)
const [manuallySet, setManuallySet] = useState<boolean>(false)

useEffect(() => {
const peerConnectedCB = (evt: any) => {
const connection = evt.detail
setPeerStats({ ...peerStats, peerIds: [...peerStats.peerIds, connection.remotePeer], connections: [...peerStats.connections, connection], connected: true })
}

libp2p.addEventListener('peer:connect', peerConnectedCB)
const interval = setInterval(() => {
const connections = libp2p.getConnections()
setPeerStats({
...peerStats,
peerIds: connections.map(conn => conn.remotePeer),
connections: connections,
connected: true
})
})
// libp2p.addEventListener('peer:connect', peerConnectedCB)
return () => {
libp2p.removeEventListener('peer:connect', peerConnectedCB)
}
// libp2p.removeEventListener('peer:connect', peerConnectedCB)
clearInterval(interval)
}
}, [libp2p, peerStats, setPeerStats])

const handleConnectToMultiaddr = useCallback(
Expand All @@ -34,7 +41,7 @@ function PeerControl() {

try {
const connection = await connectToMultiaddr(libp2p)(multiaddr(maddr))
console.log('connection: ', connection)
//console.log('connection: ', connection)

return connection
} catch (e) {
Expand All @@ -44,21 +51,36 @@ function PeerControl() {
[libp2p, maddr],
)

useEffect(() => {
const interval = setInterval(() => {
const multiaddrs = libp2p.getMultiaddrs()

setListenAddresses({
...listenAddresses,
multiaddrs
})
}, 1000)

return () => {
clearInterval(interval)
}
}, [libp2p, listenAddresses, setListenAddresses])

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

connections.forEach((conn) => {
// console.log(`connection ${conn}`)
const exists = protoNames.get(conn.toString())
const dedupedProtonames = [...new Set(conn.toString())]
// console.log(`connection ${JSON.stringify(conn)}`)
const exists = protoNames.get(conn.remotePeer.toString())
const dedupedProtonames = [...new Set(conn.remotePeer.toString())]

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

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

Expand All @@ -68,7 +90,15 @@ function PeerControl() {
}))

}

/*
useEffect(() => {
getFormattedConnections(peerStats.connections)
.map(
(pair) =>
console.log(`peer ${JSON.stringify(pair)}`)
)
},[])
*/
const handleMultiaddrChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
setMultiaddr(e.target.value)
Expand Down
5 changes: 4 additions & 1 deletion packages/frontend/src/components/topicsControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ function TopicsControl({topicSelected, setTopicSelected}: TopicsControlProps) {
}, [])

const updateTopics = () => {
//@ts-ignore: conditionally rendered
let topics = libp2p.services.pubsub.getTopics()
if (topics != topicsList) {
setTopicsList(topics)
Expand All @@ -30,6 +31,7 @@ function TopicsControl({topicSelected, setTopicSelected}: TopicsControlProps) {
)
const suscribeToTopic = () => {
if (topicToSuscribe) {
//@ts-ignore: conditionally rendered
libp2p.services.pubsub.subscribe(topicToSuscribe)
updateTopics()
setTopicToSuscribe(null)
Expand Down Expand Up @@ -60,7 +62,8 @@ function TopicsControl({topicSelected, setTopicSelected}: TopicsControlProps) {
>
{d}{' '}
-{' '}
({libp2p.services.pubsub.getSubscribers(d).length/* does not update */})
{/* @ts-ignore: conditionally rendered */}
({libp2p.services.pubsub.getSubscribers(d).length})
</li>
)}
</ul>
Expand Down
11 changes: 8 additions & 3 deletions packages/frontend/src/context/ctx.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@ import type { Libp2p } from '@libp2p/interface-libp2p'
import { startLibp2p } from '../lib/libp2p'
import { ChatProvider } from './chat-ctx'
import { PeerProvider } from './peer-ctx'
import { ListenAddressesProvider } from './listen-addresses-ctx'
import { PubSub } from '@libp2p/interface-pubsub'

//import { createHelia } from 'helia';
//import type { Helia } from '@helia/interface'

// 👇 The context type will be avilable "anywhere" in the app
interface Libp2pContextInterface {
libp2p: Libp2p
libp2p: Libp2p<{pubsub: PubSub}>
}
export const libp2pContext = createContext<Libp2pContextInterface>({
// @ts-ignore to avoid having to check isn't undefined everywhere. Can't be undefined because children are conditionally rendered
Expand All @@ -29,7 +32,7 @@ interface WrapperProps {
}
let loaded = false
export function AppWrapper({ children }: WrapperProps) {
const [libp2p, setLibp2p] = useState<Libp2p>()
const [libp2p, setLibp2p] = useState<Libp2p<{pubsub: PubSub}>>()
// const [helia, setHelia] = useState<Helia>()

useEffect(() => {
Expand Down Expand Up @@ -67,7 +70,9 @@ export function AppWrapper({ children }: WrapperProps) {
<libp2pContext.Provider value={{ libp2p }}>
<ChatProvider>
<PeerProvider>
{children}
<ListenAddressesProvider>
{children}
</ListenAddressesProvider>
</PeerProvider>
</ChatProvider>
</libp2pContext.Provider>
Expand Down
34 changes: 34 additions & 0 deletions packages/frontend/src/context/listen-addresses-ctx.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React, { ReactNode, createContext, useContext, useState } from 'react'
import { Multiaddr } from '@multiformats/multiaddr'

export interface ListenAddresses {
multiaddrs: Multiaddr[]
}

export interface ListenAddressesContextInterface {
listenAddresses: ListenAddresses;
setListenAddresses: (addresses: ListenAddresses) => void;
}

export const listenAddressesContext = createContext<ListenAddressesContextInterface>({
listenAddresses: {
multiaddrs: []
},
setListenAddresses: () => { }
})

export const useListenAddressesContext = () => {
return useContext(listenAddressesContext);
};

export const ListenAddressesProvider = ({ children }: { children: ReactNode }) => {
const [listenAddresses, setListenAddresses] = useState<ListenAddresses>({
multiaddrs: []
});

return (
<listenAddressesContext.Provider value={{ listenAddresses, setListenAddresses }}>
{children}
</listenAddressesContext.Provider>
);
};
Loading

0 comments on commit 8f332cb

Please sign in to comment.