All files / lib/gossip-old GossipFilter.ts

54.17% Statements 52/96
43.14% Branches 22/51
90% Functions 9/10
55.43% Lines 51/92

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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 2651x 1x 1x 1x   1x 1x 1x 1x       1x   1x       9x     10x     10x                                         1x   2x 2x 2x                   10x   2x   4x   4x                           4x     4x     4x 4x           4x 1x       3x     3x                     2x       2x                 2x         2x       2x                                                                                                   2x     2x     2x       2x 4x                       2x       2x 4x               2x                                 4x 4x           4x       4x         4x 4x         4x     4x      
import { HashValue, OutPoint } from "@node-lightning/core";
import { ChannelAnnouncementMessage } from "../messages/ChannelAnnouncementMessage";
import { ChannelUpdateMessage } from "../messages/ChannelUpdateMessage";
import { ExtendedChannelAnnouncementMessage } from "../messages/ExtendedChannelAnnouncementMessage";
import { IWireMessage } from "../messages/IWireMessage";
import { NodeAnnouncementMessage } from "../messages/NodeAnnouncementMessage";
import { MessageType } from "../MessageType";
import { fundingScript } from "../ScriptUtils";
import { WireError, WireErrorCode } from "../WireError";
import { IGossipStore } from "./GossipStore";
import { IGossipFilterChainClient } from "./IGossipFilterChainClient";
 
export class Result<V, E> {
    public static err<V, E>(error: E) {
        return new Result<V, E>(undefined, error);
    }
 
    public static ok<V, E>(value: V) {
        return new Result<V, E>(value);
    }
 
    constructor(readonly value?: V, readonly error?: E) {}
 
    public get isOk(): boolean {
        return this.value !== undefined;
    }
 
    public get isErr(): boolean {
        return this.error !== undefined;
    }
}
 
export type GossipFilterResult = Result<IWireMessage[], WireError>;
 
/**
 * GossipFilter recieves messages from peers and performs validation
 * on the messages to ensure that they are valid messages. These validation
 * follow messaging rules defined in Bolt #7 and include things like
 * signature checks, on-chain validation, and message sequencing requirements.
 * Successful message validation results in messages being written to an
 * instance of IGossipStore and returned as results
 *
 * The GossipFilter will also store pending messages, such as channel_update
 * message arriving before the channel_announcement.
 */
export class GossipFilter {
    constructor(
        readonly gossipStore: IGossipStore,
        readonly pendingStore: IGossipStore,
        readonly chainClient?: IGossipFilterChainClient,
    ) {}
 
    /**
     * Validates a message and writes it to the appropriate store.
     * A fully processed messages (or releated messages) will be
     * returned when a message is successfully processed.
     *
     */
    public async validateMessage(msg: IWireMessage): Promise<GossipFilterResult> {
        switch (msg.type) {
            case MessageType.ChannelAnnouncement:
                return await this._validateChannelAnnouncement(msg as ChannelAnnouncementMessage);
            case MessageType.NodeAnnouncement:
                return await this._validateNodeAnnouncement(msg as NodeAnnouncementMessage);
            case MessageType.ChannelUpdate:
                return await this._validateChannelUpdate(msg as ChannelUpdateMessage);
        }
        return Result.ok([] as IWireMessage[]);
    }
 
    /**
     * Validate a node announcement message by checking to see if the
     * message is newer than the prior timestamp and if the message
     * has a valid signature from the corresponding node
     */
    private async _validateNodeAnnouncement(
        msg: NodeAnnouncementMessage,
    ): Promise<GossipFilterResult> {
        // get or construct a node
        const existing = await this.gossipStore.findNodeAnnouncement(msg.nodeId);
 
        // check if the message is newer than the last update
        Iif (existing && existing.timestamp >= msg.timestamp) return Result.ok([] as IWireMessage[]);
 
        // queue node if we don't have any channels
        const scids = await this.gossipStore.findChannelsForNode(msg.nodeId);
        Iif (!scids.length) {
            await this.pendingStore.saveNodeAnnouncement(msg);
            return Result.ok([] as IWireMessage[]);
        }
 
        // validate message signature
        if (!NodeAnnouncementMessage.verifySignatures(msg)) {
            return Result.err(new WireError(WireErrorCode.nodeAnnSigFailed, [msg]));
        }
 
        // save the announcement
        await this.gossipStore.saveNodeAnnouncement(msg);
 
        // broadcast valid message
        return Result.ok([msg]);
    }
 
