lightning-tlv
Utility for encoding and parsing TLV packets as defined in Lightning Network's BOLT 1.
Install
npm install lightning-tlv
Usage Examples
BigSize
Lightning's BigSize integer serialization, which is the big-endian counterparty of Bitcoin's CompactSize.
To use it, we first need to import the class.
;
Serialize
; // coincidentally, also the year of the timestamp problem;;console.logserialization.toString'hex'; // fd07f6
Deserialize
;;;;; // the parser knows where the BigSize portion endsconsole.logbigintValue; // 2038nconsole.logregularValue; // 2038console.loglength; // 3
HopPayload TLV
One example TLV used in Lightning is the hop payload, which is a TLV stream consisting of three concatenated TLVs,
which are the amount_to_forward
(type 2), outgoing_cltv_value
(type 4), and short_channel_id
(type 6).
Types 2 and 4 are a tu64
and a tu32
, respectively, which are unsigned big-endian integers with trimmed leading
zeroes. short_channel_id
is simply a binary identifier.
To interact with TLVs, we first need to import the class. We will also need some of the custom type handlers.
Serialize
;; ;; ;; ; ;console.logtlvStream.toString'hex'; // 0201170401220604abcdef10
Deserialize
;; ;remainingStream = remainingStream.sliceamountToForwardTlv.tlvSize; ;remainingStream = remainingStream.sliceoutgoingCltvValueTlv.tlvSize; ; ;; ;;;console.logamountToForward; // 23nconsole.logoutgoingCltvValue; // 34console.logchannelId.toString'hex'; // abcdef10
License
MIT