# All files Witness.ts

14.29% Statements 2/14
100% Branches 0/0
0% Functions 0/7
14.29% Lines 2/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
    64
    65
    661x

    1x

     import { BufferWriter, StreamReader } from '@node-dlc/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): Witness {
        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(): string {
        return this.data.toString('hex');
      }

      /**
       * Returns the string of a piece of witness data
       */
      // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
      public toJSON() {
        return this.toString();
      }

      /**
       * Clone via deep copy
       */
      public clone(): Witness {
        return new Witness(Buffer.from(this.data));
      }
    }