All files / lib/domain Address.ts

96.15% Statements 25/26
100% Branches 0/0
75% Functions 3/4
96.15% Lines 25/26

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 651x   1x   1x 1x     1x 1x 1x   1x 1x 1x 1x   1x   1x     2x                               2x 2x                     1x 1x   1x 1x 1x 1x   1x 1x   1x      
import { BufferReader, BufferWriter } from '@node-dlc/bufio';
 
import { MessageType } from '../MessageType';
 
export class Address {
  public static type = MessageType.NodeAnnouncementAddress;
 
  public static deserialize(buf: Buffer): Address {
    const reader = new BufferReader(buf);
    reader.readBigSize(); // read off type
    reader.readBigSize(); // read size
 
    const hostLen = reader.readBigSize();
    const hostBuf = reader.readBytes(Number(hostLen));
    const host = hostBuf.toString();
    const port = reader.readUInt16BE();
 
    const instance = new Address(host, port);
 
    return instance;
  }
 
  public type = Address.type;
 
  /**
   * String notation representation of the host
   */
  public host: string;
 
  /**
   * Port number
   */
  public port: number;
 
  /**
   * Base class representing a network address
   */
  constructor(host: string, port: number) {
    this.host = host;
    this.port = port;
  }
 
  public toString(): string {
    return `${this.host}:${this.port}`;
  }
 
  /**
   * Serializes the dlc_transactions_v0 message into a Buffer
   */
  public serialize(): Buffer {
    const writer = new BufferWriter();
    writer.writeBigSize(this.type);
 
    const dataWriter = new BufferWriter();
    dataWriter.writeBigSize(this.host.length);
    dataWriter.writeBytes(Buffer.from(this.host));
    dataWriter.writeUInt16BE(this.port);
 
    writer.writeBigSize(dataWriter.size);
    writer.writeBytes(dataWriter.toBuffer());
 
    return writer.toBuffer();
  }
}