All files Witness.ts

100% Statements 14/14
100% Branches 0/0
100% Functions 7/7
100% Lines 14/14

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 641x             1x           13x 13x 13x                 1x     56x                 30x 30x 30x 30x             8x             1x             20x      
import { BufferWriter, StreamReader } from "@node-lightning/bufio";
import { ICloneable } from "./ICloneable";
 
/**
 * Represents segregated witness data. This data is nothing more than a
 * buffer.
 */
export class Witness implements ICloneable<Witness> {
    /**
     * Parses witness data
     * @param reader
     */
    public static parse(reader: StreamReader): Witness {
        const len = reader.readVarInt();
        const data = reader.readBytes(Number(len));
        return new Witness(data);
    }
 
    /**
     * Hex-encoded Witness data. This method interally creates a
     * StreamReader and uses the parse function
     * @param hex encoded as a string
     */
    public static fromHex(hex: string) {
        return Witness.parse(StreamReader.fromHex(hex));
    }
 
    constructor(readonly data: Buffer) {}
 
    /**
     * Serializes witness data into a buffer in the format:
     *
     * [varint] length
     * [length] data
     */
    public serialize(): Buffer {
        const writer = new BufferWriter();
        writer.writeVarInt(this.data.length);
        writer.writeBytes(this.data);
        return writer.toBuffer();
    }
 
    /**
     * Returns the string of a piece of witness data
     */
    public toString() {
        return this.data.toString("hex");
    }
 
    /**
     * Returns the string of a piece of witness data
     */
    public toJSON() {
        return this.toString();
    }
 
    /**
     * Clone via deep copy
     */
    public clone(): Witness {
        return new Witness(Buffer.from(this.data));
    }
}