    /**
     * Validates a ChannelAnnouncementMessage by verifying the signatures
     * and validating the transaction on chain work. This message will
     */
    private async _validateChannelAnnouncement(
        msg: ChannelAnnouncementMessage,
    ): Promise<GossipFilterResult> {
        // attempt to find the existing chan_ann message
        const existing = await this.gossipStore.findChannelAnnouncement(msg.shortChannelId);
 
        // If the message is an extended message and it has populated the outpoint and capacity we
        // can skip message processing becuase there is nothing left to do.
        Iif (existing && existing instanceof ExtendedChannelAnnouncementMessage) {
            return Result.ok([] as IWireMessage[]);
        }
 
        // If there is an existing message and we don't have a chain_client then we want
        // to abort processing to prevent from populating the gossip store with chan_ann
        // messages that do not have a extended information. Alterntaively, if we DO have an
        // an existing message that is just a chan_ann and not ext_chan_ann and there is a
        // chain_client, we want to update the chan_ann with onchain information
        Iif (existing && !this.chainClient) {
            return Result.ok([] as IWireMessage[]);
        }
 
        // validate signatures for message
        Iif (!ChannelAnnouncementMessage.verifySignatures(msg)) {
            return Result.err(new WireError(WireErrorCode.chanAnnSigFailed, [msg]));
        }
 
        Iif (this.chainClient) {
            // load the block hash for the block height
            const blockHash = await this.chainClient.getBlockHash(msg.shortChannelId.block);
            if (!blockHash) {
                return Result.err(new WireError(WireErrorCode.chanBadBlockHash, [msg]));
            }
 
            // load the block details so we can find the tx
            const block = await this.chainClient.getBlock(blockHash);
            if (!block) {
                return Result.err(new WireError(WireErrorCode.chanBadBlock, [msg, blockHash]));
            }
 
            // load the txid from the block details
            const txId = block.tx[msg.shortChannelId.txIdx];
            if (!txId) {
                return Result.err(new WireError(WireErrorCode.chanAnnBadTx, [msg]));
            }
 
            // obtain a UTXO to verify the tx hasn't been spent yet
            const utxo = await this.chainClient.getUtxo(txId, msg.shortChannelId.voutIdx);
            if (!utxo) {
                return Result.err(new WireError(WireErrorCode.chanUtxoSpent, [msg]));
            }
 
            // verify the tx script is a p2ms
            const expectedScript = fundingScript([msg.bitcoinKey1, msg.bitcoinKey2]);
            const actualScript = Buffer.from(utxo.scriptPubKey.hex, "hex");
            if (!expectedScript.equals(actualScript)) {
                return Result.err(
                    new WireError(WireErrorCode.chanBadScript, [msg, expectedScript, actualScript]),
                );
            }
 
            // construct outpoint
            const outpoint = new OutPoint(HashValue.fromRpc(txId), msg.shortChannelId.voutIdx);
 
            // calculate capacity in satoshi
            // Not sure about this code. MAX_SAFE_INTEGER is still safe
            // for Bitcoin satoshi.
            const capacity = BigInt(Math.round(utxo.value * 10 ** 8));
 
            // overright msg with extended channel_announcement
            const extended = ExtendedChannelAnnouncementMessage.fromMessage(msg);
            extended.outpoint = outpoint;
            extended.capacity = capacity;
            msg = extended;
        }
 
        // save channel_ann
        await this.gossipStore.saveChannelAnnouncement(msg);
 
        // broadcast valid message
        const results: IWireMessage[] = [msg];
 
        // process outstanding node messages
        const pendingUpdates = [
            await this.pendingStore.findChannelUpdate(msg.shortChannelId, 0),
            await this.pendingStore.findChannelUpdate(msg.shortChannelId, 1),
        ];
        for (const pendingUpdate of pendingUpdates) {
            Iif (pendingUpdate) {
                await this.pendingStore.deleteChannelUpdate(
                    pendingUpdate.shortChannelId,
                    pendingUpdate.direction,
                );
                const result = await this._validateChannelUpdate(pendingUpdate);
                if (result.isErr) return result;
                else results.push(...result.value);
            }
        }
 
        // process outstanding node messages
        const pendingNodeAnns = [
            await this.pendingStore.findNodeAnnouncement(msg.nodeId1),
            await this.pendingStore.findNodeAnnouncement(msg.nodeId2),
        ];
        for (const pendingNodeAnn of pendingNodeAnns) {
            Iif (pendingNodeAnn) {
                await this.pendingStore.deleteNodeAnnouncement(pendingNodeAnn.nodeId);
                const result = await this._validateNodeAnnouncement(pendingNodeAnn);
                if (result.isErr) return result;
                else results.push(...result.value);
            }
        }
 
        return Result.ok(results);
    }
 
    /**
     * Validates a channel_update message by ensuring that:
     * - the channel_announcement has already been recieved
     * - the channel_update is not old
     * - the channel_update is correctly signed by the node
     */
    private async _validateChannelUpdate(msg: ChannelUpdateMessage): Promise<GossipFilterResult> {
        // Ensure a channel announcement exists. If it does not,
        // we need to queue the update message until the channel announcement
        // can be adequately processed. Technically according to the specification in
        // Bolt 07, we should ignore channel_update message if we not processed
        // a valid channel_announcement. In reality, we may end up in a situation
        // where a channel_update makes it to our peer prior to the channel_announcement
        // being received.
        const channelMessage = await this.gossipStore.findChannelAnnouncement(msg.shortChannelId);
        Iif (!channelMessage) {
            await this.pendingStore.saveChannelUpdate(msg);
            return Result.ok([] as IWireMessage[]);
        }
 
        // ignore out of date message
        const existingUpdate = await this.gossipStore.findChannelUpdate(
            msg.shortChannelId,
            msg.direction,
        );
        Iif (existingUpdate && existingUpdate.timestamp >= msg.timestamp) {
            return Result.ok([] as IWireMessage[]);
        }
 
        // validate message signature for the node in
        const nodeId = msg.direction === 0 ? channelMessage.nodeId1 : channelMessage.nodeId2;
        Iif (!ChannelUpdateMessage.validateSignature(msg, nodeId)) {
            return Result.err(new WireError(WireErrorCode.chanUpdSigFailed, [msg, nodeId]));
        }
 
        // save the message
        await this.gossipStore.saveChannelUpdate(msg);
 
        // broadcast valid message
        return Result.ok([msg]);
    }
}