1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Some macros that implement [`Readable`]/[`Writeable`] traits for lightning messages.
11 //! They also handle serialization and deserialization of TLVs.
13 //! [`Readable`]: crate::util::ser::Readable
14 //! [`Writeable`]: crate::util::ser::Writeable
16 /// Implements serialization for a single TLV record.
17 /// This is exported for use by other exported macros, do not use directly.
20 macro_rules! _encode_tlv {
21 ($stream: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
22 $crate::_encode_tlv!($stream, $type, $field, required)
24 ($stream: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
25 let _ = &$field; // Ensure we "use" the $field
27 ($stream: expr, $type: expr, $field: expr, required) => {
28 BigSize($type).write($stream)?;
29 BigSize($field.serialized_length() as u64).write($stream)?;
30 $field.write($stream)?;
32 ($stream: expr, $type: expr, $field: expr, vec_type) => {
33 $crate::_encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required);
35 ($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
36 if let Some(ref field) = $optional_field {
37 BigSize($optional_type).write($stream)?;
38 BigSize(field.serialized_length() as u64).write($stream)?;
39 field.write($stream)?;
42 ($stream: expr, $type: expr, $field: expr, upgradable_required) => {
43 $crate::_encode_tlv!($stream, $type, $field, required);
45 ($stream: expr, $type: expr, $field: expr, upgradable_option) => {
46 $crate::_encode_tlv!($stream, $type, $field, option);
48 ($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
49 $crate::_encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
51 ($stream: expr, $type: expr, $field: expr, (option, encoding: $fieldty: ty)) => {
52 $crate::_encode_tlv!($stream, $type, $field, option);
56 /// Panics if the last seen TLV type is not numerically less than the TLV type currently being checked.
57 /// This is exported for use by other exported macros, do not use directly.
60 macro_rules! _check_encoded_tlv_order {
61 ($last_type: expr, $type: expr, (static_value, $value: expr)) => { };
62 ($last_type: expr, $type: expr, $fieldty: tt) => {
63 if let Some(t) = $last_type {
64 #[allow(unused_comparisons)] // Note that $type may be 0 making the following comparison always false
65 (debug_assert!(t < $type))
67 $last_type = Some($type);
71 /// Implements the TLVs serialization part in a [`Writeable`] implementation of a struct.
73 /// This should be called inside a method which returns `Result<_, `[`io::Error`]`>`, such as
74 /// [`Writeable::write`]. It will only return an `Err` if the stream `Err`s or [`Writeable::write`]
75 /// on one of the fields `Err`s.
77 /// `$stream` must be a `&mut `[`Writer`] which will receive the bytes for each TLV in the stream.
79 /// Fields MUST be sorted in `$type`-order.
81 /// Note that the lightning TLV requirements require that a single type not appear more than once,
82 /// that TLVs are sorted in type-ascending order, and that any even types be understood by the
85 /// Any `option` fields which have a value of `None` will not be serialized at all.
89 /// # use lightning::encode_tlv_stream;
90 /// # fn write<W: lightning::util::ser::Writer> (stream: &mut W) -> Result<(), lightning::io::Error> {
91 /// let mut required_value = 0u64;
92 /// let mut optional_value: Option<u64> = None;
93 /// encode_tlv_stream!(stream, {
94 /// (0, required_value, required),
95 /// (1, Some(42u64), option),
96 /// (2, optional_value, option),
98 /// // At this point `required_value` has been written as a TLV of type 0, `42u64` has been written
99 /// // as a TLV of type 1 (indicating the reader may ignore it if it is not understood), and *no*
100 /// // TLV is written with type 2.
105 /// [`Writeable`]: crate::util::ser::Writeable
106 /// [`io::Error`]: crate::io::Error
107 /// [`Writeable::write`]: crate::util::ser::Writeable::write
108 /// [`Writer`]: crate::util::ser::Writer
110 macro_rules! encode_tlv_stream {
111 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
112 #[allow(unused_imports)]
114 ln::msgs::DecodeError,
117 util::ser::Writeable,
121 $crate::_encode_tlv!($stream, $type, $field, $fieldty);
124 #[allow(unused_mut, unused_variables, unused_assignments)]
125 #[cfg(debug_assertions)]
127 let mut last_seen: Option<u64> = None;
129 $crate::_check_encoded_tlv_order!(last_seen, $type, $fieldty);
135 /// Adds the length of the serialized field to a [`LengthCalculatingWriter`].
136 /// This is exported for use by other exported macros, do not use directly.
138 /// [`LengthCalculatingWriter`]: crate::util::ser::LengthCalculatingWriter
141 macro_rules! _get_varint_length_prefixed_tlv_length {
142 ($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
143 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
145 ($len: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
147 ($len: expr, $type: expr, $field: expr, required) => {
148 BigSize($type).write(&mut $len).expect("No in-memory data may fail to serialize");
149 let field_len = $field.serialized_length();
150 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
153 ($len: expr, $type: expr, $field: expr, vec_type) => {
154 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required);
156 ($len: expr, $optional_type: expr, $optional_field: expr, option) => {
157 if let Some(ref field) = $optional_field {
158 BigSize($optional_type).write(&mut $len).expect("No in-memory data may fail to serialize");
159 let field_len = field.serialized_length();
160 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
164 ($len: expr, $type: expr, $field: expr, upgradable_required) => {
165 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required);
167 ($len: expr, $type: expr, $field: expr, upgradable_option) => {
168 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
172 /// See the documentation of [`write_tlv_fields`].
173 /// This is exported for use by other exported macros, do not use directly.
176 macro_rules! _encode_varint_length_prefixed_tlv {
177 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
178 use $crate::util::ser::BigSize;
181 let mut len = $crate::util::ser::LengthCalculatingWriter(0);
183 $crate::_get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
187 BigSize(len as u64).write($stream)?;
188 $crate::encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* });
192 /// Errors if there are missing required TLV types between the last seen type and the type currently being processed.
193 /// This is exported for use by other exported macros, do not use directly.
196 macro_rules! _check_decoded_tlv_order {
197 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
198 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
199 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
201 $field = $default.into();
204 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (static_value, $value: expr)) => {
206 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
207 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
208 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
210 return Err(DecodeError::InvalidValue);
213 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
216 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, vec_type) => {{
219 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_required) => {{
220 _check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required)
222 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_option) => {{
225 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
228 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
233 /// Errors if there are missing required TLV types after the last seen type.
234 /// This is exported for use by other exported macros, do not use directly.
237 macro_rules! _check_missing_tlv {
238 ($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
239 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
240 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
241 if missing_req_type {
242 $field = $default.into();
245 ($last_seen_type: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
248 ($last_seen_type: expr, $type: expr, $field: ident, required) => {{
249 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
250 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
251 if missing_req_type {
252 return Err(DecodeError::InvalidValue);
255 ($last_seen_type: expr, $type: expr, $field: ident, vec_type) => {{
258 ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
261 ($last_seen_type: expr, $type: expr, $field: ident, upgradable_required) => {{
262 _check_missing_tlv!($last_seen_type, $type, $field, required)
264 ($last_seen_type: expr, $type: expr, $field: ident, upgradable_option) => {{
267 ($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
270 ($last_seen_type: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
275 /// Implements deserialization for a single TLV record.
276 /// This is exported for use by other exported macros, do not use directly.
279 macro_rules! _decode_tlv {
280 ($reader: expr, $field: ident, (default_value, $default: expr)) => {{
281 $crate::_decode_tlv!($reader, $field, required)
283 ($reader: expr, $field: ident, (static_value, $value: expr)) => {{
285 ($reader: expr, $field: ident, required) => {{
286 $field = $crate::util::ser::Readable::read(&mut $reader)?;
288 ($reader: expr, $field: ident, vec_type) => {{
289 let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
292 ($reader: expr, $field: ident, option) => {{
293 $field = Some($crate::util::ser::Readable::read(&mut $reader)?);
295 ($reader: expr, $field: ident, upgradable_required) => {{
296 $field = match $crate::util::ser::MaybeReadable::read(&mut $reader)? {
301 ($reader: expr, $field: ident, upgradable_option) => {{
302 $field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
304 ($reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
305 $field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
307 ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident, $encoder:ty))) => {{
308 $crate::_decode_tlv!($reader, $field, (option, encoding: ($fieldty, $encoding)));
310 ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {{
312 let field: $encoding<$fieldty> = ser::Readable::read(&mut $reader)?;
316 ($reader: expr, $field: ident, (option, encoding: $fieldty: ty)) => {{
317 $crate::_decode_tlv!($reader, $field, option);
321 /// Checks if `$val` matches `$type`.
322 /// This is exported for use by other exported macros, do not use directly.
325 macro_rules! _decode_tlv_stream_match_check {
326 ($val: ident, $type: expr, (static_value, $value: expr)) => { false };
327 ($val: ident, $type: expr, $fieldty: tt) => { $val == $type }
330 /// Implements the TLVs deserialization part in a [`Readable`] implementation of a struct.
332 /// This should be called inside a method which returns `Result<_, `[`DecodeError`]`>`, such as
333 /// [`Readable::read`]. It will either return an `Err` or ensure all `required` fields have been
334 /// read and optionally read `optional` fields.
336 /// `$stream` must be a [`Read`] and will be fully consumed, reading until no more bytes remain
337 /// (i.e. it returns [`DecodeError::ShortRead`]).
339 /// Fields MUST be sorted in `$type`-order.
341 /// Note that the lightning TLV requirements require that a single type not appear more than once,
342 /// that TLVs are sorted in type-ascending order, and that any even types be understood by the
347 /// # use lightning::decode_tlv_stream;
348 /// # fn read<R: lightning::io::Read> (stream: R) -> Result<(), lightning::ln::msgs::DecodeError> {
349 /// let mut required_value = 0u64;
350 /// let mut optional_value: Option<u64> = None;
351 /// decode_tlv_stream!(stream, {
352 /// (0, required_value, required),
353 /// (2, optional_value, option),
355 /// // At this point, `required_value` has been overwritten with the TLV with type 0.
356 /// // `optional_value` may have been overwritten, setting it to `Some` if a TLV with type 2 was
362 /// [`Readable`]: crate::util::ser::Readable
363 /// [`DecodeError`]: crate::ln::msgs::DecodeError
364 /// [`Readable::read`]: crate::util::ser::Readable::read
365 /// [`Read`]: crate::io::Read
366 /// [`DecodeError::ShortRead`]: crate::ln::msgs::DecodeError::ShortRead
368 macro_rules! decode_tlv_stream {
369 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
370 let rewind = |_, _| { unreachable!() };
371 $crate::_decode_tlv_stream_range!($stream, .., rewind, {$(($type, $field, $fieldty)),*});
375 /// Similar to [`decode_tlv_stream`] with a custom TLV decoding capabilities.
377 /// `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
378 /// If it is provided, it will be called with the custom type and the [`FixedLengthReader`] containing
379 /// the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
380 /// `Ok(false)` if the message type is unknown, and `Err(`[`DecodeError`]`)` if parsing fails.
382 /// [`FixedLengthReader`]: crate::util::ser::FixedLengthReader
383 /// [`DecodeError`]: crate::ln::msgs::DecodeError
384 macro_rules! decode_tlv_stream_with_custom_tlv_decode {
385 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
386 $(, $decode_custom_tlv: expr)?) => { {
387 let rewind = |_, _| { unreachable!() };
388 _decode_tlv_stream_range!(
389 $stream, .., rewind, {$(($type, $field, $fieldty)),*} $(, $decode_custom_tlv)?
396 macro_rules! _decode_tlv_stream_range {
397 ($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
398 $(, $decode_custom_tlv: expr)?) => { {
399 use core::ops::RangeBounds;
400 use $crate::ln::msgs::DecodeError;
401 let mut last_seen_type: Option<u64> = None;
402 let mut stream_ref = $stream;
404 use $crate::util::ser;
406 // First decode the type of this TLV:
407 let typ: ser::BigSize = {
408 // We track whether any bytes were read during the consensus_decode call to
409 // determine whether we should break or return ShortRead if we get an
410 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
411 // pass the TLV test vectors exactly, which require this distinction.
412 let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
413 match <$crate::util::ser::BigSize as $crate::util::ser::Readable>::read(&mut tracking_reader) {
414 Err(DecodeError::ShortRead) => {
415 if !tracking_reader.have_read {
418 return Err(DecodeError::ShortRead);
421 Err(e) => return Err(e),
422 Ok(t) => if $range.contains(&t.0) { t } else {
423 drop(tracking_reader);
425 // Assumes the type id is minimally encoded, which is enforced on read.
426 use $crate::util::ser::Writeable;
427 let bytes_read = t.serialized_length();
428 $rewind(stream_ref, bytes_read);
434 // Types must be unique and monotonically increasing:
435 match last_seen_type {
436 Some(t) if typ.0 <= t => {
437 return Err(DecodeError::InvalidValue);
441 // As we read types, make sure we hit every required type between `last_seen_type` and `typ`:
443 $crate::_check_decoded_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
445 last_seen_type = Some(typ.0);
447 // Finally, read the length and value itself:
448 let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
449 let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
451 $(_t if $crate::_decode_tlv_stream_match_check!(_t, $type, $fieldty) => {
452 $crate::_decode_tlv!(s, $field, $fieldty);
453 if s.bytes_remain() {
454 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
455 return Err(DecodeError::InvalidValue);
460 if $decode_custom_tlv(t, &mut s)? {
461 // If a custom TLV was successfully read (i.e. decode_custom_tlv returns true),
462 // continue to the next TLV read.
468 return Err(DecodeError::UnknownRequiredFeature);
474 // Make sure we got to each required type after we've read every TLV:
476 $crate::_check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
481 /// Implements [`Readable`]/[`Writeable`] for a message struct that may include non-TLV and
482 /// TLV-encoded parts.
484 /// This is useful to implement a [`CustomMessageReader`].
486 /// Currently `$fieldty` may only be `option`, i.e., `$tlvfield` is optional field.
490 /// # use lightning::impl_writeable_msg;
491 /// struct MyCustomMessage {
492 /// pub field_1: u32,
493 /// pub field_2: bool,
494 /// pub field_3: String,
495 /// pub tlv_optional_integer: Option<u32>,
498 /// impl_writeable_msg!(MyCustomMessage, {
503 /// (1, tlv_optional_integer, option),
507 /// [`Readable`]: crate::util::ser::Readable
508 /// [`Writeable`]: crate::util::ser::Writeable
509 /// [`CustomMessageReader`]: crate::ln::wire::CustomMessageReader
511 macro_rules! impl_writeable_msg {
512 ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
513 impl $crate::util::ser::Writeable for $st {
514 fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
515 $( self.$field.write(w)?; )*
516 $crate::encode_tlv_stream!(w, {$(($type, self.$tlvfield, $fieldty)),*});
520 impl $crate::util::ser::Readable for $st {
521 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
522 $(let $field = $crate::util::ser::Readable::read(r)?;)*
523 $($crate::_init_tlv_field_var!($tlvfield, $fieldty);)*
524 $crate::decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
534 macro_rules! impl_writeable {
535 ($st:ident, {$($field:ident),*}) => {
536 impl $crate::util::ser::Writeable for $st {
537 fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
538 $( self.$field.write(w)?; )*
543 fn serialized_length(&self) -> usize {
544 let mut len_calc = 0;
545 $( len_calc += self.$field.serialized_length(); )*
550 impl $crate::util::ser::Readable for $st {
551 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
553 $($field: $crate::util::ser::Readable::read(r)?),*
560 /// Write out two bytes to indicate the version of an object.
562 /// $this_version represents a unique version of a type. Incremented whenever the type's
563 /// serialization format has changed or has a new interpretation. Used by a type's reader to
564 /// determine how to interpret fields or if it can understand a serialized object.
566 /// $min_version_that_can_read_this is the minimum reader version which can understand this
567 /// serialized object. Previous versions will simply err with a [`DecodeError::UnknownVersion`].
569 /// Updates to either `$this_version` or `$min_version_that_can_read_this` should be included in
572 /// Both version fields can be specific to this type of object.
574 /// [`DecodeError::UnknownVersion`]: crate::ln::msgs::DecodeError::UnknownVersion
575 macro_rules! write_ver_prefix {
576 ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
577 $stream.write_all(&[$this_version; 1])?;
578 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
582 /// Writes out a suffix to an object as a length-prefixed TLV stream which contains potentially
583 /// backwards-compatible, optional fields which old nodes can happily ignore.
585 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
586 /// [`DecodeError::UnknownRequiredFeature`] error, with unknown odd fields ignored.
588 /// This is the preferred method of adding new fields that old nodes can ignore and still function
591 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
593 macro_rules! write_tlv_fields {
594 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
595 $crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
599 /// Reads a prefix added by [`write_ver_prefix`], above. Takes the current version of the
600 /// serialization logic for this object. This is compared against the
601 /// `$min_version_that_can_read_this` added by [`write_ver_prefix`].
602 macro_rules! read_ver_prefix {
603 ($stream: expr, $this_version: expr) => { {
604 let ver: u8 = Readable::read($stream)?;
605 let min_ver: u8 = Readable::read($stream)?;
606 if min_ver > $this_version {
607 return Err(DecodeError::UnknownVersion);
613 /// Reads a suffix added by [`write_tlv_fields`].
615 /// [`write_tlv_fields`]: crate::write_tlv_fields
617 macro_rules! read_tlv_fields {
618 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
619 let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
620 let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
621 $crate::decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
622 rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
626 /// Initializes the struct fields.
628 /// This is exported for use by other exported macros, do not use directly.
631 macro_rules! _init_tlv_based_struct_field {
632 ($field: ident, (default_value, $default: expr)) => {
635 ($field: ident, (static_value, $value: expr)) => {
638 ($field: ident, option) => {
641 ($field: ident, upgradable_required) => {
644 ($field: ident, upgradable_option) => {
647 ($field: ident, required) => {
650 ($field: ident, vec_type) => {
655 /// Initializes the variable we are going to read the TLV into.
657 /// This is exported for use by other exported macros, do not use directly.
660 macro_rules! _init_tlv_field_var {
661 ($field: ident, (default_value, $default: expr)) => {
662 let mut $field = $crate::util::ser::RequiredWrapper(None);
664 ($field: ident, (static_value, $value: expr)) => {
667 ($field: ident, required) => {
668 let mut $field = $crate::util::ser::RequiredWrapper(None);
670 ($field: ident, vec_type) => {
671 let mut $field = Some(Vec::new());
673 ($field: ident, option) => {
674 let mut $field = None;
676 ($field: ident, upgradable_required) => {
677 let mut $field = $crate::util::ser::UpgradableRequired(None);
679 ($field: ident, upgradable_option) => {
680 let mut $field = None;
684 /// Equivalent to running [`_init_tlv_field_var`] then [`read_tlv_fields`].
686 /// This is exported for use by other exported macros, do not use directly.
689 macro_rules! _init_and_read_tlv_fields {
690 ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
692 $crate::_init_tlv_field_var!($field, $fieldty);
695 $crate::read_tlv_fields!($reader, {
696 $(($type, $field, $fieldty)),*
701 /// Implements [`Readable`]/[`Writeable`] for a struct storing it as a set of TLVs
702 /// If `$fieldty` is `required`, then `$field` is a required field that is not an [`Option`] nor a [`Vec`].
703 /// If `$fieldty` is `(default_value, $default)`, then `$field` will be set to `$default` if not present.
704 /// If `$fieldty` is `option`, then `$field` is optional field.
705 /// If `$fieldty` is `vec_type`, then `$field` is a [`Vec`], which needs to have its individual elements serialized.
709 /// # use lightning::impl_writeable_tlv_based;
710 /// struct LightningMessage {
711 /// tlv_integer: u32,
712 /// tlv_default_integer: u32,
713 /// tlv_optional_integer: Option<u32>,
714 /// tlv_vec_type_integer: Vec<u32>,
717 /// impl_writeable_tlv_based!(LightningMessage, {
718 /// (0, tlv_integer, required),
719 /// (1, tlv_default_integer, (default_value, 7)),
720 /// (2, tlv_optional_integer, option),
721 /// (3, tlv_vec_type_integer, vec_type),
725 /// [`Readable`]: crate::util::ser::Readable
726 /// [`Writeable`]: crate::util::ser::Writeable
728 macro_rules! impl_writeable_tlv_based {
729 ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
730 impl $crate::util::ser::Writeable for $st {
731 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
732 $crate::write_tlv_fields!(writer, {
733 $(($type, self.$field, $fieldty)),*
739 fn serialized_length(&self) -> usize {
740 use $crate::util::ser::BigSize;
743 let mut len = $crate::util::ser::LengthCalculatingWriter(0);
745 $crate::_get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
749 let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
750 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
755 impl $crate::util::ser::Readable for $st {
756 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
757 $crate::_init_and_read_tlv_fields!(reader, {
758 $(($type, $field, $fieldty)),*
762 $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
770 /// Defines a struct for a TLV stream and a similar struct using references for non-primitive types,
771 /// implementing [`Readable`] for the former and [`Writeable`] for the latter. Useful as an
772 /// intermediary format when reading or writing a type encoded as a TLV stream. Note that each field
773 /// representing a TLV record has its type wrapped with an [`Option`]. A tuple consisting of a type
774 /// and a serialization wrapper may be given in place of a type when custom serialization is
777 /// [`Readable`]: crate::util::ser::Readable
778 /// [`Writeable`]: crate::util::ser::Writeable
779 macro_rules! tlv_stream {
780 ($name:ident, $nameref:ident, $range:expr, {
781 $(($type:expr, $field:ident : $fieldty:tt)),* $(,)*
784 pub(super) struct $name {
786 pub(super) $field: Option<tlv_record_type!($fieldty)>,
790 #[cfg_attr(test, derive(PartialEq))]
792 pub(super) struct $nameref<'a> {
794 pub(super) $field: Option<tlv_record_ref_type!($fieldty)>,
798 impl<'a> $crate::util::ser::Writeable for $nameref<'a> {
799 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
800 encode_tlv_stream!(writer, {
801 $(($type, self.$field, (option, encoding: $fieldty))),*
807 impl $crate::util::ser::SeekReadable for $name {
808 fn read<R: $crate::io::Read + $crate::io::Seek>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
810 _init_tlv_field_var!($field, option);
812 let rewind = |cursor: &mut R, offset: usize| {
813 cursor.seek($crate::io::SeekFrom::Current(-(offset as i64))).expect("");
815 _decode_tlv_stream_range!(reader, $range, rewind, {
816 $(($type, $field, (option, encoding: $fieldty))),*
829 macro_rules! tlv_record_type {
830 (($type:ty, $wrapper:ident)) => { $type };
831 (($type:ty, $wrapper:ident, $encoder:ty)) => { $type };
832 ($type:ty) => { $type };
835 macro_rules! tlv_record_ref_type {
838 ((u16, $wrapper: ident)) => { u16 };
839 ((u32, $wrapper: ident)) => { u32 };
840 ((u64, $wrapper: ident)) => { u64 };
841 (($type:ty, $wrapper:ident)) => { &'a $type };
842 (($type:ty, $wrapper:ident, $encoder:ty)) => { $encoder };
843 ($type:ty) => { &'a $type };
846 macro_rules! _impl_writeable_tlv_based_enum_common {
847 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
848 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
850 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
851 impl $crate::util::ser::Writeable for $st {
852 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
854 $($st::$variant_name { $(ref $field),* } => {
855 let id: u8 = $variant_id;
857 write_tlv_fields!(writer, {
858 $(($type, *$field, $fieldty)),*
861 $($st::$tuple_variant_name (ref field) => {
862 let id: u8 = $tuple_variant_id;
864 field.write(writer)?;
873 /// Implement [`Readable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and tuple
874 /// variants stored directly.
875 /// The format is, for example
877 /// impl_writeable_tlv_based_enum!(EnumName,
878 /// (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
879 /// (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, vec_type)};
880 /// (2, TupleVariantA), (3, TupleVariantB),
883 /// The type is written as a single byte, followed by any variant data.
884 /// Attempts to read an unknown type byte result in [`DecodeError::UnknownRequiredFeature`].
886 /// [`Readable`]: crate::util::ser::Readable
887 /// [`Writeable`]: crate::util::ser::Writeable
888 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
890 macro_rules! impl_writeable_tlv_based_enum {
891 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
892 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
894 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
895 _impl_writeable_tlv_based_enum_common!($st,
896 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
897 $(($tuple_variant_id, $tuple_variant_name)),*);
899 impl $crate::util::ser::Readable for $st {
900 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
901 let id: u8 = $crate::util::ser::Readable::read(reader)?;
904 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
905 // in the same function body. Instead, we define a closure and call it.
907 _init_and_read_tlv_fields!(reader, {
908 $(($type, $field, $fieldty)),*
910 Ok($st::$variant_name {
912 $field: _init_tlv_based_struct_field!($field, $fieldty)
918 $($tuple_variant_id => {
919 Ok($st::$tuple_variant_name(Readable::read(reader)?))
922 Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature)
930 /// Implement [`MaybeReadable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and
931 /// tuple variants stored directly.
933 /// This is largely identical to [`impl_writeable_tlv_based_enum`], except that odd variants will
934 /// return `Ok(None)` instead of `Err(`[`DecodeError::UnknownRequiredFeature`]`)`. It should generally be preferred
935 /// when [`MaybeReadable`] is practical instead of just [`Readable`] as it provides an upgrade path for
936 /// new variants to be added which are simply ignored by existing clients.
938 /// [`MaybeReadable`]: crate::util::ser::MaybeReadable
939 /// [`Writeable`]: crate::util::ser::Writeable
940 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
941 /// [`Readable`]: crate::util::ser::Readable
943 macro_rules! impl_writeable_tlv_based_enum_upgradable {
944 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
945 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
948 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*)*) => {
949 _impl_writeable_tlv_based_enum_common!($st,
950 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
951 $($(($tuple_variant_id, $tuple_variant_name)),*)*);
953 impl $crate::util::ser::MaybeReadable for $st {
954 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
955 let id: u8 = $crate::util::ser::Readable::read(reader)?;
958 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
959 // in the same function body. Instead, we define a closure and call it.
961 _init_and_read_tlv_fields!(reader, {
962 $(($type, $field, $fieldty)),*
964 Ok(Some($st::$variant_name {
966 $field: _init_tlv_based_struct_field!($field, $fieldty)
972 $($($tuple_variant_id => {
973 Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
975 _ if id % 2 == 1 => Ok(None),
976 _ => Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature),
985 use crate::io::{self, Cursor};
986 use crate::prelude::*;
987 use crate::ln::msgs::DecodeError;
988 use crate::util::ser::{Writeable, HighZeroBytesDroppedBigSize, VecWriter};
989 use bitcoin::secp256k1::PublicKey;
991 // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
992 // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
993 // work with so they're baked into the decoder. Thus, we have a few additional tests below
994 fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
995 let mut s = Cursor::new(s);
998 let mut c: Option<u32> = None;
999 decode_tlv_stream!(&mut s, {(2, a, required), (3, b, required), (4, c, option)});
1004 fn tlv_v_short_read() {
1005 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
1006 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
1007 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
1009 } else { panic!(); }
1013 fn tlv_types_out_of_order() {
1014 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
1015 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
1017 } else { panic!(); }
1018 // ...even if its some field we don't understand
1019 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
1020 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
1022 } else { panic!(); }
1026 fn tlv_req_type_missing_or_extra() {
1027 // It's also bad if they included even fields we don't understand
1028 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
1029 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
1031 } else { panic!(); }
1032 // ... or if they're missing fields we need
1033 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
1034 concat!("0100", "0208deadbeef1badbeef")
1036 } else { panic!(); }
1037 // ... even if that field is even
1038 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
1039 concat!("0304deadbeef", "0500")
1041 } else { panic!(); }
1045 fn tlv_simple_good_cases() {
1046 assert_eq!(tlv_reader(&::hex::decode(
1047 concat!("0208deadbeef1badbeef", "03041bad1dea")
1048 ).unwrap()[..]).unwrap(),
1049 (0xdeadbeef1badbeef, 0x1bad1dea, None));
1050 assert_eq!(tlv_reader(&::hex::decode(
1051 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
1052 ).unwrap()[..]).unwrap(),
1053 (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
1056 #[derive(Debug, PartialEq)]
1057 struct TestUpgradable {
1063 fn upgradable_tlv_reader(s: &[u8]) -> Result<Option<TestUpgradable>, DecodeError> {
1064 let mut s = Cursor::new(s);
1067 let mut c: Option<u32> = None;
1068 decode_tlv_stream!(&mut s, {(2, a, upgradable_required), (3, b, upgradable_required), (4, c, upgradable_option)});
1069 Ok(Some(TestUpgradable { a, b, c, }))
1073 fn upgradable_tlv_simple_good_cases() {
1074 assert_eq!(upgradable_tlv_reader(&::hex::decode(
1075 concat!("0204deadbeef", "03041bad1dea", "0404deadbeef")
1076 ).unwrap()[..]).unwrap(),
1077 Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: Some(0xdeadbeef) }));
1079 assert_eq!(upgradable_tlv_reader(&::hex::decode(
1080 concat!("0204deadbeef", "03041bad1dea")
1081 ).unwrap()[..]).unwrap(),
1082 Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: None}));
1086 fn missing_required_upgradable() {
1087 if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&::hex::decode(
1088 concat!("0100", "0204deadbeef")
1090 } else { panic!(); }
1091 if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&::hex::decode(
1092 concat!("0100", "03041bad1dea")
1094 } else { panic!(); }
1097 // BOLT TLV test cases
1098 fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedBigSize<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
1099 let mut s = Cursor::new(s);
1100 let mut tlv1: Option<HighZeroBytesDroppedBigSize<u64>> = None;
1101 let mut tlv2: Option<u64> = None;
1102 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
1103 let mut tlv4: Option<u16> = None;
1104 decode_tlv_stream!(&mut s, {(1, tlv1, option), (2, tlv2, option), (3, tlv3, option), (254, tlv4, option)});
1105 Ok((tlv1, tlv2, tlv3, tlv4))
1109 fn bolt_tlv_bogus_stream() {
1110 macro_rules! do_test {
1111 ($stream: expr, $reason: ident) => {
1112 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
1113 } else { panic!(); }
1117 // TLVs from the BOLT test cases which should not decode as either n1 or n2
1118 do_test!(concat!("fd01"), ShortRead);
1119 do_test!(concat!("fd0001", "00"), InvalidValue);
1120 do_test!(concat!("fd0101"), ShortRead);
1121 do_test!(concat!("0f", "fd"), ShortRead);
1122 do_test!(concat!("0f", "fd26"), ShortRead);
1123 do_test!(concat!("0f", "fd2602"), ShortRead);
1124 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
1125 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
1127 do_test!(concat!("12", "00"), UnknownRequiredFeature);
1128 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
1129 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
1130 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
1134 fn bolt_tlv_bogus_n1_stream() {
1135 macro_rules! do_test {
1136 ($stream: expr, $reason: ident) => {
1137 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
1138 } else { panic!(); }
1142 // TLVs from the BOLT test cases which should not decode as n1
1143 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
1144 do_test!(concat!("01", "01", "00"), InvalidValue);
1145 do_test!(concat!("01", "02", "0001"), InvalidValue);
1146 do_test!(concat!("01", "03", "000100"), InvalidValue);
1147 do_test!(concat!("01", "04", "00010000"), InvalidValue);
1148 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
1149 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
1150 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
1151 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
1152 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
1153 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
1154 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
1155 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
1156 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
1157 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
1158 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
1159 do_test!(concat!("fd00fe", "00"), ShortRead);
1160 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
1161 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
1162 do_test!(concat!("00", "00"), UnknownRequiredFeature);
1164 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
1165 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
1166 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
1167 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
1169 // The last BOLT test modified to not require creating a new decoder for one trivial test.
1170 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
1174 fn bolt_tlv_valid_n1_stream() {
1175 macro_rules! do_test {
1176 ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
1177 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
1178 assert_eq!(tlv1.map(|v| v.0), $tlv1);
1179 assert_eq!(tlv2, $tlv2);
1180 assert_eq!(tlv3, $tlv3);
1181 assert_eq!(tlv4, $tlv4);
1182 } else { panic!(); }
1186 do_test!(concat!(""), None, None, None, None);
1187 do_test!(concat!("21", "00"), None, None, None, None);
1188 do_test!(concat!("fd0201", "00"), None, None, None, None);
1189 do_test!(concat!("fd00fd", "00"), None, None, None, None);
1190 do_test!(concat!("fd00ff", "00"), None, None, None, None);
1191 do_test!(concat!("fe02000001", "00"), None, None, None, None);
1192 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
1194 do_test!(concat!("01", "00"), Some(0), None, None, None);
1195 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
1196 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
1197 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
1198 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
1199 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
1200 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
1201 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
1202 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
1203 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
1204 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
1206 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
1208 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
1211 fn do_simple_test_tlv_write() -> Result<(), io::Error> {
1212 let mut stream = VecWriter(Vec::new());
1215 _encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
1216 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
1219 _encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
1220 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
1223 _encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
1224 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
1227 _encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
1228 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
1231 _encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1232 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
1235 _encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1236 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
1242 fn simple_test_tlv_write() {
1243 do_simple_test_tlv_write().unwrap();