@peerbit/stream 4.0.5-efee9d3 → 4.0.6-2bc15a6

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