All files / lib/serialize readTlvs.ts

100% Statements 16/16
100% Branches 10/10
100% Functions 1/1
100% Lines 16/16

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 381x               1x         125x 110x 104x 96x 92x   92x 5x     87x 87x   73x 9x     64x 4x     60x      
import { BufferReader } from "@node-lightning/bufio";
 
/**
 * Reads TLVs from a reader until the entire stream is processed. The handler is
 * responsible for doing something with the data bytes.
 * @param reader
 * @param handler
 */
export function readTlvs(
    reader: BufferReader,
    handler: (type: bigint, value: BufferReader) => boolean,
) {
    let lastType: bigint;
    while (!reader.eof) {
        const type = reader.readBigSize();
        const len = reader.readBigSize();
        const value = reader.readBytes(Number(len));
        const valueReader = new BufferReader(value);
 
        if (type <= lastType) {
            throw new Error("Invalid TLV stream");
        }
 
        const isEven = type % BigInt(2) === BigInt(0);
        const wasHandled = handler(type, valueReader);
 
        if (!wasHandled && isEven) {
            throw new Error("Unknown even type");
        }
 
        if (wasHandled && !valueReader.eof) {
            throw new Error("Non-canonical length");
        }
 
        lastType = type;
    }
}