Skip to content

Commit

Permalink
feat: select peer to dial from drop down
Browse files Browse the repository at this point in the history
  • Loading branch information
adklempner committed Oct 31, 2023
1 parent 5f3b0e2 commit 2391874
Showing 1 changed file with 110 additions and 27 deletions.
137 changes: 110 additions & 27 deletions examples/light-js/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,42 @@
</head>

<body>
<div><h2>Status</h2></div>
<div>
<h2>Status</h2>
</div>
<div id="status"></div>

<div><h2>Local Peer Id</h2></div>
<div>
<h2>Local Peer Id</h2>
</div>
<div id="peer-id"></div>

<div><h2>Remote Peer Id</h2></div>
<div id="remote-peer-id"></div>

<label for="remote-multiaddr">Remote peer's multiaddr</label>
<input id="remote-multiaddr" type="text" value="" />
<div>
<h2>Select Peer</h2>
</div>
<div>
<button id="getPeersButton" type="button">Refresh Peers</button>
<select id="peer-select">
<option value=""></option>
</select>
</div>
<div>
<label for="remote-multiaddr">Remote peer's multiaddr</label>
</div>
<div style="margin-right: 1em">
<input
id="remote-multiaddr"
type="text"
value=""
style="width: 100%; max-width: 900px"
/>
</div>
<button disabled id="dial" type="button">Dial</button>

<div>
<h2>Remote Peers</h2>
</div>
<div id="remote-peer-id"></div>
<br />
<button disabled id="subscribe" type="button">Subscribe with Filter</button>
<button disabled id="unsubscribe" type="button">
Expand Down Expand Up @@ -61,6 +85,8 @@
const messagesDiv = document.getElementById("messages");
const textInput = document.getElementById("textInput");
const sendButton = document.getElementById("sendButton");
const getPeersButton = document.getElementById("getPeersButton");
const peersSelector = document.getElementById("peer-select");

const ContentTopic = "/js-waku-examples/1/chat/utf8";
const decoder = createDecoder(ContentTopic);
Expand All @@ -75,7 +101,7 @@
};

try {
await searchForPeer(statusDiv, remoteMultiAddrDiv);
await getPeers();
} catch (e) {
console.log("Failed to find a peer", e);
remoteMultiAddrDiv.value =
Expand All @@ -87,6 +113,37 @@

statusDiv.innerHTML = "<p>Starting Waku node.</p>";
await node.start();

// Queries all peers from libp2p peer store and updates list of connected peers
const updatePeersList = async () => {
// Generate <p> element with connection string from each peer
const peers = await node.libp2p.peerStore.all();
const peerIdElements = peers.map((peer) => {
const element = document.createElement("p");
element.textContent = `${peer.addresses[1].multiaddr}/p2p/${peer.id}`;
return element;
});
// Update elements displaying list of peers
remotePeerIdDiv.replaceChildren(...peerIdElements);
};

// Refreshes list of connected peers each time a new one is detected
node.store.addLibp2pEventListener("peer:connect", async (event) => {
const peerId = event.detail;
console.log(`Peer connected with peer id: ${peerId}`);
// Wait half a second after receiving event for peer to show up in peer store
setTimeout(async () => {
updatePeersList();
}, 500);

// Update status
statusDiv.innerHTML = `<p>Peer dialed: ${peerId}</p>`;
// Enable send and subscribe inputs as we are now connected to a peer
textInput.disabled = false;
sendButton.disabled = false;
subscribeButton.disabled = false;
});

statusDiv.innerHTML = "<p>Waku node started.</p>";
peerIdDiv.innerHTML = "<p>" + node.libp2p.peerId.toString() + "</p>";
dialButton.disabled = false;
Expand All @@ -98,15 +155,14 @@
return;
}
statusDiv.innerHTML = "<p>Dialing peer.</p>";
const multiaddr = MultiformatsMultiaddr.multiaddr(ma);
let multiaddr;
try {
multiaddr = MultiformatsMultiaddr.multiaddr(ma);
} catch (err) {
statusDiv.innerHTML = "<p>Error: invalid multiaddr provided</p>";
throw err;
}
await node.dial(multiaddr, ["filter", "lightpush"]);
await waitForRemotePeer(node, ["filter", "lightpush"]);
const peers = await node.libp2p.peerStore.all();
statusDiv.innerHTML = "<p>Peer dialed.</p>";
remotePeerIdDiv.innerHTML = "<p>" + peers[0].id.toString() + "</p>";
textInput.disabled = false;
sendButton.disabled = false;
subscribeButton.disabled = false;
};

const callback = (wakuMessage) => {
Expand Down Expand Up @@ -139,19 +195,46 @@
textInput.value = null;
};

async function searchForPeer(statusNode, multiaddrNode) {
statusDiv.innerHTML = "<p>Discovering peer</p>";
getPeersButton.onclick = async () => {
await getPeers(statusDiv, remoteMultiAddrDiv);
};

peersSelector.addEventListener("change", function (event) {
remoteMultiAddrDiv.value = event.target.value;
});

//
async function getPeers() {
// Display status
statusDiv.innerHTML = "<p>Discovering peers</p>";

// Clear all options in select element
peersSelector.innerHTML = "";

// Get peers using DNS discovery
const defaultNodeCount = 5;
const dnsDiscovery = await DnsNodeDiscovery.dnsOverHttp();
const peersIterator = await dnsDiscovery.getNextPeer(
[enrTree["TEST"]],
{ lightPush: 1, filter: 1 }
);
const peerEnr = await peersIterator.next();
const ma = peerEnr.value.multiaddrs.map((v) => v.toString())[1];
const peerId = peerEnr.value.peerId.toString();

multiaddrNode.value = `${ma}/p2p/${peerId}`;
const peers = await dnsDiscovery.getPeers([enrTree["TEST"]], {
relay: defaultNodeCount,
store: defaultNodeCount,
filter: defaultNodeCount,
lightPush: defaultNodeCount,
});

// Create an option element for each peer's multiaddr and append to select element
const optionElements = peers.map((peer) => {
const optionElement = document.createElement("option");
optionElement.value = `${peer.multiaddrs[1]}/p2p/${peer.peerId}`;
optionElement.text = `${peer.multiaddrs[1]}/p2p/${peer.peerId}`;
return optionElement;
});
peersSelector.append(...optionElements);

// Set first peer as selected
peersSelector.options[0].selected = true;
remoteMultiAddrDiv.value = selectElement.options[0].value;

statusDiv.innerHTML = "<p>Peers discovered</p>";
}
</script>
</body>
Expand Down

0 comments on commit 2391874

Please sign in to comment.