@peerbit/blocks 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 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/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # Direct block
2
+
3
+ Block swap/share protocol built on top of [Direct Stream](./../direct-stream/README.md)
@@ -0,0 +1,26 @@
1
+ import { CID } from "multiformats/cid";
2
+ import * as raw from "multiformats/codecs/raw";
3
+ import * as dagCbor from "@ipld/dag-cbor";
4
+ import * as Block from "multiformats/block";
5
+ import type { MultihashHasher } from "multiformats/hashes/hasher";
6
+ export declare const defaultHasher: import("multiformats/hashes/hasher").Hasher<"sha2-256", 18>;
7
+ export declare const codecCodes: {
8
+ 113: typeof dagCbor;
9
+ 85: typeof raw;
10
+ };
11
+ export declare const codecMap: {
12
+ raw: typeof raw;
13
+ "dag-cbor": typeof dagCbor;
14
+ };
15
+ export declare const cidifyString: (str: string) => CID;
16
+ export declare const stringifyCid: (cid: any) => string;
17
+ export declare const checkDecodeBlock: (expectedCID: CID | string, bytes: Uint8Array, options: {
18
+ hasher?: any;
19
+ codec?: any;
20
+ }) => Promise<Block.Block<any, any, any, any>>;
21
+ export declare const getBlockValue: <T>(block: Block.Block<T, any, any, any>, links?: string[]) => Promise<T>;
22
+ export declare const prepareBlockWrite: (value: any, codec: any, links?: string[]) => any;
23
+ export declare const createBlock: (value: any, format: string, options?: {
24
+ hasher?: MultihashHasher<number>;
25
+ links?: string[];
26
+ }) => Promise<Block.Block<any, any, any, any>>;
@@ -0,0 +1,89 @@
1
+ import { CID } from "multiformats/cid";
2
+ import * as raw from "multiformats/codecs/raw";
3
+ import * as dagCbor from "@ipld/dag-cbor";
4
+ import { sha256 } from "multiformats/hashes/sha2";
5
+ import { base58btc } from "multiformats/bases/base58";
6
+ import * as Block from "multiformats/block";
7
+ const unsupportedCodecError = () => new Error("unsupported codec");
8
+ const defaultBase = base58btc;
9
+ export const defaultHasher = sha256;
10
+ export const codecCodes = {
11
+ [dagCbor.code]: dagCbor,
12
+ [raw.code]: raw,
13
+ };
14
+ export const codecMap = {
15
+ raw: raw,
16
+ "dag-cbor": dagCbor,
17
+ };
18
+ export const cidifyString = (str) => {
19
+ if (!str) {
20
+ return str; // TODO fix types
21
+ }
22
+ return CID.parse(str, defaultBase);
23
+ };
24
+ export const stringifyCid = (cid) => {
25
+ if (!cid || typeof cid === "string") {
26
+ return cid;
27
+ }
28
+ if (cid["/"]) {
29
+ return defaultBase.encode(cid["/"]);
30
+ }
31
+ return cid.toString(defaultBase);
32
+ };
33
+ export const checkDecodeBlock = async (expectedCID, bytes, options) => {
34
+ const cidObject = typeof expectedCID === "string" ? cidifyString(expectedCID) : expectedCID;
35
+ const codec = options.codec || codecCodes[cidObject.code];
36
+ const block = await Block.decode({
37
+ bytes: bytes,
38
+ codec,
39
+ hasher: options?.hasher || defaultHasher,
40
+ });
41
+ if (!block.cid.equals(cidObject)) {
42
+ throw new Error("CID does not match");
43
+ }
44
+ return block;
45
+ };
46
+ export const getBlockValue = async (block, links) => {
47
+ if (block.cid.code === dagCbor.code) {
48
+ const value = block.value;
49
+ links = links || [];
50
+ links.forEach((prop) => {
51
+ if (value[prop]) {
52
+ value[prop] = Array.isArray(value[prop])
53
+ ? value[prop].map(stringifyCid)
54
+ : stringifyCid(value[prop]);
55
+ }
56
+ });
57
+ return value;
58
+ }
59
+ if (block.cid.code === raw.code) {
60
+ return block.value;
61
+ }
62
+ throw new Error("Unsupported");
63
+ };
64
+ export const prepareBlockWrite = (value, codec, links) => {
65
+ if (!codec)
66
+ throw unsupportedCodecError();
67
+ if (codec.code === dagCbor.code) {
68
+ links = links || [];
69
+ links.forEach((prop) => {
70
+ if (value[prop]) {
71
+ value[prop] = Array.isArray(value[prop])
72
+ ? value[prop].map(cidifyString)
73
+ : cidifyString(value[prop]);
74
+ }
75
+ });
76
+ }
77
+ return value;
78
+ };
79
+ export const createBlock = async (value, format, options) => {
80
+ const codec = codecMap[format];
81
+ value = prepareBlockWrite(value, codec, options?.links);
82
+ const block = await Block.encode({
83
+ value,
84
+ codec,
85
+ hasher: options?.hasher || defaultHasher,
86
+ });
87
+ return block;
88
+ };
89
+ //# sourceMappingURL=block.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block.js","sourceRoot":"","sources":["../../src/block.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,KAAK,GAAG,MAAM,yBAAyB,CAAC;AAC/C,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtD,OAAO,KAAK,KAAK,MAAM,oBAAoB,CAAC;AAG5C,MAAM,qBAAqB,GAAG,GAAG,EAAE,CAAC,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;AAEnE,MAAM,WAAW,GAAG,SAAS,CAAC;AAE9B,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC;AAEpC,MAAM,CAAC,MAAM,UAAU,GAAG;IACzB,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO;IACvB,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG;CACf,CAAC;AACF,MAAM,CAAC,MAAM,QAAQ,GAAG;IACvB,GAAG,EAAE,GAAG;IACR,UAAU,EAAE,OAAO;CACnB,CAAC;AAEF,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,GAAW,EAAO,EAAE;IAChD,IAAI,CAAC,GAAG,EAAE;QACT,OAAO,GAAiB,CAAC,CAAC,iBAAiB;KAC3C;IAED,OAAO,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;AACpC,CAAC,CAAC;AAEF,MAAM,CAAC,M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,KAAU,EACV,MAAc,EACd,OAGC,EAC0C,EAAE;IAC7C,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC/B,KAAK,GAAG,iBAAiB,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;IACxD,MAAM,KAAK,GAAG,MAAM,KAAK,CAAC,MAAM,CAAC;QAChC,KAAK;QACL,KAAK;QACL,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,aAAa;KACxC,CAAC,CAAC;IACH,OAAO,KAAwC,CAAC;AACjD,CAAC,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { cidifyString, stringifyCid, createBlock, getBlockValue, } from "./block.js";
2
+ export { DirectBlock } from "./libp2p.js";
3
+ export * from "./store.js";
4
+ export * from "./level.js";
5
+ export * from "./libp2p.js";
@@ -0,0 +1,6 @@
1
+ export { cidifyString, stringifyCid, createBlock, getBlockValue, } from "./block.js";
2
+ export { DirectBlock } from "./libp2p.js";
3
+ export * from "./store.js";
4
+ export * from "./level.js";
5
+ export * from "./libp2p.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,aAAa,GACb,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC"}
@@ -0,0 +1,30 @@
1
+ import { Blocks } from "@peerbit/blocks-interface";
2
+ import { AbstractLevel } from "abstract-level";
3
+ import { LazyLevelOptions } from "@peerbit/lazy-level";
4
+ import { PutOptions } from "@peerbit/blocks-interface";
5
+ import { PeerId } from "@libp2p/interface-peer-id";
6
+ import { PublicSignKey } from "@peerbit/crypto";
7
+ export declare class LevelBlockStore implements Blocks {
8
+ private _level;
9
+ private _opening;
10
+ private _closed;
11
+ private _onClose;
12
+ constructor(level: AbstractLevel<any, string, Uint8Array>, options?: LazyLevelOptions);
13
+ get(cid: string, options?: {
14
+ raw?: boolean;
15
+ links?: string[];
16
+ timeout?: number;
17
+ hasher?: any;
18
+ }): Promise<Uint8Array | undefined>;
19
+ put(bytes: Uint8Array, options?: PutOptions): Promise<string>;
20
+ rm(cid: string): Promise<void>;
21
+ has(cid: string): Promise<boolean>;
22
+ start(): Promise<void>;
23
+ stop(): Promise<void>;
24
+ idle(): Promise<void>;
25
+ get status(): "open" | "opening" | "closed" | "closing";
26
+ waitFor(peer: PeerId | PublicSignKey): Promise<void>;
27
+ }
28
+ export declare class MemoryLevelBlockStore extends LevelBlockStore {
29
+ constructor(options?: LazyLevelOptions);
30
+ }
@@ -0,0 +1,88 @@
1
+ import { cidifyString, codecCodes, createBlock, defaultHasher, stringifyCid, } from "./block.js";
2
+ import * as Block from "multiformats/block";
3
+ import { MemoryLevel } from "memory-level";
4
+ import { waitFor } from "@peerbit/time";
5
+ import LazyLevel from "@peerbit/lazy-level";
6
+ export class LevelBlockStore {
7
+ _level;
8
+ _opening;
9
+ _closed = false;
10
+ _onClose;
11
+ constructor(level, options) {
12
+ this._level = new LazyLevel(level, options);
13
+ }
14
+ async get(cid, options) {
15
+ const cidObject = cidifyString(cid);
16
+ try {
17
+ const bytes = await this._level.get(cid);
18
+ if (!bytes) {
19
+ return undefined;
20
+ }
21
+ const codec = codecCodes[cidObject.code];
22
+ const block = await Block.decode({
23
+ bytes,
24
+ codec,
25
+ hasher: options?.hasher || defaultHasher,
26
+ });
27
+ return block.bytes;
28
+ }
29
+ catch (error) {
30
+ if (typeof error?.code === "string" &&
31
+ error?.code?.indexOf("LEVEL_NOT_FOUND") !== -1) {
32
+ return undefined;
33
+ }
34
+ throw error;
35
+ }
36
+ }
37
+ async put(bytes, options) {
38
+ const block = await createBlock(bytes, "raw");
39
+ const cid = stringifyCid(block.cid);
40
+ const bbytes = block.bytes;
41
+ await this._level.put(cid, bbytes);
42
+ return cid;
43
+ }
44
+ async rm(cid) {
45
+ await this._level.del(cid);
46
+ }
47
+ async has(cid) {
48
+ return !!(await this._level.get(cid));
49
+ }
50
+ async start() {
51
+ this._closed = false;
52
+ await this._level.open();
53
+ try {
54
+ this._opening = waitFor(() => this._level.status === "open", {
55
+ delayInterval: 100,
56
+ timeout: 10 * 1000,
57
+ stopperCallback: (fn) => {
58
+ this._onClose = fn;
59
+ },
60
+ });
61
+ await this._opening;
62
+ }
63
+ finally {
64
+ this._onClose = undefined;
65
+ }
66
+ }
67
+ async stop() {
68
+ await this.idle();
69
+ this._closed = true;
70
+ this._onClose && this._onClose();
71
+ return this._level.close();
72
+ }
73
+ async idle() {
74
+ await this._level.idle();
75
+ }
76
+ get status() {
77
+ return this._level.status;
78
+ }
79
+ async waitFor(peer) {
80
+ return; // Offline storage // TODO ßthis feels off resolving
81
+ }
82
+ }
83
+ export class MemoryLevelBlockStore extends LevelBlockStore {
84
+ constructor(options) {
85
+ super(new MemoryLevel({ valueEncoding: "view" }), options);
86
+ }
87
+ }
88
+ //# sourceMappingURL=level.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"level.js","sourceRoot":"","sources":["../../src/level.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EACZ,UAAU,EACV,WAAW,EACX,aAAa,EACb,YAAY,GACZ,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,KAAK,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,SAA+B,MAAM,qBAAqB,CAAC;AAKlE,MAAM,OAAO,eAAe;IACnB,MAAM,CAAY;IAClB,QAAQ,CAAe;IACvB,OAAO,GAAG,KAAK,CAAC;IAChB,QAAQ,CAA0B;IAC1C,YACC,KAA6C,EAC7C,OAA0B;QAE1B,IAAI,CAA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,eAAe;IACzD,YAAY,OAA0B;QACrC,KAAK,CAAC,IAAI,WAAW,CAAC,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;CACD"}
@@ -0,0 +1,36 @@
1
+ import { Blocks as IBlocks } from "@peerbit/blocks-interface";
2
+ import { DirectStream } from "@peerbit/stream";
3
+ import { DirectStreamComponents } from "@peerbit/stream";
4
+ import { GetOptions, PutOptions } from "@peerbit/blocks-interface";
5
+ export declare class BlockMessage {
6
+ }
7
+ export declare class BlockRequest extends BlockMessage {
8
+ cid: string;
9
+ constructor(cid: string);
10
+ }
11
+ export declare class BlockResponse extends BlockMessage {
12
+ cid: string;
13
+ bytes: Uint8Array;
14
+ constructor(cid: string, bytes: Uint8Array);
15
+ }
16
+ export type DirectBlockComponents = DirectStreamComponents;
17
+ export declare class DirectBlock extends DirectStream implements IBlocks {
18
+ private _localStore;
19
+ private _responseHandler?;
20
+ private _resolvers;
21
+ private _readFromPeersPromises;
22
+ _open: boolean;
23
+ constructor(components: DirectBlockComponents, options?: {
24
+ directory?: string;
25
+ canRelayMessage?: boolean;
26
+ localTimeout?: number;
27
+ });
28
+ put(bytes: Uint8Array, options?: PutOptions | undefined): Promise<string>;
29
+ has(cid: string): Promise<boolean>;
30
+ get(cid: string, options?: GetOptions | undefined): Promise<Uint8Array | undefined>;
31
+ rm(cid: string): Promise<void>;
32
+ start(): Promise<void>;
33
+ private _readFromPeers;
34
+ stop(): Promise<void>;
35
+ get status(): import("./store.js").StoreStatus;
36
+ }
@@ -0,0 +1,189 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { stringifyCid, cidifyString, codecCodes, checkDecodeBlock, } from "./block.js";
11
+ import { variant, field, serialize, deserialize } from "@dao-xyz/borsh";
12
+ import { DirectStream } from "@peerbit/stream";
13
+ import { LevelBlockStore, MemoryLevelBlockStore } from "./level.js";
14
+ import { Level } from "level";
15
+ export class BlockMessage {
16
+ }
17
+ export let BlockRequest = class BlockRequest extends BlockMessage {
18
+ cid;
19
+ constructor(cid) {
20
+ super();
21
+ this.cid = cid;
22
+ }
23
+ };
24
+ __decorate([
25
+ field({ type: "string" }),
26
+ __metadata("design:type", String)
27
+ ], BlockRequest.prototype, "cid", void 0);
28
+ BlockRequest = __decorate([
29
+ variant(0),
30
+ __metadata("design:paramtypes", [String])
31
+ ], BlockRequest);
32
+ export let BlockResponse = class BlockResponse extends BlockMessage {
33
+ cid;
34
+ bytes;
35
+ constructor(cid, bytes) {
36
+ super();
37
+ this.cid = cid;
38
+ this.bytes = bytes;
39
+ }
40
+ };
41
+ __decorate([
42
+ field({ type: "string" }),
43
+ __metadata("design:type", String)
44
+ ], BlockResponse.prototype, "cid", void 0);
45
+ __decorate([
46
+ field({ type: Uint8Array }),
47
+ __metadata("design:type", Uint8Array)
48
+ ], BlockResponse.prototype, "bytes", void 0);
49
+ BlockResponse = __decorate([
50
+ variant(1),
51
+ __metadata("design:paramtypes", [String, Uint8Array])
52
+ ], BlockResponse);
53
+ export class DirectBlock extends DirectStream {
54
+ _localStore;
55
+ _responseHandler;
56
+ _resolvers;
57
+ _readFromPeersPromises;
58
+ _open = false;
59
+ constructor(components, options) {
60
+ super(components, ["direct-block/1.0.0"], {
61
+ emitSelf: false,
62
+ signaturePolicy: "StrictNoSign",
63
+ messageProcessingConcurrency: 10,
64
+ canRelayMessage: options?.canRelayMessage ?? true,
65
+ });
66
+ const localTimeout = options?.localTimeout || 1000;
67
+ this._localStore =
68
+ options?.directory != null
69
+ ? new LevelBlockStore(new Level(options.directory))
70
+ : new MemoryLevelBlockStore();
71
+ this._resolvers = new Map();
72
+ this._readFromPeersPromises = new Map();
73
+ this._responseHandler = async (evt) => {
74
+ if (!evt) {
75
+ return;
76
+ }
77
+ const message = evt.detail;
78
+ try {
79
+ const decoded = deserialize(message.data, BlockMessage);
80
+ if (decoded instanceof BlockRequest && this._localStore) {
81
+ const cid = stringifyCid(decoded.cid);
82
+ const bytes = await this._localStore.get(cid, {
83
+ timeout: localTimeout,
84
+ });
85
+ if (!bytes) {
86
+ return;
87
+ }
88
+ const response = serialize(new BlockResponse(cid, bytes));
89
+ await this.publish(response);
90
+ }
91
+ else if (decoded instanceof BlockResponse) {
92
+ // TODO make sure we are not storing too much bytes in ram (like filter large blocks)
93
+ this._resolvers.get(decoded.cid)?.(decoded.bytes);
94
+ }
95
+ }
96
+ catch (error) {
97
+ console.error("Got error for libp2p block transport: ", error);
98
+ return; // timeout o r invalid cid
99
+ }
100
+ };
101
+ }
102
+ async put(bytes, options) {
103
+ if (!this._localStore) {
104
+ throw new Error("Local store not set");
105
+ }
106
+ return this._localStore.put(bytes, options);
107
+ }
108
+ async has(cid) {
109
+ return this._localStore.has(cid);
110
+ }
111
+ async get(cid, options) {
112
+ const cidObject = cidifyString(cid);
113
+ let value = this._localStore
114
+ ? await this._localStore.get(cid, options)
115
+ : undefined;
116
+ if (!value) {
117
+ // try to get it remotelly
118
+ value = await this._readFromPeers(cid, cidObject, options);
119
+ if (options?.replicate && value) {
120
+ this._localStore.put(value, options);
121
+ }
122
+ }
123
+ return value;
124
+ }
125
+ async rm(cid) {
126
+ this._localStore?.rm(cid);
127
+ }
128
+ async start() {
129
+ await this._localStore?.start();
130
+ await super.start();
131
+ this.addEventListener("data", this._responseHandler);
132
+ this._open = true;
133
+ }
134
+ async _readFromPeers(cidString, cidObject, options = {}) {
135
+ const codec = codecCodes[cidObject.code];
136
+ let promise = this._readFromPeersPromises.get(cidString);
137
+ if (!promise) {
138
+ promise = new Promise((resolve, reject) => {
139
+ const timeoutCallback = setTimeout(() => {
140
+ resolve(undefined);
141
+ }, options.timeout || 30 * 1000);
142
+ this._resolvers.set(cidString, async (bytes) => {
143
+ const value = await checkDecodeBlock(cidObject, bytes, {
144
+ codec,
145
+ hasher: options?.hasher,
146
+ });
147
+ clearTimeout(timeoutCallback);
148
+ this._resolvers.delete(cidString); // TODO concurrency might not work as expected here
149
+ resolve(value);
150
+ });
151
+ });
152
+ const publish = (to) => this.publish(serialize(new BlockRequest(cidString)), { to: to });
153
+ await publish();
154
+ const publishOnNewPeers = (e) => {
155
+ return publish([e.detail]);
156
+ };
157
+ this._readFromPeersPromises.set(cidString, promise);
158
+ // we want to make sure that if some new peers join, we also try to ask them
159
+ this.addEventListener("peer:reachable", publishOnNewPeers);
160
+ const result = await promise;
161
+ this._readFromPeersPromises.delete(cidString);
162
+ // stop asking new peers, because we already got an response
163
+ this.removeEventListener("peer:reachable", publishOnNewPeers);
164
+ return result?.bytes;
165
+ }
166
+ else {
167
+ const result = await promise;
168
+ return result?.bytes;
169
+ }
170
+ }
171
+ async stop() {
172
+ await super.stop();
173
+ this.removeEventListener("data", this._responseHandler);
174
+ await this._localStore?.stop();
175
+ this._readFromPeersPromises.clear();
176
+ this._resolvers.clear();
177
+ this._open = false;
178
+ // we dont cleanup subscription because we dont know if someone else is sbuscribing also
179
+ }
180
+ get status() {
181
+ if (this._open) {
182
+ return this._localStore?.status || this.started;
183
+ }
184
+ else {
185
+ return "closed";
186
+ }
187
+ }
188
+ }
189
+ //# sourceMappingURL=libp2p.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"libp2p.js","sourceRoot":"","sources":["../../src/libp2p.ts"],"names":[],"mappings":";;;;;;;;;AAEA,OAAO,EACN,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,gB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EAAE,CAAC;QACxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QAEnB,wFAAwF;IACzF,CAAC;IAED,IAAI,MAAM;QACT,IAAI,IAAI,CAAC,KAAK,EAAE;YACf,OAAO,IAAI,CAAC,WAAW,EAAE,MAAM,IAAI,IAAI,CAAC,OAAO,CAAC;SAChD;aAAM;YACN,OAAO,QAAQ,CAAC;SAChB;IACF,CAAC;CACD"}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,7 @@
1
+ import { Blocks as IBlockStore } from "@peerbit/blocks-interface";
2
+ export type StoreStatus = "open" | "opening" | "closed" | "closing";
3
+ export interface BlockStore extends IBlockStore {
4
+ start(): Promise<void>;
5
+ stop(): Promise<void>;
6
+ get status(): StoreStatus;
7
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/store.ts"],"names":[],"mappings":""}
@@ -0,0 +1 @@
1
+ export declare const x = 123;
@@ -0,0 +1,2 @@
1
+ export const x = 123;
2
+ //# sourceMappingURL=streams.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streams.js","sourceRoot":"","sources":["../../src/streams.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,CAAC,GAAG,GAAG,CAAC"}
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@peerbit/blocks",
3
+ "version": "1.0.1",
4
+ "description": "Block store streaming",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "private": false,
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "module": "lib/esm/index.js",
12
+ "types": "lib/esm/index.d.ts",
13
+ "exports": {
14
+ "import": "./lib/esm/index.js"
15
+ },
16
+ "scripts": {
17
+ "clean": "shx rm -rf lib/*",
18
+ "build": "yarn clean && tsc -p tsconfig.json",
19
+ "postbuild": "echo '{\"type\":\"module\"} ' | node ../../../node_modules/.bin/json > lib/esm/package.json",
20
+ "test": "node ../../../node_modules/.binß/jest test -c ../../../jest.config.ts --runInBand --forceExit",
21
+ "test:unit": "node ../../../node_modules/.bin/jest test -c ../../../jest.config.unit.ts --runInBand --forceExit",
22
+ "test:integration": "node ../node_modules/.bin/jest test -c ../../../jest.config.integration.ts --runInBand --forceExit"
23
+ },
24
+ "files": [
25
+ "lib",
26
+ "src",
27
+ "!src/**/__tests__",
28
+ "!lib/**/__tests__",
29
+ "!src/**/__benchmark__",
30
+ "!lib/**/__benchmark__",
31
+ "LICENSE"
32
+ ],
33
+ "engines": {
34
+ "node": ">=16.15.1"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/dao-xyz/peerbit.git"
39
+ },
40
+ "keywords": [
41
+ "peerbit"
42
+ ],
43
+ "author": "dao.xyz",
44
+ "license": "MIT",
45
+ "bugs": {
46
+ "url": "https://github.com/dao-xyz/peerbit/issues"
47
+ },
48
+ "homepage": "https://github.com/dao-xyz/peerbit#readme",
49
+ "localMaintainers": [
50
+ "dao.xyz"
51
+ ],
52
+ "devDependencies": {
53
+ "@peerbit/libp2p-test-utils": "1.0.0"
54
+ },
55
+ "dependencies": {
56
+ "@dao-xyz/borsh": "^5.1.5",
57
+ "@ipld/dag-cbor": "^9.0.2",
58
+ "@peerbit/blocks-interface": "1.0.1",
59
+ "@peerbit/crypto": "1.0.1",
60
+ "@peerbit/lazy-level": "1.0.0",
61
+ "@peerbit/stream": "1.0.1",
62
+ "abstract-level": "^1.0.3",
63
+ "libp2p": "^0.45.9",
64
+ "memory-level": "^1.0.0"
65
+ },
66
+ "gitHead": "069ce2f62a76c342875a1cc695c6f210beff13fd"
67
+ }
package/src/block.ts ADDED
@@ -0,0 +1,114 @@
1
+ import { CID } from "multiformats/cid";
2
+ import * as raw from "multiformats/codecs/raw";
3
+ import * as dagCbor from "@ipld/dag-cbor";
4
+ import { sha256 } from "multiformats/hashes/sha2";
5
+ import { base58btc } from "multiformats/bases/base58";
6
+ import * as Block from "multiformats/block";
7
+ import type { MultihashHasher } from "multiformats/hashes/hasher";
8
+
9
+ const unsupportedCodecError = () => new Error("unsupported codec");
10
+
11
+ const defaultBase = base58btc;
12
+
13
+ export const defaultHasher = sha256;
14
+
15
+ export const codecCodes = {
16
+ [dagCbor.code]: dagCbor,
17
+ [raw.code]: raw,
18
+ };
19
+ export const codecMap = {
20
+ raw: raw,
21
+ "dag-cbor": dagCbor,
22
+ };
23
+
24
+ export const cidifyString = (str: string): CID => {
25
+ if (!str) {
26
+ return str as any as CID; // TODO fix types
27
+ }
28
+
29
+ return CID.parse(str, defaultBase);
30
+ };
31
+
32
+ export const stringifyCid = (cid: any): string => {
33
+ if (!cid || typeof cid === "string") {
34
+ return cid;
35
+ }
36
+
37
+ if (cid["/"]) {
38
+ return defaultBase.encode(cid["/"]);
39
+ }
40
+ return cid.toString(defaultBase);
41
+ };
42
+
43
+ export const checkDecodeBlock = async (
44
+ expectedCID: CID | string,
45
+ bytes: Uint8Array,
46
+ options: { hasher?: any; codec?: any }
47
+ ): Promise<Block.Block<any, any, any, any>> => {
48
+ const cidObject =
49
+ typeof expectedCID === "string" ? cidifyString(expectedCID) : expectedCID;
50
+ const codec = options.codec || codecCodes[cidObject.code];
51
+ const block = await Block.decode({
52
+ bytes: bytes,
53
+ codec,
54
+ hasher: options?.hasher || defaultHasher,
55
+ });
56
+ if (!block.cid.equals(cidObject)) {
57
+ throw new Error("CID does not match");
58
+ }
59
+ return block as Block.Block<any, any, any, 1>;
60
+ };
61
+ export const getBlockValue = async <T>(
62
+ block: Block.Block<T, any, any, any>,
63
+ links?: string[]
64
+ ): Promise<T> => {
65
+ if (block.cid.code === dagCbor.code) {
66
+ const value = block.value as any;
67
+ links = links || [];
68
+ links.forEach((prop) => {
69
+ if (value[prop]) {
70
+ value[prop] = Array.isArray(value[prop])
71
+ ? value[prop].map(stringifyCid)
72
+ : stringifyCid(value[prop]);
73
+ }
74
+ });
75
+ return value;
76
+ }
77
+ if (block.cid.code === raw.code) {
78
+ return block.value as T;
79
+ }
80
+ throw new Error("Unsupported");
81
+ };
82
+
83
+ export const prepareBlockWrite = (value: any, codec: any, links?: string[]) => {
84
+ if (!codec) throw unsupportedCodecError();
85
+ if (codec.code === dagCbor.code) {
86
+ links = links || [];
87
+ links.forEach((prop) => {
88
+ if (value[prop]) {
89
+ value[prop] = Array.isArray(value[prop])
90
+ ? value[prop].map(cidifyString)
91
+ : cidifyString(value[prop]);
92
+ }
93
+ });
94
+ }
95
+ return value;
96
+ };
97
+
98
+ export const createBlock = async (
99
+ value: any,
100
+ format: string,
101
+ options?: {
102
+ hasher?: MultihashHasher<number>;
103
+ links?: string[];
104
+ }
105
+ ): Promise<Block.Block<any, any, any, any>> => {
106
+ const codec = codecMap[format];
107
+ value = prepareBlockWrite(value, codec, options?.links);
108
+ const block = await Block.encode({
109
+ value,
110
+ codec,
111
+ hasher: options?.hasher || defaultHasher,
112
+ });
113
+ return block as Block.Block<any, any, any, any>;
114
+ };
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ export {
2
+ cidifyString,
3
+ stringifyCid,
4
+ createBlock,
5
+ getBlockValue,
6
+ } from "./block.js";
7
+ export { DirectBlock } from "./libp2p.js";
8
+ export * from "./store.js";
9
+ export * from "./level.js";
10
+ export * from "./libp2p.js";
package/src/level.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { Blocks } from "@peerbit/blocks-interface";
2
+ import {
3
+ cidifyString,
4
+ codecCodes,
5
+ createBlock,
6
+ defaultHasher,
7
+ stringifyCid,
8
+ } from "./block.js";
9
+ import * as Block from "multiformats/block";
10
+ import { AbstractLevel } from "abstract-level";
11
+ import { MemoryLevel } from "memory-level";
12
+ import { waitFor } from "@peerbit/time";
13
+ import LazyLevel, { LazyLevelOptions } from "@peerbit/lazy-level";
14
+ import { PutOptions } from "@peerbit/blocks-interface";
15
+ import { PeerId } from "@libp2p/interface-peer-id";
16
+ import { PublicSignKey } from "@peerbit/crypto";
17
+
18
+ export class LevelBlockStore implements Blocks {
19
+ private _level: LazyLevel;
20
+ private _opening: Promise<any>;
21
+ private _closed = false;
22
+ private _onClose: (() => any) | undefined;
23
+ constructor(
24
+ level: AbstractLevel<any, string, Uint8Array>,
25
+ options?: LazyLevelOptions
26
+ ) {
27
+ this._level = new LazyLevel(level, options);
28
+ }
29
+
30
+ async get(
31
+ cid: string,
32
+ options?: {
33
+ raw?: boolean;
34
+ links?: string[];
35
+ timeout?: number;
36
+ hasher?: any;
37
+ }
38
+ ): Promise<Uint8Array | undefined> {
39
+ const cidObject = cidifyString(cid);
40
+ try {
41
+ const bytes = await this._level.get(cid);
42
+ if (!bytes) {
43
+ return undefined;
44
+ }
45
+ const codec = codecCodes[cidObject.code];
46
+ const block = await Block.decode({
47
+ bytes,
48
+ codec,
49
+ hasher: options?.hasher || defaultHasher,
50
+ });
51
+ return (block as Block.Block<Uint8Array, any, any, any>).bytes;
52
+ } catch (error: any) {
53
+ if (
54
+ typeof error?.code === "string" &&
55
+ error?.code?.indexOf("LEVEL_NOT_FOUND") !== -1
56
+ ) {
57
+ return undefined;
58
+ }
59
+ throw error;
60
+ }
61
+ }
62
+
63
+ async put(bytes: Uint8Array, options?: PutOptions): Promise<string> {
64
+ const block = await createBlock(bytes, "raw");
65
+ const cid = stringifyCid(block.cid);
66
+ const bbytes = block.bytes;
67
+ await this._level.put(cid, bbytes);
68
+ return cid;
69
+ }
70
+
71
+ async rm(cid: string): Promise<void> {
72
+ await this._level.del(cid);
73
+ }
74
+
75
+ async has(cid: string) {
76
+ return !!(await this._level.get(cid));
77
+ }
78
+
79
+ async start(): Promise<void> {
80
+ this._closed = false;
81
+ await this._level.open();
82
+
83
+ try {
84
+ this._opening = waitFor(() => this._level.status === "open", {
85
+ delayInterval: 100,
86
+ timeout: 10 * 1000,
87
+ stopperCallback: (fn) => {
88
+ this._onClose = fn;
89
+ },
90
+ });
91
+ await this._opening;
92
+ } finally {
93
+ this._onClose = undefined;
94
+ }
95
+ }
96
+
97
+ async stop(): Promise<void> {
98
+ await this.idle();
99
+ this._closed = true;
100
+ this._onClose && this._onClose();
101
+ return this._level.close();
102
+ }
103
+
104
+ async idle(): Promise<void> {
105
+ await this._level.idle();
106
+ }
107
+
108
+ get status() {
109
+ return this._level.status;
110
+ }
111
+ async waitFor(peer: PeerId | PublicSignKey): Promise<void> {
112
+ return; // Offline storage // TODO ßthis feels off resolving
113
+ }
114
+ }
115
+
116
+ export class MemoryLevelBlockStore extends LevelBlockStore {
117
+ constructor(options?: LazyLevelOptions) {
118
+ super(new MemoryLevel({ valueEncoding: "view" }), options);
119
+ }
120
+ }
package/src/libp2p.ts ADDED
@@ -0,0 +1,223 @@
1
+ import { BlockStore } from "./store.js";
2
+ import { Blocks as IBlocks } from "@peerbit/blocks-interface";
3
+ import {
4
+ stringifyCid,
5
+ cidifyString,
6
+ codecCodes,
7
+ checkDecodeBlock,
8
+ } from "./block.js";
9
+ import { variant, field, serialize, deserialize } from "@dao-xyz/borsh";
10
+ import { CID } from "multiformats/cid";
11
+ import { DataMessage } from "@peerbit/stream-interface";
12
+ import { DirectStream } from "@peerbit/stream";
13
+
14
+ import * as Block from "multiformats/block";
15
+ import { PublicSignKey } from "@peerbit/crypto";
16
+ import { DirectStreamComponents } from "@peerbit/stream";
17
+ import { LevelBlockStore, MemoryLevelBlockStore } from "./level.js";
18
+ import { Level } from "level";
19
+ import { GetOptions, PutOptions } from "@peerbit/blocks-interface";
20
+
21
+ export class BlockMessage {}
22
+
23
+ @variant(0)
24
+ export class BlockRequest extends BlockMessage {
25
+ @field({ type: "string" })
26
+ cid: string;
27
+
28
+ constructor(cid: string) {
29
+ super();
30
+ this.cid = cid;
31
+ }
32
+ }
33
+
34
+ @variant(1)
35
+ export class BlockResponse extends BlockMessage {
36
+ @field({ type: "string" })
37
+ cid: string;
38
+
39
+ @field({ type: Uint8Array })
40
+ bytes: Uint8Array;
41
+
42
+ constructor(cid: string, bytes: Uint8Array) {
43
+ super();
44
+ this.cid = cid;
45
+ this.bytes = bytes;
46
+ }
47
+ }
48
+
49
+ export type DirectBlockComponents = DirectStreamComponents;
50
+ export class DirectBlock extends DirectStream implements IBlocks {
51
+ private _localStore: BlockStore;
52
+ private _responseHandler?: (evt: CustomEvent<DataMessage>) => any;
53
+ private _resolvers: Map<string, (data: Uint8Array) => void>;
54
+ private _readFromPeersPromises: Map<
55
+ string,
56
+ Promise<Block.Block<any, any, any, 1> | undefined> | undefined
57
+ >;
58
+ _open = false;
59
+
60
+ constructor(
61
+ components: DirectBlockComponents,
62
+ options?: {
63
+ directory?: string;
64
+ canRelayMessage?: boolean;
65
+ localTimeout?: number;
66
+ }
67
+ ) {
68
+ super(components, ["direct-block/1.0.0"], {
69
+ emitSelf: false,
70
+ signaturePolicy: "StrictNoSign",
71
+ messageProcessingConcurrency: 10,
72
+ canRelayMessage: options?.canRelayMessage ?? true,
73
+ });
74
+
75
+ const localTimeout = options?.localTimeout || 1000;
76
+ this._localStore =
77
+ options?.directory != null
78
+ ? new LevelBlockStore(new Level(options.directory))
79
+ : new MemoryLevelBlockStore();
80
+ this._resolvers = new Map();
81
+ this._readFromPeersPromises = new Map();
82
+ this._responseHandler = async (evt: CustomEvent<DataMessage>) => {
83
+ if (!evt) {
84
+ return;
85
+ }
86
+ const message = evt.detail;
87
+ try {
88
+ const decoded = deserialize(message.data, BlockMessage);
89
+ if (decoded instanceof BlockRequest && this._localStore) {
90
+ const cid = stringifyCid(decoded.cid);
91
+ const bytes = await this._localStore.get(cid, {
92
+ timeout: localTimeout,
93
+ });
94
+ if (!bytes) {
95
+ return;
96
+ }
97
+ const response = serialize(new BlockResponse(cid, bytes));
98
+ await this.publish(response);
99
+ } else if (decoded instanceof BlockResponse) {
100
+ // TODO make sure we are not storing too much bytes in ram (like filter large blocks)
101
+
102
+ this._resolvers.get(decoded.cid)?.(decoded.bytes);
103
+ }
104
+ } catch (error) {
105
+ console.error("Got error for libp2p block transport: ", error);
106
+ return; // timeout o r invalid cid
107
+ }
108
+ };
109
+ }
110
+
111
+ async put(
112
+ bytes: Uint8Array,
113
+ options?: PutOptions | undefined
114
+ ): Promise<string> {
115
+ if (!this._localStore) {
116
+ throw new Error("Local store not set");
117
+ }
118
+ return this._localStore!.put(bytes, options);
119
+ }
120
+
121
+ async has(cid: string) {
122
+ return this._localStore.has(cid);
123
+ }
124
+ async get(
125
+ cid: string,
126
+ options?: GetOptions | undefined
127
+ ): Promise<Uint8Array | undefined> {
128
+ const cidObject = cidifyString(cid);
129
+ let value = this._localStore
130
+ ? await this._localStore.get(cid, options)
131
+ : undefined;
132
+
133
+ if (!value) {
134
+ // try to get it remotelly
135
+ value = await this._readFromPeers(cid, cidObject, options);
136
+ if (options?.replicate && value) {
137
+ this._localStore!.put(value, options);
138
+ }
139
+ }
140
+ return value;
141
+ }
142
+
143
+ async rm(cid: string) {
144
+ this._localStore?.rm(cid);
145
+ }
146
+
147
+ async start(): Promise<void> {
148
+ await this._localStore?.start();
149
+ await super.start();
150
+ this.addEventListener("data", this._responseHandler!);
151
+ this._open = true;
152
+ }
153
+
154
+ private async _readFromPeers(
155
+ cidString: string,
156
+ cidObject: CID,
157
+ options: { timeout?: number; hasher?: any } = {}
158
+ ): Promise<Uint8Array | undefined> {
159
+ const codec = codecCodes[cidObject.code];
160
+ let promise = this._readFromPeersPromises.get(cidString);
161
+ if (!promise) {
162
+ promise = new Promise<Block.Block<any, any, any, 1> | undefined>(
163
+ (resolve, reject) => {
164
+ const timeoutCallback = setTimeout(() => {
165
+ resolve(undefined);
166
+ }, options.timeout || 30 * 1000);
167
+
168
+ this._resolvers.set(cidString, async (bytes: Uint8Array) => {
169
+ const value = await checkDecodeBlock(cidObject, bytes, {
170
+ codec,
171
+ hasher: options?.hasher,
172
+ });
173
+
174
+ clearTimeout(timeoutCallback);
175
+ this._resolvers.delete(cidString); // TODO concurrency might not work as expected here
176
+ resolve(value);
177
+ });
178
+ }
179
+ );
180
+ const publish = (to?: PublicSignKey[]) =>
181
+ this.publish(serialize(new BlockRequest(cidString)), { to: to });
182
+ await publish();
183
+
184
+ const publishOnNewPeers = (e: CustomEvent<PublicSignKey>) => {
185
+ return publish([e.detail]);
186
+ };
187
+
188
+ this._readFromPeersPromises.set(cidString, promise);
189
+
190
+ // we want to make sure that if some new peers join, we also try to ask them
191
+ this.addEventListener("peer:reachable", publishOnNewPeers);
192
+
193
+ const result = await promise;
194
+ this._readFromPeersPromises.delete(cidString);
195
+
196
+ // stop asking new peers, because we already got an response
197
+ this.removeEventListener("peer:reachable", publishOnNewPeers);
198
+ return result?.bytes;
199
+ } else {
200
+ const result = await promise;
201
+ return result?.bytes;
202
+ }
203
+ }
204
+
205
+ async stop(): Promise<void> {
206
+ await super.stop();
207
+ this.removeEventListener("data", this._responseHandler);
208
+ await this._localStore?.stop();
209
+ this._readFromPeersPromises.clear();
210
+ this._resolvers.clear();
211
+ this._open = false;
212
+
213
+ // we dont cleanup subscription because we dont know if someone else is sbuscribing also
214
+ }
215
+
216
+ get status() {
217
+ if (this._open) {
218
+ return this._localStore?.status || this.started;
219
+ } else {
220
+ return "closed";
221
+ }
222
+ }
223
+ }
package/src/store.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { Blocks as IBlockStore } from "@peerbit/blocks-interface";
2
+
3
+ export type StoreStatus = "open" | "opening" | "closed" | "closing";
4
+ export interface BlockStore extends IBlockStore {
5
+ start(): Promise<void>;
6
+ stop(): Promise<void>;
7
+ get status(): StoreStatus;
8
+ }
package/src/streams.ts ADDED
@@ -0,0 +1 @@
1
+ export const x = 123;