All files / lib/messages ScriptWitnessV0.ts

38.89% Statements 7/18
100% Branches 0/0
50% Functions 2/4
38.89% Lines 7/18

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                                                                   43x                 211x   211x 211x   211x              
import { BufferReader, BufferWriter } from '@node-dlc/bufio';
 
/**
 * ScriptWitness is the data for a witness element in a witness stack.
 * An empty witness_stack is an error, as every input must be Segwit.
 * Witness elements should not include their length as part of the witness
 * data.
 */
export class ScriptWitnessV0 {
  /**
   * Deserializes an script_witness_v0 message
   * @param buf
   */
  public static deserialize(buf: Buffer): ScriptWitnessV0 {
    const instance = new ScriptWitnessV0();
    const reader = new BufferReader(buf);
 
    instance.length = Number(reader.readBigSize());
    instance.witness = reader.readBytes(instance.length);
 
    return instance;
  }
 
  public static getWitness(reader: BufferReader): Buffer {
    const length = Number(reader.readBigSize());
    const body = reader.readBytes(Number(length));
 
    const writer = new BufferWriter();
    writer.writeBigSize(length);
    writer.writeBytes(body);
 
    return writer.toBuffer();
  }
 
  public length: number;
 
  public witness: Buffer;
 
  /**
   * Converts script_witness_v0 to JSON
   */
  public toJSON(): IScriptWitnessV0JSON {
    return {
      witness: this.witness.toString('hex'),
    };
  }
 
  /**
   * Serializes the script_witness_v0 message into a Buffer
   */
  public serialize(): Buffer {
    const writer = new BufferWriter();
 
    writer.writeBigSize(this.witness.length);
    writer.writeBytes(this.witness);
 
    return writer.toBuffer();
  }
}
 
export interface IScriptWitnessV0JSON {
  witness: string;
}