@peerbit/stream 4.0.5 → 4.0.6-55cebfe

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/index.ts CHANGED
@@ -1,66 +1,67 @@
1
- import { TypedEventEmitter, CustomEvent } from "@libp2p/interface";
2
- import { pipe } from "it-pipe";
3
- import Queue from "p-queue";
4
- import type { PeerId } from "@libp2p/interface";
5
- import type { Connection } from "@libp2p/interface";
6
- import { PushableLanes, pushableLanes } from "./pushable-lanes.js";
7
- import type { Stream } from "@libp2p/interface";
8
- import { Uint8ArrayList } from "uint8arraylist";
9
- import { abortableSource } from "abortable-iterator";
10
- import * as lp from "it-length-prefixed";
11
- import { MAX_ROUTE_DISTANCE, Routes } from "./routes.js";
12
- import type { IncomingStreamData, Registrar } from "@libp2p/interface-internal";
13
- import type { AddressManager } from "@libp2p/interface-internal";
14
- import type { ConnectionManager } from "@libp2p/interface-internal";
15
- import { PeerStore } from "@libp2p/interface";
16
- import pDefer from "p-defer";
17
-
18
- import { AbortError, delay, TimeoutError, waitFor } from "@peerbit/time";
19
-
1
+ import { CustomEvent, TypedEventEmitter } from "@libp2p/interface";
2
+ import type {
3
+ Connection,
4
+ Libp2pEvents,
5
+ PeerId,
6
+ PeerStore,
7
+ Stream,
8
+ TypedEventTarget,
9
+ } from "@libp2p/interface";
10
+ import type {
11
+ AddressManager,
12
+ ConnectionManager,
13
+ IncomingStreamData,
14
+ Registrar,
15
+ } from "@libp2p/interface-internal";
16
+ import { multiaddr } from "@multiformats/multiaddr";
17
+ import { Cache } from "@peerbit/cache";
20
18
  import {
19
+ PublicSignKey,
20
+ type SignatureWithKey,
21
21
  getKeypairFromPeerId,
22
22
  getPublicKeyFromPeerId,
23
- PublicSignKey,
23
+ ready,
24
24
  sha256Base64,
25
- SignatureWithKey,
26
- toBase64
25
+ toBase64,
27
26
  } from "@peerbit/crypto";
28
-
29
- import { multiaddr } from "@multiformats/multiaddr";
30
- import { Components } from "libp2p/components";
31
- import type { TypedEventTarget } from "@libp2p/interface";
32
-
33
- import { logger } from "./logger.js";
34
- export { logger };
35
- import { Cache } from "@peerbit/cache";
36
-
37
- import type { Libp2pEvents } from "@libp2p/interface";
38
- import { ready } from "@peerbit/crypto";
39
27
  import {
40
- Message as Message,
41
- DataMessage,
42
- getMsgId,
43
- WaitForPeer,
44
28
  ACK,
45
- SeekDelivery,
46
29
  AcknowledgeDelivery,
47
- SilentDelivery,
48
- MessageHeader,
49
- Goodbye,
50
- StreamEvents,
51
- TracedDelivery,
52
30
  AnyWhere,
31
+ DataMessage,
32
+ DeliveryError,
33
+ Goodbye,
34
+ type IdentificationOptions,
35
+ Message,
36
+ MessageHeader,
37
+ MultiAddrinfo,
53
38
  NotStartedError,
39
+ type PriorityOptions,
40
+ SeekDelivery,
41
+ SilentDelivery,
42
+ type StreamEvents,
43
+ TracedDelivery,
44
+ type WaitForPeer,
45
+ type WithMode,
46
+ type WithTo,
54
47
  deliveryModeHasReceiver,
55
- DeliveryError,
56
- WithTo,
57
- WithMode,
58
- PriorityOptions
48
+ getMsgId,
59
49
  } from "@peerbit/stream-interface";
60
-
61
- import { MultiAddrinfo } from "@peerbit/stream-interface";
50
+ import { AbortError, TimeoutError, delay, waitFor } from "@peerbit/time";
51
+ import { abortableSource } from "abortable-iterator";
52
+ import * as lp from "it-length-prefixed";
53
+ import { pipe } from "it-pipe";
54
+ import type { Components } from "libp2p/components";
55
+ import pDefer from "p-defer";
56
+ import Queue from "p-queue";
57
+ import { Uint8ArrayList } from "uint8arraylist";
58
+ import { logger } from "./logger.js";
59
+ import { type PushableLanes, pushableLanes } from "./pushable-lanes.js";
60
+ import { MAX_ROUTE_DISTANCE, Routes } from "./routes.js";
62
61
  import { BandwidthTracker } from "./stats.js";
63
- import { IdentificationOptions } from "@peerbit/stream-interface";
62
+
63
+ export { logger };
64
+
64
65
  export { BandwidthTracker }; // might be useful for others
65
66
 
