webpeerjs 0.0.8 → 0.0.10

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/src/webpeerjs.js CHANGED
@@ -9,19 +9,24 @@ import {
9
9
  msgIdFnStrictNoSign,
10
10
  metrics,
11
11
  getDigest,
12
- mkDebug
12
+ mkDebug,
13
+ multiaddr,
14
+ pipe,
15
+ lpStream,
16
+ lp,
17
+ map
13
18
  } from './utils'
14
19
  import { createDelegatedRoutingV1HttpApiClient } from '@helia/delegated-routing-v1-http-api-client'
15
20
  import { createLibp2p } from 'libp2p'
16
21
  import { IDBDatastore } from 'datastore-idb'
17
22
  import { webTransport } from '@libp2p/webtransport'
23
+ import { webSockets } from '@libp2p/websockets'
18
24
  import { noise } from '@chainsafe/libp2p-noise'
19
25
  import { yamux } from '@chainsafe/libp2p-yamux'
20
26
  import { pubsubPeerDiscovery } from '@libp2p/pubsub-peer-discovery'
21
27
  import { circuitRelayTransport } from '@libp2p/circuit-relay-v2'
22
28
  import { gossipsub } from '@chainsafe/libp2p-gossipsub'
23
29
  import { identify, identifyPush } from '@libp2p/identify'
24
- import { multiaddr } from '@multiformats/multiaddr'
25
30
  import { peerIdFromString } from '@libp2p/peer-id'
26
31
  import { kadDHT, removePrivateAddressesMapper } from '@libp2p/kad-dht'
27
32
  import { simpleMetrics } from '@libp2p/simple-metrics'
