All files / lib graph.ts

100% Statements 24/24
100% Branches 4/4
100% Functions 6/6
100% Lines 22/22

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84    1x           1x       23x         23x         23x           34x             17x 17x 17x 16x     15x 15x     15x     15x             65x             17x             4x 4x 4x     4x     4x     4x      
import { ShortChannelId } from "@node-lightning/core";
import { Channel } from "./channel";
import { NodeNotFoundError } from "./graph-error";
import { Node } from "./node";
 
/**
 * Graph represents a
 */
export class Graph {
    /**
     * Map containing all nodes in the system
     */
    public nodes: Map<string, Node> = new Map();
 
    /**
     * Map containing all channels in the graph
     */
    public channels: Map<bigint, Channel> = new Map();
 
    /**
     * The height the graph has been synced through
     */
    public syncHeight: number = 0;
 
    /**
     * Adds a node to the graph
     */
    public addNode(node: Node) {
        this.nodes.set(node.nodeId.toString("hex"), node);
    }
 
    /**
     * Adds a channgel to the graph
     */
    public addChannel(channel: Channel) {
        const node1 = this.getNode(channel.nodeId1);
        const node2 = this.getNode(channel.nodeId2);
        if (!node1) throw new NodeNotFoundError(channel.nodeId1);
        if (!node2) throw new NodeNotFoundError(channel.nodeId2);
 
        // attach channel
        const key = channel.shortChannelId.toNumber();
        this.channels.set(key, channel);
 
        // attach channel to node 1
        node1.linkChannel(channel);
 
        // attach channel to node 2
        node2.linkChannel(channel);
    }
 
    /**
     * Gets a node in the graph
     */
    public getNode(nodeId: Buffer): Node {
        return this.nodes.get(nodeId.toString("hex"));
    }
 
    /**
     * Gets a node in the channel by shortChannelId
     */
    public getChannel(shortChannelId: ShortChannelId) {
        return this.channels.get(shortChannelId.toNumber());
    }
 
    /**
     * Removes the node from the graph
     */
    public removeChannel(channel: Channel) {
        const key = channel.shortChannelId.toNumber();
        const n1 = this.getNode(channel.nodeId1);
        const n2 = this.getNode(channel.nodeId2);
 
        // remove from channels list
        this.channels.delete(key);
 
        // detach from node 1
        n1.unlinkChannel(channel);
 
        // detach from node 2
        n2.unlinkChannel(channel);
    }
}