Skip to content

Commit

Permalink
chore: moved utilities from js-libp2p-floodsub
Browse files Browse the repository at this point in the history
Transferred utilities from js-libp2p-floodsub
  • Loading branch information
vasco-santos authored Apr 17, 2019
2 parents 5ef5a35 + b654c37 commit 308607f
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,11 @@
},
"dependencies": {
"async": "^2.6.2",
"bs58": "^4.0.1",
"debug": "^4.1.1",
"err-code": "^1.1.2",
"length-prefixed-stream": "^2.0.0",
"libp2p-crypto": "~0.16.1",
"protons": "^1.0.1",
"pull-length-prefixed": "^1.3.1",
"pull-pushable": "^2.2.0",
Expand Down
95 changes: 95 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
'use strict'

const crypto = require('libp2p-crypto')
const bs58 = require('bs58')

exports = module.exports

/**
* Generatea random sequence number.
*
* @returns {Buffer}
* @private
*/
exports.randomSeqno = () => {
return crypto.randomBytes(20)
}

/**
* Generate a message id, based on the `from` and `seqno`.
*
* @param {string} from
* @param {Buffer} seqno
* @returns {string}
* @private
*/
exports.msgId = (from, seqno) => {
return from + seqno.toString('hex')
}

/**
* Check if any member of the first set is also a member
* of the second set.
*
* @param {Set|Array} a
* @param {Set|Array} b
* @returns {boolean}
* @private
*/
exports.anyMatch = (a, b) => {
let bHas
if (Array.isArray(b)) {
bHas = (val) => b.indexOf(val) > -1
} else {
bHas = (val) => b.has(val)
}

for (let val of a) {
if (bHas(val)) {
return true
}
}

return false
}

/**
* Make everything an array.
*
* @param {any} maybeArray
* @returns {Array}
* @private
*/
exports.ensureArray = (maybeArray) => {
if (!Array.isArray(maybeArray)) {
return [maybeArray]
}

return maybeArray
}

exports.normalizeInRpcMessages = (messages) => {
if (!messages) {
return messages
}
return messages.map((msg) => {
const m = Object.assign({}, msg)
if (Buffer.isBuffer(msg.from)) {
m.from = bs58.encode(msg.from)
}
return m
})
}

exports.normalizeOutRpcMessages = (messages) => {
if (!messages) {
return messages
}
return messages.map((msg) => {
const m = Object.assign({}, msg)
if (typeof msg.from === 'string' || msg.from instanceof String) {
m.from = bs58.decode(msg.from)
}
return m
})
}

0 comments on commit 308607f

Please sign in to comment.