@@ -84,6 +89,9 @@ class webpeerjs{
84
89
  //message tracker avoid double
85
90
  #msgIdtracker
86
91
 
92
+ //map of peer exchange data
93
+ #peerexchangedata
94
+
87
95
  id
88
96
  status
89
97
  IPFS
@@ -112,6 +120,7 @@ class webpeerjs{
112
120
  this.#dialQueue = []
113
121
  this.#isDialEnabled = true
114
122
  this.#msgIdtracker = []
123
+ this.#peerexchangedata = new Map()
115
124
 
116
125
  this.peers = (function(f) {
117
126
  return f
@@ -143,8 +152,8 @@ class webpeerjs{
143
152
  const connect = connections.find((con)=>con.id == id)
144
153
  const addr = connect.addr
145
154
 
146
- if(config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS.includes(id) || config.CONFIG_KNOWN_BOOTSTRAP_HYBRID_IDS.includes(id)){
147
- if(!this.#connections.has(id)&&addr.includes('webtransport')){
155
+ if(config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS.includes(id)){
156
+ if((!this.#connections.has(id) || (this.#connections.get(id).includes('/wss/')))&&addr.includes('webtransport')){
148
157
  await this.#dbstore.put(new Key(id), new TextEncoder().encode(addr))
149
158
  }
150
159
  }
@@ -410,9 +419,8 @@ class webpeerjs{
410
419
  count++
411
420
  this.#trackDisconnect.set(id,count)
412
421
  //console.log(this.#trackDisconnect)
413
- if(count>5){
422
+ if(count>10){
414
423
  if(this.#dbstoreData.has(id)){
415
- //await this.#dbstore.delete(new Key(id))
416
424
  this.#dbstoreData.delete(id)
417
425
  }
418
426
 
@@ -425,6 +433,11 @@ class webpeerjs{
425
433
  this.#trackDisconnect.set(id,0)
426
434
  }
427
435
 
436
+ let peerexchangelist = []
437
+ for(const peer of this.#peerexchangedata.values()){
438
+ peerexchangelist.push(peer.id)
439
+ }
440
+
428
441
  //if this disconnected peer is web peer redial it
429
442
  if(this.#webPeersId.includes(id)){
430
443
  const addr = this.#connections.get(id)
@@ -436,6 +449,15 @@ class webpeerjs{
436
449
 
437
450
  //if this disconnected peer is known bootstrap redial it
438
451
  else if(this.#dialedKnownBootstrap.has(id)){
452
+ const addr = this.#connections.get(id)
453
+ if(addr.includes('/wss/'))return
454
+ let mddrs = []
455
+ const addrs = multiaddr(addr)
456
+ mddrs.push(addrs)
457
+ this.#dialMultiaddress(mddrs)
458
+ }
459
+
460
+ else if(peerexchangelist.includes(id)){
439
461
  const addr = this.#connections.get(id)
440
462
  let mddrs = []
441
463
  const addrs = multiaddr(addr)
@@ -471,37 +493,56 @@ class webpeerjs{
471
493
  this.#ping()
472
494
  })
473
495
 
474
- this.#libp2p.addEventListener('peer:identify', (evt) => {
496
+ this.#libp2p.addEventListener('peer:identify', async (evt) => {
475
497
  //console.log('peer:identify '+evt.detail.peerId.toString(),evt.detail)
498
+
499
+ const id = evt.detail.peerId.toString()
500
+
501
+ if(config.CONFIG_KNOWN_BOOTSTRAP_PUBLIC_IDS.includes(id)){
502
+ const remoteAddr = evt.detail.connection.remoteAddr.toString()
503
+ if(remoteAddr.includes('/wss/')){
504
+ let addrs = []
505
+ let mddrs = []
506
+ for(const peer of evt.detail.listenAddrs){
507
+ if(!peer.toString().includes('webtransport'))continue
508
+ const addr = peer.toString()+'/p2p/'+id
509
+ const mddr = multiaddr(addr)
510
+ addrs.push(addr)
511
+ mddrs.push(mddr)
512
+ }
513
+ this.#dialedKnownBootstrap.set(id,addrs)
514
+ await this.#libp2p.hangUp(peerIdFromString(id))
515
+ this.#dialMultiaddress(mddrs)
516
+ }
517
+ }
518
+
476
519
  if(evt.detail.protocols.includes(config.CONFIG_PROTOCOL)){
477
- //console.log('peer:identify '+evt.detail.peerId.toString(),evt.detail)
520
+ //console.log('peer:identify '+evt.detail.peerId.toString(),evt)
478
521
 
479
522
  const id = evt.detail.peerId.toString()
480
523
  let address = []
524
+ let mddrs = []
481
525
 
482
526
  for(const addrs of evt.detail.listenAddrs){
483
527
  const addr = addrs.toString()+'/p2p/'+id
528
+ const mddr = multiaddr(addr)
484
529
  if(addr.includes('webtransport')){
485
530
  address.push(addr)
531
+ mddrs.push(mddr)
486
532
  }
487
533
  }
488
534
 
489
- if(!this.#webPeersId.includes(id))this.#webPeersId.push(id)
490
-
491
535
  if(this.#connectedPeers.has(id)){
492
536
  //reset this last seen
493
537
  const now = new Date().getTime()
494
538
  const metadata = {addrs:address,last:now}
495
539
  this.#connectedPeers.set(id,metadata)
496
540
  }
497
- else{
498
- //add to connected webpeers
499
- this.#onConnectFn(id)
500
- const now = new Date().getTime()
501
- const metadata = {addrs:address,last:now}
502
- this.#connectedPeers.set(id,metadata)
503
- this.#updatePeers()
504
- }
541
+
542
+
543
+ const command = 'peer-exchange'
544
+ this.#dialProtocol(id,command)
545
+
505
546
 
506
547
  }
507
548
  })
@@ -582,14 +623,67 @@ class webpeerjs{
582
623
 
583
624
  //Listen on new peer connection
584
625
  #onConnectFn = () => {}
585
- onJoin = f => (this.#onConnectFn = f)
626
+ onConnect = f => (this.#onConnectFn = f)
586
627
 
587
628
 
588
629
  //Listen on peer disconnect
589
630
  #onDisconnectFn = () => {}
590
- onLeave = f => (this.#onDisconnectFn = f)
631
+ onDisconnect = f => (this.#onDisconnectFn = f)
632
+
633
+ joinRoom = room => {
634
+ if (this.#rooms[room]) {
635
+ return [
636
+ this.#rooms[room].sendMessage,
637
+ this.#rooms[room].listenMessage,
638
+ this.#rooms[room].onMembersChange
639
+ ]
640
+
641
+
642
+ }
591
643
 
644
+ if (!room) {
645
+ throw mkErr('room is required')
646
+ }
647
+
648
+ //join room version 1 user pupsub via pupsub peer discovery
649
+ if(config.CONFIG_JOIN_ROOM_VERSION == 1){
592
650
 
651
+ const topics = config.CONFIG_PUBSUB_PEER_DISCOVERY
652
+
653
+ this.#rooms[room] = {
654
+ onMessage : () => {},
655
+ listenMessage : f => (this.#rooms[room] = {...this.#rooms[room], onMessage: f}),
656
+ sendMessage : async (message) => {
657
+ const msgId = (new Date()).getTime()
658
+ const data = JSON.stringify({prefix:config.CONFIG_PREFIX,room,message,id:this.#libp2p.peerId.toString(),msgId})
659
+ const peer = {
660
+ publicKey: this.#libp2p.peerId.publicKey,
661
+ addrs: [uint8ArrayFromString(data)],
662
+ }
663
+ const encodedPeer = PBPeer.encode(peer)
664
+ for(const topic of topics){
665
+ await this.#libp2p.services.pubsub.publish(topic, encodedPeer)
666
+ }
667
+ },
668
+ members : [this.id],
669
+ onMembers : () => {},
670
+ onMembersChange : f => {this.#rooms[room] = {...this.#rooms[room], onMembers: f};this.#rooms[room].onMembers(this.#rooms[room].members);this.#ping()},
671
+ }
672
+ }
673
+
674
+ return [
675
+ this.#rooms[room].sendMessage,
676
+ this.#rooms[room].listenMessage,
677
+ this.#rooms[room].onMembersChange
678
+ ]
679
+ }
680
+
681
+ dial(addr){
682
+ let mddrs = []
683
+ const mddr = multiaddr(addr)
684
+ mddrs.push(mddr)
685
+ this.#dialMultiaddress(mddrs)
686
+ }
593
687
 
594
688
 
595
689
  /*
@@ -611,13 +705,96 @@ class webpeerjs{
611
705
  }
612
706
 
613
707
  async #registerProtocol(){
614
- const handler = ({ connection, stream, protocol }) => {
615
- // use stream or connection according to the needs
708
+
709
+ const handler = async ({ connection, stream, protocol }) => {
710
+ try{
711
+ const output = await pipe(
712
+ stream.source,
713
+ (source) => lp.decode(source),
714
+ (source) => map(source, (buf) => uint8ArrayToString(buf.subarray())),
715
+ async function (source) {
716
+ let string = ''
717
+ for await (const msg of source) {
718
+ string += msg.toString()
719
+ }
720
+ return string
721
+ }
722
+ )
723
+
724
+ const id = connection.remotePeer.toString()
725
+
726
+ let json = JSON.parse(output)
727
+
728
+ let jsonMessage = {
729
+ protocol:config.CONFIG_PROTOCOL,
730
+ command:null,
731
+ data:null
732
+ }
733
+
734
+ if(json.command === 'peer-exchange'){
735
+
736
+ if(json.protocol == config.CONFIG_PROTOCOL){
737
+ const address = [connection.remoteAddr.toString()]
738
+ if(this.#connectedPeers.has(id)){
739
+ //reset this last seen
740
+ const now = new Date().getTime()
741
+ const metadata = {addrs:address,last:now}
742
+ this.#connectedPeers.set(id,metadata)
743
+ }
744
+ else{
745
+ if(!this.#webPeersId.includes(id))this.#webPeersId.push(id)
746
+
747
+ //add to connected webpeers
748
+ this.#onConnectFn(id)
749
+ const now = new Date().getTime()
750
+ const metadata = {addrs:address,last:now}
751
+ this.#connectedPeers.set(id,metadata)
752
+ this.#updatePeers()
753
+ }
754
+ }
755
+
756
+ if(json.data != null){
757
+ this.#peerexchangedata.set(id,json.data)
758
+ let mddrs = []
759
+ const dataaddr = json.data.addr
760
+ const datamddr = multiaddr(dataaddr)
761
+ const dataid = json.data.id
762
+ mddrs.push(datamddr)
763
+ this.#dialMultiaddress(mddrs)
764
+ if(!this.#dbstoreData.has(dataid)){
765
+ //await this.#dbstore.put(new Key(dataid), new TextEncoder().encode(dataaddr))
766
+ //this.#dbstoreData.set(dataid,dataaddr)
767
+ }
768
+ }
769
+
770
+ const keys = Array.from(this.#dbstoreData.keys())
771
+ const randomKey = Math.floor(Math.random() * keys.length)
772
+ const key = keys[randomKey]
773
+ const addr = this.#dbstoreData.get(key)
774
+
775
+ jsonMessage.command = json.command
776
+ jsonMessage.data = {id:key,addr}
777
+ }
778
+
779
+ const message = JSON.stringify(jsonMessage)
780
+ //console.log('answer message '+id,message)
781
+
782
+ pipe(
783
+ message,
784
+ (source) => map(source, (string) => uint8ArrayFromString(string)),
785
+ (source) => lp.encode(source),
786
+ stream.sink
787
+ )
788
+ }
789
+ catch(err){
790
+ //console.warn(err)
791
+ }
616
792
  }
617
793
 
618
794
  await this.#libp2p.handle(config.CONFIG_PROTOCOL, handler, {
619
- maxInboundStreams: 5,
620
- maxOutboundStreams: 5
795
+ maxInboundStreams: 50,
796
+ maxOutboundStreams: 50,
797
+ runOnTransientConnection:true
621
798
  })
622
799
 
623
800
  await this.#libp2p.register(config.CONFIG_PROTOCOL, {
@@ -633,37 +810,129 @@ class webpeerjs{
633
810
 
634
811
  }
635
812
 
636
- #findHybridPeer(){
637
- setTimeout(async()=>{
638
- for(const target of config.CONFIG_KNOWN_BOOTSTRAP_HYBRID_IDS){
639
- if(!this.#isConnected(target) && !this.#connections.has(target) && this.#isDialEnabled ){
640
- //console.log('findPeer',target)
641
- const peerId = peerIdFromString(target)
642
- //const peerInfo = await this.#libp2p.services.aminoDHT.findPeer(peerId)
643
-
644
- //console.info(peerInfo)
645
- for await (const event of this.#libp2p.services.aminoDHT.findPeer(peerId)){
646
- //console.info('findPeer',event)
647
- if (event.name === 'FINAL_PEER'){
648
- //console.log(event.peer.id.toString(),event.peer.multiaddrs.toString())
649
- let mddrs = []
650
- let addrs = []
651
- const id = event.peer.id.toString()
652
- for(const mddr of event.peer.multiaddrs){
653
- const peeraddr = mddr.toString()+'/p2p/'+id
654
- const peermddr = multiaddr(peeraddr)
655
- addrs.push(peeraddr)
656
- mddrs.push(peermddr)
657
- }
658
- this.#dialedKnownBootstrap.set(id,addrs)
659
- if(!this.#isConnected(id)){
660
- this.#dialMultiaddress(mddrs)
661
- }
813
+ async #dialProtocol(id,command){
814
+
815
+ const connections = this.#libp2p.getConnections().map((con)=>{return {id:con.remotePeer.toString(),addr:con.remoteAddr.toString()}})
816
+ const connect = connections.find((con)=>con.id == id)
817
+ const addr = connect.addr
818
+ const mddr = multiaddr(addr)
819
+
820
+ let jsonMessage = {
821
+ protocol:config.CONFIG_PROTOCOL,
822
+ command:null,
823
+ data:null
824
+ }
825
+
826
+ if(command === 'peer-exchange'){
827
+
828
+ if(this.#peerexchangedata.has(id))return
829
+
830
+ const keys = Array.from(this.#dbstoreData.keys())
831
+ const randomKey = Math.floor(Math.random() * keys.length)
832
+ const key = keys[randomKey]
833
+ const addr = this.#dbstoreData.get(key)
834
+
835
+ jsonMessage.command = command
836
+ jsonMessage.data = {id:key,addr}
837
+ }
838
+
839
+ const message = JSON.stringify(jsonMessage)
840
+ //console.log('ask message '+id,message)
841
+
842
+ try{
843
+
844
+ const stream = await this.#libp2p.dialProtocol(mddr, config.CONFIG_PROTOCOL,{runOnTransientConnection:true})
845
+
846
+ const output = await pipe(
847
+ message,
848
+ (source) => map(source, (string) => uint8ArrayFromString(string)),
849
+ (source) => lp.encode(source),
850
+ stream,
851
+ (source) => lp.decode(source),
852
+ (source) => map(source, (buf) => uint8ArrayToString(buf.subarray())),
853
+ async function (source) {
854
+ let string = ''
855
+ for await (const msg of source) {
856
+ string += msg.toString()
857
+ }
858
+ return string
859
+ }
860
+ )
861
+
862
+ const json = JSON.parse(output)
863
+ if(json.protocol == config.CONFIG_PROTOCOL){
864
+ const address = [addr]
865
+ if(this.#connectedPeers.has(id)){
866
+ //reset this last seen
867
+ const now = new Date().getTime()
868
+ const metadata = {addrs:address,last:now}
869
+ this.#connectedPeers.set(id,metadata)
870
+ }
871
+ else{
872
+ if(!this.#webPeersId.includes(id))this.#webPeersId.push(id)
873
+
874
+ //add to connected webpeers
875
+ this.#onConnectFn(id)
876
+ const now = new Date().getTime()
877
+ const metadata = {addrs:address,last:now}
878
+ this.#connectedPeers.set(id,metadata)
879
+ this.#updatePeers()
880
+ }
881
+ }
882
+ if(json.command == 'peer-exchange'){
883
+ if(json.data != null){
884
+ this.#peerexchangedata.set(id,json.data)
885
+ let mddrs = []
886
+ const dataaddr = json.data.addr
887
+ const datamddr = multiaddr(dataaddr)
888
+ const dataid = json.data.id
889
+ mddrs.push(datamddr)
890
+ this.#dialMultiaddress(mddrs)
891
+ if(!this.#dbstoreData.has(dataid)){
892
+ //await this.#dbstore.put(new Key(dataid), new TextEncoder().encode(dataaddr))
893
+ //this.#dbstoreData.set(dataid,dataaddr)
894
+ }
895
+ }
896
+ }
897
+ }
898
+ catch(err){
899
+ //console.warn(err)
900
+ }
901
+ }
902
+
903
+ async #findHybridPeer(){
904
+
905
+ if(!navigator.onLine)return
906
+ if(!this.#isDialEnabled)return
907
+
908
+ for(const target of config.CONFIG_KNOWN_BOOTSTRAP_HYBRID_IDS){
909
+ if(!this.#isConnected(target) && !this.#connections.has(target)){
910
+ //console.log('findPeer',target)
911
+ const peerId = peerIdFromString(target)
912
+ //const peerInfo = await this.#libp2p.services.aminoDHT.findPeer(peerId)
913
+
914
+ //console.info(peerInfo)
915
+ for await (const event of this.#libp2p.services.aminoDHT.findPeer(peerId)){
916
+ //console.info('findPeer',event)
917
+ if (event.name === 'FINAL_PEER'){
918
+ //console.log(event.peer.id.toString(),event.peer.multiaddrs.toString())
919
+ let mddrs = []
920
+ let addrs = []
921
+ const id = event.peer.id.toString()
922
+ for(const mddr of event.peer.multiaddrs){
923
+ const peeraddr = mddr.toString()+'/p2p/'+id
924
+ const peermddr = multiaddr(peeraddr)
925
+ addrs.push(peeraddr)
926
+ mddrs.push(peermddr)
927
+ }
928
+ this.#dialedKnownBootstrap.set(id,addrs)
929
+ if(!this.#isConnected(id)){
930
+ this.#dialMultiaddress(mddrs)
662
931
  }
663
932
  }
664
933
  }
665
934
  }
666
- },60e3)
935
+ }
667
936
  }
668
937
 
669
938
 
@@ -719,13 +988,25 @@ class webpeerjs{
719
988
 
720
989
  const id = mddrs[0].toString().split('/').pop()
721
990
 
722
- const ids = this.#dialQueue.map((arr)=> arr[0].toString().split('/').pop())
991
+ const queueids = this.#dialQueue.map((arr)=> arr[0].toString().split('/').pop())
723
992
 
724
993
  //if peer id is already in the queque cancel queque
725
- if(ids.includes(id)){
994
+ if(queueids.includes(id)){
726
995
  return
727
996
  }
728
997
 
998
+ const webPeerCount = this.#connectedPeers.size
999
+ const allPeerCount = this.#libp2p.getPeers().length
1000
+ const nodePeerCount = allPeerCount - webPeerCount
1001
+ const limitCount = config.CONFIG_MAX_CONNECTIONS / 2
1002
+
1003
+ if(this.#webPeersId.includes(id)){
1004
+ if(webPeerCount>limitCount)return
1005
+ }
1006
+ else{
1007
+ if(nodePeerCount>limitCount)return
1008
+ }
1009
+
729
1010
  if(this.#webPeersId.includes(id) || config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS.includes(id) || config.CONFIG_KNOWN_BOOTSTRAP_HYBRID_IDS.includes(id)){
730
1011
  this.#dialQueue.unshift(mddrs)
731
1012
  }
@@ -739,7 +1020,7 @@ class webpeerjs{
739
1020
  //dial multiaddr address in queue list
740
1021
  #dialQueueList(){
741
1022
 
742
- if(!this.#isDialEnabled)return
1023
+ if(!this.#isDialEnabled || !navigator.onLine)return
743
1024
 
744
1025
  const mddrsToDial = 5
745
1026
 
@@ -804,55 +1085,6 @@ class webpeerjs{
804
1085
  await this.#libp2p.services.pubsub.publish(topic, encodedPeer)
805
1086
  }
806
1087
  }
807
-
808
-
809
- joinRoom = room => {
810
- if (this.#rooms[room]) {
811
- return [
812
- this.#rooms[room].sendMessage,
813
- this.#rooms[room].listenMessage,
814
- this.#rooms[room].onMembersChange
815
- ]
816
-
817
-
818
- }
819
-
820
- if (!room) {
821
- throw mkErr('room is required')
822
- }
823
-
824
- //join room version 1 user pupsub via pupsub peer discovery
825
- if(config.CONFIG_JOIN_ROOM_VERSION == 1){
826
-
827
- const topics = config.CONFIG_PUBSUB_PEER_DISCOVERY
828
-
829
- this.#rooms[room] = {
830
- onMessage : () => {},
831
- listenMessage : f => (this.#rooms[room] = {...this.#rooms[room], onMessage: f}),
832
- sendMessage : async (message) => {
833
- const msgId = (new Date()).getTime()
834
- const data = JSON.stringify({prefix:config.CONFIG_PREFIX,room,message,id:this.#libp2p.peerId.toString(),msgId})
835
- const peer = {
836
- publicKey: this.#libp2p.peerId.publicKey,
837
- addrs: [uint8ArrayFromString(data)],
838
- }
839
- const encodedPeer = PBPeer.encode(peer)
840
- for(const topic of topics){
841
- await this.#libp2p.services.pubsub.publish(topic, encodedPeer)
842
- }
843
- },
844
- members : [this.id],
845
- onMembers : () => {},
846
- onMembersChange : f => {this.#rooms[room] = {...this.#rooms[room], onMembers: f};this.#rooms[room].onMembers(this.#rooms[room].members);this.#ping()},
847
- }
848
- }
849
-
850
- return [
851
- this.#rooms[room].sendMessage,
852
- this.#rooms[room].listenMessage,
853
- this.#rooms[room].onMembersChange
854
- ]
855
- }
856
1088
 
857
1089
 
858
1090
  //dial discovered peers
@@ -955,8 +1187,7 @@ class webpeerjs{
955
1187
  if(besttime>bestlimit){
956
1188
  const addr = remote.toString()
957
1189
  const id = peer.toString()
958
- if(!this.#webPeersId.includes(id) && !config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS.includes(id) && !this.#dbstoreData.get(id) && !addr.includes('p2p-circuit') && addr.includes('webtransport')){
959
- //await this.#dbstore.delete(new Key(id))
1190
+ if(!this.#webPeersId.includes(id) && !config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS.includes(id) && !this.#dbstoreData.has(id) && !addr.includes('p2p-circuit') && addr.includes('webtransport')){
960
1191
  await this.#dbstore.put(new Key(id), new TextEncoder().encode(addr))
961
1192
  this.#dbstoreData.set(id,addr)
962
1193
  }
@@ -971,26 +1202,31 @@ class webpeerjs{
971
1202
  }
972
1203
 
973
1204
 
974
- let peers = []
975
- for(const peer of this.#libp2p.getPeers()){
976
- peers.push(peer.toString())
977
- }
978
-
979
-
980
1205
  //connect to saved best peer address
981
1206
  //working great
982
1207
  for(const peer of this.#dbstoreData){
983
1208
  const id = peer[0]
984
1209
  const addr = peer[1]
985
- if(peers.includes(id)){
1210
+ if(this.#isConnected(id)){
986
1211
  this.#connectionTrackerStore.set(id,0)
987
1212
  continue
988
1213
  }else{
989
1214
  if(this.#connectionTrackerStore.has(id)){
990
1215
  let current = this.#connectionTrackerStore.get(id)
991
- if(current>10)continue
992
1216
  current++
993
1217
  this.#connectionTrackerStore.set(id,current)
1218
+ if(current>5){
1219
+ if(!this.#connections.has(id) && !config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS.includes(id) && navigator.onLine)
1220
+ {
1221
+ setTimeout(async ()=> {
1222
+ if(this.#dbstoreData.has(id) && !this.#connections.has(id)){
1223
+ this.#dbstoreData.delete(id)
1224
+ await this.#dbstore.delete(new Key(id))
1225
+ }
1226
+ },60*1000)
1227
+ }
1228
+ continue
1229
+ }
994
1230
  }
995
1231
  else{
996
1232
  this.#connectionTrackerStore.set(id,0)
@@ -1005,7 +1241,7 @@ class webpeerjs{
1005
1241
  //connect to good peer address if it is disconnected
1006
1242
  const goods = Array.from(this.#dialedGoodPeers.keys())
1007
1243
  for(const id of goods){
1008
- if(peers.includes(id)){
1244
+ if(this.#isConnected(id)){
1009
1245
  this.#dialedGoodPeers.set(id,0)
1010
1246
  continue
1011
1247
  }
@@ -1040,66 +1276,52 @@ class webpeerjs{
1040
1276
  if(peers == 0){
1041
1277
  this.#dialKnownPeers()
1042
1278
  }
1043
- },60*1000)
1279
+ },120*1000)
1044
1280
  }
1045
1281
 
1046
1282
 
1047
1283
  //dial to all known bootstrap peers and DNS
1048
1284
  #dialKnownPeers(){
1049
- //this.#dialKnownBootstrap()
1050
1285
  setTimeout(()=>{
1051
1286
  this.#dialSavedKnownID()
1052
- this.#findHybridPeer()
1053
1287
  setTimeout(()=>{this.#dialUpdateSavedKnownID()},50000)
1288
+ setTimeout(()=>{this.#findHybridPeer()},60000)
1054
1289
  setTimeout(()=>{
1055
1290
  const peers = this.#libp2p.getPeers().length
1056
1291
  if(peers == 0){
1057
1292
  this.#dialKnownID()
1058
- this.#findHybridPeer()
1293
+ setTimeout(()=>{this.#findHybridPeer()},60000)
1059
1294
  setTimeout(()=>{
1060
1295
  const peers = this.#libp2p.getPeers().length
1061
1296
  if(peers == 0){
1062
- //currently not needed
1063
- //this.#dialKnownDNS()
1297
+ this.#dialKnownBootstrap()
1298
+ setTimeout(()=>{this.#findHybridPeer()},15000)
1064
1299
  setTimeout(()=>{
1065
1300
  const peers = this.#libp2p.getPeers().length
1066
1301
  if(peers == 0){
1067
- //currently not needed
1068
- //this.#dialKnownDNSonly()
1302
+ this.#dialKnownDNS()
1303
+ setTimeout(()=>{this.#findHybridPeer()},15000)
1304
+ setTimeout(()=>{
1305
+ const peers = this.#libp2p.getPeers().length
1306
+ if(peers == 0){
1307
+ this.#dialKnownDNSonly()
1308
+ setTimeout(()=>{this.#findHybridPeer()},15000)
1309
+ }
1310
+ },config.CONFIG_TIMEOUT_DIAL_KNOWN_PEERS)
1069
1311
  }
1070
- },15000)
1312
+ },config.CONFIG_TIMEOUT_DIAL_KNOWN_PEERS)
1071
1313
  }
1072
- },15000)
1314
+ },config.CONFIG_TIMEOUT_DIAL_KNOWN_PEERS)
1073
1315
  }
1074
- },15000)
1316
+ },config.CONFIG_TIMEOUT_DIAL_KNOWN_PEERS)
1075
1317
  },5000)
1076
1318
  }
1077
1319
 
1078
-
1079
- //dial based on known bootsrap peers address
1080
- #dialKnownBootstrap(){
1081
- const bootstrap = config.CONFIG_KNOWN_BOOTSTRAP_PEERS_ADDRS
1082
- for(const peer of bootstrap){
1083
- const address = peer.Peers[0].Addrs
1084
- const id = peer.Peers[0].ID
1085
- let mddrs = []
1086
- let addrs = []
1087
- for(const addr of address){
1088
- const peeraddr = addr+'/p2p/'+id
1089
- const peermddr = multiaddr(peeraddr)
1090
- addrs.push(peeraddr)
1091
- mddrs.push(peermddr)
1092
- }
1093
-
1094
- this.#dialedKnownBootstrap.set(id,addrs)
1095
- if(!this.#isConnected(id)){
1096
- this.#dialMultiaddress(mddrs)
1097
- }
1098
-
1099
- }
1100
- }
1101
-
1102
1320
  async #dialSavedKnownID(){
1321
+
1322
+ if(!navigator.onLine)return
1323
+ if(!this.#isDialEnabled)return
1324
+
1103
1325
  let firsttime = true
1104
1326
  for(const target of config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS){
1105
1327
  if(this.#dbstoreData.has(target)){
@@ -1122,6 +1344,7 @@ class webpeerjs{
1122
1344
  const api = config.CONFIG_DELEGATED_API
1123
1345
  const delegatedClient = createDelegatedRoutingV1HttpApiClient(api)
1124
1346
  const peer = await first(delegatedClient.getPeers(peerIdFromString(target)))
1347
+ if(!peer)continue
1125
1348
  const address = peer.Addrs
1126
1349
  const id = peer.ID
1127
1350
  let mddrs = []
@@ -1142,16 +1365,26 @@ class webpeerjs{
1142
1365
  }
1143
1366
 
1144
1367
  async #dialUpdateSavedKnownID(){
1368
+
1369
+ if(!navigator.onLine)return
1370
+ if(!this.#isDialEnabled)return
1371
+
1145
1372
  let firsttime = true
1146
1373
  for(const target of config.CONFIG_KNOWN_BOOTSTRAP_PEERS_IDS){
1147
1374
  if(this.#dbstoreData.has(target)){
1148
1375
  firsttime = false
1149
1376
  }
1150
- if(!this.#connections.has(target) && this.#isDialEnabled && (this.#dbstoreData.has(target) || firsttime)){
1377
+ if(!this.#connections.has(target) && (this.#dbstoreData.has(target) || firsttime)){
1151
1378
  //console.log('#dialUpdateSavedKnownID()',target)
1152
1379
  const api = config.CONFIG_DELEGATED_API
1153
1380
  const delegatedClient = createDelegatedRoutingV1HttpApiClient(api)
1154
1381
  const peer = await first(delegatedClient.getPeers(peerIdFromString(target)))
1382
+ if(!peer){
1383
+ if (navigator.onLine) {
1384
+ await this.#dbstore.delete(new Key(target))
1385
+ }
1386
+ continue
1387
+ }
1155
1388
  const address = peer.Addrs
1156
1389
  const id = peer.ID
1157
1390
  let mddrs = []
@@ -1174,6 +1407,10 @@ class webpeerjs{
1174
1407
 
1175
1408
  //dial based on known peers ID
1176
1409
  async #dialKnownID(){
1410
+
1411
+ if(!navigator.onLine)return
1412
+ if(!this.#isDialEnabled)return
1413
+
1177
1414
  //console.log('#dialKnownID()')
1178
1415
  const api = config.CONFIG_DELEGATED_API
1179
1416
  const delegatedClient = createDelegatedRoutingV1HttpApiClient(api)
@@ -1200,10 +1437,43 @@ class webpeerjs{
1200
1437
  }
1201
1438
  }
1202
1439
  }
1203
-
1440
+
1441
+
1442
+ //dial based on known bootsrap peers address using Websocket expected
1443
+ #dialKnownBootstrap(){
1444
+
1445
+ if(!navigator.onLine)return
1446
+ if(!this.#isDialEnabled)return
1447
+
1448
+ const bootstrap = config.CONFIG_KNOWN_BOOTSTRAP_PEERS_ADDRS
1449
+ for(const peer of bootstrap){
1450
+ const address = peer.Peers[0].Addrs
1451
+ const id = peer.Peers[0].ID
1452
+ let mddrs = []
1453
+ let addrs = []
1454
+ for(const addr of address){
1455
+ if(!addr.includes('wss'))continue
1456
+ const peeraddr = addr+'/p2p/'+id
1457
+ const peermddr = multiaddr(peeraddr)
1458
+ addrs.push(peeraddr)
1459
+ mddrs.push(peermddr)
1460
+ }
1461
+
1462
+ this.#dialedKnownBootstrap.set(id,addrs)
1463
+ this.#isDialWebsocket = true
1464
+ if(!this.#isConnected(id)){
1465
+ this.#dialMultiaddress(mddrs)
1466
+ }
1467
+
1468
+ }
1469
+ }
1204
1470
 
1205
1471
  //dial based on known bootstrap DNS
1206
- /*async #dialKnownDNS(){
1472
+ async #dialKnownDNS(){
1473
+
1474
+ if(!navigator.onLine)return
1475
+ if(!this.#isDialEnabled)return
1476
+
1207
1477
  const dnsresolver = config.CONFIG_DNS_RESOLVER
1208
1478
  const bootstrapdns = config.CONFIG_KNOWN_BOOTSTRAP_DNS
1209
1479
  const response = await fetch(dnsresolver+'?name='+bootstrapdns+'&type=txt')
@@ -1232,16 +1502,21 @@ class webpeerjs{
1232
1502
  }
1233
1503
 
1234
1504
  this.#dialedKnownBootstrap.set(id,addrs)
1505
+ this.#isDialWebsocket = true
1235
1506
  if(!this.#isConnected(id)){
1236
1507
  this.#dialMultiaddress(mddrs)
1237
1508
  }
1238
1509
  }
1239
1510
 
1240
- }*/
1511
+ }
1241
1512
 
1242
1513
 
1243
1514
  //dial based on known bootstrap DNS using DNS resolver only
1244
- /*async #dialKnownDNSonly(){
1515
+ async #dialKnownDNSonly(){
1516
+
1517
+ if(!navigator.onLine)return
1518
+ if(!this.#isDialEnabled)return
1519
+
1245
1520
  const dnsresolver = config.CONFIG_DNS_RESOLVER
1246
1521
  const bootstrapdns = config.CONFIG_KNOWN_BOOTSTRAP_DNS
1247
1522
  const response = await fetch(dnsresolver+'?name='+bootstrapdns+'&type=txt')
@@ -1254,11 +1529,11 @@ class webpeerjs{
1254
1529
  const dnsaddr = '_dnsaddr.'+arr[2]
1255
1530
  this.#dialDNSWebsocketWebtransport(id,dnsaddr)
1256
1531
  }
1257
- }*/
1532
+ }
1258
1533
 
1259
1534
 
1260
1535
  //dial DNS with webtransport and websocket
1261
- /*async #dialDNSWebsocketWebtransport(id,dnsaddr){
1536
+ async #dialDNSWebsocketWebtransport(id,dnsaddr){
1262
1537
  const dnsresolver = config.CONFIG_DNS_RESOLVER
1263
1538
  const response = await fetch(dnsresolver+'?name='+dnsaddr+'&type=txt')
1264
1539
  const json = await response.json()
@@ -1282,41 +1557,34 @@ class webpeerjs{
1282
1557
  this.#dialMultiaddress(mddrs)
1283
1558
  this.#dialWebsocket(mddrs)
1284
1559
  }
1285
- }*/
1560
+ }
1286
1561
 
1287
1562
 
1288
1563
  //dial only webtransport multiaddrs
1289
1564
  async #dialWebtransport(multiaddrs){
1290
1565
  const webTransportMadrs = multiaddrs.filter((maddr) => maddr.protoNames().includes('webtransport')&&maddr.protoNames().includes('certhash'))
1291
- for (const addr of webTransportMadrs) {
1566
+ for (const mddr of webTransportMadrs) {
1292
1567
  try {
1293
- //console.log(`attempting to dial webtransport multiaddr: %o`, addr.toString())
1294
- await this.#libp2p.dial(addr)
1568
+ //console.log(`attempting to dial webtransport multiaddr: %o`, mddr.toString())
1569
+ await this.#libp2p.dial(mddr)
1295
1570
  return // if we succeed dialing the peer, no need to try another address
1296
1571
  } catch (error) {
1297
- //console.log(`failed to dial webtransport multiaddr: %o`, addr.toString())
1572
+ //console.log(`failed to dial webtransport multiaddr: %o`, mddr.toString())
1298
1573
  mkDebug(error)
1299
1574
  }
1300
1575
  }
1301
1576
  }
1302
-
1303
- //dial only webtransport multiaddrs
1304
- /*#dialWebtransport1(multiaddrs){
1305
- const webTransportMadrs = multiaddrs.filter((maddr) => maddr.protoNames().includes('webtransport')&&maddr.protoNames().includes('certhash'))
1306
- if(webTransportMadrs.length == 0)return
1307
- this.#libp2p.dial(webTransportMadrs).then((data)=>{console.warn(data)},(data)=>{console.warn(data)})
1308
- }*/
1309
1577
 
1310
1578
  //dial only websocket multiaddrs
1311
1579
  async #dialWebsocket(multiaddrs){
1312
1580
  const webSocketMadrs = multiaddrs.filter((maddr) => maddr.protoNames().includes('wss'))
1313
- for (const addr of webSocketMadrs) {
1581
+ for (const mddr of webSocketMadrs) {
1314
1582
  try {
1315
- //console.log(`attempting to dial websocket multiaddr: %o`, addr)
1316
- await this.#libp2p.dial(addr)
1583
+ //console.log(`attempting to dial websocket multiaddr: %o`, mddr)
1584
+ await this.#libp2p.dial(mddr)
1317
1585
  return // if we succeed dialing the peer, no need to try another address
1318
1586
  } catch (error) {
1319
- //console.log(`failed to dial websocket multiaddr: %o`, addr)
1587
+ //console.log(`failed to dial websocket multiaddr: %o`, mddr)
1320
1588
  mkDebug(error)
1321
1589
  }
1322
1590
  }
@@ -1357,7 +1625,8 @@ class webpeerjs{
1357
1625
  ],
1358
1626
  },
1359
1627
  transports:[
1360
- webTransport(),
1628
+ webTransport(),
1629
+ webSockets(),
1361
1630
  circuitRelayTransport({
1362
1631
  discoverRelays: config.CONFIG_DISCOVER_RELAYS,
1363
1632
  reservationConcurrency: 1,