From 523f2c04f05283b9915c3cbf405e8dab6106ec77 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Thu, 5 Jan 2023 20:51:43 -0500 Subject: [PATCH] *Add new core dht plugin that allows joining a DHT topic and getting the peers of a given topic --- src/modules/plugin.ts | 2 ++ src/modules/plugins/dht.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 src/modules/plugins/dht.ts diff --git a/src/modules/plugin.ts b/src/modules/plugin.ts index ac45d55..547d5c7 100644 --- a/src/modules/plugin.ts +++ b/src/modules/plugin.ts @@ -10,6 +10,7 @@ import type { Logger } from "pino"; import { getHDKey, getSeed } from "../lib/seed.js"; import pluginRpc from "./plugins/rpc"; import pluginCore from "./plugins/core"; +import pluginDht from "./plugins/dht"; import type Config from "@lumeweb/cfg"; import EventEmitter2 from "eventemitter2"; import log from "../log.js"; @@ -229,6 +230,7 @@ export async function loadPlugins() { apiManager.loadPluginInstance(pluginCore); apiManager.loadPluginInstance(pluginRpc); + apiManager.loadPluginInstance(pluginDht); for (const plugin of [...new Set(config.array("plugins", []))] as []) { await apiManager.loadPlugin(plugin); diff --git a/src/modules/plugins/dht.ts b/src/modules/plugins/dht.ts new file mode 100644 index 0000000..2bd671a --- /dev/null +++ b/src/modules/plugins/dht.ts @@ -0,0 +1,27 @@ +import { Plugin, PluginAPI } from "@lumeweb/relay-types"; +import { getRpcServer } from "../rpc/server"; +import b4a from "b4a"; + +const plugin: Plugin = { + name: "dht", + async plugin(api: PluginAPI): Promise { + api.registerMethod("join_topic", { + cacheable: false, + async handler(topic: string): Promise { + if (!api.swarm._discovery.has(topic)) { + api.swarm.join(topic); + } + }, + }); + api.registerMethod("get_topic_peers", { + cacheable: false, + async handler(topic: string): Promise { + return [...api.swarm.peers.values()] + .filter((peerInfo) => peerInfo._seenTopics.has(topic)) + .map((peerInfo) => b4a.from(peerInfo.publicKey).toString()); + }, + }); + }, +}; + +export default plugin;