66
67
  const logError = (e?: { message: string }) => {
@@ -182,7 +183,7 @@ export class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {
182
183
  throw new Error(
183
184
  `Message too large (${data.length * 1e-6}) mb). Needs to be less than ${
184
185
  MAX_DATA_LENGTH_OUT * 1e-6
185
- } mb`
186
+ } mb`,
186
187
  );
187
188
  }
188
189
  if (this.outboundStream == null) {
@@ -195,44 +196,46 @@ export class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {
195
196
  data instanceof Uint8Array ? data : data.subarray(),
196
197
  this.outboundStream.getReadableLength(0) === 0
197
198
  ? 0
198
- : getLaneFromPriority(priority) // TODO use more lanes
199
+ : getLaneFromPriority(priority), // TODO use more lanes
199
200
  );
200
201
  }
201
202
 
202
203
  async waitForWrite(bytes: Uint8Array | Uint8ArrayList, priority: number = 0) {
203
204
  if (this.closed) {
204
- logger.error("Failed to send to stream: " + this.peerId + ". Closed");
205
+ logger.error(
206
+ "Failed to send to stream: " + this.peerId.toString() + ". Closed",
207
+ );
205
208
  return;
206
209
  }
207
210
 
208
211
  if (!this.isWritable) {
209
212
  // Catch the event where the outbound stream is attach, but also abort if we shut down
210
- const outboundPromise = new Promise<void>((rs, rj) => {
211
- const resolve = () => {
213
+ const outboundPromise = new Promise<void>((resolve, reject) => {
214
+ const resolveClear = () => {
212
215
  this.removeEventListener("stream:outbound", listener);
213
216
  clearTimeout(timer);
214
- rs();
217
+ resolve();
215
218
  };
216
- const reject = (err: Error) => {
219
+ const rejectClear = (err: Error) => {
217
220
  this.removeEventListener("stream:outbound", listener);
218
221
  clearTimeout(timer);
219
- rj(err);
222
+ reject(err);
220
223
  };
221
224
  const timer = setTimeout(() => {
222
- reject(new Error("Timed out"));
225
+ rejectClear(new Error("Timed out"));
223
226
  }, 3 * 1000); // TODO if this timeout > 10s we run into issues in the tests when running in CI
224
227
  const abortHandler = () => {
225
228
  this.removeEventListener("close", abortHandler);
226
- reject(new AbortError("Closed"));
229
+ rejectClear(new AbortError("Closed"));
227
230
  };
228
231
  this.addEventListener("close", abortHandler);
229
232
 
230
233
  const listener = () => {
231
- resolve();
234
+ resolveClear();
232
235
  };
233
236
  this.addEventListener("stream:outbound", listener);
234
237
  if (this.isWritable) {
235
- resolve();
238
+ resolveClear();
236
239
  }
237
240
  });
238
241
 
@@ -265,15 +268,15 @@ export class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {
265
268
  this.rawInboundStream = stream;
266
269
  this.inboundStream = abortableSource(
267
270
  pipe(this.rawInboundStream, (source) =>
268
- lp.decode(source, { maxDataLength: MAX_DATA_LENGTH_IN })
271
+ lp.decode(source, { maxDataLength: MAX_DATA_LENGTH_IN }),
269
272
  ),
270
273
  this.inboundAbortController.signal,
271
274
  {
272
275
  returnOnAbort: true,
273
276
  onReturnError: (err) => {
274
277
  logger.error("Inbound stream error", err?.message);
275
- }
276
- }
278
+ },
279
+ },
277
280
  );
278
281
 
279
282
  this.dispatchEvent(new CustomEvent("stream:inbound"));
@@ -289,7 +292,7 @@ export class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {
289
292
  const _prevStream = this.outboundStream;
290
293
  if (_prevStream) {
291
294
  logger.info(
292
- `Stream already exist. This can be due to that you are opening two or more connections to ${this.peerId.toString()}. A stream will only be created for the first succesfully created connection`
295
+ `Stream already exist. This can be due to that you are opening two or more connections to ${this.peerId.toString()}. A stream will only be created for the first succesfully created connection`,
293
296
  );
294
297
  return;
295
298
  }
@@ -299,7 +302,7 @@ export class PeerStreams extends TypedEventEmitter<PeerStreamEvents> {
299
302
  pipe(
300
303
  this.outboundStream,
301
304
  (source) => lp.encode(source),
302
- this.rawOutboundStream
305
+ this.rawOutboundStream,
303
306
  ).catch(logError);
304
307
 
305
308
  // Emit if the connection is new
@@ -356,6 +359,13 @@ type ConnectionManagerOptions = {
356
359
  pruner?: PrunerOptions;
357
360
  };
358
361
 
362
+ export type ConnectionManagerArguments =
363
+ | (Partial<Pick<ConnectionManagerOptions, "minConnections">> &
364
+ Partial<Pick<ConnectionManagerOptions, "maxConnections">> & {
365
+ pruner?: Partial<PrunerOptions> | false;
366
+ } & { dialer?: Partial<DialerOptions> | false })
367
+ | false;
368
+
359
369
  export type DirectStreamOptions = {
360
370
  canRelayMessage?: boolean;
361
371
  messageProcessingConcurrency?: number;
@@ -376,15 +386,8 @@ export interface DirectStreamComponents extends Components {
376
386
  events: TypedEventTarget<Libp2pEvents>;
377
387
  }
378
388
 
379
- export type ConnectionManagerArguments =
380
- | (Partial<Pick<ConnectionManagerOptions, "minConnections">> &
381
- Partial<Pick<ConnectionManagerOptions, "maxConnections">> & {
382
- pruner?: Partial<PrunerOptions> | false;
383
- } & { dialer?: Partial<DialerOptions> | false })
384
- | false;
385
-
386
389
  export abstract class DirectStream<
387
- Events extends { [s: string]: any } = StreamEvents
390
+ Events extends { [s: string]: any } = StreamEvents,
388
391
  >
389
392
  extends TypedEventEmitter<Events>
390
393
  implements WaitForPeer
@@ -434,7 +437,7 @@ export abstract class DirectStream<
434
437
  callback: (
435
438
  ack: ACK,
436
439
  messageThrough: PeerStreams,
437
- messageFrom?: PeerStreams
440
+ messageFrom?: PeerStreams,
438
441
  ) => void;
439
442
  clear: () => void;
440
443
  }
@@ -443,7 +446,7 @@ export abstract class DirectStream<
443
446
  constructor(
444
447
  readonly components: DirectStreamComponents,
445
448
  multicodecs: string[],
446
- options?: DirectStreamOptions
449
+ options?: DirectStreamOptions,
447
450
  ) {
448
451
  super();
449
452
  const {
@@ -454,7 +457,7 @@ export abstract class DirectStream<
454
457
  connectionManager,
455
458
  routeSeekInterval = ROUTE_UPDATE_DELAY_FACTOR,
456
459
  seekTimeout = SEEK_DELIVERY_TIMEOUT,
457
- routeMaxRetentionPeriod = ROUTE_MAX_RETANTION_PERIOD
460
+ routeMaxRetentionPeriod = ROUTE_MAX_RETANTION_PERIOD,
458
461
  } = options || {};
459
462
 
460
463
  const signKey = getKeypairFromPeerId(components.peerId);
@@ -485,7 +488,7 @@ export abstract class DirectStream<
485
488
  maxConnections: Number.MAX_SAFE_INTEGER,
486
489
  minConnections: 0,
487
490
  dialer: undefined,
488
- pruner: undefined
491
+ pruner: undefined,
489
492
  };
490
493
  } else {
491
494
  this.connectionManagerOptions = {
@@ -504,23 +507,23 @@ export abstract class DirectStream<
504
507
  connectionTimeout: DEFAULT_PRUNED_CONNNECTIONS_TIMEOUT,
505
508
  interval: DEFAULT_PRUNE_CONNECTIONS_INTERVAL,
506
509
  maxBuffer: MAX_QUEUED_BYTES,
507
- ...connectionManager?.pruner
510
+ ...connectionManager?.pruner,
508
511
  }
509
- : undefined
512
+ : undefined,
510
513
  };
511
514
  }
512
515
 
513
516
  this.recentDials = this.connectionManagerOptions.dialer
514
517
  ? new Cache({
515
518
  ttl: this.connectionManagerOptions.dialer.retryDelay,
516
- max: 1e3
519
+ max: 1e3,
517
520
  })
518
521
  : undefined;
519
522
 
520
523
  this.prunedConnectionsCache = this.connectionManagerOptions.pruner
521
524
  ? new Cache({
522
525
  max: 1e6,
523
- ttl: this.connectionManagerOptions.pruner.connectionTimeout
526
+ ttl: this.connectionManagerOptions.pruner.connectionTimeout,
524
527
  })
525
528
  : undefined;
526
529
  }
@@ -537,7 +540,7 @@ export abstract class DirectStream<
537
540
 
538
541
  this.routes = new Routes(this.publicKeyHash, {
539
542
  routeMaxRetentionPeriod: this.routeMaxRetentionPeriod,
540
- signal: this.closeController.signal
543
+ signal: this.closeController.signal,
541
544
  });
542
545
 
543
546
  this.started = true;
@@ -551,9 +554,9 @@ export abstract class DirectStream<
551
554
  this.components.registrar.handle(multicodec, this._onIncomingStream, {
552
555
  maxInboundStreams: this.maxInboundStreams,
553
556
  maxOutboundStreams: this.maxOutboundStreams,
554
- runOnTransientConnection: false
555
- })
556
- )
557
+ runOnTransientConnection: false,
558
+ }),
559
+ ),
557
560
  );
558
561
 
559
562
  // register protocol with topology
@@ -563,9 +566,9 @@ export abstract class DirectStream<
563
566
  this.components.registrar.register(multicodec, {
564
567
  onConnect: this.onPeerConnected.bind(this),
565
568
  onDisconnect: this.onPeerDisconnected.bind(this),
566
- notifyOnTransient: false
567
- })
568
- )
569
+ notifyOnTransient: false,
570
+ }),
571
+ ),
569
572
  );
570
573
 
571
574
  // All existing connections are like new ones for us. To deduplication on remotes so we only resuse one connection for this protocol (we could be connected with many connections)
@@ -620,13 +623,13 @@ export abstract class DirectStream<
620
623
  clearTimeout(this.pruneConnectionsTimeout);
621
624
 
622
625
  await Promise.all(
623
- this.multicodecs.map((x) => this.components.registrar.unhandle(x))
626
+ this.multicodecs.map((x) => this.components.registrar.unhandle(x)),
624
627
  );
625
628
 
626
629
  // unregister protocol and handlers
627
630
  if (this._registrarTopologyIds != null) {
628
631
  this._registrarTopologyIds?.map((id) =>
629
- this.components.registrar.unregister(id)
632
+ this.components.registrar.unregister(id),
630
633
  );
631
634
  }
632
635
 
@@ -640,7 +643,7 @@ export abstract class DirectStream<
640
643
  await peerStreams.close();
641
644
  }
642
645
 
643
- for (const [k, v] of this.healthChecks) {
646
+ for (const [_k, v] of this.healthChecks) {
644
647
  clearTimeout(v);
645
648
  }
646
649
  this.healthChecks.clear();
@@ -652,7 +655,7 @@ export abstract class DirectStream<
652
655
  this.routes.clear();
653
656
  this.peerKeyHashToPublicKey.clear();
654
657
 
655
- for (const [k, v] of this._ackCallbacks) {
658
+ for (const [_k, v] of this._ackCallbacks) {
656
659
  v.clear();
657
660
  }
658
661
 
@@ -693,7 +696,7 @@ export abstract class DirectStream<
693
696
  peerId,
694
697
  publicKey,
695
698
  stream.protocol,
696
- connection.id
699
+ connection.id,
697
700
  );
698
701
  const inboundStream = peer.attachInboundStream(stream);
699
702
  this.processMessages(peer.publicKey, inboundStream, peer).catch(logError);
@@ -736,6 +739,7 @@ export abstract class DirectStream<
736
739
  let stream: Stream = undefined as any; // TODO types
737
740
  let tries = 0;
738
741
  let peer: PeerStreams = undefined as any;
742
+
739
743
  while (tries <= 3) {
740
744
  tries++;
741
745
  if (!this.started) {
@@ -778,7 +782,7 @@ export abstract class DirectStream<
778
782
  peerKey,
779
783
  -1,
780
784
  +new Date(),
781
- -1
785
+ -1,
782
786
  );
783
787
  } catch (err: any) {
784
788
  logger.error(err);
@@ -803,7 +807,7 @@ export abstract class DirectStream<
803
807
  .getConnectionsMap()
804
808
  .get(peerId)
805
809
  ?.find(
806
- (x) => x.id === conn.id
810
+ (x) => x.id === conn.id,
807
811
  ) /* TODO this should work but does not? peer?.connId !== conn.id */
808
812
  ) {
809
813
  return;
@@ -830,9 +834,9 @@ export abstract class DirectStream<
830
834
  leaving: [peerKeyHash],
831
835
  header: new MessageHeader({
832
836
  session: this.session,
833
- mode: new SilentDelivery({ to: dependent, redundancy: 2 })
834
- })
835
- }).sign(this.sign)
837
+ mode: new SilentDelivery({ to: dependent, redundancy: 2 }),
838
+ }),
839
+ }).sign(this.sign),
836
840
  );
837
841
  }
838
842
 
@@ -860,7 +864,7 @@ export abstract class DirectStream<
860
864
  target: PublicSignKey,
861
865
  distance: number,
862
866
  session: number,
863
- remoteSession: number
867
+ remoteSession: number,
864
868
  ) {
865
869
  const targetHash = typeof target === "string" ? target : target.hashcode();
866
870
 
@@ -870,7 +874,7 @@ export abstract class DirectStream<
870
874
  targetHash,
871
875
  distance,
872
876
  session,
873
- remoteSession
877
+ remoteSession,
874
878
  );
875
879
 
876
880
  // second condition is that we don't want to emit 'reachable' events for routes where we act only as a relay
@@ -883,29 +887,21 @@ export abstract class DirectStream<
883
887
  }
884
888
  }
885
889
 
886
- /**
887
- * invoked when a new peer becomes reachable
888
- * @param publicKeyHash
889
- */
890
890
  public onPeerReachable(publicKey: PublicSignKey) {
891
891
  // override this fn
892
892
  this.dispatchEvent(
893
- new CustomEvent("peer:reachable", { detail: publicKey })
893
+ new CustomEvent("peer:reachable", { detail: publicKey }),
894
894
  );
895
895
  }
896
896
 
897
- /**
898
- * invoked when a new peer becomes unreachable
899
- * @param publicKeyHash
900
- */
901
897
  public onPeerUnreachable(hash: string) {
902
898
  // override this fn
903
899
 
904
900
  this.dispatchEvent(
905
901
  // TODO types
906
902
  new CustomEvent("peer:unreachable", {
907
- detail: this.peerKeyHashToPublicKey.get(hash)!
908
- })
903
+ detail: this.peerKeyHashToPublicKey.get(hash)!,
904
+ }),
909
905
  );
910
906
  }
911
907
 
@@ -922,8 +918,8 @@ export abstract class DirectStream<
922
918
  this.dispatchEvent(
923
919
  // TODO types
924
920
  new CustomEvent("peer:session", {
925
- detail: key
926
- })
921
+ detail: key,
922
+ }),
927
923
  );
928
924
  }
929
925
 
@@ -934,7 +930,7 @@ export abstract class DirectStream<
934
930
  peerId: PeerId,
935
931
  publicKey: PublicSignKey,
936
932
  protocol: string,
937
- connId: string
933
+ connId: string,
938
934
  ): PeerStreams {
939
935
  const publicKeyHash = publicKey.hashcode();
940
936
 
@@ -956,14 +952,14 @@ export abstract class DirectStream<
956
952
  peerId,
957
953
  publicKey,
958
954
  protocol,
959
- connId
955
+ connId,
960
956
  });
961
957
 
962
958
  this.peers.set(publicKeyHash, peerStreams);
963
959
  this.updateSession(publicKey, -1);
964
960
 
965
961
  peerStreams.addEventListener("close", () => this._removePeer(publicKey), {
966
- once: true
962
+ once: true,
967
963
  });
968
964
 
969
965
  return peerStreams;
@@ -998,7 +994,7 @@ export abstract class DirectStream<
998
994
  async processMessages(
999
995
  peerId: PublicSignKey,
1000
996
  stream: AsyncIterable<Uint8ArrayList>,
1001
- peerStreams: PeerStreams
997
+ peerStreams: PeerStreams,
1002
998
  ) {
1003
999
  try {
1004
1000
  await pipe(stream, async (source) => {
@@ -1011,7 +1007,7 @@ export abstract class DirectStream<
1011
1007
  "Failed processing messages to id: " +
1012
1008
  peerStreams.peerId.toString() +
1013
1009
  ". " +
1014
- err?.message
1010
+ err?.message,
1015
1011
  );
1016
1012
  this.onPeerDisconnected(peerStreams.peerId);
1017
1013
  }
@@ -1023,7 +1019,7 @@ export abstract class DirectStream<
1023
1019
  async processRpc(
1024
1020
  from: PublicSignKey,
1025
1021
  peerStreams: PeerStreams,
1026
- message: Uint8ArrayList
1022
+ message: Uint8ArrayList,
1027
1023
  ): Promise<boolean> {
1028
1024
  // logger.debug("rpc from " + from + ", " + this.peerIdStr);
1029
1025
 
@@ -1045,7 +1041,7 @@ export abstract class DirectStream<
1045
1041
 
1046
1042
  private async modifySeenCache(
1047
1043
  message: Uint8Array,
1048
- getIdFn: (bytes: Uint8Array) => Promise<string> = getMsgId
1044
+ getIdFn: (bytes: Uint8Array) => Promise<string> = getMsgId,
1049
1045
  ) {
1050
1046
  const msgId = await getIdFn(message);
1051
1047
  const seen = this.seenCache.get(msgId);
@@ -1059,7 +1055,7 @@ export abstract class DirectStream<
1059
1055
  async processMessage(
1060
1056
  from: PublicSignKey,
1061
1057
  peerStream: PeerStreams,
1062
- msg: Uint8ArrayList
1058
+ msg: Uint8ArrayList,
1063
1059
  ) {
1064
1060
  if (!this.started) {
1065
1061
  return;
@@ -1069,8 +1065,8 @@ export abstract class DirectStream<
1069
1065
  const message: Message | undefined = Message.from(msg);
1070
1066
  this.dispatchEvent(
1071
1067
  new CustomEvent("message", {
1072
- detail: message
1073
- })
1068
+ detail: message,
1069
+ }),
1074
1070
  );
1075
1071
 
1076
1072
  if (message instanceof DataMessage) {
@@ -1089,7 +1085,7 @@ export abstract class DirectStream<
1089
1085
 
1090
1086
  public shouldIgnore(message: DataMessage, seenBefore: number) {
1091
1087
  const fromMe = message.header.signatures?.publicKeys.find((x) =>
1092
- x.equals(this.publicKey)
1088
+ x.equals(this.publicKey),
1093
1089
  );
1094
1090
 
1095
1091
  if (fromMe) {
@@ -1112,7 +1108,7 @@ export abstract class DirectStream<
1112
1108
  from: PublicSignKey,
1113
1109
  peerStream: PeerStreams,
1114
1110
  message: DataMessage,
1115
- seenBefore: number
1111
+ seenBefore: number,
1116
1112
  ) {
1117
1113
  if (this.shouldIgnore(message, seenBefore)) {
1118
1114
  return false;
@@ -1142,8 +1138,8 @@ export abstract class DirectStream<
1142
1138
  if (seenBefore === 0 && message.data) {
1143
1139
  this.dispatchEvent(
1144
1140
  new CustomEvent("data", {
1145
- detail: message
1146
- })
1141
+ detail: message,
1142
+ }),
1147
1143
  );
1148
1144
  }
1149
1145
  }
@@ -1170,8 +1166,8 @@ export abstract class DirectStream<
1170
1166
  const to = [...this.peers.values()].filter(
1171
1167
  (x) =>
1172
1168
  !message.header.signatures?.publicKeys.find((y) =>
1173
- y.equals(x.publicKey)
1174
- ) && x != peerStream
1169
+ y.equals(x.publicKey),
1170
+ ) && x !== peerStream,
1175
1171
  );
1176
1172
  if (to.length > 0) {
1177
1173
  this.relayMessage(from, message, to);
@@ -1201,7 +1197,7 @@ export abstract class DirectStream<
1201
1197
  async maybeAcknowledgeMessage(
1202
1198
  peerStream: PeerStreams,
1203
1199
  message: DataMessage | Goodbye,
1204
- seenBefore: number
1200
+ seenBefore: number,
1205
1201
  ) {
1206
1202
  if (
1207
1203
  (message.header.mode instanceof SeekDelivery ||
@@ -1215,7 +1211,7 @@ export abstract class DirectStream<
1215
1211
  return;
1216
1212
  }
1217
1213
  const signers = message.header.signatures!.publicKeys.map((x) =>
1218
- x.hashcode()
1214
+ x.hashcode(),
1219
1215
  );
1220
1216
  await this.publishMessage(
1221
1217
  this.publicKey,
@@ -1231,17 +1227,17 @@ export abstract class DirectStream<
1231
1227
  origin:
1232
1228
  message.header.mode instanceof SeekDelivery &&
1233
1229
  !message.header.signatures!.publicKeys.find((x) =>
1234
- this.prunedConnectionsCache?.has(x.hashcode())
1230
+ this.prunedConnectionsCache?.has(x.hashcode()),
1235
1231
  )
1236
1232
  ? new MultiAddrinfo(
1237
1233
  this.components.addressManager
1238
1234
  .getAddresses()
1239
- .map((x) => x.toString())
1235
+ .map((x) => x.toString()),
1240
1236
  )
1241
- : undefined
1242
- })
1237
+ : undefined,
1238
+ }),
1243
1239
  }).sign(this.sign),
1244
- [peerStream]
1240
+ [peerStream],
1245
1241
  );
1246
1242
  }
1247
1243
  }
@@ -1250,12 +1246,12 @@ export abstract class DirectStream<
1250
1246
  from: PublicSignKey,
1251
1247
  peerStream: PeerStreams,
1252
1248
  messageBytes: Uint8ArrayList | Uint8Array,
1253
- message: DataMessage
1249
+ message: DataMessage,
1254
1250
  ) {
1255
1251
  const seenBefore = await this.modifySeenCache(
1256
1252
  messageBytes instanceof Uint8ArrayList
1257
1253
  ? messageBytes.subarray()
1258
- : messageBytes
1254
+ : messageBytes,
1259
1255
  );
1260
1256
 
1261
1257
  return this.onDataMessage(from, peerStream, message, seenBefore);
@@ -1265,18 +1261,18 @@ export abstract class DirectStream<
1265
1261
  publicKey: PublicSignKey,
1266
1262
  peerStream: PeerStreams,
1267
1263
  messageBytes: Uint8ArrayList | Uint8Array,
1268
- message: ACK
1264
+ message: ACK,
1269
1265
  ) {
1270
1266
  const seenBefore = await this.modifySeenCache(
1271
1267
  messageBytes instanceof Uint8Array
1272
1268
  ? messageBytes
1273
1269
  : messageBytes.subarray(),
1274
- (bytes) => sha256Base64(bytes)
1270
+ (bytes) => sha256Base64(bytes),
1275
1271
  );
1276
1272
 
1277
1273
  if (seenBefore > 0) {
1278
1274
  logger.debug(
1279
- "Received message already seen of type: " + message.constructor.name
1275
+ "Received message already seen of type: " + message.constructor.name,
1280
1276
  );
1281
1277
  return false;
1282
1278
  }
@@ -1288,7 +1284,7 @@ export abstract class DirectStream<
1288
1284
 
1289
1285
  const messageIdString = toBase64(message.messageIdToAcknowledge);
1290
1286
  const myIndex = message.header.mode.trace.findIndex(
1291
- (x) => x === this.publicKeyHash
1287
+ (x) => x === this.publicKeyHash,
1292
1288
  );
1293
1289
  const next = message.header.mode.trace[myIndex - 1];
1294
1290
  const nextStream = next ? this.peers.get(next) : undefined;
@@ -1311,7 +1307,7 @@ export abstract class DirectStream<
1311
1307
  if (message.header.origin && this.connectionManagerOptions.dialer) {
1312
1308
  this.maybeConnectDirectly(
1313
1309
  message.header.signatures!.publicKeys[0].hashcode(),
1314
- message.header.origin
1310
+ message.header.origin,
1315
1311
  );
1316
1312
  }
1317
1313
  }
@@ -1321,17 +1317,17 @@ export abstract class DirectStream<
1321
1317
  publicKey: PublicSignKey,
1322
1318
  peerStream: PeerStreams,
1323
1319
  messageBytes: Uint8ArrayList | Uint8Array,
1324
- message: Goodbye
1320
+ message: Goodbye,
1325
1321
  ) {
1326
1322
  const seenBefore = await this.modifySeenCache(
1327
1323
  messageBytes instanceof Uint8Array
1328
1324
  ? messageBytes
1329
- : messageBytes.subarray()
1325
+ : messageBytes.subarray(),
1330
1326
  );
1331
1327
 
1332
1328
  if (seenBefore > 0) {
1333
1329
  logger.debug(
1334
- "Received message already seen of type: " + message.constructor.name
1330
+ "Received message already seen of type: " + message.constructor.name,
1335
1331
  );
1336
1332
  return;
1337
1333
  }
@@ -1344,7 +1340,7 @@ export abstract class DirectStream<
1344
1340
  await this.maybeAcknowledgeMessage(peerStream, message, seenBefore);
1345
1341
 
1346
1342
  const filteredLeaving = message.leaving.filter((x) =>
1347
- this.routes.hasTarget(x)
1343
+ this.routes.hasTarget(x),
1348
1344
  );
1349
1345
 
1350
1346
  // Forward to all dependent
@@ -1380,8 +1376,8 @@ export abstract class DirectStream<
1380
1376
  return this.publish(undefined, {
1381
1377
  mode: new SeekDelivery({
1382
1378
  to: remotes,
1383
- redundancy: DEFAULT_SEEK_MESSAGE_REDUDANCY
1384
- })
1379
+ redundancy: DEFAULT_SEEK_MESSAGE_REDUDANCY,
1380
+ }),
1385
1381
  })
1386
1382
  .then(() => true)
1387
1383
  .catch((e) => {
@@ -1403,7 +1399,7 @@ export abstract class DirectStream<
1403
1399
 
1404
1400
  async createMessage(
1405
1401
  data: Uint8Array | Uint8ArrayList | undefined,
1406
- options: (WithTo | WithMode) & PriorityOptions & IdentificationOptions
1402
+ options: (WithTo | WithMode) & PriorityOptions & IdentificationOptions,
1407
1403
  ) {
1408
1404
  // dispatch the event if we are interested
1409
1405
 
@@ -1413,7 +1409,7 @@ export abstract class DirectStream<
1413
1409
  ? (options as WithMode).mode!
1414
1410
  : new SilentDelivery({
1415
1411
  to: (options as WithTo).to!,
1416
- redundancy: DEFAULT_SILENT_MESSAGE_REDUDANCY
1412
+ redundancy: DEFAULT_SILENT_MESSAGE_REDUDANCY,
1417
1413
  });
1418
1414
 
1419
1415
  if (
@@ -1441,7 +1437,7 @@ export abstract class DirectStream<
1441
1437
  ) {
1442
1438
  mode = new SeekDelivery({
1443
1439
  to: mode.to,
1444
- redundancy: DEFAULT_SEEK_MESSAGE_REDUDANCY
1440
+ redundancy: DEFAULT_SEEK_MESSAGE_REDUDANCY,
1445
1441
  });
1446
1442
  break;
1447
1443
  }
@@ -1454,8 +1450,8 @@ export abstract class DirectStream<
1454
1450
  id: options.id,
1455
1451
  mode,
1456
1452
  session: this.session,
1457
- priority: options.priority
1458
- })
1453
+ priority: options.priority,
1454
+ }),
1459
1455
  });
1460
1456
 
1461
1457
  // TODO allow messages to also be sent unsigned (signaturePolicy property)
@@ -1468,8 +1464,8 @@ export abstract class DirectStream<
1468
1464
  async publish(
1469
1465
  data: Uint8Array | Uint8ArrayList | undefined,
1470
1466
  options: (WithMode | WithTo) & PriorityOptions = {
1471
- mode: new SeekDelivery({ redundancy: DEFAULT_SEEK_MESSAGE_REDUDANCY })
1472
- }
1467
+ mode: new SeekDelivery({ redundancy: DEFAULT_SEEK_MESSAGE_REDUDANCY }),
1468
+ },
1473
1469
  ): Promise<Uint8Array> {
1474
1470
  if (!this.started) {
1475
1471
  throw new NotStartedError();
@@ -1477,7 +1473,7 @@ export abstract class DirectStream<
1477
1473
 
1478
1474
  if ((options as WithMode).mode && (options as WithTo).to) {
1479
1475
  throw new Error(
1480
- "Expecting either 'to' or 'mode' to be provided not both"
1476
+ "Expecting either 'to' or 'mode' to be provided not both",
1481
1477
  );
1482
1478
  }
1483
1479
 
@@ -1489,7 +1485,7 @@ export abstract class DirectStream<
1489
1485
  public async relayMessage(
1490
1486
  from: PublicSignKey,
1491
1487
  message: Message,
1492
- to?: PeerStreams[] | Map<string, PeerStreams>
1488
+ to?: PeerStreams[] | Map<string, PeerStreams>,
1493
1489
  ) {
1494
1490
  if (this.canRelayMessage) {
1495
1491
  if (message instanceof DataMessage) {
@@ -1502,7 +1498,7 @@ export abstract class DirectStream<
1502
1498
  }
1503
1499
  if (deliveryModeHasReceiver(message.header.mode)) {
1504
1500
  message.header.mode.to = message.header.mode.to.filter(
1505
- (x) => x !== this.publicKeyHash
1501
+ (x) => x !== this.publicKeyHash,
1506
1502
  );
1507
1503
  if (message.header.mode.to.length === 0) {
1508
1504
  return; // non to send to
@@ -1524,7 +1520,7 @@ export abstract class DirectStream<
1524
1520
  private async createDeliveryPromise(
1525
1521
  from: PublicSignKey,
1526
1522
  message: DataMessage | Goodbye,
1527
- relayed?: boolean
1523
+ relayed?: boolean,
1528
1524
  ): Promise<{ promise: Promise<void> }> {
1529
1525
  if (message.header.mode instanceof AnyWhere) {
1530
1526
  return { promise: Promise.resolve() };
@@ -1550,7 +1546,7 @@ export abstract class DirectStream<
1550
1546
  to,
1551
1547
  setTimeout(() => {
1552
1548
  this.removePeerFromRoutes(to);
1553
- }, this.seekTimeout)
1549
+ }, this.seekTimeout),
1554
1550
  );
1555
1551
  }
1556
1552
  }
@@ -1561,9 +1557,9 @@ export abstract class DirectStream<
1561
1557
  return {
1562
1558
  promise: Promise.reject(
1563
1559
  new DeliveryError(
1564
- "Cannnot deliver message to peers because there are no peers to deliver to"
1565
- )
1566
- )
1560
+ "Cannnot deliver message to peers because there are no peers to deliver to",
1561
+ ),
1562
+ ),
1567
1563
  };
1568
1564
  }
1569
1565
 
@@ -1586,15 +1582,15 @@ export abstract class DirectStream<
1586
1582
 
1587
1583
  const onUnreachable =
1588
1584
  !relayed &&
1589
- ((ev) => {
1585
+ ((ev: any) => {
1590
1586
  const deletedReceiver = messageToSet.delete(ev.detail.hashcode());
1591
1587
  if (deletedReceiver) {
1592
1588
  // Only reject if we are the sender
1593
1589
  clear();
1594
1590
  deliveryDeferredPromise.reject(
1595
1591
  new DeliveryError(
1596
- `At least one recipent became unreachable while delivering messsage of type ${message.constructor.name}} to ${ev.detail.hashcode()}`
1597
- )
1592
+ `At least one recipent became unreachable while delivering messsage of type ${message.constructor.name}} to ${ev.detail.hashcode()}`,
1593
+ ),
1598
1594
  );
1599
1595
  }
1600
1596
  });
@@ -1631,13 +1627,13 @@ export abstract class DirectStream<
1631
1627
  deliveryDeferredPromise.reject(
1632
1628
  new DeliveryError(
1633
1629
  `Failed to get message ${idString} ${filterMessageForSeenCounter} ${[
1634
- ...messageToSet
1630
+ ...messageToSet,
1635
1631
  ]} delivery acknowledges from all nodes (${
1636
1632
  fastestNodesReached.size
1637
1633
  }/${messageToSet.size}). Mode: ${
1638
1634
  message.header.mode.constructor.name
1639
- }. Redundancy: ${message.header.mode["redundancy"]}`
1640
- )
1635
+ }. Redundancy: ${(message.header.mode as any)["redundancy"]}`,
1636
+ ),
1641
1637
  );
