import { BufferReader , BufferWriter } from "@node-lightning/bufio" ; import { BitField } from "@node-lightning/core" ; import { InitFeatureFlags } from "../flags/InitFeatureFlags" ; import { MessageType } from "../MessageType" ; import { readTlvs } from "../serialize/readTlvs" ; import { IWireMessage } from "./IWireMessage" ; /**
 * InitMessage is defined in BOLT #1. Once authentication is complete, the first
 * message reveals the features supported or required by the node sending the
 * message. This message is sent even on a reconnection.
 *
 * This message contains two fields; global features and local features, that
 * are used to signal how the message should operate. The values of are defined
 * in the BOLT #9.
 */ export class InitMessage implements IWireMessage { /**
     * Processes a buffer containing the message information. This method
     * will capture the arbitrary length global and local
     * features into two internal properties of the newly constructed
     * init message object.
     */ public static deserialize ( buffer ) { const instance = new InitMessage ( ) ; const reader = new BufferReader ( buffer ) ; reader . readUInt16BE ( ) ; const gflen = reader . readUInt16BE ( ) ; const gf = BitField . fromBuffer ( reader . readBytes ( gflen ) ) ; const lflen = reader . readUInt16BE ( ) ; const lf = BitField . fromBuffer ( reader . readBytes ( lflen ) ) ; instance . features = new BitField ( ) . or ( gf ) . or ( lf ) ; readTlvs ( reader , ( type , valueReader ) => { switch ( type ) { case BigInt ( 1 ) : { while ( ! valueReader . eof ) { const chainHash = valueReader . readBytes ( 32 ) ; instance . chainHashes . push ( chainHash ) ; } return true ; } } } ) ; return instance ; } /**
     * Message type 16
     */ public type : MessageType = MessageType . Init ; /**
     * BitField containing the features provided in by the local or remote node
     */ public features : BitField < InitFeatureFlags > = new BitField ( ) ; /**
     * Supported chain_hashes for the remote peer
     */ public chainHashes : Buffer [ ] = [ ] ; /**
     * Serialize will construct a properly formatted message based on the
     * properties of the configured message.
     */ public serialize ( ) { const writer = new BufferWriter ( ) ; writer . writeUInt16BE ( this . type ) ; const gflen = 0 ; writer . writeUInt16BE ( gflen ) ; const features = this . features . toBuffer ( ) ; const featuresLen = features . length ; writer . writeUInt16BE ( featuresLen ) ; writer . writeBytes ( features ) ; if ( this . chainHashes . length ) { writer . writeBigSize ( 1 ) ; writer . writeBigSize ( this . chainHashes . length * 32 ) ; writer . writeBytes ( Buffer . concat ( this . chainHashes ) ) ; } return writer . toBuffer ( ) ; } }