relay/src/modules/swarm.ts

99 lines
2.2 KiB
TypeScript
Raw Normal View History

//const require = createRequire(import.meta.url);
//import { createRequire } from "module";
// @ts-ignore
import Hyperswarm from "hyperswarm";
// @ts-ignore
import DHT from "@hyperswarm/dht";
// @ts-ignore
import Protomux from "protomux";
2022-06-27 17:53:00 +00:00
// @ts-ignore
import sodium from "sodium-universal";
import b4a from "b4a";
2022-12-19 16:44:11 +00:00
import log from "../log.js";
import { getKeyPair } from "../lib/seed.js";
const LUMEWEB = b4a.from("lumeweb");
export const LUMEWEB_TOPIC_HASH = b4a.allocUnsafe(32);
sodium.crypto_generichash(LUMEWEB_TOPIC_HASH, LUMEWEB);
export type SecretStream = any;
let node: Hyperswarm;
let protocolManager: ProtocolManager;
2022-06-27 17:53:00 +00:00
export async function start() {
const keyPair = getKeyPair();
const bootstrap = DHT.bootstrapper(49737, "0.0.0.0");
await bootstrap.ready();
const address = bootstrap.address();
node = new Hyperswarm({
keyPair,
dht: new DHT({
keyPair,
bootstrap: [{ host: address.host, port: address.port }].concat(
require("@hyperswarm/dht/lib/constants").BOOTSTRAP_NODES
),
}),
});
2022-06-27 17:53:00 +00:00
// @ts-ignore
await node.dht.ready();
await node.listen();
node.join(LUMEWEB_TOPIC_HASH);
2022-12-06 22:03:30 +00:00
log.info(
2022-12-19 19:17:07 +00:00
"Relay Identity is %s",
b4a.from(getKeyPair().publicKey).toString("hex")
2022-12-06 22:03:30 +00:00
);
2022-07-19 22:31:15 +00:00
return node;
2022-06-27 17:53:00 +00:00
}
export function get(): Hyperswarm {
2022-07-19 22:31:15 +00:00
return node;
2022-06-27 17:53:00 +00:00
}
export class ProtocolManager {
private _protocols: Map<string, Function> = new Map<string, Function>();
private _swarm;
constructor(swarm: any) {
this._swarm = swarm;
this._swarm.on("connection", (peer: any) => {
for (const protocol of this._protocols) {
Protomux.from(peer).pair(
protocol[0],
this.handler.bind(this, protocol[0], peer)
);
}
});
}
private handler(protocol: string, peer: any) {
if (this._protocols.has(protocol)) {
this._protocols.get(protocol)?.(peer, Protomux.from(peer));
}
}
public register(name: string, handler: Function): boolean {
if (this._protocols.has(name)) {
return false;
}
this._protocols.set(name, handler);
return true;
}
}
export function getProtocolManager(): ProtocolManager {
if (!protocolManager) {
protocolManager = new ProtocolManager(get());
}
return protocolManager;
}