This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathbitswap.js
72 lines (58 loc) · 1.99 KB
/
bitswap.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
'use strict'
const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR
const callbackify = require('callbackify')
const Big = require('bignumber.js')
const CID = require('cids')
const PeerId = require('peer-id')
const errCode = require('err-code')
function formatWantlist (list, cidBase) {
return Array.from(list).map((e) => ({ '/': e[1].cid.toBaseEncodedString(cidBase) }))
}
module.exports = function bitswap (self) {
return {
wantlist: callbackify.variadic(async (peerId) => { // eslint-disable-line require-await
if (!self.isOnline()) {
throw new Error(OFFLINE_ERROR)
}
let list
if (peerId) {
peerId = PeerId.createFromCID(peerId)
list = self._bitswap.wantlistForPeer(peerId)
} else {
list = self._bitswap.getWantlist()
}
return { Keys: formatWantlist(list) }
}),
stat: callbackify(async () => { // eslint-disable-line require-await
if (!self.isOnline()) {
throw new Error(OFFLINE_ERROR)
}
const snapshot = self._bitswap.stat().snapshot
return {
provideBufLen: parseInt(snapshot.providesBufferLength.toString()),
blocksReceived: new Big(snapshot.blocksReceived),
wantlist: formatWantlist(self._bitswap.getWantlist()),
peers: self._bitswap.peers().map((id) => id.toB58String()),
dupBlksReceived: new Big(snapshot.dupBlksReceived),
dupDataReceived: new Big(snapshot.dupDataReceived),
dataReceived: new Big(snapshot.dataReceived),
blocksSent: new Big(snapshot.blocksSent),
dataSent: new Big(snapshot.dataSent)
}
}),
unwant: callbackify(async (keys) => { // eslint-disable-line require-await
if (!self.isOnline()) {
throw new Error(OFFLINE_ERROR)
}
if (!Array.isArray(keys)) {
keys = [keys]
}
try {
keys = keys.map((key) => new CID(key))
} catch (err) {
throw errCode(err, 'ERR_INVALID_CID')
}
return self._bitswap.unwant(keys)
})
}
}