All files / lib/serialize/address ipv6StringToBuffer.ts

100% Statements 19/19
100% Branches 8/8
100% Functions 2/2
100% Lines 17/17

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 391x           1x         15x 9x   15x   15x   15x 15x   15x 97x 8x 8x 8x   89x 89x       15x       89x    
import { BufferWriter } from "@node-lightning/bufio";
 
/**
 * Converts an IPv6 address in string notation to the
 * byte representation.
 */
export function ipv6StringToBuffer(host: string): Buffer {
    // replace start or end expansion with single part to retain correct
    // number of parts (8) that are used in the remainder of the logic.
    // ie: ::1:2:3:4:5:6:7 would split to ['','',1,2,3,4,5,6,7] and
    // result in overflows
    if (host.startsWith("::")) host = host.substr(1);
    else if (host.endsWith("::")) host = host.substr(0, host.length - 1);
 
    const parts = host.split(":");
 
    const writer = new BufferWriter(Buffer.alloc(16));
 
    const expandBy = 8 - parts.length;
    let needsExpansion = expandBy > 0;
 
    for (const part of parts) {
        if (needsExpansion && part === "") {
            const b = Buffer.alloc((expandBy + 1) * 2);
            writer.writeBytes(b);
            needsExpansion = false;
        } else {
            const b = Buffer.from(expandZeros(part), "hex");
            writer.writeBytes(b);
        }
    }
 
    return writer.toBuffer();
}
 
function expandZeros(part: string): string {
    return part.padStart(4, "0");
}