webpeerjs 0.1.4 → 0.1.6

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webpeerjs",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "WebPEER.js is decentralized P2P JS library for communication between applications in browser.",
5
5
  "main": "./dist/umd/webpeerjs.js",
6
6
  "module": "./src/webpeerjs.js",
@@ -19,8 +19,8 @@
19
19
  "start": "npm run dev",
20
20
  "dev": "vite serve test",
21
21
  "demo": "vite serve demo",
22
- "eslint": "eslint ./src",
23
- "eslint:fix": "eslint ./src --fix",
22
+ "eslint": "eslint -c ./config/eslint.config.mjs ./src",
23
+ "eslint:fix": "eslint -c ./config/eslint.config.mjs ./src --fix",
24
24
  "removedir": "node -e \"var fs = require('fs'); try{process.argv.slice(1).map((fpath) => fs.rmdirSync(fpath, { recursive: true }))}catch(err){console.log(`Dist not found`)}; process.exit(0);\"",
25
25
  "build-all": "tsc -p config/tsconfig-rollup.json && rollup -c temp/config/rollup.config.build.js && echo {\"type\": \"commonjs\"}>dist\\umd\\package.json && echo {\"type\": \"module\"}>dist\\esm\\package.json",
26
26
  "build-types": "tsc -p config/tsconfig-esm.json",
package/src/config.js CHANGED
@@ -13,7 +13,7 @@ export const CONFIG_PEER_DISCOVERY_UNIVERSAL_CONNECTIVITY = 'universal-connectiv
13
13
  export const CONFIG_PEER_DISCOVERY_GLOBAL = '_peer-discovery._p2p._pubsub'
14
14
  export const CONFIG_PEER_DISCOVERY_WEBPEERJS= prefix+'-peer-discovery'
15
15
  export const CONFIG_PUBSUB_PEER_DISCOVERY_HYBRID = [CONFIG_PEER_DISCOVERY_UNIVERSAL_CONNECTIVITY]
16
- export const CONFIG_PUBSUB_PEER_DISCOVERY_WEBPEER = [CONFIG_PEER_DISCOVERY_GLOBAL, CONFIG_PEER_DISCOVERY_WEBPEERJS]
16
+ export const CONFIG_PUBSUB_PEER_DISCOVERY_WEBPEER = [CONFIG_PEER_DISCOVERY_WEBPEERJS]
17
17
  export const CONFIG_PUPSUB_PEER_DATA = ['_'+prefix+'-peer-data_']
18
18
  export const CONFIG_PUPSUB_TOPIC = prefix+'-room'
19
19
  export const CONFIG_DELEGATED_API = 'https://delegated-ipfs.dev'
package/src/utils.js CHANGED
@@ -27,7 +27,8 @@ const prefix = config.CONFIG_PREFIX
27
27
 
28
28
  export const mkErr = msg => new Error(`${prefix}: ${msg}`)
29
29
 
