Skip to content

Commit 308607f

Browse files
authored
chore: moved utilities from js-libp2p-floodsub
Transferred utilities from js-libp2p-floodsub
2 parents 5ef5a35 + b654c37 commit 308607f

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,11 @@
5656
},
5757
"dependencies": {
5858
"async": "^2.6.2",
59+
"bs58": "^4.0.1",
5960
"debug": "^4.1.1",
6061
"err-code": "^1.1.2",
6162
"length-prefixed-stream": "^2.0.0",
63+
"libp2p-crypto": "~0.16.1",
6264
"protons": "^1.0.1",
6365
"pull-length-prefixed": "^1.3.1",
6466
"pull-pushable": "^2.2.0",

src/utils.js

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
'use strict'
2+
3+
const crypto = require('libp2p-crypto')
4+
const bs58 = require('bs58')
5+
6+
exports = module.exports
7+
8+
/**
9+
* Generatea random sequence number.
10+
*
11+
* @returns {Buffer}
12+
* @private
13+
*/
14+
exports.randomSeqno = () => {
15+
return crypto.randomBytes(20)
16+
}
17+
18+
/**
19+
* Generate a message id, based on the `from` and `seqno`.
20+
*
21+
* @param {string} from
22+
* @param {Buffer} seqno
23+
* @returns {string}
24+
* @private
25+
*/
26+
exports.msgId = (from, seqno) => {
27+
return from + seqno.toString('hex')
28+
}
29+
30+
/**
31+
* Check if any member of the first set is also a member
32+
* of the second set.
33+
*
34+
* @param {Set|Array} a
35+
* @param {Set|Array} b
36+
* @returns {boolean}
37+
* @private
38+
*/
39+
exports.anyMatch = (a, b) => {
40+
let bHas
41+
if (Array.isArray(b)) {
42+
bHas = (val) => b.indexOf(val) > -1
43+
} else {
44+
bHas = (val) => b.has(val)
45+
}
46+
47+
for (let val of a) {
48+
if (bHas(val)) {
49+
return true
50+
}
51+
}
52+
53+
return false
54+
}
55+
56+
/**
57+
* Make everything an array.
58+
*
59+
* @param {any} maybeArray
60+
* @returns {Array}
61+
* @private
62+
*/
63+
exports.ensureArray = (maybeArray) => {
64+
if (!Array.isArray(maybeArray)) {
65+
return [maybeArray]
66+
}
67+
68+
return maybeArray
69+
}
70+
71+
exports.normalizeInRpcMessages = (messages) => {
72+
if (!messages) {
73+
return messages
74+
}
75+
return messages.map((msg) => {
76+
const m = Object.assign({}, msg)
77+
if (Buffer.isBuffer(msg.from)) {
78+
m.from = bs58.encode(msg.from)
79+
}
80+
return m
81+
})
82+
}
83+
84+
exports.normalizeOutRpcMessages = (messages) => {
85+
if (!messages) {
86+
return messages
87+
}
88+
return messages.map((msg) => {
89+
const m = Object.assign({}, msg)
90+
if (typeof msg.from === 'string' || msg.from instanceof String) {
91+
m.from = bs58.decode(msg.from)
92+
}
93+
return m
94+
})
95+
}

0 commit comments

Comments
 (0)