relay/src/modules/swarm.ts

59 lines
1.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";
2022-09-21 12:59:22 +00:00
import config from "../config.js";
import { errorExit } from "../lib/error.js";
2022-09-21 11:13:48 +00:00
import {
deriveMyskyRootKeypair,
seedPhraseToSeed,
validSeedPhrase,
} from "libskynet";
2022-06-27 17:53:00 +00:00
// @ts-ignore
import sodium from "sodium-universal";
import b4a from "b4a";
const LUMEWEB = b4a.from("lumeweb");
export type SecretStream = any;
let node: Hyperswarm;
2022-06-27 17:53:00 +00:00
export function getKeyPair() {
2022-07-22 23:55:09 +00:00
const seed = config.str("seed");
2022-07-05 19:02:07 +00:00
2022-07-22 23:51:11 +00:00
let err = validSeedPhrase(seed);
2022-07-19 22:31:15 +00:00
if (err !== null) {
errorExit("LUME_WEB_RELAY_SEED is invalid. Aborting.");
2022-07-19 22:31:15 +00:00
}
2022-06-27 17:53:00 +00:00
return deriveMyskyRootKeypair(seedPhraseToSeed(seed)[0]);
}
async function start() {
const keyPair = getKeyPair();
2022-06-27 17:53:00 +00:00
node = new Hyperswarm({ keyPair, dht: new DHT({ keyPair }) });
const topic = b4a.allocUnsafe(32);
sodium.crypto_generichash(topic, LUMEWEB);
2022-06-27 17:53:00 +00:00
// @ts-ignore
await node.dht.ready();
await node.listen();
node.join(topic);
2022-07-19 22:31:15 +00:00
return node;
2022-06-27 17:53:00 +00:00
}
export async function get(): Promise<Hyperswarm> {
2022-07-19 22:31:15 +00:00
if (!node) {
await start();
}
2022-07-19 22:31:15 +00:00
return node;
2022-06-27 17:53:00 +00:00
}