30
- export function mkDebug(error){
30
+ export function mkDebug(msg){
31
+ console.debug(msg)
31
32
  return
32
33
  }
33
34
 
@@ -167,14 +168,14 @@ export function metrics(data){
167
168
  if ((fail-lastfailtreshold)>30){
168
169
  if(isDialEnabled){
169
170
  isDialEnabled = false
170
- const str = JSON.stringify({isDialEnabled,fail,lastfailtreshold})
171
- console.warn('dial disabled')
171
+ //const str = JSON.stringify({isDialEnabled,fail,lastfailtreshold})
172
+ console.warn('Peer dial is temporary disabled')
172
173
  setTimeout(()=>{
173
174
  if(!isDialEnabled){
174
175
  isDialEnabled = true
175
176
  lastfailtreshold = fail
176
- const str = JSON.stringify({isDialEnabled,fail,lastfailtreshold})
177
- console.warn('dial enabled')
177
+ //const str = JSON.stringify({isDialEnabled,fail,lastfailtreshold})
178
+ console.warn('Peer dial is enabled')
178
179
  }
179
180
  },6*60*1000)
180
181
  }
package/src/webpeerjs.js CHANGED
@@ -10,11 +10,10 @@ import {
10
10
  Key,
11
11
  msgIdFnStrictNoSign,
12
12
  metrics,
13
- getDigest,
13
+ //getDigest,
14
14
  mkDebug,
15
15
  multiaddr,
16
16
  pipe,
17
- lpStream,
18
17
  lp,
19
18
  map
20
19
  } from './utils'
@@ -96,6 +95,13 @@ class webpeerjs{
96
95
  //map of peer exchange data
97
96
  #peerexchangedata
98
97
 
98
+ //track last connect to webpeer network
99
+ #lastTimeConnectToNetwork
100
+ #lastTimeReceiveData
101
+
102
+ //arr to track on connect event
103
+ #onConnectQueue
104
+
99
105
  id
100
106
  status
101
107
  IPFS
@@ -125,6 +131,9 @@ class webpeerjs{
125
131
  this.#isDialEnabled = true
126
132
  this.#msgIdtracker = []
127
133
  this.#peerexchangedata = new Map()
134
+ this.#lastTimeConnectToNetwork = new Date().getTime()
135
+ this.#lastTimeReceiveData = new Date().getTime()
136
+ this.#onConnectQueue = []
128
137
 
129
138
  this.peers = (function(f) {
130
139
  return f
@@ -154,7 +163,7 @@ class webpeerjs{
154
163
  //listen to peer connect event
155
164
  this.#libp2p.addEventListener("peer:connect",async (evt) => {
156
165
 
157
- const connection = evt.detail;
166
+ //const connection = evt.detail;
158
167
  const id = evt.detail.toString()
159
168
 
160
169
  //console.log('peer:connect '+id,evt)
@@ -185,6 +194,14 @@ class webpeerjs{
185
194
 
186
195
  if(this.#webPeersId.includes(id)){
187
196
 
197
+ setTimeout(()=>{
198
+ this.#ping()
199
+ },10000)
200
+
201
+ setTimeout(()=>{
202
+ this.#ping()
203
+ },15000)
204
+
188
205
  let address = [addr]
189
206
 
190
207
  if(this.#connectedPeers.has(id)){
@@ -193,9 +210,9 @@ class webpeerjs{
193
210
  const metadata = {addrs:address,last:now}
194
211
  this.#connectedPeers.set(id,metadata)
195
212
  }
196
- else{
213
+ else if(this.#lastTimeReceiveData < 10*1000){
197
214
  //add to connected webpeers
198
- this.#onConnectFn(id)
215
+ this.#onConnectFnUpdate(id)
199
216
  const now = new Date().getTime()
200
217
  const metadata = {addrs:address,last:now}
201
218
  this.#connectedPeers.set(id,metadata)
@@ -217,12 +234,29 @@ class webpeerjs{
217
234
  if (event.detail.type !== 'signed') {
218
235
  return
219
236
  }
237
+
220
238
  if(config.CONFIG_JOIN_ROOM_VERSION == 1){
221
239
  const topic = event.detail.topic
222
240
  const senderPeerId = event.detail.from.toString()
223
241
 
224
242
  try{
225
243
 
244
+ if(topic === config.CONFIG_PUPSUB_PEER_DATA || config.CONFIG_PUBSUB_PEER_DISCOVERY_WEBPEER.includes(topic) || config.CONFIG_RUN_ON_TRANSIENT_CONNECTION){
245
+ this.#lastTimeReceiveData = new Date().getTime()
246
+ }
247
+
248
+ //track last connect to webpeer network
249
+ if(config.CONFIG_PUBSUB_PEER_DISCOVERY_WEBPEER.includes(topic)){
250
+ const now = new Date().getTime()
251
+ const limit = 15*1000
252
+ const lastConnectTime = now - this.#lastTimeConnectToNetwork
253
+ if(lastConnectTime > limit){
254
+ //console.log('need re announce')
255
+ this.#announce()
256
+ }
257
+ this.#lastTimeConnectToNetwork = now
258
+ }
259
+
226
260
  //if it is webpeer
227
261
  if(this.#webPeersId.includes(senderPeerId)){
228
262
 
@@ -233,9 +267,9 @@ class webpeerjs{
233
267
  const metadata = {addrs:address,last:now}
234
268
  this.#connectedPeers.set(senderPeerId,metadata)
235
269
  }
236
- else{
270
+ else if(this.#lastTimeReceiveData < 10*1000){
237
271
  //add to connected webpeers
238
- this.#onConnectFn(senderPeerId)
272
+ this.#onConnectFnUpdate(senderPeerId)
239
273
  const address = this.#webPeersAddrs.get(senderPeerId)
240
274
  const now = new Date().getTime()
241
275
  const metadata = {addrs:address,last:now}
@@ -279,6 +313,20 @@ class webpeerjs{
279
313
 
280
314
  //parse the message over pupsub peer discovery
281
315
  const peer = PBPeer.decode(event.detail.data)
316
+
317
+ //detect libp2p pupsub peer discovery
318
+ if(peer.addrs.length > 1 && this.#libp2p.getPeers().length < config.CONFIG_MAX_CONNECTIONS){
319
+ let mddrs = []
320
+ for(const uaddr of peer.addrs){
321
+ const mddr = multiaddr(uaddr)
322
+ if(mddr.toString().includes('webtransport') && mddr.toString().includes('certhash')){
323
+ mddrs.push(mddr)
324
+ }
325
+ }
326
+ this.#dialMultiaddress(mddrs)
327
+ //console.log('dial '+senderPeerId,mddrs.toString())
328
+ }
329
+
282
330
  const msg = uint8ArrayToString(peer.addrs[0])
283
331
  const json = JSON.parse(msg)
284
332
  const prefix = json.prefix
@@ -288,25 +336,37 @@ class webpeerjs{
288
336
  const msgId = json.msgId
289
337
  const signal = json.signal
290
338
  const id = json.id
291
- //console.log(`from ${id}:${signal} = ${message}`)
339
+ const address = json.address
340
+ //console.log(`from ${id}:${signal} = ${msg}`)
341
+
292
342
  if(id != senderPeerId)return
293
- let address = json.address
294
343
 
295
344
  //detect special webpeer identity
296
345
  if(prefix === config.CONFIG_PREFIX){
297
346
 
347
+ this.#lastTimeReceiveData = new Date().getTime()
348
+
298
349
  //add to webpeers id
299
350
  if(!this.#webPeersId.includes(id))this.#webPeersId.push(id)
300
351
 
301
352
  //add to connected webpeers
302
353
  if(!this.#connectedPeers.has(id)){
303
- this.#onConnectFn(id)
304
- address = []
354
+ this.#onConnectFnUpdate(id)
305
355
  const now = new Date().getTime()
306
356
  const metadata = {addrs:address,last:now}
307
357
  this.#connectedPeers.set(id,metadata)
308
- this.#webPeersAddrs.set(id,address)
358
+ if(address){
359
+ if(address.length > 0){
360
+ this.#webPeersAddrs.set(id,address)
361
+ }
362
+ }
309
363
  this.#updatePeers()
364
+ }else{
365
+ if(address){
366
+ if(address.length > 0){
367
+ this.#webPeersAddrs.set(id,address)
368
+ }
369
+ }
310
370
  }
311
371
 
312
372
 
@@ -366,13 +426,16 @@ class webpeerjs{
366
426
  }
367
427
  else if(prefix === 'hybrid'){
368
428
 
369
- if(address.length>0 && !this.#connections.has(id)){
429
+ //console.log('hybrid' +id,address)
430
+ const limit = config.CONFIG_MAX_CONNECTIONS / 2
431
+ if(address.length>0 && ((!this.#connections.has(id))||(this.#connectedPeers.size < limit))){
370
432
  let mddrs = []
371
433
  for(const addr of address){
372
434
  const mddr = multiaddr(addr)
373
435
  mddrs.push(mddr)
374
436
  }
375
437
  this.#dialMultiaddress(mddrs)
438
+ //console.log('dial '+id,mddrs.toString())
376
439
  }
377
440
 
378
441
  }
@@ -451,7 +514,12 @@ class webpeerjs{
451
514
  count++
452
515
  this.#trackDisconnect.set(id,count)
453
516
  //console.log(this.#trackDisconnect)
454
- if(count>10){
517
+ if(count>5){
518
+ if(config.CONFIG_KNOWN_BOOTSTRAP_PUBLIC_IDS.includes(id)){
519
+ return
520
+ }
521
+ }
522
+ else if(count>10){
455
523
  if(this.#dbstoreData.has(id)){
456
524
  this.#dbstoreData.delete(id)
457
525
  }
@@ -619,6 +687,8 @@ class webpeerjs{
619
687
 
620
688
  setInterval(()=>{
621
689
  this.#peerDiscoveryHybrid()
690
+ this.#trackHybridPeersConnection()
691
+ this.#trackWebpeerConnection()
622
692
  },10e3)
623
693
 
624
694
 
@@ -738,6 +808,58 @@ class webpeerjs{
738
808
  /*
739
809
  PRIVATE FUNCTION
740
810
  */
811
+
812
+ //track hybrid peer connection and try to dial if not connected at least 1
813
+ #trackHybridPeersConnection(){
814
+ let isConnectedToHybridPeers = false
815
+ for(const id of config.CONFIG_KNOWN_BOOTSTRAP_HYBRID_IDS){
816
+ if(this.#isConnected(id))isConnectedToHybridPeers = true
817
+ }
818
+ if(!isConnectedToHybridPeers){
819
+ for(const id of config.CONFIG_KNOWN_BOOTSTRAP_HYBRID_IDS){
820
+ if(this.status !== 'connected' && this.#connections.has(id))
821
+ {
822
+ let mddrs = []
823
+ const addr = this.#connections.get(id)
824
+ const mddr = multiaddr(addr)
825
+ mddrs.push(mddr)
826
+ this.#dialMultiaddress(mddrs)
827
+ }
828
+ }
829
+ }
830
+ }
831
+
832
+ //track webpeer connection and try to dial if not connected to network using saved webpeer address
833
+ #trackWebpeerConnection(){
834
+ if(this.status === 'connected')return
835
+ if(this.#webPeersAddrs.size < 1)return
836
+
837
+ const keys = Array.from(this.#webPeersAddrs.keys())
838
+ const randomKey = Math.floor(Math.random() * keys.length)
839
+ const key = keys[randomKey]
840
+ const addrs = this.#webPeersAddrs.get(key)
841
+
842
+ let mddrs = []
843
+ for(const addr of addrs){
844
+ const mddr = multiaddr(addr)
845
+ mddrs.push(mddr)
846
+ }
847
+ this.#dialMultiaddress(mddrs)
848
+ }
849
+
850
+ //prevent double on connect event
851
+ #onConnectFnUpdate(id){
852
+ if(!this.#onConnectQueue.includes(id)){
853
+ this.#onConnectQueue.push(id)
854
+ this.#onConnectFn(id)
855
+ setTimeout(()=>{
856
+ const index = this.#onConnectQueue.indexOf(id)
857
+ if (index > -1) {
858
+ this.#onConnectQueue.splice(index, 1)
859
+ }
860
+ },5000)
861
+ }
862
+ }
741
863
 
742
864
  #updatePeers(){
743
865
  this.#connectedPeersArr.length = 0
@@ -756,7 +878,7 @@ class webpeerjs{
756
878
 
757
879
  async #registerProtocol(){
758
880
 
759
- const handler = async ({ connection, stream, protocol }) => {
881
+ const handler = async ({ connection, stream }) => {
760
882
  try{
761
883
  const output = await pipe(
762
884
  stream.source,
@@ -795,7 +917,7 @@ class webpeerjs{
795
917
  if(!this.#webPeersId.includes(id))this.#webPeersId.push(id)
796
918
 
797
919
  //add to connected webpeers
798
- this.#onConnectFn(id)
920
+ this.#onConnectFnUpdate(id)
799
921
  const now = new Date().getTime()
800
922
  const metadata = {addrs:address,last:now}
801
923
  this.#connectedPeers.set(id,metadata)
@@ -837,7 +959,7 @@ class webpeerjs{
837
959
  )
838
960
  }
839
961
  catch(err){
840
- //console.warn(err)
962
+ mkDebug(err)
841
963
  }
842
964
  }
843
965
 
@@ -848,14 +970,14 @@ class webpeerjs{
848
970
  })
849
971
 
850
972
  await this.#libp2p.register(config.CONFIG_PROTOCOL, {
851
- onConnect: (peer, connection) => {
852
- // handle connect
973
+ /*onConnect: (peer, connection) => {
974
+ //handle connect
853
975
  //console.log('handle connect',peer)
854
976
  },
855
977
  onDisconnect: (peer, connection) => {
856
- // handle disconnect
978
+ //handle disconnect
857
979
  //console.log('handle disconnect',peer)
858
- }
980
+ }*/
859
981
  })
860
982
 
861
983
  }
@@ -922,7 +1044,7 @@ class webpeerjs{
922
1044
  if(!this.#webPeersId.includes(id))this.#webPeersId.push(id)
923
1045
 
924
1046
  //add to connected webpeers
925
- this.#onConnectFn(id)
1047
+ this.#onConnectFnUpdate(id)
926
1048
  const now = new Date().getTime()
927
1049
  const metadata = {addrs:address,last:now}
928
1050
  this.#connectedPeers.set(id,metadata)
@@ -946,7 +1068,7 @@ class webpeerjs{
946
1068
  }
947
1069
  }
948
1070
  catch(err){
949
- //console.warn(err)
1071
+ mkDebug(err)
950
1072
  }
951
1073
  }
952
1074
 
@@ -988,7 +1110,7 @@ class webpeerjs{
988
1110
 
989
1111
  //check the last seen in web peer
990
1112
  #trackLastSeen(){
991
- const timeout = 25*1000
1113
+ const timeout = 10*1000
992
1114
  const forcetimeout = 60*1000
993
1115
  const now = new Date().getTime()
994
1116
 
@@ -1045,6 +1167,8 @@ class webpeerjs{
1045
1167
  return
1046
1168
  }
1047
1169
 
1170
+ if(this.status === 'connected' && config.CONFIG_KNOWN_BOOTSTRAP_PUBLIC_IDS.includes(id))return
1171
+
1048
1172
  const webPeerCount = this.#connectedPeers.size
1049
1173
  const allPeerCount = this.#libp2p.getPeers().length
1050
1174
  const nodePeerCount = allPeerCount - webPeerCount
@@ -1056,7 +1180,7 @@ class webpeerjs{
1056
1180
  }
1057
1181
  }
1058
1182
  else{
1059
- if(nodePeerCount>limitCount){
1183
+ if((nodePeerCount>(limitCount-5))||(allPeerCount>(config.CONFIG_MAX_CONNECTIONS-5))){
1060
1184
  //close random peers
1061
1185
  let peers = []
1062
1186
  for(const peer of this.#libp2p.getPeers()){
@@ -1064,7 +1188,9 @@ class webpeerjs{
1064
1188
  }
1065
1189
  const randomKey = Math.floor(Math.random() * peers.length)
1066
1190
  const randompeerid = peers[randomKey]
1067
- await this.#libp2p.hangUp(peerIdFromString(randompeerid))
1191
+ if(!config.CONFIG_KNOWN_BOOTSTRAP_HYBRID_IDS.includes(id)){
1192
+ await this.#libp2p.hangUp(peerIdFromString(randompeerid))
1193
+ }
1068
1194
  }
1069
1195
  }
1070
1196
 
@@ -1081,7 +1207,7 @@ class webpeerjs{
1081
1207
  //dial multiaddr address in queue list
1082
1208
  #dialQueueList(){
1083
1209
 
1084
- if(!this.#isDialEnabled || !navigator.onLine)return
1210
+ if(!this.#isDialEnabled || !navigator.onLine || (document.visibilityState === 'hidden' && ('ontouchstart' in document.documentElement)) )return
1085
1211
 
1086
1212
  const mddrsToDial = 5
1087
1213
 
@@ -1802,7 +1928,7 @@ class webpeerjs{
1802
1928
  };
1803
1929
 
1804
1930
  pc.onicecandidateerror = (e) => {
1805
- //console.error(e);
1931
+ console.debug(e);
1806
1932
  };
1807
1933
 
1808
1934
  pc.createDataChannel('webpeerjs');
@@ -1875,7 +2001,7 @@ class webpeerjs{
1875
2001
  },
1876
2002
  peerDiscovery: [
1877
2003
  pubsubPeerDiscovery({
1878
- interval: 10_000,
2004
+ interval: 5_000,
1879
2005
  topics: config.CONFIG_PUBSUB_PEER_DISCOVERY_WEBPEER,
1880
2006
  listenOnly: false,
1881
2007
  }),