UNPKG

libp2p-pubsub

Version:
80 lines 2.13 kB
import { randomBytes } from 'iso-random-stream'; import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'; import { PeerId } from 'libp2p-peer-id'; import { sha256 } from 'multiformats/hashes/sha2'; /** * Generate a random sequence number */ export const randomSeqno = () => { return randomBytes(8); }; /** * Generate a message id, based on the `from` and `seqno` */ export const msgId = (from, seqno) => { let fromBytes; if (from instanceof Uint8Array) { fromBytes = PeerId.fromBytes(from).multihash.digest; } else { fromBytes = PeerId.fromString(from).multihash.digest; } const msgId = new Uint8Array(fromBytes.length + seqno.length); msgId.set(fromBytes, 0); msgId.set(seqno, fromBytes.length); return msgId; }; /** * Generate a message id, based on message `data` */ export const noSignMsgId = (data) => sha256.encode(data); /** * Check if any member of the first set is also a member * of the second set */ export const anyMatch = (a, b) => { let bHas; if (Array.isArray(b)) { bHas = (val) => b.includes(val); } else { bHas = (val) => b.has(val); } for (const val of a) { if (bHas(val)) { return true; } } return false; }; /** * Make everything an array */ export const ensureArray = function (maybeArray) { if (!Array.isArray(maybeArray)) { return [maybeArray]; } return maybeArray; }; /** * Ensures `message.from` is base58 encoded */ export const normalizeInRpcMessage = (message, peerId) => { // @ts-expect-error receivedFrom not yet defined const m = Object.assign({}, message); if (peerId != null) { m.receivedFrom = peerId; } return m; }; export const normalizeOutRpcMessage = (message) => { const m = Object.assign({}, message); if (typeof message.from === 'string') { m.from = uint8ArrayFromString(message.from, 'base58btc'); } if (typeof message.data === 'string') { m.data = uint8ArrayFromString(message.data); } return m; }; //# sourceMappingURL=utils.js.map