1642
1638
  } else {
1643
1639
  deliveryDeferredPromise.resolve();
@@ -1681,7 +1677,7 @@ export abstract class DirectStream<
1681
1677
  messageTarget,
1682
1678
  seenCounter,
1683
1679
  session,
1684
- Number(ack.header.session)
1680
+ Number(ack.header.session),
1685
1681
  ); // we assume the seenCounter = distance. The more the message has been seen by the target the longer the path is to the target
1686
1682
  }
1687
1683
 
@@ -1710,7 +1706,7 @@ export abstract class DirectStream<
1710
1706
  clear: () => {
1711
1707
  clear();
1712
1708
  deliveryDeferredPromise.resolve();
1713
- }
1709
+ },
1714
1710
  });
1715
1711
  return deliveryDeferredPromise;
1716
1712
  }
@@ -1719,7 +1715,7 @@ export abstract class DirectStream<
1719
1715
  from: PublicSignKey,
1720
1716
  message: Message,
1721
1717
  to?: PeerStreams[] | Map<string, PeerStreams>,
1722
- relayed?: boolean
1718
+ relayed?: boolean,
1723
1719
  ): Promise<void> {
1724
1720
  if (this.stopping || !this.started) {
1725
1721
  throw new NotStartedError();
@@ -1783,7 +1779,7 @@ export abstract class DirectStream<
1783
1779
  const fanout = this.routes.getFanout(
1784
1780
  from.hashcode(),
1785
1781
  message.header.mode.to,
1786
- message.header.mode.redundancy
1782
+ message.header.mode.redundancy,
1787
1783
  );
1788
1784
 
1789
1785
  if (fanout) {
@@ -1793,7 +1789,7 @@ export abstract class DirectStream<
1793
1789
  const stream = this.peers.get(neighbour);
1794
1790
  stream &&
1795
1791
  promises.push(
1796
- stream.waitForWrite(bytes, message.header.priority)
1792
+ stream.waitForWrite(bytes, message.header.priority),
1797
1793
  );
1798
1794
  }
1799
1795
  await Promise.all(promises);
@@ -1832,7 +1828,7 @@ export abstract class DirectStream<
1832
1828
  // Dont send message back to any of the signers (they have already seen the message)
1833
1829
  if (
1834
1830
  message.header.signatures?.publicKeys.find((x) =>
1835
- x.equals(id.publicKey)
1831
+ x.equals(id.publicKey),
1836
1832
  )
1837
1833
  ) {
1838
1834
  continue;
@@ -1866,13 +1862,15 @@ export abstract class DirectStream<
1866
1862
  .map((x) => multiaddr(x));
1867
1863
  if (addresses.length > 0) {
1868
1864
  try {
1869
- await this.components.connectionManager.openConnection(addresses);
1865
+ await this.components.connectionManager.openConnection([
1866
+ addresses[addresses.length - 1],
1867
+ ]);
1870
1868
  } catch (error: any) {
1871
1869
  logger.info(
1872
1870
  "Failed to connect directly to: " +
1873
1871
  JSON.stringify(addresses.map((x) => x.toString())) +
1874
1872
  ". " +
1875
- error?.message
1873
+ error?.message,
1876
1874
  );
1877
1875
  }
1878
1876
  }
@@ -1880,7 +1878,7 @@ export abstract class DirectStream<
1880
1878
 
1881
1879
  async waitFor(
1882
1880
  peer: PeerId | PublicSignKey,
1883
- options?: { timeout?: number; signal?: AbortSignal; neighbour?: boolean }
1881
+ options?: { timeout?: number; signal?: AbortSignal; neighbour?: boolean },
1884
1882
  ) {
1885
1883
  const hash = (
1886
1884
  peer instanceof PublicSignKey ? peer : getPublicKeyFromPeerId(peer)
@@ -1900,8 +1898,8 @@ export abstract class DirectStream<
1900
1898
  },
1901
1899
  {
1902
1900
  signal: options?.signal,
1903
- timeout: options?.timeout ?? 10 * 1000
1904
- }
1901
+ timeout: options?.timeout ?? 10 * 1000,
1902
+ },
1905
1903
  );
1906
1904
  } catch (error) {
1907
1905
  throw new Error(
@@ -1910,7 +1908,7 @@ export abstract class DirectStream<
1910
1908
  " does not exist. Connection exist: " +
1911
1909
  this.peers.has(hash) +
1912
1910
  ". Route exist: " +
1913
- this.routes.isReachable(this.publicKeyHash, hash, 0)
1911
+ this.routes.isReachable(this.publicKeyHash, hash, 0),
1914
1912
  );
1915
1913
  }
1916
1914
  if (options?.neighbour) {
@@ -1919,7 +1917,7 @@ export abstract class DirectStream<
1919
1917
  // Dontwait for readlable https://github.com/libp2p/js-libp2p/issues/2321
1920
1918
  await waitFor(() => /* stream.isReadable && */ stream.isWritable, {
1921
1919
  signal: options?.signal,
1922
- timeout: options?.timeout ?? 10 * 1000
1920
+ timeout: options?.timeout ?? 10 * 1000,
1923
1921
  });
1924
1922
  } catch (error) {
1925
1923
  throw new Error(
@@ -1928,7 +1926,7 @@ export abstract class DirectStream<
1928
1926
  " not ready. Readable: " +
1929
1927
  stream.isReadable +
1930
1928
  ". Writable " +
1931
- stream.isWritable
1929
+ stream.isWritable,
1932
1930
  );
1933
1931
  }
1934
1932
  }