-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
393 lines (324 loc) · 8.58 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import { unixfs } from "@helia/unixfs";
import { peerIdFromString } from "@libp2p/peer-id";
import { fileTypeFromBuffer } from "file-type";
import { CID } from "multiformats/cid";
import path from "node:path";
import express from "express";
import { fileURLToPath } from "url";
import multer from "multer";
import { multiaddr } from "@multiformats/multiaddr";
import { autoPeeringHandler } from "./cron.js";
import { helia } from "./helia.js";
const storage = multer.memoryStorage();
const upload = multer({ storage });
// console.log("Created Helia instance");
// await helia.libp2p.services.dht.setMode("server");
// console.log("Switched DHT to server mode");
helia.libp2p.getMultiaddrs().forEach((addr) => {
console.log(`Listening on ${addr.toString()}`);
// @todo
// cron.autoPeering.start()
});
helia.libp2p.addEventListener("peer:discovery", (evt) => {
const peer = evt.detail;
if (logNewPeers) {
console.log("Discovered peer:", peer.id);
}
});
let logNewPeers = false;
helia.libp2p.addEventListener("peer:connect", (evt) => {
const peerId = evt.detail;
if (logNewPeers) {
console.log("Peer connected:", peerId);
}
});
helia.libp2p.addEventListener("peer:disconnect", (evt) => {
const peerId = evt.detail;
if (logNewPeers) {
console.log("Peer disconnected:", peerId);
}
});
helia.libp2p.addEventListener("start", (event) => {
console.info("Libp2p node started");
});
helia.libp2p.addEventListener("stop", (event) => {
console.info("Libp2p node stopped");
});
const ifs = unixfs(helia);
console.info(`Helia is running! PeerID: ${helia.libp2p.peerId.toString()}`);
// const cid = await ifs.addFile({
// path: "/hello.txt",
// content: readFileSync("./files/hello.txt"),
// });
//
// console.log("CID", cid);
const PORT = 4000;
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.get("/routing/findProviders/:cid", async (req, res) => {
try {
const cid = CID.parse(req.params.cid);
const providers = [];
for await (const provider of helia.routing.findProviders(cid)) {
console.log(
`Found provider of CID:${cid.toString()}, PeerId:${provider.id.toString()}`,
);
providers.push(provider.id.toString());
}
res.send({
providers,
});
} catch (err) {
res.send({
error: err.message,
});
console.error(err);
}
});
app.get("/cron/autopeering", async (req, res) => {
const successPeers = await autoPeeringHandler();
res.send({
peeredSuccessfullyTo: successPeers,
});
});
app.get("/libp2p/services/ping", async (req, res) => {
try {
const peerId = peerIdFromString(req.query.peerId);
const pong = await helia.libp2p.services.ping.ping(peerId);
res.send({
pong,
});
} catch (err) {
res.send({
error: err.message,
});
}
});
app.get("/libp2p/peerStore", async (req, res) => {
const peerId = req.query.peerId;
try {
const peers = await helia.libp2p.peerStore.all({
filters: [
(peer) => {
if (!peerId) {
return true;
}
return peer.id.toString() === peerId;
},
],
limit: 10,
});
res.send({
length: peers.length,
peers: peers.map((peer) => {
return {
id: peer.id.toString(),
};
}),
});
} catch (err) {
res.send({
error: err.message,
});
}
});
app.get("/libp2p/peerInfo", async (req, res) => {
const peerId = req.query.peerId;
try {
const peers = await helia.libp2p.peerStore.all({
filters: [(peer) => peer.id.toString() === peerId],
limit: 10,
});
res.send({
length: peers.length,
peer: peers,
});
} catch (err) {
res.send({
error: err.message,
});
}
});
app.get("/libp2p/dial", async (req, res) => {
let peerId;
let multiAddr;
try {
if (req.query.peerId) {
peerId = peerIdFromString(req.query.peerId);
}
if (req.query.multiAddr) {
multiAddr = multiaddr(req.query.multiAddr);
}
} catch (err) {
console.log("Invalid peer ID:", err.message);
res.send({
success: false,
error: "Invalid peer ID",
});
return;
}
if (multiAddr) {
console.log(`Peering by multiaddress: ${multiAddr}`);
} else if (peerId) {
console.log(`Peering by PeerID: ${peerId}`);
}
try {
const connection = await helia.libp2p.dial(multiAddr || peerId);
res.send({ success: true, connection });
} catch (err) {
console.log("Cannot dial peer", err.message);
res.send({
success: false,
error: err.message,
});
console.log(err);
}
});
app.get("/libp2p/new-peers/log", async (req, res) => {
logNewPeers = !logNewPeers;
res.send({
logNewPeers,
});
});
app.get("/libp2p/connections", async (req, res) => {
const peerId = req.query.peerId;
const connections = helia.libp2p.getConnections(
peerId ? peerIdFromString(peerId) : undefined,
);
res.send({
length: connections.length,
connections,
});
});
app.get("/libp2p/status", async (req, res) => {
res.send({
status: helia.libp2p.status,
});
});
app.get("/file/:cid", async (req, res) => {
const cid = CID.parse(req.params.cid);
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Operation timed out")), 30000),
);
try {
const filePromise = (async () => {
const file = ifs.cat(cid);
const chunks = [];
for await (const chunk of file) {
chunks.push(chunk);
}
return Buffer.concat(chunks);
})();
const result = await Promise.race([filePromise, timeoutPromise]);
// If filePromise wins the race, send the file
const fileType = await fileTypeFromBuffer(result);
if (fileType) {
res.set("Content-Type", fileType.mime);
}
res.send(result);
} catch (error) {
console.error(error);
if (error.message === "Operation timed out") {
res.status(408).send({
error: "Can not find requested CID. Operation timed out.",
});
} else {
res.status(500).send({
error: "Internal Server Error. Check the logs for details.",
});
}
}
});
app.get("/pins", async (req, res) => {
const pins = [];
for await (const pin of helia.pins.ls()) {
console.log("PIN LS", pin);
pins.push(pin);
}
res.send({
pins,
});
});
app.post("/pins/pin/:cid", async (req, res) => {
const cid = CID.parse(req.params.cid);
try {
for await (const pin of helia.pins.add(cid)) {
console.log("PINNED", pin);
}
} catch (err) {
console.error("Error:", err.message);
res.statusCode = 500;
return res.send({
error: err.message,
});
}
res.send({
pinned: true,
cid: cid.toString(),
});
});
app.get("/pins/isPinned/:cid", async (req, res) => {
const cid = CID.parse(req.params.cid);
const isPinned = await helia.pins.isPinned(cid);
res.send({
cid: cid.toString(),
isPinned,
});
});
app.post("/file/upload", upload.array("files", 5), async (req, res) => {
if (!req.files) {
res.statusCode = 400;
return res.send({
error: "No file uploaded",
});
}
console.log("req.files", req.files);
const cids = [];
for (const file of req.files) {
console.log(`Adding ${file.originalname} to IPFS`);
const { buffer, originalname } = file;
const cid = await ifs.addFile({
path: `/${originalname}`,
content: buffer,
});
console.log("Successfully added file", cid.toString());
cids.push(cid);
const isPinned = await helia.pins.isPinned(cid);
if (isPinned) {
console.log("File already pinned", cid.toString());
} else {
// Pin the file
for await (const pinned of helia.pins.add(cid)) {
console.log("Filed pinned", pinned);
}
}
// Tell the network we can provide content for the passed CID
await helia.libp2p.services.dht.provide(cid);
console.log("Provided CID via DHT", cid.toString());
console.log(`Routing: Providing ${cid}`);
void helia.routing.provide(cid);
console.log("Routing: Provide DONE");
}
res.send({
filesNames: req.files.map((file) => file.originalname),
cids: cids.map((cid) => cid.toString()),
});
});
app.post("/test", async (req, res) => {
const textEncoder = new TextEncoder();
const cid = await ifs.addFile({
content: textEncoder.encode("Hello world asldgfhkasjdghsk;adjflkasgjd!"),
});
// @ts-ignore
for await (const event of helia.libp2p.services.dht.provide(cid)) {
console.log("PROVIDE", event);
}
res.send({
cid: cid.toString(),
});
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});