All files / lib PeerServer.ts

100% Statements 20/20
100% Branches 0/0
100% Functions 5/5
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52      1x 1x   1x   1x       1x 1x 1x 1x 1x 1x   1x 1x 1x                 1x             1x               1x 1x 1x 1x      
import { BitField } from "@node-lightning/core";
import { ILogger } from "@node-lightning/logger";
import { NoiseSocket } from "@node-lightning/noise";
import { NoiseServer } from "@node-lightning/noise";
import { EventEmitter } from "events";
import { InitFeatureFlags } from "./flags/InitFeatureFlags";
import { Peer } from "./Peer";
 
export class PeerServer extends EventEmitter {
    protected _server: NoiseServer;
 
    constructor(
        readonly host: string,
        readonly port: number,
        readonly localSecret: Buffer,
        readonly localFeatures: BitField<InitFeatureFlags>,
        readonly localChains: Buffer[],
        readonly logger: ILogger,
    ) {
        super();
        this._server = new NoiseServer({ ls: localSecret }, this._onSocket.bind(this));
        this._server.on("listening", () => this.emit("listening"));
    }
 
    /**
     * Starts the peer manager listening
     * @param host
     * @param port
     */
    public listen() {
        this._server.listen({ host: this.host, port: this.port });
    }
 
    /**
     * Shuts down the server
     */
    public shutdown() {
        this._server.close();
    }
 
    /**
     * Handles when a socket connects to us
     * @param socket
     */
    protected _onSocket(socket: NoiseSocket) {
        this.logger.info("peer connected");
        const peer = new Peer(this.localSecret, this.localFeatures, this.localChains, this.logger);
        peer.attach(socket);
        this.emit("peer", peer);
    }
}