libp2p 0.35.8-bf1fc32 → 0.35.8-d8ceb0b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"auto-relay.d.ts","sourceRoot":"","sources":["../../../src/circuit/auto-relay.js"],"names":[],"mappings":";AAqBA;;;;GAIG;AAEH;;;;;;;GAOG;AAEH;IACE;;;;;OAKG;IACH,+CAFW,mBAAmB,GAAG,gBAAgB,EA+BhD;IA5BC,uBAAqB;IACrB,2BAA4B;IAC5B,oDAAkC;IAClC,oDAAkD;IAClD,kDAAgD;IAChD,gHAAiD;IAEjD,qBAAgC;IAEhC;;OAEG;IACH,eAFU,IAAI,MAAM,CAAC,CAES;IAkBhC;;;;;;;;;;OAUG;IACH;QAJyB,MAAM,EAApB,MAAM;QACU,SAAS,EAAzB,MAAM,EAAE;QACN,QAAQ,IAAI,CAAC,CAsCzB;IAED;;;;OAIG;IACH,gCAFW,UAAU,QAcpB;IA5EC;;;OAGG;IACH,kBAHW,KAAK,oCAMf;IAuEH;;;;;;;OAOG;IACH,wBA0BC;IAED;;;;;OAKG;IACH,2BAKC;IAED;;;;;;;;OAQG;IACH,iFAwEC;IAED;;OAEG;IACH,4BAFW,MAAM,iBAShB;CACF;;;;cArQY,OAAO,SAAS,CAAC;;;YAKhB,OAAO,KAAK,CAAC;;;;;;;uBAIL,KAAK,+BAAmB,EAAE;;eAVnC,OAAO,qBAAqB,EAAE,OAAO"}
1
+ {"version":3,"file":"auto-relay.d.ts","sourceRoot":"","sources":["../../../src/circuit/auto-relay.js"],"names":[],"mappings":";AAsBA;;;;GAIG;AAEH;;;;;;;GAOG;AAEH;IACE;;;;;OAKG;IACH,+CAFW,mBAAmB,GAAG,gBAAgB,EA+BhD;IA5BC,uBAAqB;IACrB,2BAA4B;IAC5B,oDAAkC;IAClC,oDAAkD;IAClD,kDAAgD;IAChD,gHAAiD;IAEjD,qBAAgC;IAEhC;;OAEG;IACH,eAFU,IAAI,MAAM,CAAC,CAES;IAkBhC;;;;;;;;;;OAUG;IACH;QAJyB,MAAM,EAApB,MAAM;QACU,SAAS,EAAzB,MAAM,EAAE;QACN,QAAQ,IAAI,CAAC,CAsCzB;IAED;;;;OAIG;IACH,gCAFW,UAAU,QAcpB;IA5EC;;;OAGG;IACH,kBAHW,KAAK,oCAMf;IAuEH;;;;;;;OAOG;IACH,wBAkCC;IAED;;;;;OAKG;IACH,2BAKC;IAED;;;;;;;;OAQG;IACH,iFA6EC;IAED;;OAEG;IACH,4BAFW,MAAM,iBAShB;CACF;;;;cAlRY,OAAO,SAAS,CAAC;;;YAKhB,OAAO,KAAK,CAAC;;;;;;;uBAIL,KAAK,+BAAmB,EAAE;;eAVnC,OAAO,qBAAqB,EAAE,OAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/connection-manager/index.js"],"names":[],"mappings":";AAsCA;;;GAGG;AAEH;;;;;;;;;;;;;GAaG;AAEH;;;;GAIG;AACH;IACE;;;;;;OAMG;IACH,oBAHW,MAAM,YACN,wBAAwB,EA6ClC;IAxCC,uBAAqB;IACrB,gBAA0C;IAE1C,cAAqF;IAOrF;;;;OAIG;IACH,aAFU,IAAI,MAAM,EAAE,MAAM,CAAC,CAM3B;IAEF;;;;OAIG;IACH,aAFU,IAAI,MAAM,EAAE,UAAU,EAAE,CAAC,CAMjC;IAEF,kBAAqB;IACrB,YAAkB;IAoFpB;;;;;OAKG;IACH,sBAiBC;IAxGC,gCAGE;IAGJ;;OAEG;IACH,mBAGC;IAED;;;OAGG;IACH,cAYC;IAgKD;;;;;OAKG;IACH,0BAKC;IAzKD;;;;OAIG;IACH,sBASC;IAED;;;;OAIG;IACH,wBAWC;IAED;;;;;;;OAOG;IACH,qBAJW,MAAM,SACN,MAAM,GACJ,IAAI,CAOhB;IA2BD;;;;OAIG;IACH,sBAFW,UAAU,iBAsBpB;IAED;;;;;OAKG;IACH,yBAHW,UAAU,GACR,IAAI,CAgBhB;IAED;;;;;OAKG;IACH,YAHW,MAAM,GACJ,UAAU,GAAC,IAAI,CAQ3B;IAED;;;;;OAKG;IACH,eAHW,MAAM,GACJ,UAAU,EAAE,CAexB;IAeD;;;;;;OAMG;IACH,uBAOC;IAED;;;;;OAKG;IACH,4BAqBC;CACF;;;;;;;;cA9TY,OAAO,KAAK,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/connection-manager/index.js"],"names":[],"mappings":";AAsCA;;;GAGG;AAEH;;;;;;;;;;;;;GAaG;AAEH;;;;GAIG;AACH;IACE;;;;;;OAMG;IACH,oBAHW,MAAM,YACN,wBAAwB,EAgDlC;IA3CC,uBAAqB;IACrB,gBAA0C;IAE1C,cAAqF;IAOrF;;;;OAIG;IACH,aAFU,IAAI,MAAM,EAAE,MAAM,CAAC,CAM3B;IAEF;;;;OAIG;IACH,aAFU,IAAI,MAAM,EAAE,UAAU,EAAE,CAAC,CAMjC;IAEF,kBAAqB;IACrB,YAAkB;IAuFpB;;;;;OAKG;IACH,sBAiBC;IA3GC,gCAGE;IAMJ;;OAEG;IACH,mBAGC;IAED;;;OAGG;IACH,cAYC;IAgKD;;;;;OAKG;IACH,0BAKC;IAzKD;;;;OAIG;IACH,sBASC;IAED;;;;OAIG;IACH,wBAWC;IAED;;;;;;;OAOG;IACH,qBAJW,MAAM,SACN,MAAM,GACJ,IAAI,CAOhB;IA2BD;;;;OAIG;IACH,sBAFW,UAAU,iBAsBpB;IAED;;;;;OAKG;IACH,yBAHW,UAAU,GACR,IAAI,CAgBhB;IAED;;;;;OAKG;IACH,YAHW,MAAM,GACJ,UAAU,GAAC,IAAI,CAQ3B;IAED;;;;;OAKG;IACH,eAHW,MAAM,GACJ,UAAU,EAAE,CAexB;IAeD;;;;;;OAMG;IACH,uBAOC;IAED;;;;;OAKG;IACH,4BAqBC;CACF;;;;;;;;cAjUY,OAAO,KAAK,CAAC"}
@@ -0,0 +1,2 @@
1
+ export const PROTOCOL: string;
2
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/fetch/constants.js"],"names":[],"mappings":""}
@@ -0,0 +1,76 @@
1
+ export = FetchProtocol;
2
+ /**
3
+ * @typedef {import('../')} Libp2p
4
+ * @typedef {import('multiaddr').Multiaddr} Multiaddr
5
+ * @typedef {import('peer-id')} PeerId
6
+ * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream
7
+ * @typedef {(key: string) => Promise<Uint8Array | null>} LookupFunction
8
+ */
9
+ /**
10
+ * A simple libp2p protocol for requesting a value corresponding to a key from a peer.
11
+ * Developers can register one or more lookup function for retrieving the value corresponding to
12
+ * a given key. Each lookup function must act on a distinct part of the overall key space, defined
13
+ * by a fixed prefix that all keys that should be routed to that lookup function will start with.
14
+ */
15
+ declare class FetchProtocol {
16
+ /**
17
+ * @param {Libp2p} libp2p
18
+ */
19
+ constructor(libp2p: Libp2p);
20
+ _lookupFunctions: Map<any, any>;
21
+ _libp2p: import("../");
22
+ /**
23
+ * Invoked when a fetch request is received. Reads the request message off the given stream and
24
+ * responds based on looking up the key in the request via the lookup callback that corresponds
25
+ * to the key's prefix.
26
+ *
27
+ * @param {object} options
28
+ * @param {MuxedStream} options.stream
29
+ * @param {string} options.protocol
30
+ */
31
+ handleMessage(options: {
32
+ stream: MuxedStream;
33
+ protocol: string;
34
+ }): Promise<void>;
35
+ /**
36
+ * Sends a request to fetch the value associated with the given key from the given peer.
37
+ *
38
+ * @param {PeerId|Multiaddr} peer
39
+ * @param {string} key
40
+ * @returns {Promise<Uint8Array | null>}
41
+ */
42
+ fetch(peer: PeerId | Multiaddr, key: string): Promise<Uint8Array | null>;
43
+ /**
44
+ * Given a key, finds the appropriate function for looking up its corresponding value, based on
45
+ * the key's prefix.
46
+ *
47
+ * @param {string} key
48
+ */
49
+ _getLookupFunction(key: string): any;
50
+ /**
51
+ * Registers a new lookup callback that can map keys to values, for a given set of keys that
52
+ * share the same prefix.
53
+ *
54
+ * @param {string} prefix
55
+ * @param {LookupFunction} lookup
56
+ */
57
+ registerLookupFunction(prefix: string, lookup: LookupFunction): void;
58
+ /**
59
+ * Registers a new lookup callback that can map keys to values, for a given set of keys that
60
+ * share the same prefix.
61
+ *
62
+ * @param {string} prefix
63
+ * @param {LookupFunction} [lookup]
64
+ */
65
+ unregisterLookupFunction(prefix: string, lookup?: LookupFunction | undefined): void;
66
+ }
67
+ declare namespace FetchProtocol {
68
+ export { PROTOCOL, Libp2p, Multiaddr, PeerId, MuxedStream, LookupFunction };
69
+ }
70
+ type MuxedStream = import('libp2p-interfaces/src/stream-muxer/types').MuxedStream;
71
+ type PeerId = import('peer-id');
72
+ type Multiaddr = import('multiaddr').Multiaddr;
73
+ type LookupFunction = (key: string) => Promise<Uint8Array | null>;
74
+ type Libp2p = import('../');
75
+ import { PROTOCOL } from "./constants";
76
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/fetch/index.js"],"names":[],"mappings":";AAcA;;;;;;GAMG;AAEH;;;;;GAKG;AACH;IACE;;OAEG;IACH,oBAFW,MAAM,EAMhB;IAHC,gCAAiC;IACjC,uBAAqB;IA0CvB;;;;;;;;OAQG;IACH;QAHgC,MAAM,EAA3B,WAAW;QACK,QAAQ,EAAxB,MAAM;sBAsBhB;IAnED;;;;;;OAMG;IACH,YAJW,MAAM,GAAC,SAAS,OAChB,MAAM,GACJ,QAAQ,UAAU,GAAG,IAAI,CAAC,CA+BtC;IAiCD;;;;;OAKG;IACH,wBAFW,MAAM,OAShB;IAED;;;;;;OAMG;IACH,+BAHW,MAAM,gCAQhB;IAED;;;;;;OAMG;IACH,iCAHW,MAAM,6CAahB;CACF;;;;mBAxIY,OAAO,0CAA0C,EAAE,WAAW;cAD9D,OAAO,SAAS,CAAC;iBADjB,OAAO,WAAW,EAAE,SAAS;4BAGvB,MAAM,KAAK,QAAQ,UAAU,GAAG,IAAI,CAAC;cAJ3C,OAAO,KAAK,CAAC"}
@@ -0,0 +1,134 @@
1
+ import * as $protobuf from "protobufjs";
2
+ /** Properties of a FetchRequest. */
3
+ export interface IFetchRequest {
4
+
5
+ /** FetchRequest identifier */
6
+ identifier?: (string|null);
7
+ }
8
+
9
+ /** Represents a FetchRequest. */
10
+ export class FetchRequest implements IFetchRequest {
11
+
12
+ /**
13
+ * Constructs a new FetchRequest.
14
+ * @param [p] Properties to set
15
+ */
16
+ constructor(p?: IFetchRequest);
17
+
18
+ /** FetchRequest identifier. */
19
+ public identifier: string;
20
+
21
+ /**
22
+ * Encodes the specified FetchRequest message. Does not implicitly {@link FetchRequest.verify|verify} messages.
23
+ * @param m FetchRequest message or plain object to encode
24
+ * @param [w] Writer to encode to
25
+ * @returns Writer
26
+ */
27
+ public static encode(m: IFetchRequest, w?: $protobuf.Writer): $protobuf.Writer;
28
+
29
+ /**
30
+ * Decodes a FetchRequest message from the specified reader or buffer.
31
+ * @param r Reader or buffer to decode from
32
+ * @param [l] Message length if known beforehand
33
+ * @returns FetchRequest
34
+ * @throws {Error} If the payload is not a reader or valid buffer
35
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
36
+ */
37
+ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): FetchRequest;
38
+
39
+ /**
40
+ * Creates a FetchRequest message from a plain object. Also converts values to their respective internal types.
41
+ * @param d Plain object
42
+ * @returns FetchRequest
43
+ */
44
+ public static fromObject(d: { [k: string]: any }): FetchRequest;
45
+
46
+ /**
47
+ * Creates a plain object from a FetchRequest message. Also converts values to other types if specified.
48
+ * @param m FetchRequest
49
+ * @param [o] Conversion options
50
+ * @returns Plain object
51
+ */
52
+ public static toObject(m: FetchRequest, o?: $protobuf.IConversionOptions): { [k: string]: any };
53
+
54
+ /**
55
+ * Converts this FetchRequest to JSON.
56
+ * @returns JSON object
57
+ */
58
+ public toJSON(): { [k: string]: any };
59
+ }
60
+
61
+ /** Properties of a FetchResponse. */
62
+ export interface IFetchResponse {
63
+
64
+ /** FetchResponse status */
65
+ status?: (FetchResponse.StatusCode|null);
66
+
67
+ /** FetchResponse data */
68
+ data?: (Uint8Array|null);
69
+ }
70
+
71
+ /** Represents a FetchResponse. */
72
+ export class FetchResponse implements IFetchResponse {
73
+
74
+ /**
75
+ * Constructs a new FetchResponse.
76
+ * @param [p] Properties to set
77
+ */
78
+ constructor(p?: IFetchResponse);
79
+
80
+ /** FetchResponse status. */
81
+ public status: FetchResponse.StatusCode;
82
+
83
+ /** FetchResponse data. */
84
+ public data: Uint8Array;
85
+
86
+ /**
87
+ * Encodes the specified FetchResponse message. Does not implicitly {@link FetchResponse.verify|verify} messages.
88
+ * @param m FetchResponse message or plain object to encode
89
+ * @param [w] Writer to encode to
90
+ * @returns Writer
91
+ */
92
+ public static encode(m: IFetchResponse, w?: $protobuf.Writer): $protobuf.Writer;
93
+
94
+ /**
95
+ * Decodes a FetchResponse message from the specified reader or buffer.
96
+ * @param r Reader or buffer to decode from
97
+ * @param [l] Message length if known beforehand
98
+ * @returns FetchResponse
99
+ * @throws {Error} If the payload is not a reader or valid buffer
100
+ * @throws {$protobuf.util.ProtocolError} If required fields are missing
101
+ */
102
+ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): FetchResponse;
103
+
104
+ /**
105
+ * Creates a FetchResponse message from a plain object. Also converts values to their respective internal types.
106
+ * @param d Plain object
107
+ * @returns FetchResponse
108
+ */
109
+ public static fromObject(d: { [k: string]: any }): FetchResponse;
110
+
111
+ /**
112
+ * Creates a plain object from a FetchResponse message. Also converts values to other types if specified.
113
+ * @param m FetchResponse
114
+ * @param [o] Conversion options
115
+ * @returns Plain object
116
+ */
117
+ public static toObject(m: FetchResponse, o?: $protobuf.IConversionOptions): { [k: string]: any };
118
+
119
+ /**
120
+ * Converts this FetchResponse to JSON.
121
+ * @returns JSON object
122
+ */
123
+ public toJSON(): { [k: string]: any };
124
+ }
125
+
126
+ export namespace FetchResponse {
127
+
128
+ /** StatusCode enum. */
129
+ enum StatusCode {
130
+ OK = 0,
131
+ NOT_FOUND = 1,
132
+ ERROR = 2
133
+ }
134
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/identify/index.js"],"names":[],"mappings":";AAkCA;;;GAGG;AAEH;;;GAGG;AAEH;IACE;;OAEG;IACH,8BAFW,OAAO,KAAK,CAAC;;;MAOvB;IAuSD;;;;;OAKG;IACH,+BAHW,UAAU,GAAG,MAAM,GACjB,SAAS,GAAC,IAAI,CAW1B;IApTD;;;;OAIG;IACH;QAFkC,MAAM,EAA7B,OAAO,KAAK,CAAC;OAuCvB;IApCC,uBAAqB;IACrB,mDAAiC;IACjC,6CAA2C;IAC3C,mDAAiD;IACjD,eAA2B;IA6K7B;;;;;;;;OAQG;IACH;oBALW,UAAU;gBACV,WAAW;kBACX,MAAM;QACJ,QAAQ,IAAI,CAAC,GAAC,SAAS,CAWnC;IA1LC,4BAA0D;IAC1D,gCAAkE;IAGlE;sBAjCU,MAAM;;MAoCf;IAsBH,uBAGC;IAED,sBAEC;IAED;;;;;OAKG;IACH,kBAHW,UAAU,EAAE,GACV,QAAQ,IAAI,EAAE,CAAC,CA4B3B;IAED;;OAEG;IACH,iCAeC;IAED;;;;;;;;OAQG;IACH,qBAHW,UAAU,GACR,QAAQ,IAAI,CAAC,CAmEzB;IAsBD;;;;;;;;;OASG;IACH,wBA6BC;IAED;;;;;;;;OAQG;IACH,oBAsCC;CAkBF;;;;;;;;;;;;mBAxUY,OAAO,0CAA0C,EAAE,WAAW;;kBAK7D,MAAM"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/identify/index.js"],"names":[],"mappings":";AAkCA;;;GAGG;AAEH;;;GAGG;AAEH;IACE;;OAEG;IACH,8BAFW,OAAO,KAAK,CAAC;;;MAOvB;IA2SD;;;;;OAKG;IACH,+BAHW,UAAU,GAAG,MAAM,GACjB,SAAS,GAAC,IAAI,CAW1B;IAxTD;;;;OAIG;IACH;QAFkC,MAAM,EAA7B,OAAO,KAAK,CAAC;OAuCvB;IApCC,uBAAqB;IACrB,mDAAiC;IACjC,6CAA2C;IAC3C,mDAAiD;IACjD,eAA2B;IA6K7B;;;;;;;;OAQG;IACH;oBALW,UAAU;gBACV,WAAW;kBACX,MAAM;QACJ,QAAQ,IAAI,CAAC,GAAC,SAAS,CAWnC;IA1LC,4BAA0D;IAC1D,gCAAkE;IAGlE;sBAjCU,MAAM;;MAoCf;IAsBH,uBAGC;IAED,sBAEC;IAED;;;;;OAKG;IACH,kBAHW,UAAU,EAAE,GACV,QAAQ,IAAI,EAAE,CAAC,CA4B3B;IAED;;OAEG;IACH,iCAeC;IAED;;;;;;;;OAQG;IACH,qBAHW,UAAU,GACR,QAAQ,IAAI,CAAC,CAmEzB;IAsBD;;;;;;;;;OASG;IACH,wBA6BC;IAED;;;;;;;;OAQG;IACH,oBA0CC;CAkBF;;;;;;;;;;;;mBA5UY,OAAO,0CAA0C,EAAE,WAAW;;kBAK7D,MAAM"}
@@ -271,6 +271,7 @@ declare class Libp2p extends EventEmitter {
271
271
  * @param {{ id: PeerId, multiaddrs: Multiaddr[], protocols: string[] }} peer
272
272
  */
273
273
  private _onDiscoveryPeer;
274
+ fetchService: FetchService;
274
275
  /**
275
276
  * Starts the libp2p node and all its subsystems
276
277
  *
@@ -355,6 +356,14 @@ declare class Libp2p extends EventEmitter {
355
356
  * @returns {Promise<void>}
356
357
  */
357
358
  hangUp(peer: PeerId | Multiaddr | string): Promise<void>;
359
+ /**
360
+ * Sends a request to fetch the value associated with the given key from the given peer.
361
+ *
362
+ * @param {PeerId|Multiaddr} peer
363
+ * @param {string} key
364
+ * @returns {Promise<Uint8Array | null>}
365
+ */
366
+ fetch(peer: PeerId | Multiaddr, key: string): Promise<Uint8Array | null>;
358
367
  /**
359
368
  * Pings the given peer in order to obtain the operation latency.
360
369
  *
@@ -468,6 +477,7 @@ import Relay = require("./circuit");
468
477
  import IdentifyService = require("./identify");
469
478
  import PeerRouting = require("./peer-routing");
470
479
  import ContentRouting = require("./content-routing");
480
+ import FetchService = require("./fetch");
471
481
  import { Multiaddr } from "multiaddr";
472
482
  type Connection = import("libp2p-interfaces/src/connection/connection");
473
483
  type CreateOptions = {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.js"],"names":[],"mappings":";AAoCA;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyEG;AACH;IACE;;;;;;OAMG;IACH,uBAHW,aAAa,GAAG,aAAa,GAC3B,QAAQ,MAAM,CAAC,CAa3B;IAED;;;;;OAKG;IACH,sBAFW,aAAa,GAAG,kBAAkB,EA6K5C;IAvKC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAAwC;IAExC,qBAAqB;IACrB,QADW,MAAM,CACiB;IAClC,+DAAwC;IAQtC,6BAAsB;IAGxB,qDAAqD;IACrD,WADW,OAAO,oBAAoB,EAAE,SAAS,CAI/C;IAGF;;;;;6CAAwC;IACxC,+BAA8E;IAS9E,wBAAqC;IACrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAAmC;IACnC,kBAAoB;IACpB,0BAA2B;IAG3B,qCAEE;IACF,0BAIE;IAQA,+BAGE;IAMJ,mBAKE;IAGF,mCAIE;IAGF,uBAME;IAGF,qBAGE;IA2UJ;;;;;OAKG;IACH,kBAHW,MAAM,EAAE,GAAC,MAAM,mBACP,YAAY,KAAK,IAAI,iBAUvC;IA3UC,eAKE;IAWA,yBAA4B;IAW5B,6CAA4D;IAc5D,UAGE;IAOF,qBAAqB;IACrB,+CAA8D;IAKhE,yBAAwC;IACxC,+BAA8C;IAiWhD;;;;;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U,CAAC,CAoE/B;IAED;;;;;;;;;;;;OAYG;IACH,0BAgHC;IAED;;;;;;;;OAQG;IACH,kBAGC;IAED;;;;;;;;;OASG;IACH,wBAqBC;IAED;;;;;;;;;;;OAWG;IACH,yBAqBC;IAED;;;;;;;;;OASG;IACH,2BAYC;IAED;;;;;;;;;OASG;IACH,0BAWC;CACF;;;;;2BA3bY,OAAO,uCAAuC,EAAE,mBAAmB;;oBACnE,OAAO,0CAA0C,EAAE,YAAY;aAC/D,OAAO,0CAA0C,EAAE,KAAK;mBACxD,OAAO,0CAA0C,EAAE,WAAW;cAC9D,OAAO,oCAAoC,EAAE,MAAM;;iBAEnD,OAAO,WAAW,EAAE,SAAS;;;;;UAK5B,mBAAmB;gBACnB,MAAM;cACN,MAAM"}
1
+ {"version":3,"file":"upgrader.d.ts","sourceRoot":"","sources":["../../src/upgrader.js"],"names":[],"mappings":";AAgBA;;;;;;;;GAQG;AAEH;;;;;GAKG;AAEH;IACE;;;;;;;;OAQG;IACH;mBAPW,MAAM;;;;mCAIO,UAAU,KAAK,IAAI;sCACnB,UAAU,KAAK,IAAI;OAmB1C;IATC,kBAA0B;IAC1B,yCAAsB;IACtB,0EAAsB;IACtB,qFAAoB;IACpB,sCAAsC;IACtC,WADW,OAAO,QAAQ,CAAC,GAAG,IAAI,CACb;IACrB,yBAA0B;IAC1B,2BAlBsB,UAAU,KAAK,IAAI,CAkBT;IAChC,8BAlBsB,UAAU,KAAK,IAAI,CAkBH;IAGxC;;;;;;OAMG;IACH,uBAHW,mBAAmB,GACjB,QAAQ,UAAU,CAAC,CA6D/B;IAED;;;;;;OAMG;IACH,wBAHW,mBAAmB,GACjB,QAAQ,UAAU,CAAC,CAoE/B;IAED;;;;;;;;;;;;OAYG;IACH,0BAgHC;IAED;;;;;;;;OAQG;IACH,kBAGC;IAED;;;;;;;;;OASG;IACH,wBAqBC;IAED;;;;;;;;;;;OAWG;IACH,yBAqBC;IAED;;;;;;;;;OASG;IACH,2BAYC;IAED;;;;;;;;;OASG;IACH,0BAWC;CACF;;;;;2BA3bY,OAAO,uCAAuC,EAAE,mBAAmB;;oBACnE,OAAO,0CAA0C,EAAE,YAAY;aAC/D,OAAO,0CAA0C,EAAE,KAAK;mBACxD,OAAO,0CAA0C,EAAE,WAAW;cAC9D,OAAO,oCAAoC,EAAE,MAAM;;iBAEnD,OAAO,WAAW,EAAE,SAAS;;;;;UAK5B,mBAAmB;gBACnB,MAAM;cACN,MAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libp2p",
3
- "version": "0.35.8-bf1fc32",
3
+ "version": "0.35.8-d8ceb0b",
4
4
  "description": "JavaScript implementation of libp2p, a modular peer to peer network stack",
5
5
  "leadMaintainer": "Jacob Heun <jacobheun@gmail.com>",
6
6
  "main": "src/index.js",
@@ -20,15 +20,17 @@
20
20
  "scripts": {
21
21
  "lint": "aegir lint",
22
22
  "build": "aegir build",
23
- "build:proto": "npm run build:proto:circuit && npm run build:proto:identify && npm run build:proto:plaintext && npm run build:proto:address-book && npm run build:proto:proto-book && npm run build:proto:peer && npm run build:proto:peer-record && npm run build:proto:envelope",
23
+ "build:proto": "npm run build:proto:circuit && npm run build:proto:fetch && npm run build:proto:identify && npm run build:proto:plaintext && npm run build:proto:address-book && npm run build:proto:proto-book && npm run build:proto:peer && npm run build:proto:peer-record && npm run build:proto:envelope",
24
24
  "build:proto:circuit": "pbjs -t static-module -w commonjs -r libp2p-circuit --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/circuit/protocol/index.js ./src/circuit/protocol/index.proto",
25
+ "build:proto:fetch": "pbjs -t static-module -w commonjs -r libp2p-fetch --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/fetch/proto.js ./src/fetch/proto.proto",
25
26
  "build:proto:identify": "pbjs -t static-module -w commonjs -r libp2p-identify --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/identify/message.js ./src/identify/message.proto",
26
27
  "build:proto:plaintext": "pbjs -t static-module -w commonjs -r libp2p-plaintext --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/insecure/proto.js ./src/insecure/proto.proto",
27
28
  "build:proto:peer": "pbjs -t static-module -w commonjs -r libp2p-peer --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/peer-store/pb/peer.js ./src/peer-store/pb/peer.proto",
28
29
  "build:proto:peer-record": "pbjs -t static-module -w commonjs -r libp2p-peer-record --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/record/peer-record/peer-record.js ./src/record/peer-record/peer-record.proto",
29
30
  "build:proto:envelope": "pbjs -t static-module -w commonjs -r libp2p-envelope --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/record/envelope/envelope.js ./src/record/envelope/envelope.proto",
30
- "build:proto-types": "npm run build:proto-types:circuit && npm run build:proto-types:identify && npm run build:proto-types:plaintext && npm run build:proto-types:address-book && npm run build:proto-types:proto-book && npm run build:proto-types:peer && npm run build:proto-types:peer-record && npm run build:proto-types:envelope",
31
+ "build:proto-types": "npm run build:proto-types:circuit && npm run build:proto-types:fetch && npm run build:proto-types:identify && npm run build:proto-types:plaintext && npm run build:proto-types:address-book && npm run build:proto-types:proto-book && npm run build:proto-types:peer && npm run build:proto-types:peer-record && npm run build:proto-types:envelope",
31
32
  "build:proto-types:circuit": "pbts -o src/circuit/protocol/index.d.ts src/circuit/protocol/index.js",
33
+ "build:proto-types:fetch": "pbts -o src/fetch/proto.d.ts src/fetch/proto.js",
32
34
  "build:proto-types:identify": "pbts -o src/identify/message.d.ts src/identify/message.js",
33
35
  "build:proto-types:plaintext": "pbts -o src/insecure/proto.d.ts src/insecure/proto.js",
34
36
  "build:proto-types:peer": "pbts -o src/peer-store/pb/peer.d.ts src/peer-store/pb/peer.js",
@@ -99,7 +101,7 @@
99
101
  "it-merge": "^1.0.0",
100
102
  "it-pipe": "^1.1.0",
101
103
  "it-take": "^1.0.0",
102
- "libp2p-crypto": "^0.21.1",
104
+ "libp2p-crypto": "^0.21.2",
103
105
  "libp2p-interfaces": "^4.0.0",
104
106
  "libp2p-utils": "^0.4.0",
105
107
  "mafmt": "^10.0.0",
@@ -107,10 +109,10 @@
107
109
  "mortice": "^2.0.1",
108
110
  "multiaddr": "^10.0.0",
109
111
  "multiformats": "^9.0.0",
110
- "multistream-select": "^2.0.0",
112
+ "multistream-select": "^3.0.0",
111
113
  "mutable-proxy": "^1.0.0",
112
114
  "nat-api": "^0.3.1",
113
- "node-forge": "^0.10.0",
115
+ "node-forge": "^1.2.1",
114
116
  "p-any": "^3.0.0",
115
117
  "p-fifo": "^1.0.0",
116
118
  "p-retry": "^4.4.0",
@@ -133,7 +135,7 @@
133
135
  "@nodeutils/defaults-deep": "^1.1.0",
134
136
  "@types/es6-promisify": "^6.0.0",
135
137
  "@types/node": "^16.0.1",
136
- "@types/node-forge": "^0.10.1",
138
+ "@types/node-forge": "^1.0.0",
137
139
  "@types/varint": "^6.0.0",
138
140
  "aegir": "^36.0.0",
139
141
  "buffer": "^6.0.3",
@@ -8,6 +8,7 @@ const log = Object.assign(debug('libp2p:auto-relay'), {
8
8
  const { fromString: uint8ArrayFromString } = require('uint8arrays/from-string')
9
9
  const { toString: uint8ArrayToString } = require('uint8arrays/to-string')
10
10
  const { Multiaddr } = require('multiaddr')
11
+ const all = require('it-all')
11
12
 
12
13
  const { relay: multicodec } = require('./multicodec')
13
14
  const { canHop } = require('./circuit/hop')
@@ -149,27 +150,35 @@ class AutoRelay {
149
150
  * @returns {Promise<void>}
150
151
  */
151
152
  async _addListenRelay (connection, id) {
152
- // Check if already listening on enough relays
153
- if (this._listenRelays.size >= this.maxListeners) {
154
- return
155
- }
156
-
157
- // Get peer known addresses and sort them per public addresses first
158
- const remoteAddrs = await this._peerStore.addressBook.getMultiaddrsForPeer(
159
- connection.remotePeer, this._addressSorter
160
- )
161
-
162
- if (!remoteAddrs || !remoteAddrs.length) {
163
- return
164
- }
165
-
166
- const listenAddr = `${remoteAddrs[0].toString()}/p2p-circuit`
167
- this._listenRelays.add(id)
168
-
169
- // Attempt to listen on relay
170
153
  try {
171
- await this._transportManager.listen([new Multiaddr(listenAddr)])
172
- // Announce multiaddrs will update on listen success by TransportManager event being triggered
154
+ // Check if already listening on enough relays
155
+ if (this._listenRelays.size >= this.maxListeners) {
156
+ return
157
+ }
158
+
159
+ // Get peer known addresses and sort them per public addresses first
160
+ const remoteAddrs = await this._peerStore.addressBook.getMultiaddrsForPeer(
161
+ connection.remotePeer, this._addressSorter
162
+ )
163
+
164
+ // Attempt to listen on relay
165
+ const result = await Promise.all(
166
+ remoteAddrs.map(async addr => {
167
+ try {
168
+ // Announce multiaddrs will update on listen success by TransportManager event being triggered
169
+ await this._transportManager.listen([new Multiaddr(`${addr.toString()}/p2p-circuit`)])
170
+ return true
171
+ } catch (/** @type {any} */ err) {
172
+ this._onError(err)
173
+ }
174
+
175
+ return false
176
+ })
177
+ )
178
+
179
+ if (result.includes(true)) {
180
+ this._listenRelays.add(id)
181
+ }
173
182
  } catch (/** @type {any} */ err) {
174
183
  this._onError(err)
175
184
  this._listenRelays.delete(id)
@@ -206,13 +215,18 @@ class AutoRelay {
206
215
  }
207
216
 
208
217
  const knownHopsToDial = []
218
+ const peers = await all(this._peerStore.getPeers())
209
219
 
210
220
  // Check if we have known hop peers to use and attempt to listen on the already connected
211
- for await (const { id, metadata } of this._peerStore.getPeers()) {
221
+ for await (const { id, metadata } of peers) {
212
222
  const idStr = id.toB58String()
213
223
 
214
224
  // Continue to next if listening on this or peer to ignore
215
- if (this._listenRelays.has(idStr) || peersToIgnore.includes(idStr)) {
225
+ if (this._listenRelays.has(idStr)) {
226
+ continue
227
+ }
228
+
229
+ if (peersToIgnore.includes(idStr)) {
216
230
  continue
217
231
  }
218
232
 
@@ -112,6 +112,9 @@ class ConnectionManager extends EventEmitter {
112
112
  latencyCheckIntervalMs: this._options.pollInterval,
113
113
  dataEmitIntervalMs: this._options.pollInterval
114
114
  })
115
+
116
+ // This emitter gets listened to a lot
117
+ this.setMaxListeners(Infinity)
115
118
  }
116
119
 
117
120
  /**
@@ -0,0 +1,36 @@
1
+ libp2p-fetch JavaScript Implementation
2
+ =====================================
3
+
4
+ > Libp2p fetch protocol JavaScript implementation
5
+
6
+ ## Overview
7
+
8
+ An implementation of the Fetch protocol as described here: https://github.com/libp2p/specs/tree/master/fetch
9
+
10
+ The fetch protocol is a simple protocol for requesting a value corresponding to a key from a peer.
11
+
12
+ ## Usage
13
+
14
+ ```javascript
15
+ const Libp2p = require('libp2p')
16
+
17
+ /**
18
+ * Given a key (as a string) returns a value (as a Uint8Array), or null if the key isn't found.
19
+ * All keys must be prefixed my the same prefix, which will be used to find the appropriate key
20
+ * lookup function.
21
+ * @param key - a string
22
+ * @returns value - a Uint8Array value that corresponds to the given key, or null if the key doesn't
23
+ * have a corresponding value.
24
+ */
25
+ async function my_subsystem_key_lookup(key) {
26
+ // app specific callback to lookup key-value pairs.
27
+ }
28
+
29
+ // Enable this peer to respond to fetch requests for keys that begin with '/my_subsystem_key_prefix/'
30
+ const libp2p = Libp2p.create(...)
31
+ libp2p.fetchService.registerLookupFunction('/my_subsystem_key_prefix/', my_subsystem_key_lookup)
32
+
33
+ const key = '/my_subsystem_key_prefix/{...}'
34
+ const peerDst = PeerId.parse('Qmfoo...') // or Multiaddr instance
35
+ const value = await libp2p.fetch(peerDst, key)
36
+ ```
@@ -0,0 +1,6 @@
1
+ 'use strict'
2
+
3
+ module.exports = {
4
+ // https://github.com/libp2p/specs/tree/master/fetch#wire-protocol
5
+ PROTOCOL: '/libp2p/fetch/0.0.1'
6
+ }
@@ -0,0 +1,159 @@
1
+ 'use strict'
2
+
3
+ const debug = require('debug')
4
+ const log = Object.assign(debug('libp2p:fetch'), {
5
+ error: debug('libp2p:fetch:err')
6
+ })
7
+ const errCode = require('err-code')
8
+ const { codes } = require('../errors')
9
+ const lp = require('it-length-prefixed')
10
+ const { FetchRequest, FetchResponse } = require('./proto')
11
+ // @ts-ignore it-handshake does not export types
12
+ const handshake = require('it-handshake')
13
+ const { PROTOCOL } = require('./constants')
14
+
15
+ /**
16
+ * @typedef {import('../')} Libp2p
17
+ * @typedef {import('multiaddr').Multiaddr} Multiaddr
18
+ * @typedef {import('peer-id')} PeerId
19
+ * @typedef {import('libp2p-interfaces/src/stream-muxer/types').MuxedStream} MuxedStream
20
+ * @typedef {(key: string) => Promise<Uint8Array | null>} LookupFunction
21
+ */
22
+
23
+ /**
24
+ * A simple libp2p protocol for requesting a value corresponding to a key from a peer.
25
+ * Developers can register one or more lookup function for retrieving the value corresponding to
26
+ * a given key. Each lookup function must act on a distinct part of the overall key space, defined
27
+ * by a fixed prefix that all keys that should be routed to that lookup function will start with.
28
+ */
29
+ class FetchProtocol {
30
+ /**
31
+ * @param {Libp2p} libp2p
32
+ */
33
+ constructor (libp2p) {
34
+ this._lookupFunctions = new Map() // Maps key prefix to value lookup function
35
+ this._libp2p = libp2p
36
+ this.handleMessage = this.handleMessage.bind(this)
37
+ }
38
+
39
+ /**
40
+ * Sends a request to fetch the value associated with the given key from the given peer.
41
+ *
42
+ * @param {PeerId|Multiaddr} peer
43
+ * @param {string} key
44
+ * @returns {Promise<Uint8Array | null>}
45
+ */
46
+ async fetch (peer, key) {
47
+ // @ts-ignore multiaddr might not have toB58String
48
+ log('dialing %s to %s', this._protocol, peer.toB58String ? peer.toB58String() : peer)
49
+
50
+ const connection = await this._libp2p.dial(peer)
51
+ const { stream } = await connection.newStream(FetchProtocol.PROTOCOL)
52
+ const shake = handshake(stream)
53
+
54
+ // send message
55
+ const request = new FetchRequest({ identifier: key })
56
+ shake.write(lp.encode.single(FetchRequest.encode(request).finish()))
57
+
58
+ // read response
59
+ const response = FetchResponse.decode((await lp.decode.fromReader(shake.reader).next()).value.slice())
60
+ switch (response.status) {
61
+ case (FetchResponse.StatusCode.OK): {
62
+ return response.data
63
+ }
64
+ case (FetchResponse.StatusCode.NOT_FOUND): {
65
+ return null
66
+ }
67
+ case (FetchResponse.StatusCode.ERROR): {
68
+ const errmsg = (new TextDecoder()).decode(response.data)
69
+ throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS)
70
+ }
71
+ default: {
72
+ throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE)
73
+ }
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Invoked when a fetch request is received. Reads the request message off the given stream and
79
+ * responds based on looking up the key in the request via the lookup callback that corresponds
80
+ * to the key's prefix.
81
+ *
82
+ * @param {object} options
83
+ * @param {MuxedStream} options.stream
84
+ * @param {string} options.protocol
85
+ */
86
+ async handleMessage (options) {
87
+ const { stream } = options
88
+ const shake = handshake(stream)
89
+ const request = FetchRequest.decode((await lp.decode.fromReader(shake.reader).next()).value.slice())
90
+
91
+ let response
92
+ const lookup = this._getLookupFunction(request.identifier)
93
+ if (lookup) {
94
+ const data = await lookup(request.identifier)
95
+ if (data) {
96
+ response = new FetchResponse({ status: FetchResponse.StatusCode.OK, data })
97
+ } else {
98
+ response = new FetchResponse({ status: FetchResponse.StatusCode.NOT_FOUND })
99
+ }
100
+ } else {
101
+ const errmsg = (new TextEncoder()).encode('No lookup function registered for key: ' + request.identifier)
102
+ response = new FetchResponse({ status: FetchResponse.StatusCode.ERROR, data: errmsg })
103
+ }
104
+
105
+ shake.write(lp.encode.single(FetchResponse.encode(response).finish()))
106
+ }
107
+
108
+ /**
109
+ * Given a key, finds the appropriate function for looking up its corresponding value, based on
110
+ * the key's prefix.
111
+ *
112
+ * @param {string} key
113
+ */
114
+ _getLookupFunction (key) {
115
+ for (const prefix of this._lookupFunctions.keys()) {
116
+ if (key.startsWith(prefix)) {
117
+ return this._lookupFunctions.get(prefix)
118
+ }
119
+ }
120
+ return null
121
+ }
122
+
123
+ /**
124
+ * Registers a new lookup callback that can map keys to values, for a given set of keys that
125
+ * share the same prefix.
126
+ *
127
+ * @param {string} prefix
128
+ * @param {LookupFunction} lookup
129
+ */
130
+ registerLookupFunction (prefix, lookup) {
131
+ if (this._lookupFunctions.has(prefix)) {
132
+ throw errCode(new Error("Fetch protocol handler for key prefix '" + prefix + "' already registered"), codes.ERR_KEY_ALREADY_EXISTS)
133
+ }
134
+ this._lookupFunctions.set(prefix, lookup)
135
+ }
136
+
137
+ /**
138
+ * Registers a new lookup callback that can map keys to values, for a given set of keys that
139
+ * share the same prefix.
140
+ *
141
+ * @param {string} prefix
142
+ * @param {LookupFunction} [lookup]
143
+ */
144
+ unregisterLookupFunction (prefix, lookup) {
145
+ if (lookup != null) {
146
+ const existingLookup = this._lookupFunctions.get(prefix)
147
+
148
+ if (existingLookup !== lookup) {
149
+ return
150
+ }
151
+ }
152
+
153
+ this._lookupFunctions.delete(prefix)
154
+ }
155
+ }
156
+
157
+ FetchProtocol.PROTOCOL = PROTOCOL
158
+
159
+ exports = module.exports = FetchProtocol