|
| 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