webpeerjs 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  //! WebPEER.js -- https://github.com/nuzulul/webpeerjs
2
2
 
3
- import * as config from './config'
3
+ import * as config from './config.js'
4
4
  import {
5
5
  mkErr,
6
6
  PBPeer,
@@ -16,8 +16,8 @@ import {
16
16
  pipe,
17
17
  lp,
18
18
  map
19
- } from './utils'
20
- import { createDelegatedRoutingV1HttpApiClient } from '@helia/delegated-routing-v1-http-api-client'
19
+ } from './utils.js'
20
+ import { delegatedRoutingV1HttpApiClient } from '@helia/delegated-routing-v1-http-api-client'
21
21
  import { createLibp2p } from 'libp2p'
22
22
  import { IDBDatastore } from 'datastore-idb'
23
23
  import { webTransport } from '@libp2p/webtransport'
@@ -28,13 +28,18 @@ import { noise } from '@chainsafe/libp2p-noise'
28
28
  import { yamux } from '@chainsafe/libp2p-yamux'
29
29
  import { pubsubPeerDiscovery } from '@libp2p/pubsub-peer-discovery'
30
30
  import { circuitRelayTransport } from '@libp2p/circuit-relay-v2'
31
- import { gossipsub } from '@chainsafe/libp2p-gossipsub'
31
+ import { gossipsub } from '@libp2p/gossipsub'
32
32
  import { identify, identifyPush } from '@libp2p/identify'
33
33
  import { peerIdFromString } from '@libp2p/peer-id'
34
34
  import { kadDHT, removePrivateAddressesMapper } from '@libp2p/kad-dht'
35
35
  import { simpleMetrics } from '@libp2p/simple-metrics'
36
+ import { ping } from '@libp2p/ping';
37
+ import { defaultLogger } from '@libp2p/logger';
38
+ import {createSignalingServer} from 'signalingserver.js';
36
39
 
