@waku/core
Version:
TypeScript implementation of the Waku v2 protocol
70 lines • 2.57 kB
JavaScript
import { contentTopicToShardIndex, decodeRelayShard, Logger, pubsubTopicToSingleShardInfo } from "@waku/utils";
const log = new Logger("shard-reader");
/**
* This class is responsible for reading the shard info from the libp2p peer store or from the current node's network config.
*/
export class ShardReader {
libp2p;
staticShard;
constructor(options) {
this.libp2p = options.libp2p;
this.staticShard = this.getStaticShardFromNetworkConfig(options.networkConfig);
}
async isPeerOnNetwork(id) {
const shardInfo = await this.getShardInfo(id);
if (!shardInfo) {
return false;
}
const clusterMatch = shardInfo.clusterId === this.staticShard.clusterId;
const shardOverlap = this.staticShard.shards.some((s) => shardInfo.shards.includes(s));
return clusterMatch && shardOverlap;
}
async hasShardInfo(id) {
const shardInfo = await this.getShardInfo(id);
return !!shardInfo;
}
async isPeerOnTopic(id, pubsubTopic) {
try {
const shardInfo = pubsubTopicToSingleShardInfo(pubsubTopic);
return await this.isPeerOnShard(id, shardInfo);
}
catch (error) {
log.error(`Error comparing pubsub topic ${pubsubTopic} with shard info for ${id}`, error);
return false;
}
}
async isPeerOnShard(id, shard) {
const peerShardInfo = await this.getShardInfo(id);
if (!peerShardInfo || shard.shard === undefined) {
return false;
}
return (peerShardInfo.clusterId === shard.clusterId &&
peerShardInfo.shards.includes(shard.shard));
}
async getShardInfo(id) {
try {
const peer = await this.libp2p.peerStore.get(id);
const shardInfoBytes = peer.metadata.get("shardInfo");
if (!shardInfoBytes) {
return undefined;
}
const decodedShardInfo = decodeRelayShard(shardInfoBytes);
return decodedShardInfo;
}
catch (error) {
log.error(`Error getting shard info for ${id}`, error);
return undefined;
}
}
getStaticShardFromNetworkConfig(networkConfig) {
if ("shards" in networkConfig) {
return networkConfig;
}
const shards = networkConfig.contentTopics.map((topic) => contentTopicToShardIndex(topic));
return {
clusterId: networkConfig.clusterId,
shards
};
}
}
//# sourceMappingURL=shard_reader.js.map