peerbit 1.0.1
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/LICENSE +202 -0
- package/lib/esm/index.d.ts +2 -0
- package/lib/esm/index.js +3 -0
- package/lib/esm/index.js.map +1 -0
- package/lib/esm/libp2p.d.ts +20 -0
- package/lib/esm/libp2p.js +50 -0
- package/lib/esm/libp2p.js.map +1 -0
- package/lib/esm/package.json +3 -0
- package/lib/esm/peer.d.ts +65 -0
- package/lib/esm/peer.js +284 -0
- package/lib/esm/peer.js.map +1 -0
- package/lib/esm/transports-browser.d.ts +2 -0
- package/lib/esm/transports-browser.js +13 -0
- package/lib/esm/transports-browser.js.map +1 -0
- package/lib/esm/transports.d.ts +2 -0
- package/lib/esm/transports.js +12 -0
- package/lib/esm/transports.js.map +1 -0
- package/package.json +68 -0
- package/src/index.ts +8 -0
- package/src/libp2p.ts +73 -0
- package/src/peer.ts +401 -0
- package/src/transports-browser.ts +14 -0
- package/src/transports.ts +12 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2022 dao.xyz
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/lib/esm/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,OAAO,EACN,oBAAoB,GAKpB,MAAM,aAAa,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Libp2p, Libp2pOptions, ServiceFactoryMap } from "libp2p";
|
|
2
|
+
import { DirectSub } from "@peerbit/pubsub";
|
|
3
|
+
import { DirectBlock } from "@peerbit/blocks";
|
|
4
|
+
import { CircuitRelayService } from "libp2p/dist/src/circuit-relay/index.js";
|
|
5
|
+
export type Libp2pExtendServices = {
|
|
6
|
+
pubsub: DirectSub;
|
|
7
|
+
blocks: DirectBlock;
|
|
8
|
+
};
|
|
9
|
+
export type Libp2pExtended = Libp2p<{
|
|
10
|
+
relay: CircuitRelayService;
|
|
11
|
+
identify: any;
|
|
12
|
+
} & Libp2pExtendServices>;
|
|
13
|
+
export type Libp2pCreateOptions = Libp2pOptions<Libp2pExtendServices & {
|
|
14
|
+
relay: CircuitRelayService;
|
|
15
|
+
identify: any;
|
|
16
|
+
}>;
|
|
17
|
+
export type Libp2pCreateOptionsWithServices = Libp2pCreateOptions & {
|
|
18
|
+
services: ServiceFactoryMap<Libp2pExtendServices>;
|
|
19
|
+
};
|
|
20
|
+
export declare const createLibp2pExtended: (opts?: Libp2pCreateOptions) => Promise<Libp2pExtended>;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createLibp2p } from "libp2p";
|
|
2
|
+
import { DirectSub } from "@peerbit/pubsub";
|
|
3
|
+
import { DirectBlock } from "@peerbit/blocks";
|
|
4
|
+
import { noise } from "@dao-xyz/libp2p-noise";
|
|
5
|
+
import { mplex } from "@libp2p/mplex";
|
|
6
|
+
import { transports, relay } from "./transports.js";
|
|
7
|
+
import { identifyService } from "libp2p/identify";
|
|
8
|
+
export const createLibp2pExtended = (opts = {
|
|
9
|
+
services: {
|
|
10
|
+
blocks: (c) => new DirectBlock(c),
|
|
11
|
+
pubsub: (c) => new DirectSub(c),
|
|
12
|
+
},
|
|
13
|
+
}) => {
|
|
14
|
+
const relayIdentify = {
|
|
15
|
+
relay: relay(),
|
|
16
|
+
identify: identifyService(),
|
|
17
|
+
};
|
|
18
|
+
// https://github.com/libp2p/js-libp2p/issues/1757
|
|
19
|
+
Object.keys(relayIdentify).forEach((key) => {
|
|
20
|
+
if (relayIdentify[key] === undefined) {
|
|
21
|
+
delete relayIdentify[key];
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
return createLibp2p({
|
|
25
|
+
connectionManager: {
|
|
26
|
+
minConnections: 0,
|
|
27
|
+
},
|
|
28
|
+
addresses: {
|
|
29
|
+
listen: ["/ip4/127.0.0.1/tcp/0", "/ip4/127.0.0.1/tcp/0/ws"],
|
|
30
|
+
},
|
|
31
|
+
transports: transports(),
|
|
32
|
+
connectionEncryption: [noise()],
|
|
33
|
+
streamMuxers: [mplex()],
|
|
34
|
+
...opts,
|
|
35
|
+
services: {
|
|
36
|
+
...relayIdentify,
|
|
37
|
+
pubsub: opts.services?.pubsub ||
|
|
38
|
+
((c) => new DirectSub(c, {
|
|
39
|
+
canRelayMessage: true,
|
|
40
|
+
signaturePolicy: "StrictNoSign",
|
|
41
|
+
connectionManager: {
|
|
42
|
+
autoDial: true,
|
|
43
|
+
},
|
|
44
|
+
})),
|
|
45
|
+
blocks: opts.services?.blocks || ((c) => new DirectBlock(c)),
|
|
46
|
+
...opts.services,
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
};
|
|
50
|
+
//# sourceMappingURL=libp2p.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"libp2p.js","sourceRoot":"","sources":["../../src/libp2p.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA4C,MAAM,QAAQ,CAAC;AAChF,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAmBlD,M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AW,CAAC,CAAC,CAAC,CAAC;YAC5D,GAAG,IAAI,CAAC,QAAQ;SAChB;KACD,CAAC,CAAC;AACJ,CAAC,CAAC"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import LazyLevel from "@peerbit/lazy-level";
|
|
2
|
+
import { Multiaddr } from "@multiformats/multiaddr";
|
|
3
|
+
import { Ed25519Keypair, Libp2pKeychain } from "@peerbit/crypto";
|
|
4
|
+
import { Program, Address, ProgramInitializationOptions, ProgramClient } from "@peerbit/program";
|
|
5
|
+
import "@libp2p/peer-id";
|
|
6
|
+
import { Libp2pExtended, Libp2pCreateOptions as ClientCreateOptions } from "./libp2p.js";
|
|
7
|
+
export declare const logger: import("pino").Logger<import("pino").LoggerOptions | import("pino").DestinationStream>;
|
|
8
|
+
export type OptionalCreateOptions = {
|
|
9
|
+
limitSigning?: boolean;
|
|
10
|
+
minReplicas?: number;
|
|
11
|
+
refreshIntreval?: number;
|
|
12
|
+
libp2pExternal?: boolean;
|
|
13
|
+
};
|
|
14
|
+
export type CreateOptions = {
|
|
15
|
+
directory?: string;
|
|
16
|
+
cache: LazyLevel;
|
|
17
|
+
identity: Ed25519Keypair;
|
|
18
|
+
keychain: Libp2pKeychain;
|
|
19
|
+
} & OptionalCreateOptions;
|
|
20
|
+
export type CreateInstanceOptions = {
|
|
21
|
+
libp2p?: Libp2pExtended | ClientCreateOptions;
|
|
22
|
+
directory?: string;
|
|
23
|
+
cache?: LazyLevel;
|
|
24
|
+
} & OptionalCreateOptions;
|
|
25
|
+
export type OpenOptions<Args> = {
|
|
26
|
+
timeout?: number;
|
|
27
|
+
} & ProgramInitializationOptions<Args>;
|
|
28
|
+
export declare class Peerbit implements ProgramClient {
|
|
29
|
+
_libp2p: Libp2pExtended;
|
|
30
|
+
directory?: string;
|
|
31
|
+
programs: Map<string, Program>;
|
|
32
|
+
limitSigning: boolean;
|
|
33
|
+
private _cache;
|
|
34
|
+
private _libp2pExternal?;
|
|
35
|
+
private _identity;
|
|
36
|
+
private _keychain;
|
|
37
|
+
constructor(libp2p: Libp2pExtended, options: CreateOptions);
|
|
38
|
+
static create(options?: CreateInstanceOptions): Promise<Peerbit>;
|
|
39
|
+
get libp2p(): Libp2pExtended;
|
|
40
|
+
get identity(): Ed25519Keypair;
|
|
41
|
+
get peerId(): import("@libp2p/interface-peer-id").PeerId;
|
|
42
|
+
get services(): {
|
|
43
|
+
relay: import("libp2p/dist/src/circuit-relay/index.js").CircuitRelayService;
|
|
44
|
+
identify: any;
|
|
45
|
+
} & import("./libp2p.js").Libp2pExtendServices;
|
|
46
|
+
get keychain(): Libp2pKeychain;
|
|
47
|
+
getMultiaddrs(): Multiaddr[];
|
|
48
|
+
/**
|
|
49
|
+
* Dial a peer with an Ed25519 peerId
|
|
50
|
+
*/
|
|
51
|
+
dial(address: string | Multiaddr | Multiaddr[] | ProgramClient): Promise<boolean>;
|
|
52
|
+
start(): Promise<void>;
|
|
53
|
+
stop(): Promise<void>;
|
|
54
|
+
private _onProgamClose;
|
|
55
|
+
private _onProgramOpen;
|
|
56
|
+
/**
|
|
57
|
+
* Default behaviour of a store is only to accept heads that are forks (new roots) with some probability
|
|
58
|
+
* and to replicate heads (and updates) which is requested by another peer
|
|
59
|
+
* @param store
|
|
60
|
+
* @param options
|
|
61
|
+
* @returns
|
|
62
|
+
*/
|
|
63
|
+
open<S extends Program<Args>, Args = any>(storeOrAddress: S | Address | string, options?: OpenOptions<Args>): Promise<S>;
|
|
64
|
+
get memory(): LazyLevel;
|
|
65
|
+
}
|
package/lib/esm/peer.js
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import LazyLevel from "@peerbit/lazy-level";
|
|
2
|
+
import { Level } from "level";
|
|
3
|
+
import { MemoryLevel } from "memory-level";
|
|
4
|
+
import { multiaddr, isMultiaddr } from "@multiformats/multiaddr";
|
|
5
|
+
import { Ed25519Keypair, Ed25519PublicKey, Libp2pKeychain, } from "@peerbit/crypto";
|
|
6
|
+
import { Program, } from "@peerbit/program";
|
|
7
|
+
import { logger as loggerFn } from "@peerbit/logger";
|
|
8
|
+
import { DirectSub } from "@peerbit/pubsub";
|
|
9
|
+
import sodium from "libsodium-wrappers";
|
|
10
|
+
import path from "path-browserify";
|
|
11
|
+
import { waitFor } from "@peerbit/time";
|
|
12
|
+
import "@libp2p/peer-id";
|
|
13
|
+
import { createLibp2pExtended, } from "./libp2p.js";
|
|
14
|
+
import { DirectBlock } from "@peerbit/blocks";
|
|
15
|
+
import { LevelDatastore } from "datastore-level";
|
|
16
|
+
import { BinaryWriter } from "@dao-xyz/borsh";
|
|
17
|
+
export const logger = loggerFn({ module: "client" });
|
|
18
|
+
const isLibp2pInstance = (libp2p) => !!libp2p.getMultiaddrs;
|
|
19
|
+
const createLevel = (path) => {
|
|
20
|
+
return path
|
|
21
|
+
? new Level(path, { valueEncoding: "view" })
|
|
22
|
+
: new MemoryLevel({ valueEncoding: "view" });
|
|
23
|
+
};
|
|
24
|
+
const createCache = async (directory, options) => {
|
|
25
|
+
const cache = await new LazyLevel(createLevel(directory));
|
|
26
|
+
// "Wake up" the caches if they need it
|
|
27
|
+
if (cache)
|
|
28
|
+
await cache.open();
|
|
29
|
+
if (options?.reset) {
|
|
30
|
+
await cache["_store"].clear();
|
|
31
|
+
}
|
|
32
|
+
return cache;
|
|
33
|
+
};
|
|
34
|
+
export class Peerbit {
|
|
35
|
+
_libp2p;
|
|
36
|
+
directory;
|
|
37
|
+
/// program address => Program metadata
|
|
38
|
+
programs;
|
|
39
|
+
limitSigning;
|
|
40
|
+
_cache;
|
|
41
|
+
_libp2pExternal = false;
|
|
42
|
+
// Libp2p peerid in Identity form
|
|
43
|
+
_identity;
|
|
44
|
+
_keychain; // Keychain + Caching + X25519 keys
|
|
45
|
+
constructor(libp2p, options) {
|
|
46
|
+
if (libp2p == null) {
|
|
47
|
+
throw new Error("Libp2p required");
|
|
48
|
+
}
|
|
49
|
+
this._libp2p = libp2p;
|
|
50
|
+
if (this.libp2p.peerId.type !== "Ed25519") {
|
|
51
|
+
throw new Error("Unsupported id type, expecting Ed25519 but got " +
|
|
52
|
+
this.libp2p.peerId.type);
|
|
53
|
+
}
|
|
54
|
+
if (this.libp2p.peerId.type !== "Ed25519") {
|
|
55
|
+
throw new Error("Only Ed25519 peerIds are supported");
|
|
56
|
+
}
|
|
57
|
+
this._identity = options.identity;
|
|
58
|
+
this._keychain = options.keychain;
|
|
59
|
+
this.directory = options.directory;
|
|
60
|
+
this.programs = new Map();
|
|
61
|
+
this.limitSigning = options.limitSigning || false;
|
|
62
|
+
this._cache = options.cache;
|
|
63
|
+
this._libp2pExternal = options.libp2pExternal;
|
|
64
|
+
}
|
|
65
|
+
static async create(options = {}) {
|
|
66
|
+
await sodium.ready; // Some of the modules depends on sodium to be readyy
|
|
67
|
+
let libp2pExtended = options.libp2p;
|
|
68
|
+
const blocksDirectory = options.directory != null
|
|
69
|
+
? path.join(options.directory, "/blocks").toString()
|
|
70
|
+
: undefined;
|
|
71
|
+
let libp2pExternal = false;
|
|
72
|
+
const datastore = options.directory != null
|
|
73
|
+
? new LevelDatastore(path.join(options.directory, "/libp2p").toString())
|
|
74
|
+
: undefined;
|
|
75
|
+
if (datastore) {
|
|
76
|
+
await datastore.open();
|
|
77
|
+
}
|
|
78
|
+
if (!libp2pExtended) {
|
|
79
|
+
libp2pExtended = await createLibp2pExtended({
|
|
80
|
+
services: {
|
|
81
|
+
blocks: (c) => new DirectBlock(c, { directory: blocksDirectory }),
|
|
82
|
+
pubsub: (c) => new DirectSub(c),
|
|
83
|
+
},
|
|
84
|
+
// If directory is passed, we store keys within that directory, else we will use memory datastore (which is the default behaviour)
|
|
85
|
+
datastore,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
if (isLibp2pInstance(libp2pExtended)) {
|
|
90
|
+
libp2pExternal = true; // libp2p was created outside
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
const extendedOptions = libp2pExtended;
|
|
94
|
+
libp2pExtended = await createLibp2pExtended({
|
|
95
|
+
...extendedOptions,
|
|
96
|
+
services: {
|
|
97
|
+
blocks: (c) => new DirectBlock(c, { directory: blocksDirectory }),
|
|
98
|
+
pubsub: (c) => new DirectSub(c),
|
|
99
|
+
...extendedOptions?.services,
|
|
100
|
+
},
|
|
101
|
+
datastore,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (datastore) {
|
|
106
|
+
const stopFn = libp2pExtended.stop.bind(libp2pExtended);
|
|
107
|
+
libp2pExtended.stop = async () => {
|
|
108
|
+
await stopFn();
|
|
109
|
+
await datastore?.close();
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
if (!libp2pExtended.isStarted()) {
|
|
113
|
+
await libp2pExtended.start();
|
|
114
|
+
}
|
|
115
|
+
if (libp2pExtended.peerId.type !== "Ed25519") {
|
|
116
|
+
throw new Error("Unsupported id type, expecting Ed25519 but got " +
|
|
117
|
+
libp2pExtended.peerId.type);
|
|
118
|
+
}
|
|
119
|
+
const directory = options.directory;
|
|
120
|
+
const cache = options.cache ||
|
|
121
|
+
(await createCache(directory ? path.join(directory, "/cache") : undefined));
|
|
122
|
+
const identity = Ed25519Keypair.fromPeerId(libp2pExtended.peerId);
|
|
123
|
+
const keychain = new Libp2pKeychain(libp2pExtended.keychain);
|
|
124
|
+
// Import identity into keychain
|
|
125
|
+
try {
|
|
126
|
+
const writer = new BinaryWriter();
|
|
127
|
+
writer.string("identity");
|
|
128
|
+
await keychain.import(identity, writer.finalize());
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error.code == "ERR_KEY_ALREADY_EXISTS") {
|
|
132
|
+
// Do nothing
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const peer = new Peerbit(libp2pExtended, {
|
|
139
|
+
directory,
|
|
140
|
+
cache,
|
|
141
|
+
libp2pExternal,
|
|
142
|
+
limitSigning: options.limitSigning,
|
|
143
|
+
minReplicas: options.minReplicas,
|
|
144
|
+
refreshIntreval: options.refreshIntreval,
|
|
145
|
+
identity,
|
|
146
|
+
keychain,
|
|
147
|
+
});
|
|
148
|
+
return peer;
|
|
149
|
+
}
|
|
150
|
+
get libp2p() {
|
|
151
|
+
return this._libp2p;
|
|
152
|
+
}
|
|
153
|
+
get identity() {
|
|
154
|
+
return this._identity;
|
|
155
|
+
}
|
|
156
|
+
get peerId() {
|
|
157
|
+
return this.libp2p.peerId;
|
|
158
|
+
}
|
|
159
|
+
get services() {
|
|
160
|
+
return this.libp2p.services;
|
|
161
|
+
}
|
|
162
|
+
get keychain() {
|
|
163
|
+
return this._keychain;
|
|
164
|
+
}
|
|
165
|
+
getMultiaddrs() {
|
|
166
|
+
return this.libp2p.getMultiaddrs();
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Dial a peer with an Ed25519 peerId
|
|
170
|
+
*/
|
|
171
|
+
async dial(address) {
|
|
172
|
+
const maddress = typeof address == "string"
|
|
173
|
+
? multiaddr(address)
|
|
174
|
+
: isMultiaddr(address) || Array.isArray(address)
|
|
175
|
+
? address
|
|
176
|
+
: address.getMultiaddrs();
|
|
177
|
+
const connection = await this.libp2p.dial(maddress);
|
|
178
|
+
const publicKey = Ed25519PublicKey.fromPeerId(connection.remotePeer);
|
|
179
|
+
// TODO, do this as a promise instead using the onPeerConnected vents in pubsub and blocks
|
|
180
|
+
return ((await waitFor(() => this.libp2p.services.pubsub.peers.has(publicKey.hashcode()) &&
|
|
181
|
+
this.libp2p.services.blocks.peers.has(publicKey.hashcode()))) || false);
|
|
182
|
+
}
|
|
183
|
+
async start() {
|
|
184
|
+
if (!this.libp2p.isStarted()) {
|
|
185
|
+
this._libp2pExternal = false; // this means we will also close libp2p client on close
|
|
186
|
+
return this.libp2p.start();
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
async stop() {
|
|
190
|
+
// Close a direct connection and remove it from internal state
|
|
191
|
+
// Close all open databases
|
|
192
|
+
await Promise.all([...this.programs.values()].map((program) => program.close()));
|
|
193
|
+
await this._cache.close();
|
|
194
|
+
// Close libp2p (after above)
|
|
195
|
+
if (!this._libp2pExternal) {
|
|
196
|
+
// only close it if we created it
|
|
197
|
+
await this.libp2p.stop();
|
|
198
|
+
}
|
|
199
|
+
// Remove all databases from the state
|
|
200
|
+
this.programs = new Map();
|
|
201
|
+
}
|
|
202
|
+
_onProgamClose(program) {
|
|
203
|
+
this.programs.delete(program.address.toString());
|
|
204
|
+
}
|
|
205
|
+
_onProgramOpen(program) {
|
|
206
|
+
const programAddress = program.address?.toString();
|
|
207
|
+
if (!programAddress) {
|
|
208
|
+
throw new Error("Missing program address");
|
|
209
|
+
}
|
|
210
|
+
if (this.programs.has(programAddress)) {
|
|
211
|
+
// second condition only makes this throw error if we are to add a new instance with the same address
|
|
212
|
+
throw new Error(`Program at ${programAddress} is already open`);
|
|
213
|
+
}
|
|
214
|
+
this.programs.set(programAddress, program);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Default behaviour of a store is only to accept heads that are forks (new roots) with some probability
|
|
218
|
+
* and to replicate heads (and updates) which is requested by another peer
|
|
219
|
+
* @param store
|
|
220
|
+
* @param options
|
|
221
|
+
* @returns
|
|
222
|
+
*/
|
|
223
|
+
async open(storeOrAddress, options = {}) {
|
|
224
|
+
if (!this.libp2p.isStarted()) {
|
|
225
|
+
throw new Error("Can not open a store while disconnected");
|
|
226
|
+
}
|
|
227
|
+
// TODO add locks for store lifecycle, e.g. what happens if we try to open and close a store at the same time?
|
|
228
|
+
let program = storeOrAddress;
|
|
229
|
+
if (typeof storeOrAddress === "string") {
|
|
230
|
+
try {
|
|
231
|
+
if (this.programs?.has(storeOrAddress.toString())) {
|
|
232
|
+
throw new Error(`Program at ${storeOrAddress.toString()} is already open`);
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
program = (await Program.load(storeOrAddress, this._libp2p.services.blocks, options)); // TODO fix typings
|
|
236
|
+
if (program instanceof Program === false) {
|
|
237
|
+
throw new Error(`Failed to open program because program is of type ${program?.constructor.name} and not ${Program.name}`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
logger.error("Failed to load store with address: " + storeOrAddress.toString());
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
else if (!program.closed) {
|
|
247
|
+
const existing = this.programs.get(program.address);
|
|
248
|
+
if (existing === program) {
|
|
249
|
+
return program;
|
|
250
|
+
}
|
|
251
|
+
else if (existing) {
|
|
252
|
+
throw new Error(`Program at ${program.address} is already open, but is another instance`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
logger.debug(`Open database '${program.constructor.name}`);
|
|
256
|
+
await program.beforeOpen(this, {
|
|
257
|
+
onOpen: (p) => {
|
|
258
|
+
if (p instanceof Program && p.parents.length === 1 && !p.parents[0]) {
|
|
259
|
+
return this._onProgramOpen(p);
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
onClose: (p) => {
|
|
263
|
+
if (p instanceof Program) {
|
|
264
|
+
return this._onProgamClose(p);
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
onDrop: (p) => {
|
|
268
|
+
if (p instanceof Program) {
|
|
269
|
+
return this._onProgamClose(p);
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
...options,
|
|
273
|
+
// If the program opens more programs
|
|
274
|
+
// reset: options.reset,
|
|
275
|
+
});
|
|
276
|
+
await program.open(options.args);
|
|
277
|
+
await program.afterOpen();
|
|
278
|
+
return program;
|
|
279
|
+
}
|
|
280
|
+
get memory() {
|
|
281
|
+
return this._cache;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
//# sourceMappingURL=peer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"peer.js","sourceRoot":"","sources":["../../src/peer.ts"],"names":[],"mappings":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iBAC9B;YACF,CAAC;YACD,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;gBACd,IAAI,CAAC,YAAY,OAAO,EAAE;oBACzB,OAAO,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;iBAC9B;YACF,CAAC;YACD,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE;gBACb,IAAI,CAAC,YAAY,OAAO,EAAE;oBACzB,OAAO,IAAI,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;iBAC9B;YACF,CAAC;YACD,GAAG,OAAO;YACV,qCAAqC;YACrC,wBAAwB;SACxB,CAAC,CAAC;QAEH,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACjC,MAAM,OAAO,CAAC,SAAS,EAAE,CAAC;QAE1B,OAAO,OAAY,CAAC;IACrB,CAAC;IAED,IAAI,MAAM;QACT,OAAO,IAAI,CAAC,MAAM,CAAC;IACpB,CAAC;CACD"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { webSockets } from "@libp2p/websockets";
|
|
2
|
+
import { circuitRelayTransport } from "libp2p/circuit-relay";
|
|
3
|
+
import { webRTC } from "@libp2p/webrtc";
|
|
4
|
+
import { all } from "@libp2p/websockets/filters";
|
|
5
|
+
export const transports = () => [
|
|
6
|
+
webSockets({ filter: all }),
|
|
7
|
+
circuitRelayTransport({
|
|
8
|
+
discoverRelays: 1,
|
|
9
|
+
}),
|
|
10
|
+
webRTC({}),
|
|
11
|
+
];
|
|
12
|
+
export const relay = () => undefined;
|
|
13
|
+
//# sourceMappingURL=transports-browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transports-browser.js","sourceRoot":"","sources":["../../src/transports-browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AAEjD,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC;IAC/B,UAAU,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;IAC3B,qBAAqB,CAAC;QACrB,cAAc,EAAE,CAAC;KACjB,CAAC;IACF,MAAM,CAAC,EAAE,CAAC;CACV,CAAC;AAEF,MAAM,CAAC,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,SAAS,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export declare const transports: () => (((components: import("libp2p/dist/src/circuit-relay/transport").CircuitRelayTransportComponents) => import("@libp2p/interface-transport").Transport) | ((components?: import("@libp2p/tcp").TCPComponents | undefined) => import("@libp2p/interface-transport").Transport))[];
|
|
2
|
+
export declare const relay: () => (components: import("libp2p/dist/src/circuit-relay/server").CircuitRelayServerComponents) => import("libp2p/circuit-relay").CircuitRelayService;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { webSockets } from "@libp2p/websockets";
|
|
2
|
+
import { circuitRelayTransport } from "libp2p/circuit-relay";
|
|
3
|
+
import { tcp } from "@libp2p/tcp";
|
|
4
|
+
import { circuitRelayServer } from "libp2p/circuit-relay";
|
|
5
|
+
import { all } from "@libp2p/websockets/filters";
|
|
6
|
+
export const transports = () => [
|
|
7
|
+
webSockets({ filter: all }),
|
|
8
|
+
circuitRelayTransport(),
|
|
9
|
+
tcp(),
|
|
10
|
+
];
|
|
11
|
+
export const relay = () => circuitRelayServer({ reservations: { maxReservations: 1000 } });
|
|
12
|
+
//# sourceMappingURL=transports.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transports.js","sourceRoot":"","sources":["../../src/transports.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AACjD,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC;IAC/B,UAAU,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;IAC3B,qBAAqB,EAAE;IACvB,GAAG,EAAE;CACL,CAAC;AACF,MAAM,CAAC,MAAM,KAAK,GAAG,GAAG,EAAE,CACzB,kBAAkB,CAAC,EAAE,YAAY,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "peerbit",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Peerbit client",
|
|
5
|
+
"author": "dao.xyz",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/dao-xyz/peerbit"
|
|
11
|
+
},
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=16.15.1"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"lib",
|
|
17
|
+
"src",
|
|
18
|
+
"!src/**/__tests__",
|
|
19
|
+
"!lib/**/__tests__",
|
|
20
|
+
"!src/**/__benchmark__",
|
|
21
|
+
"!lib/**/__benchmark__",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"module": "lib/esm/index.js",
|
|
28
|
+
"types": "lib/esm/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
"import": "./lib/esm/index.js"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@dao-xyz/borsh": "^5.1.5",
|
|
34
|
+
"@peerbit/blocks": "^1.0.1",
|
|
35
|
+
"@peerbit/crypto": "1.0.1",
|
|
36
|
+
"@peerbit/lazy-level": "1.0.0",
|
|
37
|
+
"@peerbit/logger": "1.0.0",
|
|
38
|
+
"@peerbit/program": "1.0.1",
|
|
39
|
+
"@peerbit/pubsub": "^1.0.1",
|
|
40
|
+
"@peerbit/uint8arrays": "2.0.0",
|
|
41
|
+
"level": "^8.0.0",
|
|
42
|
+
"memory-level": "^1.0.0",
|
|
43
|
+
"p-queue": "^7.3.4"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"p-each-series": "^3.0.0",
|
|
47
|
+
"p-map-series": "^3.0.0"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"clean": "shx rm -rf lib/*",
|
|
51
|
+
"build": "yarn clean && tsc -p tsconfig.json",
|
|
52
|
+
"postbuild": "echo '{\"type\":\"module\"} ' | node ../../../node_modules/.bin/json > lib/esm/package.json"
|
|
53
|
+
},
|
|
54
|
+
"localMaintainers": [
|
|
55
|
+
"dao.xyz"
|
|
56
|
+
],
|
|
57
|
+
"keywords": [
|
|
58
|
+
"crdt",
|
|
59
|
+
"database",
|
|
60
|
+
"distributed",
|
|
61
|
+
"decentralised",
|
|
62
|
+
"distributed",
|
|
63
|
+
"ipfs",
|
|
64
|
+
"p2p",
|
|
65
|
+
"peer-to-peer"
|
|
66
|
+
],
|
|
67
|
+
"gitHead": "069ce2f62a76c342875a1cc695c6f210beff13fd"
|
|
68
|
+
}
|
package/src/index.ts
ADDED
package/src/libp2p.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { createLibp2p, Libp2p, Libp2pOptions, ServiceFactoryMap } from "libp2p";
|
|
2
|
+
import { DirectSub } from "@peerbit/pubsub";
|
|
3
|
+
import { DirectBlock } from "@peerbit/blocks";
|
|
4
|
+
import { noise } from "@dao-xyz/libp2p-noise";
|
|
5
|
+
import { mplex } from "@libp2p/mplex";
|
|
6
|
+
import { transports, relay } from "./transports.js";
|
|
7
|
+
import { identifyService } from "libp2p/identify";
|
|
8
|
+
import { CircuitRelayService } from "libp2p/dist/src/circuit-relay/index.js";
|
|
9
|
+
|
|
10
|
+
export type Libp2pExtendServices = {
|
|
11
|
+
pubsub: DirectSub;
|
|
12
|
+
blocks: DirectBlock;
|
|
13
|
+
};
|
|
14
|
+
export type Libp2pExtended = Libp2p<
|
|
15
|
+
{ relay: CircuitRelayService; identify: any } & Libp2pExtendServices
|
|
16
|
+
>;
|
|
17
|
+
|
|
18
|
+
export type Libp2pCreateOptions = Libp2pOptions<
|
|
19
|
+
Libp2pExtendServices & { relay: CircuitRelayService; identify: any }
|
|
20
|
+
>;
|
|
21
|
+
|
|
22
|
+
export type Libp2pCreateOptionsWithServices = Libp2pCreateOptions & {
|
|
23
|
+
services: ServiceFactoryMap<Libp2pExtendServices>;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export const createLibp2pExtended = (
|
|
27
|
+
opts: Libp2pCreateOptions = {
|
|
28
|
+
services: {
|
|
29
|
+
blocks: (c) => new DirectBlock(c),
|
|
30
|
+
pubsub: (c) => new DirectSub(c),
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
): Promise<Libp2pExtended> => {
|
|
34
|
+
const relayIdentify = {
|
|
35
|
+
relay: relay(),
|
|
36
|
+
identify: identifyService(),
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// https://github.com/libp2p/js-libp2p/issues/1757
|
|
40
|
+
Object.keys(relayIdentify).forEach((key) => {
|
|
41
|
+
if (relayIdentify[key] === undefined) {
|
|
42
|
+
delete relayIdentify[key];
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
return createLibp2p({
|
|
47
|
+
connectionManager: {
|
|
48
|
+
minConnections: 0,
|
|
49
|
+
},
|
|
50
|
+
addresses: {
|
|
51
|
+
listen: ["/ip4/127.0.0.1/tcp/0", "/ip4/127.0.0.1/tcp/0/ws"],
|
|
52
|
+
},
|
|
53
|
+
transports: transports(),
|
|
54
|
+
connectionEncryption: [noise()],
|
|
55
|
+
streamMuxers: [mplex()],
|
|
56
|
+
...opts,
|
|
57
|
+
services: {
|
|
58
|
+
...relayIdentify,
|
|
59
|
+
pubsub:
|
|
60
|
+
opts.services?.pubsub ||
|
|
61
|
+
((c) =>
|
|
62
|
+
new DirectSub(c, {
|
|
63
|
+
canRelayMessage: true,
|
|
64
|
+
signaturePolicy: "StrictNoSign",
|
|
65
|
+
connectionManager: {
|
|
66
|
+
autoDial: true,
|
|
67
|
+
},
|
|
68
|
+
})),
|
|
69
|
+
blocks: opts.services?.blocks || ((c) => new DirectBlock(c)),
|
|
70
|
+
...opts.services,
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
};
|
package/src/peer.ts
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import LazyLevel from "@peerbit/lazy-level";
|
|
2
|
+
import { AbstractLevel } from "abstract-level";
|
|
3
|
+
import { Level } from "level";
|
|
4
|
+
import { MemoryLevel } from "memory-level";
|
|
5
|
+
import { multiaddr, Multiaddr, isMultiaddr } from "@multiformats/multiaddr";
|
|
6
|
+
import type { Libp2p } from "libp2p";
|
|
7
|
+
import {
|
|
8
|
+
Ed25519Keypair,
|
|
9
|
+
Ed25519PublicKey,
|
|
10
|
+
Libp2pKeychain,
|
|
11
|
+
} from "@peerbit/crypto";
|
|
12
|
+
import {
|
|
13
|
+
Program,
|
|
14
|
+
Address,
|
|
15
|
+
ProgramInitializationOptions,
|
|
16
|
+
ProgramClient,
|
|
17
|
+
} from "@peerbit/program";
|
|
18
|
+
import { logger as loggerFn } from "@peerbit/logger";
|
|
19
|
+
import { DirectSub } from "@peerbit/pubsub";
|
|
20
|
+
import sodium from "libsodium-wrappers";
|
|
21
|
+
import path from "path-browserify";
|
|
22
|
+
import { waitFor } from "@peerbit/time";
|
|
23
|
+
import "@libp2p/peer-id";
|
|
24
|
+
|
|
25
|
+
import {
|
|
26
|
+
createLibp2pExtended,
|
|
27
|
+
Libp2pExtended,
|
|
28
|
+
Libp2pCreateOptions as ClientCreateOptions,
|
|
29
|
+
} from "./libp2p.js";
|
|
30
|
+
import { DirectBlock } from "@peerbit/blocks";
|
|
31
|
+
import { LevelDatastore } from "datastore-level";
|
|
32
|
+
import { BinaryWriter } from "@dao-xyz/borsh";
|
|
33
|
+
|
|
34
|
+
export const logger = loggerFn({ module: "client" });
|
|
35
|
+
|
|
36
|
+
export type OptionalCreateOptions = {
|
|
37
|
+
limitSigning?: boolean;
|
|
38
|
+
minReplicas?: number;
|
|
39
|
+
refreshIntreval?: number;
|
|
40
|
+
libp2pExternal?: boolean;
|
|
41
|
+
};
|
|
42
|
+
export type CreateOptions = {
|
|
43
|
+
directory?: string;
|
|
44
|
+
cache: LazyLevel;
|
|
45
|
+
identity: Ed25519Keypair;
|
|
46
|
+
keychain: Libp2pKeychain;
|
|
47
|
+
} & OptionalCreateOptions;
|
|
48
|
+
|
|
49
|
+
export type CreateInstanceOptions = {
|
|
50
|
+
libp2p?: Libp2pExtended | ClientCreateOptions;
|
|
51
|
+
directory?: string;
|
|
52
|
+
cache?: LazyLevel;
|
|
53
|
+
} & OptionalCreateOptions;
|
|
54
|
+
export type OpenOptions<Args> = {
|
|
55
|
+
timeout?: number;
|
|
56
|
+
/*
|
|
57
|
+
reset?: boolean; */
|
|
58
|
+
} & ProgramInitializationOptions<Args>;
|
|
59
|
+
|
|
60
|
+
const isLibp2pInstance = (libp2p: Libp2pExtended | ClientCreateOptions) =>
|
|
61
|
+
!!(libp2p as Libp2p).getMultiaddrs;
|
|
62
|
+
|
|
63
|
+
const createLevel = (path?: string): AbstractLevel<any, string, Uint8Array> => {
|
|
64
|
+
return path
|
|
65
|
+
? new Level(path, { valueEncoding: "view" })
|
|
66
|
+
: new MemoryLevel({ valueEncoding: "view" });
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const createCache = async (
|
|
70
|
+
directory: string | undefined,
|
|
71
|
+
options?: { reset?: boolean }
|
|
72
|
+
) => {
|
|
73
|
+
const cache = await new LazyLevel(createLevel(directory));
|
|
74
|
+
|
|
75
|
+
// "Wake up" the caches if they need it
|
|
76
|
+
if (cache) await cache.open();
|
|
77
|
+
if (options?.reset) {
|
|
78
|
+
await cache["_store"].clear();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return cache;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
export class Peerbit implements ProgramClient {
|
|
85
|
+
_libp2p: Libp2pExtended;
|
|
86
|
+
|
|
87
|
+
directory?: string;
|
|
88
|
+
|
|
89
|
+
/// program address => Program metadata
|
|
90
|
+
programs: Map<string, Program>;
|
|
91
|
+
limitSigning: boolean;
|
|
92
|
+
|
|
93
|
+
private _cache: LazyLevel;
|
|
94
|
+
private _libp2pExternal?: boolean = false;
|
|
95
|
+
|
|
96
|
+
// Libp2p peerid in Identity form
|
|
97
|
+
private _identity: Ed25519Keypair;
|
|
98
|
+
|
|
99
|
+
private _keychain: Libp2pKeychain; // Keychain + Caching + X25519 keys
|
|
100
|
+
|
|
101
|
+
constructor(libp2p: Libp2pExtended, options: CreateOptions) {
|
|
102
|
+
if (libp2p == null) {
|
|
103
|
+
throw new Error("Libp2p required");
|
|
104
|
+
}
|
|
105
|
+
this._libp2p = libp2p;
|
|
106
|
+
if (this.libp2p.peerId.type !== "Ed25519") {
|
|
107
|
+
throw new Error(
|
|
108
|
+
"Unsupported id type, expecting Ed25519 but got " +
|
|
109
|
+
this.libp2p.peerId.type
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (this.libp2p.peerId.type !== "Ed25519") {
|
|
114
|
+
throw new Error("Only Ed25519 peerIds are supported");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
this._identity = options.identity;
|
|
118
|
+
this._keychain = options.keychain;
|
|
119
|
+
|
|
120
|
+
this.directory = options.directory;
|
|
121
|
+
this.programs = new Map();
|
|
122
|
+
this.limitSigning = options.limitSigning || false;
|
|
123
|
+
this._cache = options.cache;
|
|
124
|
+
this._libp2pExternal = options.libp2pExternal;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
static async create(options: CreateInstanceOptions = {}): Promise<Peerbit> {
|
|
128
|
+
await sodium.ready; // Some of the modules depends on sodium to be readyy
|
|
129
|
+
|
|
130
|
+
let libp2pExtended: Libp2pExtended = options.libp2p as Libp2pExtended;
|
|
131
|
+
const blocksDirectory =
|
|
132
|
+
options.directory != null
|
|
133
|
+
? path.join(options.directory, "/blocks").toString()
|
|
134
|
+
: undefined;
|
|
135
|
+
let libp2pExternal = false;
|
|
136
|
+
|
|
137
|
+
const datastore =
|
|
138
|
+
options.directory != null
|
|
139
|
+
? new LevelDatastore(path.join(options.directory, "/libp2p").toString())
|
|
140
|
+
: undefined;
|
|
141
|
+
if (datastore) {
|
|
142
|
+
await datastore.open();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (!libp2pExtended) {
|
|
146
|
+
libp2pExtended = await createLibp2pExtended({
|
|
147
|
+
services: {
|
|
148
|
+
blocks: (c) => new DirectBlock(c, { directory: blocksDirectory }),
|
|
149
|
+
pubsub: (c) => new DirectSub(c),
|
|
150
|
+
},
|
|
151
|
+
// If directory is passed, we store keys within that directory, else we will use memory datastore (which is the default behaviour)
|
|
152
|
+
datastore,
|
|
153
|
+
});
|
|
154
|
+
} else {
|
|
155
|
+
if (isLibp2pInstance(libp2pExtended)) {
|
|
156
|
+
libp2pExternal = true; // libp2p was created outside
|
|
157
|
+
} else {
|
|
158
|
+
const extendedOptions = libp2pExtended as any as ClientCreateOptions;
|
|
159
|
+
libp2pExtended = await createLibp2pExtended({
|
|
160
|
+
...extendedOptions,
|
|
161
|
+
services: {
|
|
162
|
+
blocks: (c) => new DirectBlock(c, { directory: blocksDirectory }),
|
|
163
|
+
pubsub: (c) => new DirectSub(c),
|
|
164
|
+
...extendedOptions?.services,
|
|
165
|
+
},
|
|
166
|
+
datastore,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (datastore) {
|
|
171
|
+
const stopFn = libp2pExtended.stop.bind(libp2pExtended);
|
|
172
|
+
libp2pExtended.stop = async () => {
|
|
173
|
+
await stopFn();
|
|
174
|
+
await datastore?.close();
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (!libp2pExtended.isStarted()) {
|
|
179
|
+
await libp2pExtended.start();
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (libp2pExtended.peerId.type !== "Ed25519") {
|
|
183
|
+
throw new Error(
|
|
184
|
+
"Unsupported id type, expecting Ed25519 but got " +
|
|
185
|
+
libp2pExtended.peerId.type
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const directory = options.directory;
|
|
190
|
+
const cache =
|
|
191
|
+
options.cache ||
|
|
192
|
+
(await createCache(
|
|
193
|
+
directory ? path.join(directory, "/cache") : undefined
|
|
194
|
+
));
|
|
195
|
+
|
|
196
|
+
const identity = Ed25519Keypair.fromPeerId(libp2pExtended.peerId);
|
|
197
|
+
const keychain = new Libp2pKeychain(libp2pExtended.keychain);
|
|
198
|
+
|
|
199
|
+
// Import identity into keychain
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
const writer = new BinaryWriter();
|
|
203
|
+
writer.string("identity");
|
|
204
|
+
await keychain.import(identity, writer.finalize());
|
|
205
|
+
} catch (error: any) {
|
|
206
|
+
if (error.code == "ERR_KEY_ALREADY_EXISTS") {
|
|
207
|
+
// Do nothing
|
|
208
|
+
} else {
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const peer = new Peerbit(libp2pExtended, {
|
|
214
|
+
directory,
|
|
215
|
+
cache,
|
|
216
|
+
libp2pExternal,
|
|
217
|
+
limitSigning: options.limitSigning,
|
|
218
|
+
minReplicas: options.minReplicas,
|
|
219
|
+
refreshIntreval: options.refreshIntreval,
|
|
220
|
+
identity,
|
|
221
|
+
keychain,
|
|
222
|
+
});
|
|
223
|
+
return peer;
|
|
224
|
+
}
|
|
225
|
+
get libp2p(): Libp2pExtended {
|
|
226
|
+
return this._libp2p;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
get identity(): Ed25519Keypair {
|
|
230
|
+
return this._identity;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
get peerId() {
|
|
234
|
+
return this.libp2p.peerId;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
get services() {
|
|
238
|
+
return this.libp2p.services;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
get keychain(): Libp2pKeychain {
|
|
242
|
+
return this._keychain;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
getMultiaddrs(): Multiaddr[] {
|
|
246
|
+
return this.libp2p.getMultiaddrs();
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Dial a peer with an Ed25519 peerId
|
|
250
|
+
*/
|
|
251
|
+
async dial(
|
|
252
|
+
address: string | Multiaddr | Multiaddr[] | ProgramClient
|
|
253
|
+
): Promise<boolean> {
|
|
254
|
+
const maddress =
|
|
255
|
+
typeof address == "string"
|
|
256
|
+
? multiaddr(address)
|
|
257
|
+
: isMultiaddr(address) || Array.isArray(address)
|
|
258
|
+
? address
|
|
259
|
+
: address.getMultiaddrs();
|
|
260
|
+
const connection = await this.libp2p.dial(maddress);
|
|
261
|
+
const publicKey = Ed25519PublicKey.fromPeerId(connection.remotePeer);
|
|
262
|
+
|
|
263
|
+
// TODO, do this as a promise instead using the onPeerConnected vents in pubsub and blocks
|
|
264
|
+
return (
|
|
265
|
+
(await waitFor(
|
|
266
|
+
() =>
|
|
267
|
+
this.libp2p.services.pubsub.peers.has(publicKey.hashcode()) &&
|
|
268
|
+
this.libp2p.services.blocks.peers.has(publicKey.hashcode())
|
|
269
|
+
)) || false
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async start() {
|
|
274
|
+
if (!this.libp2p.isStarted()) {
|
|
275
|
+
this._libp2pExternal = false; // this means we will also close libp2p client on close
|
|
276
|
+
return this.libp2p.start();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
async stop() {
|
|
280
|
+
// Close a direct connection and remove it from internal state
|
|
281
|
+
|
|
282
|
+
// Close all open databases
|
|
283
|
+
await Promise.all(
|
|
284
|
+
[...this.programs.values()].map((program) => program.close())
|
|
285
|
+
);
|
|
286
|
+
|
|
287
|
+
await this._cache.close();
|
|
288
|
+
|
|
289
|
+
// Close libp2p (after above)
|
|
290
|
+
if (!this._libp2pExternal) {
|
|
291
|
+
// only close it if we created it
|
|
292
|
+
await this.libp2p.stop();
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Remove all databases from the state
|
|
296
|
+
this.programs = new Map();
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private _onProgamClose(program: Program) {
|
|
300
|
+
this.programs.delete(program.address!.toString());
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
private _onProgramOpen(program: Program) {
|
|
304
|
+
const programAddress = program.address?.toString();
|
|
305
|
+
if (!programAddress) {
|
|
306
|
+
throw new Error("Missing program address");
|
|
307
|
+
}
|
|
308
|
+
if (this.programs.has(programAddress)) {
|
|
309
|
+
// second condition only makes this throw error if we are to add a new instance with the same address
|
|
310
|
+
throw new Error(`Program at ${programAddress} is already open`);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
this.programs.set(programAddress, program);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Default behaviour of a store is only to accept heads that are forks (new roots) with some probability
|
|
318
|
+
* and to replicate heads (and updates) which is requested by another peer
|
|
319
|
+
* @param store
|
|
320
|
+
* @param options
|
|
321
|
+
* @returns
|
|
322
|
+
*/
|
|
323
|
+
|
|
324
|
+
async open<S extends Program<Args>, Args = any>(
|
|
325
|
+
storeOrAddress: S | Address | string,
|
|
326
|
+
options: OpenOptions<Args> = {}
|
|
327
|
+
): Promise<S> {
|
|
328
|
+
if (!this.libp2p.isStarted()) {
|
|
329
|
+
throw new Error("Can not open a store while disconnected");
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// TODO add locks for store lifecycle, e.g. what happens if we try to open and close a store at the same time?
|
|
333
|
+
|
|
334
|
+
let program = storeOrAddress as S;
|
|
335
|
+
if (typeof storeOrAddress === "string") {
|
|
336
|
+
try {
|
|
337
|
+
if (this.programs?.has(storeOrAddress.toString())) {
|
|
338
|
+
throw new Error(
|
|
339
|
+
`Program at ${storeOrAddress.toString()} is already open`
|
|
340
|
+
);
|
|
341
|
+
} else {
|
|
342
|
+
program = (await Program.load(
|
|
343
|
+
storeOrAddress,
|
|
344
|
+
this._libp2p.services.blocks,
|
|
345
|
+
options
|
|
346
|
+
)) as S; // TODO fix typings
|
|
347
|
+
if (program instanceof Program === false) {
|
|
348
|
+
throw new Error(
|
|
349
|
+
`Failed to open program because program is of type ${program?.constructor.name} and not ${Program.name}`
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
} catch (error) {
|
|
354
|
+
logger.error(
|
|
355
|
+
"Failed to load store with address: " + storeOrAddress.toString()
|
|
356
|
+
);
|
|
357
|
+
throw error;
|
|
358
|
+
}
|
|
359
|
+
} else if (!program.closed) {
|
|
360
|
+
const existing = this.programs.get(program.address);
|
|
361
|
+
if (existing === program) {
|
|
362
|
+
return program;
|
|
363
|
+
} else if (existing) {
|
|
364
|
+
throw new Error(
|
|
365
|
+
`Program at ${program.address} is already open, but is another instance`
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
logger.debug(`Open database '${program.constructor.name}`);
|
|
371
|
+
await program.beforeOpen(this, {
|
|
372
|
+
onOpen: (p) => {
|
|
373
|
+
if (p instanceof Program && p.parents.length === 1 && !p.parents[0]) {
|
|
374
|
+
return this._onProgramOpen(p);
|
|
375
|
+
}
|
|
376
|
+
},
|
|
377
|
+
onClose: (p) => {
|
|
378
|
+
if (p instanceof Program) {
|
|
379
|
+
return this._onProgamClose(p);
|
|
380
|
+
}
|
|
381
|
+
},
|
|
382
|
+
onDrop: (p) => {
|
|
383
|
+
if (p instanceof Program) {
|
|
384
|
+
return this._onProgamClose(p);
|
|
385
|
+
}
|
|
386
|
+
},
|
|
387
|
+
...options,
|
|
388
|
+
// If the program opens more programs
|
|
389
|
+
// reset: options.reset,
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
await program.open(options.args);
|
|
393
|
+
await program.afterOpen();
|
|
394
|
+
|
|
395
|
+
return program as S;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
get memory() {
|
|
399
|
+
return this._cache;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { webSockets } from "@libp2p/websockets";
|
|
2
|
+
import { circuitRelayTransport } from "libp2p/circuit-relay";
|
|
3
|
+
import { webRTC } from "@libp2p/webrtc";
|
|
4
|
+
import { all } from "@libp2p/websockets/filters";
|
|
5
|
+
|
|
6
|
+
export const transports = () => [
|
|
7
|
+
webSockets({ filter: all }),
|
|
8
|
+
circuitRelayTransport({
|
|
9
|
+
discoverRelays: 1,
|
|
10
|
+
}),
|
|
11
|
+
webRTC({}),
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
export const relay = () => undefined;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { webSockets } from "@libp2p/websockets";
|
|
2
|
+
import { circuitRelayTransport } from "libp2p/circuit-relay";
|
|
3
|
+
import { tcp } from "@libp2p/tcp";
|
|
4
|
+
import { circuitRelayServer } from "libp2p/circuit-relay";
|
|
5
|
+
import { all } from "@libp2p/websockets/filters";
|
|
6
|
+
export const transports = () => [
|
|
7
|
+
webSockets({ filter: all }),
|
|
8
|
+
circuitRelayTransport(),
|
|
9
|
+
tcp(),
|
|
10
|
+
];
|
|
11
|
+
export const relay = () =>
|
|
12
|
+
circuitRelayServer({ reservations: { maxReservations: 1000 } });
|