37
-
40
+ /**************************************************************************
41
+ * Main class
42
+ **************************************************************************/
38
43
  class webpeerjs{
39
44
 
40
45
  //libp2p instance
@@ -117,7 +122,7 @@ class webpeerjs{
117
122
  address
118
123
  peers
119
124
 
120
- constructor(libp2p,dbstore,onMetrics,onWebsocketFn,onDialFn){
125
+ constructor(signalingserver,libp2p,dbstore,onMetrics,onWebsocketFn,onDialFn){
121
126
 
122
127
  this.#libp2p = libp2p
123
128
  this.#dbstore = dbstore
@@ -127,7 +132,7 @@ class webpeerjs{
127
132
  this.#webPeersId = []
128
133
  this.#webPeersAddrs = new Map()
129
134
  this.#dialedGoodPeers = new Map()
130
- this.#isDialWebsocket = false
135
+ this.#isDialWebsocket = false;
131
136
  this.#dialedKnownBootstrap = new Map()
132
137
  //this.#dialedDiscoveredPeers = []
133
138
  this.address = []
@@ -170,9 +175,37 @@ class webpeerjs{
170
175
 
171
176
  for(const topic of config.CONFIG_PUBSUB_PEER_DISCOVERY_HYBRID){
172
177
  this.#libp2p.services.pubsub.subscribe(topic)
173
- }
178
+ }
179
+
180
+
181
+ /**************************************************************************
182
+ * Signaling server
183
+ **************************************************************************/
184
+ signalingserver.data((signal,signal_id)=>{
185
+ if(!this.#connections.has(signal.id)){
186
+ let mddrs = []
187
+ for(const addr of signal.address){
188
+ if(!addr.includes('webrtc'))continue
189
+ const mddr = multiaddr(addr)
190
+ mddrs.push(mddr)
191
+ }
192
+ this.#dialMultiaddress(mddrs)
193
+ }
194
+ })
195
+
196
+ setInterval(()=>{
197
+ const broadcast = {
198
+ id : this.id,
199
+ address : this.address
200
+ }
201
+ signalingserver.send(broadcast);
202
+ },10*1500)
203
+
174
204
 
175
- //listen to peer connect event
205
+
206
+ /**************************************************************************
207
+ * Listen on incoming connection
208
+ **************************************************************************/
176
209
  this.#libp2p.addEventListener("peer:connect",async (evt) => {
177
210
 
178
211
  //const connection = evt.detail;
@@ -240,7 +273,10 @@ class webpeerjs{
240
273
  });
241
274
 
242
275
 
243
- //listen message from subscribed pupsub topic
276
+
277
+ /**************************************************************************
278
+ * Listen message from subscribed pupsub topic
279
+ **************************************************************************/
244
280
  this.#libp2p.services.pubsub.addEventListener('message', event => {
245
281
 
246
282
  //console.log('on:'+event.detail.topic,event.detail.data)
@@ -410,13 +446,14 @@ class webpeerjs{
410
446
 
411
447
  //inbound message
412
448
  //use #msgIdtracker to prevent double message
413
- //use #msgTimeTracker to limit inbound message 1msg/s
449
+ //use #msgTimeTracker to limit inbound message count /s
414
450
  if(message){
415
451
  const msgID = msgId+id
416
452
  let oldmsgtime = 0
417
453
  let newmsgtime = new Date().getTime()
418
454
  if(this.#msgTimeTracker.has(id))oldmsgtime = this.#msgTimeTracker.get(id)
419
- const msgtimelimit = 1000
455
+ //const msgtimelimit = 1000
456
+ const msgtimelimit = -1
420
457
  if(!this.#msgIdtracker.has(msgID) && newmsgtime-oldmsgtime>msgtimelimit){
421
458
  this.#msgIdtracker.set(msgID,newmsgtime)
422
459
  this.#msgTimeTracker.set(id,newmsgtime)
@@ -484,7 +521,10 @@ class webpeerjs{
484
521
  })
485
522
 
486
523
 
487
- //listen to peer discovery event
524
+
525
+ /**************************************************************************
526
+ * Listen to peer discovery event
527
+ **************************************************************************/
488
528
  this.#libp2p.addEventListener('peer:discovery', (evt) => {
489
529
 
490
530
  //console.log('Discovered:', evt.detail.id.toString())
@@ -535,7 +575,10 @@ class webpeerjs{
535
575
  })
536
576
 
537
577
 
538
- //listen to peer disconnect event
578
+
579
+ /**************************************************************************
580
+ * Listen to peer disconnect event
581
+ **************************************************************************/
539
582
  this.#libp2p.addEventListener("peer:disconnect",async (evt) => {
540
583
 
541
584
  //const connection = evt.detail;
@@ -610,10 +653,16 @@ class webpeerjs{
610
653
  });
611
654
 
612
655
 
613
- //listen to self peer update
656
+
657
+ /**************************************************************************
658
+ * Listen to listen address change
659
+ **************************************************************************/
614
660
  this.#libp2p.addEventListener('self:peer:update', ({ detail: { peer } }) => {
661
+
662
+ //console.log('peer',peer)
615
663
  //const multiaddrs = peer.addresses.map(({ multiaddr }) => multiaddr)
616
664
  //console.log(`changed multiaddrs: peer ${peer.id.toString()} multiaddrs: ${multiaddrs}`)
665
+
617
666
  const id = peer.id.toString()
618
667
  const addrs = []
619
668
  peer.addresses.forEach((address)=>{
@@ -629,6 +678,10 @@ class webpeerjs{
629
678
  this.#peerDiscoveryHybrid()
630
679
  })
631
680
 
681
+
682
+ /**************************************************************************
683
+ * Listen on identity service
684
+ **************************************************************************/
632
685
  this.#libp2p.addEventListener('peer:identify', async (evt) => {
633
686
  //console.log('peer:identify '+evt.detail.peerId.toString(),evt.detail)
634
687
 
@@ -672,10 +725,9 @@ class webpeerjs{
672
725
  //reset this last seen
673
726
  const now = new Date().getTime()
674
727
  const metadata = {addrs:address,last:now}
675
- this.#connectedPeers.set(id,metadata)
728
+ this.#connectedPeers.set(id,metadata);
676
729
  }
677
730
 
678
-
679
731
  const command = 'peer-exchange'
680
732
  this.#dialProtocol(id,command)
681
733
 
@@ -757,8 +809,10 @@ class webpeerjs{
757
809
  },30e3)*/
758
810
 
759
811
  }
760
-
761
-
812
+
813
+ //this.#getAddress = (function(address) {
814
+ ///return this.address
815
+ //})(this.address);
762
816
 
763
817
 
764
818
  /*
@@ -806,16 +860,16 @@ class webpeerjs{
806
860
  listenMessage : f => (this.#rooms[room] = {...this.#rooms[room], onMessage: f}),
807
861
  sendMessage : async (message) => {
808
862
  const now = (new Date()).getTime()
809
- if(now-this.#sendMessageTimeTracker < 1000){
810
- throw mkErr('can not send more than 1 message/s')
811
- }
863
+ //if(now-this.#sendMessageTimeTracker < 1000){
864
+ //throw mkErr('can not send more than 1 message/s')
865
+ //}
812
866
  this.#sendMessageTimeTracker = now
813
- const msgId = (new Date()).getTime()
867
+ const msgId = crypto.randomUUID();
814
868
  const data = JSON.stringify({prefix:config.CONFIG_PREFIX,room,message,id:this.#libp2p.peerId.toString(),msgId})
815
869
  const arr = uint8ArrayFromString(data)
816
870
  const sizelimit = config.CONFIG_MESSAGE_SIZE_LIMIT
817
871
  if(arr.byteLength > sizelimit){
818
- throw mkErr('message too large')
872
+ throw mkErr(`Message too large more than ${sizelimit} byte`);
819
873
  }
820
874
  const peer = {
821
875
  publicKey: this.#libp2p.peerId.publicKey,
@@ -832,11 +886,11 @@ class webpeerjs{
832
886
  }
833
887
  }
834
888
 
835
- return [
836
- this.#rooms[room].sendMessage,
837
- this.#rooms[room].listenMessage,
838
- this.#rooms[room].onMembersChange
839
- ]
889
+ return {
890
+ sendMessage : this.#rooms[room].sendMessage,
891
+ onMessage : this.#rooms[room].listenMessage,
892
+ onMembersChange : this.#rooms[room].onMembersChange
893
+ }
840
894
  }
841
895
 
842
896
  dial(addr){
@@ -930,10 +984,18 @@ class webpeerjs{
930
984
  }
931
985
  this.#ping()
932
986
  }
933
-
987
+
988
+
989
+
990
+ /**************************************************************************
991
+ * Handle custom protocol
992
+ **************************************************************************/
934
993
  async #registerProtocol(){
935
994
 
936
995
  const handler = async ({ connection, stream }) => {
996
+
997
+ //console.log('onprotocol',connection);
998
+
937
999
  try{
938
1000
  const output = await pipe(
939
1001
  stream.source,
@@ -1021,7 +1083,7 @@ class webpeerjs{
1021
1083
  await this.#libp2p.handle(config.CONFIG_PROTOCOL, handler, {
1022
1084
  maxInboundStreams: 100,
1023
1085
  maxOutboundStreams: 100,
1024
- runOnTransientConnection:config.CONFIG_RUN_ON_TRANSIENT_CONNECTION
1086
+ runOnLimitedConnection:config.CONFIG_RUN_ON_TRANSIENT_CONNECTION
1025
1087
  })
1026
1088
 
1027
1089
  await this.#libp2p.register(config.CONFIG_PROTOCOL, {
@@ -1036,7 +1098,11 @@ class webpeerjs{
1036
1098
  })
1037
1099
 
1038
1100
  }
1039
-
1101
+
1102
+
1103
+ /**************************************************************************
1104
+ * Dial custom protocol
1105
+ **************************************************************************/
1040
1106
  async #dialProtocol(id,command){
1041
1107
 
1042
1108
  const connections = this.#libp2p.getConnections().map((con)=>{return {id:con.remotePeer.toString(),addr:con.remoteAddr.toString()}})
@@ -1068,7 +1134,7 @@ class webpeerjs{
1068
1134
 
1069
1135
  try{
1070
1136
 
1071
- const stream = await this.#libp2p.dialProtocol(mddr, config.CONFIG_PROTOCOL,{runOnTransientConnection:config.CONFIG_RUN_ON_TRANSIENT_CONNECTION})
1137
+ const stream = await this.#libp2p.dialProtocol(mddr, config.CONFIG_PROTOCOL,{runOnLimitedConnection:config.CONFIG_RUN_ON_TRANSIENT_CONNECTION})
1072
1138
 
1073
1139
  const output = await pipe(
1074
1140
  message,
@@ -1128,6 +1194,8 @@ class webpeerjs{
1128
1194
  }
1129
1195
 
1130
1196
  async #findHybridPeer(){
1197
+
1198
+ return;
1131
1199
 
1132
1200
  if(!navigator.onLine)return
1133
1201
  if(!this.#isDialEnabled)return
@@ -1622,7 +1690,7 @@ class webpeerjs{
1622
1690
  if(firsttime){
1623
1691
  for(const target of config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS){
1624
1692
  const api = config.CONFIG_DELEGATED_API
1625
- const delegatedClient = createDelegatedRoutingV1HttpApiClient(api)
1693
+ const delegatedClient = delegatedRoutingV1HttpApiClient({url:api})({logger: defaultLogger()})
1626
1694
  const peer = await first(delegatedClient.getPeers(peerIdFromString(target)))
1627
1695
  if(!peer)continue
1628
1696
  const address = peer.Addrs
@@ -1657,7 +1725,7 @@ class webpeerjs{
1657
1725
  if(!this.#connections.has(target) && (this.#dbstoreData.has(target) || firsttime)){
1658
1726
  //console.log('#dialUpdateSavedKnownID()',target)
1659
1727
  const api = config.CONFIG_DELEGATED_API
1660
- const delegatedClient = createDelegatedRoutingV1HttpApiClient(api)
1728
+ const delegatedClient = delegatedRoutingV1HttpApiClient({url:api})({logger: defaultLogger()})
1661
1729
  const peer = await first(delegatedClient.getPeers(peerIdFromString(target)))
1662
1730
  if(!peer){
1663
1731
  if (navigator.onLine) {
@@ -1693,7 +1761,7 @@ class webpeerjs{
1693
1761
 
1694
1762
  //console.log('#dialKnownID()')
1695
1763
  const api = config.CONFIG_DELEGATED_API
1696
- const delegatedClient = createDelegatedRoutingV1HttpApiClient(api)
1764
+ const delegatedClient = delegatedRoutingV1HttpApiClient({url:api})({logger: defaultLogger()})
1697
1765
  const BOOTSTRAP_PEER_IDS = config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS
1698
1766
  const peers = await Promise.all(
1699
1767
  BOOTSTRAP_PEER_IDS.map((peerId) => first(delegatedClient.getPeers(peerIdFromString(peerId)))),
@@ -1766,7 +1834,7 @@ class webpeerjs{
1766
1834
  BOOTSTRAP_PEER_IDS.push(id)
1767
1835
  }
1768
1836
  const api = config.CONFIG_DELEGATED_API
1769
- const delegatedClient = createDelegatedRoutingV1HttpApiClient(api)
1837
+ const delegatedClient = delegatedRoutingV1HttpApiClient({url:api})({logger: defaultLogger()})
1770
1838
  const peers = await Promise.all(
1771
1839
  BOOTSTRAP_PEER_IDS.map((peerId) => first(delegatedClient.getPeers(peerIdFromString(peerId)))),
1772
1840
  )
@@ -1845,7 +1913,7 @@ class webpeerjs{
1845
1913
 
1846
1914
  //dial only webtransport multiaddrs
1847
1915
  async #dialWebtransport(multiaddrs){
1848
- const webTransportMadrs = multiaddrs.filter((maddr) => maddr.protoNames().includes('webtransport')&&maddr.protoNames().includes('certhash'))
1916
+ const webTransportMadrs = multiaddrs.filter((maddr) => maddr.toString().includes('webtransport')&&maddr.toString().includes('certhash'))
1849
1917
  for (const mddr of webTransportMadrs) {
1850
1918
  try {
1851
1919
  //console.log(`attempting to dial webtransport multiaddr: %o`, mddr.toString())
@@ -1860,7 +1928,7 @@ class webpeerjs{
1860
1928
 
1861
1929
  //dial only websocket multiaddrs
1862
1930
  async #dialWebsocket(multiaddrs){
1863
- const webSocketMadrs = multiaddrs.filter((maddr) => maddr.protoNames().includes('wss'))
1931
+ const webSocketMadrs = multiaddrs.filter((maddr) => maddr.toString().includes('wss'))
1864
1932
  for (const mddr of webSocketMadrs) {
1865
1933
  try {
1866
1934
  //console.log(`attempting to dial websocket multiaddr: %o`, mddr)
@@ -1872,293 +1940,185 @@ class webpeerjs{
1872
1940
  }
1873
1941
  }
1874
1942
  }
1875
-
1876
-
1877
- //entry point to webpeerjs
1878
- static async createWebpeer(){
1879
-
1880
- // all libp2p debug logs
1881
- //localStorage.setItem('debug', 'libp2p:*')
1882
-
1883
- const dbstore = new IDBDatastore(config.CONFIG_DBSTORE_PATH)
1884
- await dbstore.open()
1885
-
1886
- const bootstrapAddrs = []
1887
-
1888
- //let addrs = []
1889
- const getbootstrap = config.CONFIG_KNOWN_BOOTSTRAP_PEERS_ADDRS
1890
- for(const peer of getbootstrap){
1891
- const addrs = peer.Peers[0].Addrs
1892
- const id = peer.Peers[0].ID
1893
- //let mddrs = []
1894
- for(const addr of addrs){
1895
- if(addr.includes('webtransport')&&addr.includes('certhash')){
1896
- bootstrapAddrs.push(addr+'/p2p/'+id)
1897
- }
1898
- }
1899
- }
1900
-
1901
- let onMetricsFn = () => {}
1902
- const onMetrics = f => (onMetricsFn = f)
1903
-
1904
- let isWebsocket = false
1905
- let onWebsocketFn = () => {}
1906
- const onWebsocket = f => (onWebsocketFn = f)
1907
- onWebsocket((data)=>{
1908
- isWebsocket = data
1909
- })
1910
-
1911
- let isDial = true
1912
- let onDialFn = () => {}
1913
- const onDial = f => (onDialFn = f)
1914
- onDial((data)=>{
1915
- //if(isDial!=data)console.warn('isDial',data)
1916
- isDial = data
1917
- })
1918
-
1919
- let listenaddress = []
1920
-
1921
- if(config.CONFIG_RUN_ON_TRANSIENT_CONNECTION == false){
1922
- listenaddress.push('/webrtc')
1923
- }
1924
-
1925
- const stunurls = config.CONFIG_WEBRTC_STUN_URLS
1926
- const stunurlsbackup = config.CONFIG_WEBRTC_STUN_URLS_BACKUP
1927
-
1928
- const turnurls = atob(config.CONFIG_WEBRTC_TURN_HOST)
1929
- const turnusername = atob(config.CONFIG_WEBRTC_TURN_USER)
1930
- const turncredential = atob(config.CONFIG_WEBRTC_TURN_PWD)
1931
1943
 
1932
- const turnurlsbackup = atob(config.CONFIG_WEBRTC_TURN_HOST_BACKUP)
1933
- const turnusernamebackup = atob(config.CONFIG_WEBRTC_TURN_USER_BACKUP)
1934
- const turncredentialbackup = atob(config.CONFIG_WEBRTC_TURN_PWD_BACKUP)
1935
-
1936
- async function checkice(stunurls,turnurls,turnusername,turncredential,time){
1937
- return new Promise((resolve)=>{
1938
-
1939
- let stun = false
1940
- let turn = false
1941
-
1942
- const timeout = setTimeout(()=>{
1943
- let ice = []
1944
- ice.push(stun)
1945
- ice.push(turn)
1946
- resolve(ice)
1947
- },time)
1948
-
1949
- function check(){
1950
- if(stun && turn){
1951
- let ice = []
1952
- ice.push(stun)
1953
- ice.push(turn)
1954
- clearTimeout(timeout)
1955
- resolve(ice)
1956
- }
1957
- }
1958
-
1959
- //test ice servers
1960
-
1961
- const iceServers = [
1962
- {
1963
- urls: stunurls
1964
- },
1965
- {
1966
- urls: turnurls,
1967
- username: turnusername,
1968
- credential: turncredential
1969
- }
1970
- ];
1971
-
1972
- const pc = new RTCPeerConnection({
1973
- iceServers
1974
- });
1975
-
1976
- pc.onicecandidate = (e) => {
1977
- if (!e.candidate) return;
1944
+ }
1978
1945
 
1979
- //console.log(e.candidate.candidate);
1980
1946
 
1981
- // stun works
1982
- if(e.candidate.type == "srflx"){
1983
- //console.log('publicip',e.candidate.address);
1984
- stun = {
1985
- urls: stunurls
1986
- }
1987
- check()
1988
- }
1989
-
1990
- // turn works
1991
- if(e.candidate.type == "relay"){
1992
- turn = {
1993
- urls: turnurls,
1994
- username: turnusername,
1995
- credential: turncredential
1996
- }
1997
- check()
1998
- }
1999
- };
1947
+ /**************************************************************************
1948
+ * Entry point to create a new peer
1949
+ **************************************************************************/
1950
+ const createWebPEER = async (configuration) => {
2000
1951
 
2001
- pc.onicecandidateerror = (e) => {
2002
- console.debug(e);
2003
- };
2004
-
2005
- pc.createDataChannel('webpeerjs');
2006
- pc.createOffer().then(offer => pc.setLocalDescription(offer));
2007
- })
2008
- }
2009
-
2010
- let ice = []
2011
-
2012
- let configuration = {}
2013
-
2014
- if(arguments.length > 0){
2015
- configuration = arguments[0]
1952
+ // all libp2p debug logs
1953
+ if(config.CONFIG_DEBUG_ENABLED){
1954
+ localStorage.setItem('debug', 'libp2p:*');
1955
+ }
1956
+
1957
+ let signalconfig = {};
1958
+ if(configuration && configuration.networkName){
1959
+ signalconfig['appid'] = configuration.networkName;
1960
+ }else{
1961
+ signalconfig['appid'] = config.CONFIG_PREFIX;
1962
+ }
1963
+
1964
+ const signalingserver = createSignalingServer(signalconfig);
1965
+
1966
+ const dbstore = new IDBDatastore(config.CONFIG_DBSTORE_PATH)
1967
+ await dbstore.open()
1968
+
1969
+ const bootstrapAddrs = []
1970
+
1971
+ //let addrs = []
1972
+ const getbootstrap = config.CONFIG_KNOWN_BOOTSTRAP_PEERS_ADDRS
1973
+ for(const peer of getbootstrap){
1974
+ const addrs = peer.Peers[0].Addrs
1975
+ const id = peer.Peers[0].ID
1976
+ //let mddrs = []
1977
+ for(const addr of addrs){
1978
+ if(addr.includes('webtransport')&&addr.includes('certhash')){
1979
+ bootstrapAddrs.push(addr+'/p2p/'+id)
1980
+ }
2016
1981
  }
2017
-
2018
- //set rtc configuration
2019
- if(configuration.rtcConfiguration === undefined){
2020
-
2021
- ice = await checkice(stunurls,turnurls,turnusername,turncredential,5000)
1982
+ }
2022
1983
 
2023
- //console.log(ice)
2024
-
2025
- //recheck ice
2026
- if(!ice[0] && !ice[1]){
2027
- ice = await checkice(stunurlsbackup,turnurlsbackup,turnusernamebackup,turncredentialbackup,5000)
2028
- }else if (ice[0] && !ice[1]){
2029
- ice = await checkice(stunurls,turnurlsbackup,turnusernamebackup,turncredentialbackup,5000)
2030
- }else if (!ice[0] && ice[1]){
2031
- ice = await checkice(stunurlsbackup,turnurls,turnusername,turncredential,5000)
2032
- }
2033
-
2034
- //console.log(ice)
2035
-
2036
- //final ice remove false value
2037
- ice.forEach(function(value, index) {
2038
- if(!value){
2039
- this.splice(index, 1)
2040
- }
2041
- }, ice);
2042
-
2043
- //console.log(ice)
1984
+ let onMetricsFn = () => {}
1985
+ const onMetrics = f => (onMetricsFn = f)
1986
+
1987
+ let isWebsocket = false
1988
+ let onWebsocketFn = () => {}
1989
+ const onWebsocket = f => (onWebsocketFn = f)
1990
+ onWebsocket((data)=>{
1991
+ isWebsocket = data
1992
+ })
1993
+
1994
+ let isDial = true
1995
+ let onDialFn = () => {}
1996
+ const onDial = f => (onDialFn = f)
1997
+ onDial((data)=>{
1998
+ //if(isDial!=data)console.warn('isDial',data)
1999
+ isDial = data
2000
+ })
2001
+
2002
+ let listenaddress = ['/p2p-circuit']
2003
+
2004
+ if(config.CONFIG_RUN_ON_TRANSIENT_CONNECTION == false){
2005
+ listenaddress.push('/webrtc')
2006
+ }
2007
+
2008
+ let webrtcconfig = {}
2044
2009
 
2045
- configuration.rtcConfiguration = {
2046
- iceServers: ice,
2047
- }
2048
- }
2049
-
2050
-
2051
- //create libp2p instance
2052
- const libp2p = await createLibp2p({
2053
- addresses: {
2054
- listen: listenaddress,
2055
- },
2056
- transports:[
2057
- webTransport(),
2058
- webSockets(),
2059
- webRTC({
2060
- rtcConfiguration: configuration.rtcConfiguration,
2061
- }),
2062
- circuitRelayTransport({
2063
- discoverRelays: config.CONFIG_DISCOVER_RELAYS,
2064
- reservationConcurrency: 1,
2065
- maxReservationQueueLength: 3
2066
- }),
2067
- ],
2068
- connectionManager: {
2069
- maxConnections: config.CONFIG_MAX_CONNECTIONS,
2070
- minConnections: config.CONFIG_MIN_CONNECTIONS,
2071
- autoDialInterval:60e3,
2072
- autoDialConcurrency:0,
2073
- autoDialMaxQueueLength:0,
2074
- autoDialPriority:1000,
2075
- autoDialDiscoveredPeersDebounce:60e3,
2076
- maxParallelDials: 3,
2077
- dialTimeout: 5e3,
2078
- maxIncomingPendingConnections: 5,
2079
- maxDialQueueLength:10,
2080
- inboundConnectionThreshold:3,
2081
- maxPeerAddrsToDial:2,
2082
- inboundUpgradeTimeout:5e3
2083
- },
2084
- connectionEncryption: [noise()],
2085
- streamMuxers: [
2086
- yamux({
2087
- maxInboundStreams: 100,
2088
- maxOutboundStreams: 100,
2089
- })
2090
- ],
2091
- connectionGater: {
2092
- filterMultiaddrForPeer: async (peer, multiaddrTest) => {
2093
- const multiaddrString = multiaddrTest.toString()
2094
- if (
2095
- multiaddrString.includes("/ip4/127.0.0.1") ||
2096
- multiaddrString.includes("/ip6/")
2097
- ) {
2098
- return false
2099
- }
2100
- if(multiaddrString.includes("/ws/") || multiaddrString.includes("/wss/"))return isWebsocket
2101
- return isDial
2102
- },
2103
- denyDialMultiaddr: async (multiaddrTest) => {
2104
- const multiaddrString = multiaddrTest.toString()
2105
- if (
2106
- multiaddrString.includes("/ip4/127.0.0.1") ||
2107
- multiaddrString.includes("/ip6/")
2108
- ) {
2109
- return true
2110
- }
2111
- if(multiaddrString.includes("/ws/") || multiaddrString.includes("/wss/"))return !isWebsocket
2112
- return !isDial
2113
- },
2114
- },
2115
- peerDiscovery: [
2116
- pubsubPeerDiscovery({
2117
- interval: 5_000,
2118
- topics: config.CONFIG_PUBSUB_PEER_DISCOVERY_WEBPEER,
2119
- listenOnly: false,
2120
- }),
2121
-
2122
- ],
2123
- services: {
2124
- pubsub: gossipsub({
2125
- allowPublishToZeroTopicPeers: true,
2126
- msgIdFn: msgIdFnStrictNoSign,
2127
- ignoreDuplicatePublishError: true,
2128
- runOnTransientConnection:config.CONFIG_RUN_ON_TRANSIENT_CONNECTION,
2129
- }),
2130
- identify: identify(),
2131
- identifyPush: identifyPush(),
2132
- aminoDHT: kadDHT({
2133
- protocol: '/ipfs/kad/1.0.0',
2134
- peerInfoMapper: removePrivateAddressesMapper,
2135
- clientMode: false
2136
- }),
2137
- dcutr: dcutr()
2010
+ if(configuration && configuration.rtcConfiguration){
2011
+ webrtcconfig[rtcConfiguration] = configuration.rtcConfiguration
2012
+ }
2013
+
2014
+
2015
+ //create libp2p instance
2016
+ const libp2p = await createLibp2p({
2017
+ addresses: {
2018
+ listen: listenaddress,
2019
+ },
2020
+ transports:[
2021
+ webTransport(),
2022
+ webSockets(),
2023
+ webRTC(webrtcconfig),
2024
+ circuitRelayTransport({
2025
+ discoverRelays: config.CONFIG_DISCOVER_RELAYS,
2026
+ reservationConcurrency: 1,
2027
+ maxReservationQueueLength: 3
2028
+ }),
2029
+ ],
2030
+ connectionManager: {
2031
+ maxConnections: config.CONFIG_MAX_CONNECTIONS,
2032
+ minConnections: config.CONFIG_MIN_CONNECTIONS,
2033
+ autoDialInterval:60e3,
2034
+ autoDialConcurrency:0,
2035
+ autoDialMaxQueueLength:0,
2036
+ autoDialPriority:1000,
2037
+ autoDialDiscoveredPeersDebounce:60e3,
2038
+ maxParallelDials: 3,
2039
+ dialTimeout: 5e3,
2040
+ maxIncomingPendingConnections: 5,
2041
+ maxDialQueueLength:10,
2042
+ inboundConnectionThreshold:3,
2043
+ maxPeerAddrsToDial:2,
2044
+ inboundUpgradeTimeout:5e3
2045
+ },
2046
+ connectionEncrypters: [noise()],
2047
+ streamMuxers: [
2048
+ yamux({
2049
+ maxInboundStreams: 100,
2050
+ maxOutboundStreams: 100,
2051
+ })
2052
+ ],
2053
+ connectionGater: {
2054
+ filterMultiaddrForPeer: async (peer, multiaddrTest) => {
2055
+ const multiaddrString = multiaddrTest.toString()
2056
+ if (
2057
+ multiaddrString.includes("/ip4/127.0.0.1") ||
2058
+ multiaddrString.includes("/ip6/")
2059
+ ) {
2060
+ return false
2061
+ }
2062
+ if(multiaddrString.includes("/ws/") || multiaddrString.includes("/wss/"))return isWebsocket
2063
+ return isDial
2138
2064
  },
2139
- peerStore: {
2140
- persistence: true,
2141
- threshold: 1
2065
+ denyDialMultiaddr: async (multiaddrTest) => {
2066
+ const multiaddrString = multiaddrTest.toString()
2067
+ if (
2068
+ multiaddrString.includes("/ip4/127.0.0.1") ||
2069
+ multiaddrString.includes("/ip6/")
2070
+ ) {
2071
+ return true
2072
+ }
2073
+ if(multiaddrString.includes("/ws/") || multiaddrString.includes("/wss/"))return !isWebsocket
2074
+ return !isDial
2142
2075
  },
2143
- metrics: simpleMetrics({
2144
- onMetrics: (metrics) => {onMetricsFn(metrics)},
2145
- intervalMs: 1000
2146
- })
2076
+ },
2077
+ peerDiscovery: [
2078
+ pubsubPeerDiscovery({
2079
+ interval: 5_000,
2080
+ topics: config.CONFIG_PUBSUB_PEER_DISCOVERY_WEBPEER,
2081
+ listenOnly: false,
2082
+ }),
2083
+
2084
+ ],
2085
+ services: {
2086
+ pubsub: gossipsub({
2087
+ allowPublishToZeroTopicPeers: true,
2088
+ msgIdFn: msgIdFnStrictNoSign,
2089
+ ignoreDuplicatePublishError: true,
2090
+ runOnLimitedConnection:config.CONFIG_RUN_ON_TRANSIENT_CONNECTION,
2091
+ }),
2092
+ identify: identify(),
2093
+ ping: ping(),
2094
+ identifyPush: identifyPush(),
2095
+ aminoDHT: kadDHT({
2096
+ protocol: '/ipfs/kad/1.0.0',
2097
+ peerInfoMapper: removePrivateAddressesMapper,
2098
+ clientMode: false
2099
+ }),
2100
+ dcutr: dcutr()
2101
+ },
2102
+ peerStore: {
2103
+ persistence: true,
2104
+ threshold: 1
2105
+ },
2106
+ metrics: simpleMetrics({
2107
+ onMetrics: (metrics) => {onMetricsFn(metrics)},
2108
+ intervalMs: 1000
2147
2109
  })
2148
-
2149
-
2150
-
2151
- //console.log(`Node started with id ${libp2p.peerId.toString()}`)
2110
+ })
2111
+
2112
+ //console.log(`Node started with id ${libp2p.peerId.toString()}`)
2152
2113
 
2153
- //DHT server mode act as bootstrap peer in IPFS network
2154
- await libp2p.services.aminoDHT.setMode("server")
2155
-
2156
-
2157
- //return webpeerjs class
2158
- return new webpeerjs(libp2p,dbstore,onMetrics,onWebsocketFn,onDialFn)
2159
- }
2114
+ //DHT server mode act as bootstrap peer in IPFS network
2115
+ await libp2p.services.aminoDHT.setMode("server")
2116
+
2117
+
2118
+ //return webpeerjs class
2119
+ return new webpeerjs(signalingserver,libp2p,dbstore,onMetrics,onWebsocketFn,onDialFn)
2160
2120
  }
2161
2121
 
2162
2122
 
2163
2123
  //export module
2164
- export {webpeerjs}
2124
+ export {createWebPEER}