Skip to content

Commit

Permalink
added useWebRTC and useWebsocket toggle button so both transports can…
Browse files Browse the repository at this point in the history
… be tested independently
  • Loading branch information
silkroadnomad committed Mar 26, 2024
1 parent df8cbb5 commit e9017a5
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 23 deletions.
12 changes: 6 additions & 6 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,11 @@ export const config = {
protocol: '/ipfs/kad/1.0.0',
peerInfoMapper: removePrivateAddressesMapper
})*/
dht: kadDHT({
protocolPrefix: "/svelte-pubsub",
maxInboundStreams: 5000,
maxOutboundStreams: 5000,
clientMode: true,
})
// dht: kadDHT({
// protocolPrefix: "/svelte-pubsub",
// maxInboundStreams: 5000,
// maxOutboundStreams: 5000,
// clientMode: true,
// })
}
}
30 changes: 18 additions & 12 deletions src/lib/components/Settings.svelte
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
<script>
import { TextInput, Button, Column, Grid, Row, PasswordInput } from "carbon-components-svelte";
import { writable } from 'svelte/store';
import { TextInput, PasswordInput, Button, Column, Grid, Row, Toggle } from "carbon-components-svelte";
import {
libp2p,
connectedPeers,
masterSeed,
orbitdb, seedPhrase,
dbMyAddressBook, selectedAddr, selectedTab
dbMyAddressBook, selectedAddr, selectedTab,
useWebRTC,
useWebSocket
} from "../../stores.js"
$:window.localStorage.setItem('seed', $masterSeed);
$:window.localStorage.setItem('seedPhrase', $seedPhrase);
</script>
$:window.localStorage.setItem('useWebRTC', $useWebRTC.toString());
$:window.localStorage.setItem('useWebSocket', $useWebSocket.toString());
console.log("useWebRTC",$useWebRTC)
</script>

<!--
@component Settings component displays current address of db and my handle
The handle is used in order to set write permissions for the databases
*/
-->
<Grid>
<Row>
Expand All @@ -27,12 +33,6 @@

<Row class="custom-row">
<Column sm={3}><PasswordInput labelText="Seed Phrase" helperText="If you change the seed phrase a new DID is generated" size="sm" bind:value={$seedPhrase} /></Column>
<!-- <Column size="small"><Button kind="tertiary" on:click={ async () => {-->
<!-- const result = await confirm({ data: {-->
<!-- text: "the contact data of this user are (will be) stored in an own orbit-db document table, " +-->
<!-- "all data inside are encrypted so from outside nobody could ever decrypt it even when connecting to our peer this database." +-->
<!-- "when this button is clicked the OrbitDBs will be re-connected according to our new seed." } })-->
<!-- }}>Sync My Devices</Button></Column>-->
</Row>

<Row>
Expand All @@ -49,6 +49,14 @@
size="sm"
value={$connectedPeers} /></Column>
</Row>
<Row>
<Column sm={3}>
<Toggle id="webrtc-toggle" labelText="WebRTC" bind:toggled={$useWebRTC} /></Column>
</Row>
<Row>
<Column sm={3}>
<Toggle id="websocket-toggle" labelText="WebSocket" bind:toggled={$useWebSocket} /></Column>
</Row>
<Row class="custom-row">
<Column sm={1}><Button data-cy="DropFollowerDBs" size="sm" on:click={async () => {
const addressRecords = await $dbMyAddressBook.all();
Expand Down Expand Up @@ -76,8 +84,6 @@
selectedAddr.set({})
selectedTab.set(0)
}}>Drop AddressDB</Button></Column>


</Row>

</Grid>
Expand Down
70 changes: 65 additions & 5 deletions src/lib/network/p2p-operations.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { LevelBlockstore } from "blockstore-level"
import { LevelDatastore } from "datastore-level";
import { bitswap } from '@helia/block-brokers'
import { config } from "../../config.js";
import { webSockets } from "@libp2p/websockets";
import * as filters from "@libp2p/websockets/filters";
import { webRTC, webRTCDirect } from "@libp2p/webrtc";
import { webTransport } from "@libp2p/webtransport";
import {
libp2p,
helia,
Expand All @@ -15,8 +19,10 @@ import {
dbMyAddressBook,
subscription,
connectedPeers,
followList, dbMessages, selectedTab, syncedDevices,
followList, dbMessages, selectedTab, syncedDevices,useWebRTC, useWebSocket
} from "../../stores.js";

import { get } from 'svelte/store';
import { confirm } from "../components/addressModal.js"
import {notify, sha256} from "../../utils/utils.js";
import { getIdentityAndCreateOrbitDB } from "$lib/network/getIdendityAndCreateOrbitDB.js";
Expand All @@ -27,6 +33,10 @@ let datastore = new LevelDatastore("./helia-data")
let messageQueue = {};
let activeConfirmations = {};

let _libp2p; /** @type {import('libp2p').Libp2p} Value of to the libp2p store variable containing the libp2p instance*/
libp2p.subscribe((val) => {
_libp2p = val
});

/**
* The PubSub topic where deContact is publishing and subscribing
Expand Down Expand Up @@ -133,6 +143,60 @@ async function handleMessage(dContactMessage) {
await processMessageQueue();
}


// Function to restart libp2p with selected transports
async function restartLibp2p() {
const webRTCEnabled = get(useWebRTC);
const webSocketEnabled = get(useWebSocket);

// Assuming you have a function to stop the current libp2p instance
if (_libp2p) {
await _libp2p.stop();
}


// Clear existing transports before adding new ones
config.transports = [];

if (webRTCEnabled) {
const webRTCConfig = webRTC({
rtcConfiguration: {
iceServers: [{
urls: [
'stun:stun.l.google.com:19302',
'stun:global.stun.twilio.com:3478'
]
}]
}
});
config.transports.push(webRTCConfig, webRTCDirect());
}

if (webSocketEnabled) {
const webSocketConfig = webSockets({filter: filters.all});
config.transports.push(webSocketConfig);
}
console.log("restarting libp2p with config",config)
_libp2p = await createLibp2p(config)

}

// React to changes in the toggle states with initial call prevention
let isInitialCall = true;

useWebRTC.subscribe(() => {
if (!isInitialCall) {
restartLibp2p();
}
});

useWebSocket.subscribe(() => {
if (!isInitialCall) {
restartLibp2p();
}
});

isInitialCall = false;
/**
* We want to open a confirmation dialog for each sender sending a pub sub message. (in case it's coming in same time)
* @returns {Promise<void>}
Expand Down Expand Up @@ -420,10 +484,6 @@ export async function writeMyAddressIntoRequesterDB(requesterDB) {
}
}

let _libp2p; /** @type {import('libp2p').Libp2p} Value of to the libp2p store variable containing the libp2p instance*/
libp2p.subscribe((val) => {
_libp2p = val
});

/**
* Subscription to the helia store variable containing the Helia instance
Expand Down
3 changes: 3 additions & 0 deletions src/stores.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ export const recordsSynced = writable(0)
export const showNotification = writable()
export const notificationMessage = writable()

export const useWebRTC = writable(window.localStorage.getItem('useWebRTC') !== null ? window.localStorage.getItem('useWebRTC') === 'true' : true);
export const useWebSocket = writable(window.localStorage.getItem('useWebSocket') === 'true' ? true : false); // Default off

export const followList = writable([] )
export const qrCodeOpen = writable(false)
export const qrCodeData = writable()
Expand Down

0 comments on commit e9017a5

Please sign in to comment.