relay-plugin-handshake/src/index.ts

93 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-12-07 09:24:42 +00:00
import type { Plugin, PluginAPI } from "@lumeweb/relay-types";
2022-08-28 17:07:45 +00:00
// @ts-ignore
import rand from "random-key";
// @ts-ignore
import FullNode from "hsd/lib/node/fullnode.js";
import { Proxy, Socket } from "@lumeweb/libhyperproxy";
2022-08-28 17:07:45 +00:00
let server: FullNode;
let api: PluginAPI;
const PROTOCOL = "lumeweb.proxy.handshake";
async function abort(err: any) {
const timeout = setTimeout(() => {
api.logger.error("Shutdown is taking a long time. Exiting.");
process.exit(3);
}, 5000);
timeout.unref();
2022-08-28 17:07:45 +00:00
try {
api.logger.error("Shutting down...");
await server.close();
clearTimeout(timeout);
api.logger.error((err as Error).stack);
process.exit(2);
} catch (e: any) {
api.logger.error(`Error occurred during shutdown: ${(e as Error).message}`);
process.exit(3);
}
}
async function boot(api: PluginAPI) {
const { pluginConfig: config } = api;
2022-12-07 09:27:19 +00:00
const apiKey = rand.generate();
2022-08-28 17:07:45 +00:00
if (!config.bool("external")) {
server = new FullNode({
2022-08-28 17:07:45 +00:00
config: false,
argv: false,
env: true,
noDns: false,
2022-08-28 17:07:45 +00:00
memory: false,
httpHost: "127.0.0.1",
apiKey,
logFile: true,
2022-08-28 17:07:45 +00:00
logConsole: true,
logLevel: "info",
2023-02-06 17:25:20 +00:00
workers: false,
2022-08-28 17:07:45 +00:00
network: "main",
bip37: true,
2022-08-28 17:07:45 +00:00
});
server.on("abort", abort);
2022-08-28 17:07:45 +00:00
api.logger.info("API Key %s", apiKey);
2022-08-28 17:07:45 +00:00
try {
await server.ensure();
await server.open();
await server.connect();
2022-08-28 17:07:45 +00:00
server.startSync();
} catch (e: any) {
api.logger.error((e as Error).stack);
}
2022-08-28 17:07:45 +00:00
}
}
const plugin: Plugin = {
name: "handshake",
async plugin(_api: PluginAPI): Promise<void> {
api = _api;
2023-02-18 14:55:23 +00:00
boot(api);
const proxy = new Proxy({
swarm: api.swarm,
protocol: PROTOCOL,
});
api.swarm.join(api.util.crypto.createHash(PROTOCOL));
api.protocols.register(PROTOCOL, (peer: any, muxer: any) => {
proxy.handlePeer({
peer,
muxer,
onopen(socket: Socket) {
server.pool.server.emit("connection", socket);
},
});
2022-08-28 17:07:45 +00:00
});
},
};
export default plugin;