lightning/util/
ser_macros.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
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
8// licenses.
9
10//! Some macros that implement [`Readable`]/[`Writeable`] traits for lightning messages.
11//! They also handle serialization and deserialization of TLVs.
12//!
13//! [`Readable`]: crate::util::ser::Readable
14//! [`Writeable`]: crate::util::ser::Writeable
15
16// There are quite a few TLV serialization "types" which behave differently. We currently only
17// publicly document the `optional` and `required` types, not supporting anything else publicly and
18// changing them at will.
19//
20// Some of the other types include:
21//  * (default_value, $default) - reads optionally, reading $default if no TLV is present
22//  * (static_value, $value) - ignores any TLVs, always using $value
23//  * required_vec - reads into a Vec without a length prefix, failing if no TLV is present.
24//  * optional_vec - reads into an Option<Vec> without a length prefix, continuing if no TLV is
25//                   present. Writes from a Vec directly, only if any elements are present. Note
26//                   that the struct deserialization macros return a Vec, not an Option.
27//  * upgradable_option - reads via MaybeReadable.
28//  * upgradable_required - reads via MaybeReadable, requiring a TLV be present but may return None
29//                          if MaybeReadable::read() returns None.
30
31/// Implements serialization for a single TLV record.
32/// This is exported for use by other exported macros, do not use directly.
33#[doc(hidden)]
34#[macro_export]
35macro_rules! _encode_tlv {
36	($stream: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
37		$crate::_encode_tlv!($stream, $type, $field, required)
38	};
39	($stream: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
40		let _ = &$field; // Ensure we "use" the $field
41	};
42	($stream: expr, $type: expr, $field: expr, required) => {
43		BigSize($type).write($stream)?;
44		BigSize($field.serialized_length() as u64).write($stream)?;
45		$field.write($stream)?;
46	};
47	($stream: expr, $type: expr, $field: expr, required_vec) => {
48		$crate::_encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required);
49	};
50	($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
51		if let Some(ref field) = $optional_field {
52			BigSize($optional_type).write($stream)?;
53			BigSize(field.serialized_length() as u64).write($stream)?;
54			field.write($stream)?;
55		}
56	};
57	($stream: expr, $type: expr, $field: expr, optional_vec) => {
58		if !$field.is_empty() {
59			$crate::_encode_tlv!($stream, $type, $field, required_vec);
60		}
61	};
62	($stream: expr, $type: expr, $field: expr, upgradable_required) => {
63		$crate::_encode_tlv!($stream, $type, $field, required);
64	};
65	($stream: expr, $type: expr, $field: expr, upgradable_option) => {
66		$crate::_encode_tlv!($stream, $type, $field, option);
67	};
68	($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
69		$crate::_encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
70	};
71	($stream: expr, $type: expr, $field: expr, (option, encoding: $fieldty: ty)) => {
72		$crate::_encode_tlv!($stream, $type, $field, option);
73	};
74	($stream: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
75		// Just a read-mapped type
76		$crate::_encode_tlv!($stream, $type, $field, option);
77	};
78}
79
80/// Panics if the last seen TLV type is not numerically less than the TLV type currently being checked.
81/// This is exported for use by other exported macros, do not use directly.
82#[doc(hidden)]
83#[macro_export]
84macro_rules! _check_encoded_tlv_order {
85	($last_type: expr, $type: expr, (static_value, $value: expr)) => { };
86	($last_type: expr, $type: expr, $fieldty: tt) => {
87		if let Some(t) = $last_type {
88			#[allow(unused_comparisons)] // Note that $type may be 0 making the following comparison always false
89			(debug_assert!(t < $type))
90		}
91		$last_type = Some($type);
92	};
93}
94
95/// Implements the TLVs serialization part in a [`Writeable`] implementation of a struct.
96///
97/// This should be called inside a method which returns `Result<_, `[`io::Error`]`>`, such as
98/// [`Writeable::write`]. It will only return an `Err` if the stream `Err`s or [`Writeable::write`]
99/// on one of the fields `Err`s.
100///
101/// `$stream` must be a `&mut `[`Writer`] which will receive the bytes for each TLV in the stream.
102///
103/// Fields MUST be sorted in `$type`-order.
104///
105/// Note that the lightning TLV requirements require that a single type not appear more than once,
106/// that TLVs are sorted in type-ascending order, and that any even types be understood by the
107/// decoder.
108///
109/// Any `option` fields which have a value of `None` will not be serialized at all.
110///
111/// For example,
112/// ```
113/// # use lightning::encode_tlv_stream;
114/// # fn write<W: lightning::util::ser::Writer> (stream: &mut W) -> Result<(), lightning::io::Error> {
115/// let mut required_value = 0u64;
116/// let mut optional_value: Option<u64> = None;
117/// encode_tlv_stream!(stream, {
118///     (0, required_value, required),
119///     (1, Some(42u64), option),
120///     (2, optional_value, option),
121/// });
122/// // At this point `required_value` has been written as a TLV of type 0, `42u64` has been written
123/// // as a TLV of type 1 (indicating the reader may ignore it if it is not understood), and *no*
124/// // TLV is written with type 2.
125/// # Ok(())
126/// # }
127/// ```
128///
129/// [`Writeable`]: crate::util::ser::Writeable
130/// [`io::Error`]: crate::io::Error
131/// [`Writeable::write`]: crate::util::ser::Writeable::write
132/// [`Writer`]: crate::util::ser::Writer
133#[macro_export]
134macro_rules! encode_tlv_stream {
135	($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
136		$crate::_encode_tlv_stream!($stream, {$(($type, $field, $fieldty)),*})
137	}
138}
139
140/// Implementation of [`encode_tlv_stream`].
141/// This is exported for use by other exported macros, do not use directly.
142#[doc(hidden)]
143#[macro_export]
144macro_rules! _encode_tlv_stream {
145	($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
146		$crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, &[])
147	} };
148	($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}, $extra_tlvs: expr) => { {
149		#[allow(unused_imports)]
150		use $crate::{
151			ln::msgs::DecodeError,
152			util::ser,
153			util::ser::BigSize,
154			util::ser::Writeable,
155		};
156
157		$(
158			$crate::_encode_tlv!($stream, $type, $field, $fieldty);
159		)*
160		for tlv in $extra_tlvs {
161			let (typ, value): &(u64, Vec<u8>) = tlv;
162			$crate::_encode_tlv!($stream, *typ, *value, required_vec);
163		}
164
165		#[allow(unused_mut, unused_variables, unused_assignments)]
166		#[cfg(debug_assertions)]
167		{
168			let mut last_seen: Option<u64> = None;
169			$(
170				$crate::_check_encoded_tlv_order!(last_seen, $type, $fieldty);
171			)*
172			for tlv in $extra_tlvs {
173				let (typ, _): &(u64, Vec<u8>) = tlv;
174				$crate::_check_encoded_tlv_order!(last_seen, *typ, required_vec);
175			}
176		}
177	} };
178}
179
180/// Adds the length of the serialized field to a [`LengthCalculatingWriter`].
181/// This is exported for use by other exported macros, do not use directly.
182///
183/// [`LengthCalculatingWriter`]: crate::util::ser::LengthCalculatingWriter
184#[doc(hidden)]
185#[macro_export]
186macro_rules! _get_varint_length_prefixed_tlv_length {
187	($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
188		$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
189	};
190	($len: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
191	};
192	($len: expr, $type: expr, $field: expr, required) => {
193		BigSize($type).write(&mut $len).expect("No in-memory data may fail to serialize");
194		let field_len = $field.serialized_length();
195		BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
196		$len.0 += field_len;
197	};
198	($len: expr, $type: expr, $field: expr, required_vec) => {
199		$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required);
200	};
201	($len: expr, $optional_type: expr, $optional_field: expr, option) => {
202		if let Some(ref field) = $optional_field {
203			BigSize($optional_type).write(&mut $len).expect("No in-memory data may fail to serialize");
204			let field_len = field.serialized_length();
205			BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
206			$len.0 += field_len;
207		}
208	};
209	($len: expr, $type: expr, $field: expr, optional_vec) => {
210		if !$field.is_empty() {
211			$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required_vec);
212		}
213	};
214	($len: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
215		$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
216	};
217	($len: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
218		$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field.map(|f| $encoding(f)), option);
219	};
220	($len: expr, $type: expr, $field: expr, upgradable_required) => {
221		$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required);
222	};
223	($len: expr, $type: expr, $field: expr, upgradable_option) => {
224		$crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
225	};
226}
227
228/// See the documentation of [`write_tlv_fields`].
229/// This is exported for use by other exported macros, do not use directly.
230#[doc(hidden)]
231#[macro_export]
232macro_rules! _encode_varint_length_prefixed_tlv {
233	($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
234		$crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*}, &[])
235	} };
236	($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}, $extra_tlvs: expr) => { {
237		extern crate alloc;
238		use $crate::util::ser::BigSize;
239		use alloc::vec::Vec;
240		let len = {
241			#[allow(unused_mut)]
242			let mut len = $crate::util::ser::LengthCalculatingWriter(0);
243			$(
244				$crate::_get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
245			)*
246			for tlv in $extra_tlvs {
247				let (typ, value): &(u64, Vec<u8>) = tlv;
248				$crate::_get_varint_length_prefixed_tlv_length!(len, *typ, *value, required_vec);
249			}
250			len.0
251		};
252		BigSize(len as u64).write($stream)?;
253		$crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, $extra_tlvs);
254	} };
255}
256
257/// Errors if there are missing required TLV types between the last seen type and the type currently being processed.
258/// This is exported for use by other exported macros, do not use directly.
259#[doc(hidden)]
260#[macro_export]
261macro_rules! _check_decoded_tlv_order {
262	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
263		#[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
264		let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
265		if invalid_order {
266			$field = $default.into();
267		}
268	}};
269	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (static_value, $value: expr)) => {
270	};
271	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
272		#[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
273		let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
274		if invalid_order {
275			return Err(DecodeError::InvalidValue);
276		}
277	}};
278	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
279		$crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
280	}};
281	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
282		// no-op
283	}};
284	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option, explicit_type: $fieldty: ty)) => {{
285		// no-op
286	}};
287	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (required, explicit_type: $fieldty: ty)) => {{
288		_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
289	}};
290	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required_vec) => {{
291		$crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
292	}};
293	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, optional_vec) => {{
294		// no-op
295	}};
296	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_required) => {{
297		_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required)
298	}};
299	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_option) => {{
300		// no-op
301	}};
302	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
303		// no-op
304	}};
305	($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
306		// no-op
307	}};
308}
309
310/// Errors if there are missing required TLV types after the last seen type.
311/// This is exported for use by other exported macros, do not use directly.
312#[doc(hidden)]
313#[macro_export]
314macro_rules! _check_missing_tlv {
315	($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
316		#[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
317		let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
318		if missing_req_type {
319			$field = $default.into();
320		}
321	}};
322	($last_seen_type: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
323		$field = $value;
324	};
325	($last_seen_type: expr, $type: expr, $field: ident, required) => {{
326		#[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
327		let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
328		if missing_req_type {
329			return Err(DecodeError::InvalidValue);
330		}
331	}};
332	($last_seen_type: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
333		$crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
334	}};
335	($last_seen_type: expr, $type: expr, $field: ident, required_vec) => {{
336		$crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
337	}};
338	($last_seen_type: expr, $type: expr, $field: ident, option) => {{
339		// no-op
340	}};
341	($last_seen_type: expr, $type: expr, $field: ident, (option, explicit_type: $fieldty: ty)) => {{
342		// no-op
343	}};
344	($last_seen_type: expr, $type: expr, $field: ident, (required, explicit_type: $fieldty: ty)) => {{
345		_check_missing_tlv!($last_seen_type, $type, $field, required);
346	}};
347	($last_seen_type: expr, $type: expr, $field: ident, optional_vec) => {{
348		// no-op
349	}};
350	($last_seen_type: expr, $type: expr, $field: ident, upgradable_required) => {{
351		_check_missing_tlv!($last_seen_type, $type, $field, required)
352	}};
353	($last_seen_type: expr, $type: expr, $field: ident, upgradable_option) => {{
354		// no-op
355	}};
356	($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
357		// no-op
358	}};
359	($last_seen_type: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
360		// no-op
361	}};
362}
363
364/// Implements deserialization for a single TLV record.
365/// This is exported for use by other exported macros, do not use directly.
366#[doc(hidden)]
367#[macro_export]
368macro_rules! _decode_tlv {
369	($outer_reader: expr, $reader: expr, $field: ident, (default_value, $default: expr)) => {{
370		$crate::_decode_tlv!($outer_reader, $reader, $field, required)
371	}};
372	($outer_reader: expr, $reader: expr, $field: ident, (static_value, $value: expr)) => {{
373	}};
374	($outer_reader: expr, $reader: expr, $field: ident, required) => {{
375		$field = $crate::util::ser::Readable::read(&mut $reader)?;
376	}};
377	($outer_reader: expr, $reader: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
378		$field = $trait::read(&mut $reader $(, $read_arg)*)?;
379	}};
380	($outer_reader: expr, $reader: expr, $field: ident, required_vec) => {{
381		let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
382		$field = f.0;
383	}};
384	($outer_reader: expr, $reader: expr, $field: ident, option) => {{
385		$field = Some($crate::util::ser::Readable::read(&mut $reader)?);
386	}};
387	($outer_reader: expr, $reader: expr, $field: ident, (option, explicit_type: $fieldty: ty)) => {{
388		let _field: &Option<$fieldty> = &$field;
389		_decode_tlv!($outer_reader, $reader, $field, option);
390	}};
391	($outer_reader: expr, $reader: expr, $field: ident, (required, explicit_type: $fieldty: ty)) => {{
392		let _field: &$fieldty = &$field;
393		_decode_tlv!($outer_reader, $reader, $field, required);
394	}};
395	($outer_reader: expr, $reader: expr, $field: ident, optional_vec) => {{
396		let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
397		$field = Some(f.0);
398	}};
399	// `upgradable_required` indicates we're reading a required TLV that may have been upgraded
400	// without backwards compat. We'll error if the field is missing, and return `Ok(None)` if the
401	// field is present but we can no longer understand it.
402	// Note that this variant can only be used within a `MaybeReadable` read.
403	($outer_reader: expr, $reader: expr, $field: ident, upgradable_required) => {{
404		$field = match $crate::util::ser::MaybeReadable::read(&mut $reader)? {
405			Some(res) => res,
406			None => {
407				// If we successfully read a value but we don't know how to parse it, we give up
408				// and immediately return `None`. However, we need to make sure we read the correct
409				// number of bytes for this TLV stream, which is implicitly the end of the stream.
410				// Thus, we consume everything left in the `$outer_reader` here, ensuring that if
411				// we're being read as a part of another TLV stream we don't spuriously fail to
412				// deserialize the outer object due to a TLV length mismatch.
413				$crate::io_extras::copy($outer_reader, &mut $crate::io_extras::sink()).unwrap();
414				return Ok(None)
415			},
416		};
417	}};
418	// `upgradable_option` indicates we're reading an Option-al TLV that may have been upgraded
419	// without backwards compat. $field will be None if the TLV is missing or if the field is present
420	// but we can no longer understand it.
421	($outer_reader: expr, $reader: expr, $field: ident, upgradable_option) => {{
422		$field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
423		if $field.is_none() {
424			#[cfg(not(debug_assertions))] {
425				// In general, MaybeReadable implementations are required to consume all the bytes
426				// of the object even if they don't understand it, but due to a bug in the
427				// serialization format for `impl_writeable_tlv_based_enum_upgradable` we sometimes
428				// don't know how many bytes that is. In such cases, we'd like to spuriously allow
429				// TLV length mismatches, which we do here by calling `eat_remaining` so that the
430				// `s.bytes_remain()` check in `_decode_tlv_stream_range` doesn't fail.
431				$reader.eat_remaining()?;
432			}
433		}
434	}};
435	($outer_reader: expr, $reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
436		$field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
437	}};
438	($outer_reader: expr, $reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident, $encoder:ty))) => {{
439		$crate::_decode_tlv!($outer_reader, $reader, $field, (option, encoding: ($fieldty, $encoding)));
440	}};
441	($outer_reader: expr, $reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {{
442		$field = {
443			let field: $encoding<$fieldty> = ser::Readable::read(&mut $reader)?;
444			Some(field.0)
445		};
446	}};
447	($outer_reader: expr, $reader: expr, $field: ident, (option, encoding: $fieldty: ty)) => {{
448		$crate::_decode_tlv!($outer_reader, $reader, $field, option);
449	}};
450}
451
452/// Checks if `$val` matches `$type`.
453/// This is exported for use by other exported macros, do not use directly.
454#[doc(hidden)]
455#[macro_export]
456macro_rules! _decode_tlv_stream_match_check {
457	($val: ident, $type: expr, (static_value, $value: expr)) => { false };
458	($val: ident, $type: expr, $fieldty: tt) => { $val == $type }
459}
460
461/// Implements the TLVs deserialization part in a [`Readable`] implementation of a struct.
462///
463/// This should be called inside a method which returns `Result<_, `[`DecodeError`]`>`, such as
464/// [`Readable::read`]. It will either return an `Err` or ensure all `required` fields have been
465/// read and optionally read `optional` fields.
466///
467/// `$stream` must be a [`Read`] and will be fully consumed, reading until no more bytes remain
468/// (i.e. it returns [`DecodeError::ShortRead`]).
469///
470/// Fields MUST be sorted in `$type`-order.
471///
472/// Note that the lightning TLV requirements require that a single type not appear more than once,
473/// that TLVs are sorted in type-ascending order, and that any even types be understood by the
474/// decoder.
475///
476/// For example,
477/// ```
478/// # use lightning::decode_tlv_stream;
479/// # fn read<R: lightning::io::Read> (stream: &mut R) -> Result<(), lightning::ln::msgs::DecodeError> {
480/// let mut required_value = 0u64;
481/// let mut optional_value: Option<u64> = None;
482/// decode_tlv_stream!(stream, {
483///     (0, required_value, required),
484///     (2, optional_value, option),
485/// });
486/// // At this point, `required_value` has been overwritten with the TLV with type 0.
487/// // `optional_value` may have been overwritten, setting it to `Some` if a TLV with type 2 was
488/// // present.
489/// # Ok(())
490/// # }
491/// ```
492///
493/// [`Readable`]: crate::util::ser::Readable
494/// [`DecodeError`]: crate::ln::msgs::DecodeError
495/// [`Readable::read`]: crate::util::ser::Readable::read
496/// [`Read`]: crate::io::Read
497/// [`DecodeError::ShortRead`]: crate::ln::msgs::DecodeError::ShortRead
498#[macro_export]
499macro_rules! decode_tlv_stream {
500	($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
501		let rewind = |_, _| { unreachable!() };
502		$crate::_decode_tlv_stream_range!($stream, .., rewind, {$(($type, $field, $fieldty)),*});
503	}
504}
505
506/// Similar to [`decode_tlv_stream`] with a custom TLV decoding capabilities.
507///
508/// `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
509/// If it is provided, it will be called with the custom type and the [`FixedLengthReader`] containing
510/// the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
511/// `Ok(false)` if the message type is unknown, and `Err(`[`DecodeError`]`)` if parsing fails.
512///
513/// [`FixedLengthReader`]: crate::util::ser::FixedLengthReader
514/// [`DecodeError`]: crate::ln::msgs::DecodeError
515macro_rules! decode_tlv_stream_with_custom_tlv_decode {
516	($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
517	 $(, $decode_custom_tlv: expr)?) => { {
518		let rewind = |_, _| { unreachable!() };
519		_decode_tlv_stream_range!(
520			$stream, .., rewind, {$(($type, $field, $fieldty)),*} $(, $decode_custom_tlv)?
521		);
522	} }
523}
524
525#[doc(hidden)]
526#[macro_export]
527macro_rules! _decode_tlv_stream_range {
528	($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
529	 $(, $decode_custom_tlv: expr)?) => { {
530		use $crate::ln::msgs::DecodeError;
531		let mut last_seen_type: Option<u64> = None;
532		let stream_ref = $stream;
533		'tlv_read: loop {
534			use $crate::util::ser;
535
536			// First decode the type of this TLV:
537			let typ: ser::BigSize = {
538				// We track whether any bytes were read during the consensus_decode call to
539				// determine whether we should break or return ShortRead if we get an
540				// UnexpectedEof. This should in every case be largely cosmetic, but its nice to
541				// pass the TLV test vectors exactly, which require this distinction.
542				let mut tracking_reader = ser::ReadTrackingReader::new(stream_ref);
543				match <$crate::util::ser::BigSize as $crate::util::ser::Readable>::read(&mut tracking_reader) {
544					Err(DecodeError::ShortRead) => {
545						if !tracking_reader.have_read {
546							break 'tlv_read;
547						} else {
548							return Err(DecodeError::ShortRead);
549						}
550					},
551					Err(e) => return Err(e),
552					Ok(t) => if core::ops::RangeBounds::contains(&$range, &t.0) { t } else {
553						drop(tracking_reader);
554
555						// Assumes the type id is minimally encoded, which is enforced on read.
556						use $crate::util::ser::Writeable;
557						let bytes_read = t.serialized_length();
558						$rewind(stream_ref, bytes_read);
559						break 'tlv_read;
560					},
561				}
562			};
563
564			// Types must be unique and monotonically increasing:
565			match last_seen_type {
566				Some(t) if typ.0 <= t => {
567					return Err(DecodeError::InvalidValue);
568				},
569				_ => {},
570			}
571			// As we read types, make sure we hit every required type between `last_seen_type` and `typ`:
572			$({
573				$crate::_check_decoded_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
574			})*
575			last_seen_type = Some(typ.0);
576
577			// Finally, read the length and value itself:
578			let length: ser::BigSize = $crate::util::ser::Readable::read(stream_ref)?;
579			let mut s = ser::FixedLengthReader::new(stream_ref, length.0);
580			match typ.0 {
581				$(_t if $crate::_decode_tlv_stream_match_check!(_t, $type, $fieldty) => {
582					$crate::_decode_tlv!($stream, s, $field, $fieldty);
583					if s.bytes_remain() {
584						s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
585						return Err(DecodeError::InvalidValue);
586					}
587				},)*
588				t => {
589					$(
590						if $decode_custom_tlv(t, &mut s)? {
591							// If a custom TLV was successfully read (i.e. decode_custom_tlv returns true),
592							// continue to the next TLV read.
593							s.eat_remaining()?;
594							continue 'tlv_read;
595						}
596					)?
597					if t % 2 == 0 {
598						return Err(DecodeError::UnknownRequiredFeature);
599					}
600				}
601			}
602			s.eat_remaining()?;
603		}
604		// Make sure we got to each required type after we've read every TLV:
605		$({
606			$crate::_check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
607		})*
608	} }
609}
610
611/// Implements [`Readable`]/[`Writeable`] for a message struct that may include non-TLV and
612/// TLV-encoded parts.
613///
614/// This is useful to implement a [`CustomMessageReader`].
615///
616/// Currently `$fieldty` may only be `option`, i.e., `$tlvfield` is optional field.
617///
618/// For example,
619/// ```
620/// # use lightning::impl_writeable_msg;
621/// struct MyCustomMessage {
622/// 	pub field_1: u32,
623/// 	pub field_2: bool,
624/// 	pub field_3: String,
625/// 	pub tlv_optional_integer: Option<u32>,
626/// }
627///
628/// impl_writeable_msg!(MyCustomMessage, {
629/// 	field_1,
630/// 	field_2,
631/// 	field_3
632/// }, {
633/// 	(1, tlv_optional_integer, option),
634/// });
635/// ```
636///
637/// [`Readable`]: crate::util::ser::Readable
638/// [`Writeable`]: crate::util::ser::Writeable
639/// [`CustomMessageReader`]: crate::ln::wire::CustomMessageReader
640#[macro_export]
641macro_rules! impl_writeable_msg {
642	($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
643		impl $crate::util::ser::Writeable for $st {
644			fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
645				$( self.$field.write(w)?; )*
646				$crate::encode_tlv_stream!(w, {$(($type, self.$tlvfield.as_ref(), $fieldty)),*});
647				Ok(())
648			}
649		}
650		impl $crate::util::ser::Readable for $st {
651			fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
652				$(let $field = $crate::util::ser::Readable::read(r)?;)*
653				$($crate::_init_tlv_field_var!($tlvfield, $fieldty);)*
654				$crate::decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
655				Ok(Self {
656					$($field,)*
657					$($tlvfield),*
658				})
659			}
660		}
661	}
662}
663
664macro_rules! impl_writeable {
665	($st:ident, {$($field:ident),*}) => {
666		impl $crate::util::ser::Writeable for $st {
667			fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
668				$( self.$field.write(w)?; )*
669				Ok(())
670			}
671
672			#[inline]
673			fn serialized_length(&self) -> usize {
674				let mut len_calc = 0;
675				$( len_calc += self.$field.serialized_length(); )*
676				return len_calc;
677			}
678		}
679
680		impl $crate::util::ser::Readable for $st {
681			fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
682				Ok(Self {
683					$($field: $crate::util::ser::Readable::read(r)?),*
684				})
685			}
686		}
687	}
688}
689
690/// Write out two bytes to indicate the version of an object.
691///
692/// $this_version represents a unique version of a type. Incremented whenever the type's
693/// serialization format has changed or has a new interpretation. Used by a type's reader to
694/// determine how to interpret fields or if it can understand a serialized object.
695///
696/// $min_version_that_can_read_this is the minimum reader version which can understand this
697/// serialized object. Previous versions will simply err with a [`DecodeError::UnknownVersion`].
698///
699/// Updates to either `$this_version` or `$min_version_that_can_read_this` should be included in
700/// release notes.
701///
702/// Both version fields can be specific to this type of object.
703///
704/// [`DecodeError::UnknownVersion`]: crate::ln::msgs::DecodeError::UnknownVersion
705macro_rules! write_ver_prefix {
706	($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
707		$stream.write_all(&[$this_version; 1])?;
708		$stream.write_all(&[$min_version_that_can_read_this; 1])?;
709	}
710}
711
712/// Writes out a suffix to an object as a length-prefixed TLV stream which contains potentially
713/// backwards-compatible, optional fields which old nodes can happily ignore.
714///
715/// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
716/// [`DecodeError::UnknownRequiredFeature`] error, with unknown odd fields ignored.
717///
718/// This is the preferred method of adding new fields that old nodes can ignore and still function
719/// correctly.
720///
721/// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
722#[macro_export]
723macro_rules! write_tlv_fields {
724	($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
725		$crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
726	}
727}
728
729/// Reads a prefix added by [`write_ver_prefix`], above. Takes the current version of the
730/// serialization logic for this object. This is compared against the
731/// `$min_version_that_can_read_this` added by [`write_ver_prefix`].
732macro_rules! read_ver_prefix {
733	($stream: expr, $this_version: expr) => { {
734		let ver: u8 = Readable::read($stream)?;
735		let min_ver: u8 = Readable::read($stream)?;
736		if min_ver > $this_version {
737			return Err(DecodeError::UnknownVersion);
738		}
739		ver
740	} }
741}
742
743/// Reads a suffix added by [`write_tlv_fields`].
744///
745/// [`write_tlv_fields`]: crate::write_tlv_fields
746#[macro_export]
747macro_rules! read_tlv_fields {
748	($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
749		let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
750		let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
751		$crate::decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
752		rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
753	} }
754}
755
756/// Initializes the struct fields.
757///
758/// This is exported for use by other exported macros, do not use directly.
759#[doc(hidden)]
760#[macro_export]
761macro_rules! _init_tlv_based_struct_field {
762	($field: ident, (default_value, $default: expr)) => {
763		$field.0.unwrap()
764	};
765	($field: ident, (static_value, $value: expr)) => {
766		$field
767	};
768	($field: ident, option) => {
769		$field
770	};
771	($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
772		$crate::_init_tlv_based_struct_field!($field, option)
773	};
774	($field: ident, upgradable_required) => {
775		$field.0.unwrap()
776	};
777	($field: ident, upgradable_option) => {
778		$field
779	};
780	($field: ident, required) => {
781		$field.0.unwrap()
782	};
783	($field: ident, required_vec) => {
784		$field
785	};
786	($field: ident, optional_vec) => {
787		$field.unwrap()
788	};
789}
790
791/// Initializes the variable we are going to read the TLV into.
792///
793/// This is exported for use by other exported macros, do not use directly.
794#[doc(hidden)]
795#[macro_export]
796macro_rules! _init_tlv_field_var {
797	($field: ident, (default_value, $default: expr)) => {
798		let mut $field = $crate::util::ser::RequiredWrapper(None);
799	};
800	($field: ident, (static_value, $value: expr)) => {
801		let $field;
802	};
803	($field: ident, required) => {
804		let mut $field = $crate::util::ser::RequiredWrapper(None);
805	};
806	($field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {
807		$crate::_init_tlv_field_var!($field, required);
808	};
809	($field: ident, required_vec) => {
810		let mut $field = Vec::new();
811	};
812	($field: ident, option) => {
813		let mut $field = None;
814	};
815	($field: ident, optional_vec) => {
816		let mut $field = Some(Vec::new());
817	};
818	($field: ident, (option, explicit_type: $fieldty: ty)) => {
819		let mut $field: Option<$fieldty> = None;
820	};
821	($field: ident, (required, explicit_type: $fieldty: ty)) => {
822		let mut $field = $crate::util::ser::RequiredWrapper::<$fieldty>(None);
823	};
824	($field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
825		$crate::_init_tlv_field_var!($field, option);
826	};
827	($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
828		$crate::_init_tlv_field_var!($field, option);
829	};
830	($field: ident, upgradable_required) => {
831		let mut $field = $crate::util::ser::UpgradableRequired(None);
832	};
833	($field: ident, upgradable_option) => {
834		let mut $field = None;
835	};
836}
837
838/// Equivalent to running [`_init_tlv_field_var`] then [`read_tlv_fields`].
839///
840/// If any unused values are read, their type MUST be specified or else `rustc` will read them as an
841/// `i64`.
842///
843/// This is exported for use by other exported macros, do not use directly.
844#[doc(hidden)]
845#[macro_export]
846macro_rules! _init_and_read_len_prefixed_tlv_fields {
847	($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
848		$(
849			$crate::_init_tlv_field_var!($field, $fieldty);
850		)*
851
852		$crate::read_tlv_fields!($reader, {
853			$(($type, $field, $fieldty)),*
854		});
855	}
856}
857
858/// Equivalent to running [`_init_tlv_field_var`] then [`decode_tlv_stream`].
859///
860/// If any unused values are read, their type MUST be specified or else `rustc` will read them as an
861/// `i64`.
862macro_rules! _init_and_read_tlv_stream {
863	($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
864		$(
865			$crate::_init_tlv_field_var!($field, $fieldty);
866		)*
867
868		$crate::decode_tlv_stream!($reader, {
869			$(($type, $field, $fieldty)),*
870		});
871	}
872}
873
874/// Implements [`Readable`]/[`Writeable`] for a struct storing it as a set of TLVs
875/// If `$fieldty` is `required`, then `$field` is a required field that is not an [`Option`] nor a [`Vec`].
876/// If `$fieldty` is `(default_value, $default)`, then `$field` will be set to `$default` if not present.
877/// If `$fieldty` is `option`, then `$field` is optional field.
878/// If `$fieldty` is `optional_vec`, then `$field` is a [`Vec`], which needs to have its individual elements serialized.
879///    Note that for `optional_vec` no bytes are written if the vec is empty
880///
881/// For example,
882/// ```
883/// # use lightning::impl_writeable_tlv_based;
884/// struct LightningMessage {
885/// 	tlv_integer: u32,
886/// 	tlv_default_integer: u32,
887/// 	tlv_optional_integer: Option<u32>,
888/// 	tlv_vec_type_integer: Vec<u32>,
889/// }
890///
891/// impl_writeable_tlv_based!(LightningMessage, {
892/// 	(0, tlv_integer, required),
893/// 	(1, tlv_default_integer, (default_value, 7)),
894/// 	(2, tlv_optional_integer, option),
895/// 	(3, tlv_vec_type_integer, optional_vec),
896/// });
897/// ```
898///
899/// [`Readable`]: crate::util::ser::Readable
900/// [`Writeable`]: crate::util::ser::Writeable
901/// [`Vec`]: crate::prelude::Vec
902#[macro_export]
903macro_rules! impl_writeable_tlv_based {
904	($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
905		impl $crate::util::ser::Writeable for $st {
906			fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
907				$crate::write_tlv_fields!(writer, {
908					$(($type, self.$field, $fieldty)),*
909				});
910				Ok(())
911			}
912
913			#[inline]
914			fn serialized_length(&self) -> usize {
915				use $crate::util::ser::BigSize;
916				let len = {
917					#[allow(unused_mut)]
918					let mut len = $crate::util::ser::LengthCalculatingWriter(0);
919					$(
920						$crate::_get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
921					)*
922					len.0
923				};
924				let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
925				BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
926				len + len_calc.0
927			}
928		}
929
930		impl $crate::util::ser::Readable for $st {
931			fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
932				$crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
933					$(($type, $field, $fieldty)),*
934				});
935				Ok(Self {
936					$(
937						$field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
938					),*
939				})
940			}
941		}
942	}
943}
944
945/// Defines a struct for a TLV stream and a similar struct using references for non-primitive types,
946/// implementing [`Readable`] for the former and [`Writeable`] for the latter. Useful as an
947/// intermediary format when reading or writing a type encoded as a TLV stream. Note that each field
948/// representing a TLV record has its type wrapped with an [`Option`]. A tuple consisting of a type
949/// and a serialization wrapper may be given in place of a type when custom serialization is
950/// required.
951///
952/// [`Readable`]: crate::util::ser::Readable
953/// [`Writeable`]: crate::util::ser::Writeable
954macro_rules! tlv_stream {
955	($name:ident, $nameref:ident $(<$lifetime:lifetime>)?, $range:expr, {
956		$(($type:expr, $field:ident : $fieldty:tt)),* $(,)*
957	}) => {
958		#[derive(Debug)]
959		pub(super) struct $name {
960			$(
961				pub(super) $field: Option<tlv_record_type!($fieldty)>,
962			)*
963		}
964
965		#[cfg_attr(test, derive(PartialEq))]
966		#[derive(Debug)]
967		pub(crate) struct $nameref<$($lifetime)*> {
968			$(
969				pub(super) $field: Option<tlv_record_ref_type!($fieldty)>,
970			)*
971		}
972
973		impl<$($lifetime)*> $crate::util::ser::Writeable for $nameref<$($lifetime)*> {
974			fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
975				encode_tlv_stream!(writer, {
976					$(($type, self.$field, (option, encoding: $fieldty))),*
977				});
978				Ok(())
979			}
980		}
981
982		impl $crate::util::ser::CursorReadable for $name {
983			fn read<R: AsRef<[u8]>>(reader: &mut crate::io::Cursor<R>) -> Result<Self, $crate::ln::msgs::DecodeError> {
984				$(
985					_init_tlv_field_var!($field, option);
986				)*
987				let rewind = |cursor: &mut crate::io::Cursor<R>, offset: usize| {
988					cursor.set_position(cursor.position().checked_sub(offset as u64).expect("Cannot rewind past 0."));
989				};
990				_decode_tlv_stream_range!(reader, $range, rewind, {
991					$(($type, $field, (option, encoding: $fieldty))),*
992				});
993
994				Ok(Self {
995					$(
996						$field: $field
997					),*
998				})
999			}
1000		}
1001	}
1002}
1003
1004macro_rules! tlv_record_type {
1005	(($type:ty, $wrapper:ident)) => { $type };
1006	(($type:ty, $wrapper:ident, $encoder:ty)) => { $type };
1007	($type:ty) => { $type };
1008}
1009
1010macro_rules! tlv_record_ref_type {
1011	(char) => { char };
1012	(u8) => { u8 };
1013	((u16, $wrapper: ident)) => { u16 };
1014	((u32, $wrapper: ident)) => { u32 };
1015	((u64, $wrapper: ident)) => { u64 };
1016	(($type:ty, $wrapper:ident)) => { &'a $type };
1017	(($type:ty, $wrapper:ident, $encoder:ty)) => { $encoder };
1018	($type:ty) => { &'a $type };
1019}
1020
1021#[doc(hidden)]
1022#[macro_export]
1023macro_rules! _impl_writeable_tlv_based_enum_common {
1024	($st: ident, $(($variant_id: expr, $variant_name: ident) =>
1025		{$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1026	),* $(,)?;
1027	// $tuple_variant_* are only passed from `impl_writeable_tlv_based_enum_*_legacy`
1028	$(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)?;
1029	// $length_prefixed_* are only passed from `impl_writeable_tlv_based_enum_*` non-`legacy`
1030	$(($length_prefixed_tuple_variant_id: expr, $length_prefixed_tuple_variant_name: ident)),* $(,)?) => {
1031		impl $crate::util::ser::Writeable for $st {
1032			fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
1033				match self {
1034					$($st::$variant_name { $(ref $field, )* .. } => {
1035						let id: u8 = $variant_id;
1036						id.write(writer)?;
1037						$crate::write_tlv_fields!(writer, {
1038							$(($type, *$field, $fieldty)),*
1039						});
1040					}),*
1041					$($st::$tuple_variant_name (ref field) => {
1042						let id: u8 = $tuple_variant_id;
1043						id.write(writer)?;
1044						field.write(writer)?;
1045					}),*
1046					$($st::$length_prefixed_tuple_variant_name (ref field) => {
1047						let id: u8 = $length_prefixed_tuple_variant_id;
1048						id.write(writer)?;
1049						$crate::util::ser::BigSize(field.serialized_length() as u64).write(writer)?;
1050						field.write(writer)?;
1051					}),*
1052				}
1053				Ok(())
1054			}
1055		}
1056	}
1057}
1058
1059/// Implement [`Readable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and tuple
1060/// variants stored directly.
1061///
1062/// The format is, for example,
1063/// ```
1064/// enum EnumName {
1065///   StructVariantA {
1066///     required_variant_field: u64,
1067///     optional_variant_field: Option<u8>,
1068///   },
1069///   StructVariantB {
1070///     variant_field_a: bool,
1071///     variant_field_b: u32,
1072///     variant_vec_field: Vec<u32>,
1073///   },
1074///   TupleVariantA(),
1075///   TupleVariantB(Vec<u8>),
1076/// }
1077/// # use lightning::impl_writeable_tlv_based_enum;
1078/// impl_writeable_tlv_based_enum!(EnumName,
1079///   (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
1080///   (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, optional_vec)},
1081///   (2, TupleVariantA) => {}, // Note that empty tuple variants have to use the struct syntax due to rust limitations
1082///   {3, TupleVariantB} => (),
1083/// );
1084/// ```
1085///
1086/// The type is written as a single byte, followed by length-prefixed variant data.
1087///
1088/// Attempts to read an unknown type byte result in [`DecodeError::UnknownRequiredFeature`].
1089///
1090/// Note that the serialization for tuple variants (as well as the call format) was changed in LDK
1091/// 0.0.124.
1092///
1093/// [`Readable`]: crate::util::ser::Readable
1094/// [`Writeable`]: crate::util::ser::Writeable
1095/// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
1096#[macro_export]
1097macro_rules! impl_writeable_tlv_based_enum {
1098	($st: ident,
1099		$(($variant_id: expr, $variant_name: ident) =>
1100			{$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1101		),*
1102		$($(,)? {$tuple_variant_id: expr, $tuple_variant_name: ident} => ()),*
1103		$(,)?
1104	) => {
1105		$crate::_impl_writeable_tlv_based_enum_common!($st,
1106			$(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*
1107			;;
1108			$(($tuple_variant_id, $tuple_variant_name)),*);
1109
1110		impl $crate::util::ser::Readable for $st {
1111			#[allow(unused_mut)]
1112			fn read<R: $crate::io::Read>(mut reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
1113				let id: u8 = $crate::util::ser::Readable::read(reader)?;
1114				match id {
1115					$($variant_id => {
1116						// Because read_tlv_fields creates a labeled loop, we cannot call it twice
1117						// in the same function body. Instead, we define a closure and call it.
1118						let mut f = || {
1119							$crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
1120								$(($type, $field, $fieldty)),*
1121							});
1122							Ok($st::$variant_name {
1123								$(
1124									$field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1125								),*
1126							})
1127						};
1128						f()
1129					}),*
1130					$($tuple_variant_id => {
1131						let length: $crate::util::ser::BigSize = $crate::util::ser::Readable::read(reader)?;
1132						let mut s = $crate::util::ser::FixedLengthReader::new(reader, length.0);
1133						let res = $crate::util::ser::Readable::read(&mut s)?;
1134						if s.bytes_remain() {
1135							s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
1136							return Err($crate::ln::msgs::DecodeError::InvalidValue);
1137						}
1138						Ok($st::$tuple_variant_name(res))
1139					}),*
1140					_ => {
1141						Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature)
1142					},
1143				}
1144			}
1145		}
1146	}
1147}
1148
1149/// See [`impl_writeable_tlv_based_enum`] and use that unless backwards-compatibility with tuple
1150/// variants is required.
1151macro_rules! impl_writeable_tlv_based_enum_legacy {
1152	($st: ident, $(($variant_id: expr, $variant_name: ident) =>
1153		{$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1154	),* $(,)*;
1155	$(($tuple_variant_id: expr, $tuple_variant_name: ident)),+  $(,)?) => {
1156		$crate::_impl_writeable_tlv_based_enum_common!($st,
1157			$(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
1158			$(($tuple_variant_id, $tuple_variant_name)),+;);
1159
1160		impl $crate::util::ser::Readable for $st {
1161			fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
1162				let id: u8 = $crate::util::ser::Readable::read(reader)?;
1163				match id {
1164					$($variant_id => {
1165						// Because read_tlv_fields creates a labeled loop, we cannot call it twice
1166						// in the same function body. Instead, we define a closure and call it.
1167						let mut f = || {
1168							$crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
1169								$(($type, $field, $fieldty)),*
1170							});
1171							Ok($st::$variant_name {
1172								$(
1173									$field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1174								),*
1175							})
1176						};
1177						f()
1178					}),*
1179					$($tuple_variant_id => {
1180						Ok($st::$tuple_variant_name($crate::util::ser::Readable::read(reader)?))
1181					}),+
1182					_ => {
1183						Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature)
1184					},
1185				}
1186			}
1187		}
1188	}
1189}
1190
1191/// Implement [`MaybeReadable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and
1192/// tuple variants stored directly.
1193///
1194/// This is largely identical to [`impl_writeable_tlv_based_enum`], except that odd variants will
1195/// return `Ok(None)` instead of `Err(`[`DecodeError::UnknownRequiredFeature`]`)`. It should generally be preferred
1196/// when [`MaybeReadable`] is practical instead of just [`Readable`] as it provides an upgrade path for
1197/// new variants to be added which are simply ignored by existing clients.
1198///
1199/// Note that the serialization for tuple variants (as well as the call format) was changed in LDK
1200/// 0.0.124.
1201///
1202/// [`MaybeReadable`]: crate::util::ser::MaybeReadable
1203/// [`Writeable`]: crate::util::ser::Writeable
1204/// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
1205/// [`Readable`]: crate::util::ser::Readable
1206#[macro_export]
1207macro_rules! impl_writeable_tlv_based_enum_upgradable {
1208	($st: ident,
1209		$(($variant_id: expr, $variant_name: ident) =>
1210			{$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1211		),*
1212		$(, {$tuple_variant_id: expr, $tuple_variant_name: ident} => ())*
1213		$(, unread_variants: $($unread_variant: ident),*)?
1214		$(,)?
1215	) => {
1216		$crate::_impl_writeable_tlv_based_enum_common!($st,
1217			$(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*
1218			$(, $((255, $unread_variant) => {}),*)?
1219			;;
1220			$(($tuple_variant_id, $tuple_variant_name)),*);
1221
1222		impl $crate::util::ser::MaybeReadable for $st {
1223			#[allow(unused_mut)]
1224			fn read<R: $crate::io::Read>(mut reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
1225				let id: u8 = $crate::util::ser::Readable::read(reader)?;
1226				match id {
1227					$($variant_id => {
1228						// Because read_tlv_fields creates a labeled loop, we cannot call it twice
1229						// in the same function body. Instead, we define a closure and call it.
1230						let mut f = || {
1231							$crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
1232								$(($type, $field, $fieldty)),*
1233							});
1234							Ok(Some($st::$variant_name {
1235								$(
1236									$field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1237								),*
1238							}))
1239						};
1240						f()
1241					}),*
1242					$($tuple_variant_id => {
1243						let length: $crate::util::ser::BigSize = $crate::util::ser::Readable::read(reader)?;
1244						let mut s = $crate::util::ser::FixedLengthReader::new(reader, length.0);
1245						let res = $crate::util::ser::Readable::read(&mut s)?;
1246						if s.bytes_remain() {
1247							s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
1248							return Err($crate::ln::msgs::DecodeError::InvalidValue);
1249						}
1250						Ok(Some($st::$tuple_variant_name(res)))
1251					}),*
1252					// Note that we explicitly match 255 here to reserve it for use in
1253					// `unread_variants`.
1254					255|_ if id % 2 == 1 => {
1255						let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read(reader)?;
1256						let mut rd = $crate::util::ser::FixedLengthReader::new(reader, tlv_len.0);
1257						rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
1258						Ok(None)
1259					},
1260					_ => Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature),
1261				}
1262			}
1263		}
1264	}
1265}
1266
1267/// See [`impl_writeable_tlv_based_enum_upgradable`] and use that unless backwards-compatibility
1268/// with tuple variants is required.
1269macro_rules! impl_writeable_tlv_based_enum_upgradable_legacy {
1270	($st: ident, $(($variant_id: expr, $variant_name: ident) =>
1271		{$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1272	),* $(,)?
1273	;
1274	$(($tuple_variant_id: expr, $tuple_variant_name: ident)),+  $(,)?) => {
1275		$crate::_impl_writeable_tlv_based_enum_common!($st,
1276			$(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
1277			$(($tuple_variant_id, $tuple_variant_name)),+;);
1278
1279		impl $crate::util::ser::MaybeReadable for $st {
1280			fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
1281				let id: u8 = $crate::util::ser::Readable::read(reader)?;
1282				match id {
1283					$($variant_id => {
1284						// Because read_tlv_fields creates a labeled loop, we cannot call it twice
1285						// in the same function body. Instead, we define a closure and call it.
1286						let mut f = || {
1287							$crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
1288								$(($type, $field, $fieldty)),*
1289							});
1290							Ok(Some($st::$variant_name {
1291								$(
1292									$field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1293								),*
1294							}))
1295						};
1296						f()
1297					}),*
1298					$($tuple_variant_id => {
1299						Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
1300					}),+
1301					_ if id % 2 == 1 => {
1302						// Assume that a $variant_id was written, not a $tuple_variant_id, and read
1303						// the length prefix and discard the correct number of bytes.
1304						let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read(reader)?;
1305						let mut rd = $crate::util::ser::FixedLengthReader::new(reader, tlv_len.0);
1306						rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
1307						Ok(None)
1308					},
1309					_ => Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature),
1310				}
1311			}
1312		}
1313	}
1314}
1315
1316#[cfg(test)]
1317mod tests {
1318	#[allow(unused_imports)]
1319	use crate::prelude::*;
1320
1321	use crate::io::{self, Cursor};
1322	use crate::ln::msgs::DecodeError;
1323	use crate::util::ser::{MaybeReadable, Readable, Writeable, HighZeroBytesDroppedBigSize, VecWriter};
1324	use bitcoin::hex::FromHex;
1325	use bitcoin::secp256k1::PublicKey;
1326
1327	// The BOLT TLV test cases don't include any tests which use our "required-value" logic since
1328	// the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
1329	// work with so they're baked into the decoder. Thus, we have a few additional tests below
1330	fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
1331		let mut s = Cursor::new(s);
1332		let mut a: u64 = 0;
1333		let mut b: u32 = 0;
1334		let mut c: Option<u32> = None;
1335		decode_tlv_stream!(&mut s, {(2, a, required), (3, b, required), (4, c, option)});
1336		Ok((a, b, c))
1337	}
1338
1339	#[test]
1340	fn tlv_v_short_read() {
1341		// We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
1342		if let Err(DecodeError::ShortRead) = tlv_reader(&<Vec<u8>>::from_hex(
1343				concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
1344				).unwrap()[..]) {
1345		} else { panic!(); }
1346	}
1347
1348	#[test]
1349	fn tlv_types_out_of_order() {
1350		if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1351				concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
1352				).unwrap()[..]) {
1353		} else { panic!(); }
1354		// ...even if its some field we don't understand
1355		if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1356				concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
1357				).unwrap()[..]) {
1358		} else { panic!(); }
1359	}
1360
1361	#[test]
1362	fn tlv_req_type_missing_or_extra() {
1363		// It's also bad if they included even fields we don't understand
1364		if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&<Vec<u8>>::from_hex(
1365				concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
1366				).unwrap()[..]) {
1367		} else { panic!(); }
1368		// ... or if they're missing fields we need
1369		if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1370				concat!("0100", "0208deadbeef1badbeef")
1371				).unwrap()[..]) {
1372		} else { panic!(); }
1373		// ... even if that field is even
1374		if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1375				concat!("0304deadbeef", "0500")
1376				).unwrap()[..]) {
1377		} else { panic!(); }
1378	}
1379
1380	#[test]
1381	fn tlv_simple_good_cases() {
1382		assert_eq!(tlv_reader(&<Vec<u8>>::from_hex(
1383				concat!("0208deadbeef1badbeef", "03041bad1dea")
1384				).unwrap()[..]).unwrap(),
1385			(0xdeadbeef1badbeef, 0x1bad1dea, None));
1386		assert_eq!(tlv_reader(&<Vec<u8>>::from_hex(
1387				concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
1388				).unwrap()[..]).unwrap(),
1389			(0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
1390	}
1391
1392	#[derive(Debug, PartialEq)]
1393	struct TestUpgradable {
1394		a: u32,
1395		b: u32,
1396		c: Option<u32>,
1397	}
1398
1399	fn upgradable_tlv_reader(s: &[u8]) -> Result<Option<TestUpgradable>, DecodeError> {
1400		let mut s = Cursor::new(s);
1401		let mut a = 0;
1402		let mut b = 0;
1403		let mut c: Option<u32> = None;
1404		decode_tlv_stream!(&mut s, {(2, a, upgradable_required), (3, b, upgradable_required), (4, c, upgradable_option)});
1405		Ok(Some(TestUpgradable { a, b, c, }))
1406	}
1407
1408	#[test]
1409	fn upgradable_tlv_simple_good_cases() {
1410		assert_eq!(upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1411			concat!("0204deadbeef", "03041bad1dea", "0404deadbeef")
1412		).unwrap()[..]).unwrap(),
1413		Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: Some(0xdeadbeef) }));
1414
1415		assert_eq!(upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1416			concat!("0204deadbeef", "03041bad1dea")
1417		).unwrap()[..]).unwrap(),
1418		Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: None}));
1419	}
1420
1421	#[test]
1422	fn missing_required_upgradable() {
1423		if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1424			concat!("0100", "0204deadbeef")
1425			).unwrap()[..]) {
1426		} else { panic!(); }
1427		if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1428			concat!("0100", "03041bad1dea")
1429		).unwrap()[..]) {
1430		} else { panic!(); }
1431	}
1432
1433	/// A "V1" enum with only one variant
1434	enum InnerEnumV1 {
1435		StructVariantA {
1436			field: u32,
1437		},
1438	}
1439
1440	impl_writeable_tlv_based_enum_upgradable!(InnerEnumV1,
1441		(0, StructVariantA) => {
1442			(0, field, required),
1443		},
1444	);
1445
1446	struct OuterStructOptionalEnumV1 {
1447		inner_enum: Option<InnerEnumV1>,
1448		other_field: u32,
1449	}
1450
1451	impl_writeable_tlv_based!(OuterStructOptionalEnumV1, {
1452		(0, inner_enum, upgradable_option),
1453		(2, other_field, required),
1454	});
1455
1456	/// An upgraded version of [`InnerEnumV1`] that added a second variant
1457	enum InnerEnumV2 {
1458		StructVariantA {
1459			field: u32,
1460		},
1461		StructVariantB {
1462			field2: u64,
1463		}
1464	}
1465
1466	impl_writeable_tlv_based_enum_upgradable!(InnerEnumV2,
1467		(0, StructVariantA) => {
1468			(0, field, required),
1469		},
1470		(1, StructVariantB) => {
1471			(0, field2, required),
1472		},
1473	);
1474
1475	struct OuterStructOptionalEnumV2 {
1476		inner_enum: Option<InnerEnumV2>,
1477		other_field: u32,
1478	}
1479
1480	impl_writeable_tlv_based!(OuterStructOptionalEnumV2, {
1481		(0, inner_enum, upgradable_option),
1482		(2, other_field, required),
1483	});
1484
1485	#[test]
1486	fn upgradable_enum_option() {
1487		// Test downgrading from `OuterStructOptionalEnumV2` to `OuterStructOptionalEnumV1` and
1488		// ensure we still read the `other_field` just fine.
1489		let serialized_bytes = OuterStructOptionalEnumV2 {
1490			inner_enum: Some(InnerEnumV2::StructVariantB { field2: 64 }),
1491			other_field: 0x1bad1dea,
1492		}.encode();
1493		let mut s = Cursor::new(serialized_bytes);
1494
1495		let outer_struct: OuterStructOptionalEnumV1 = Readable::read(&mut s).unwrap();
1496		assert!(outer_struct.inner_enum.is_none());
1497		assert_eq!(outer_struct.other_field, 0x1bad1dea);
1498	}
1499
1500	/// A struct that is read with an [`InnerEnumV1`] but is written with an [`InnerEnumV2`].
1501	struct OuterStructRequiredEnum {
1502		#[allow(unused)]
1503		inner_enum: InnerEnumV1,
1504	}
1505
1506	impl MaybeReadable for OuterStructRequiredEnum {
1507		fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
1508			let mut inner_enum = crate::util::ser::UpgradableRequired(None);
1509			read_tlv_fields!(reader, {
1510				(0, inner_enum, upgradable_required),
1511			});
1512			Ok(Some(Self {
1513				inner_enum: inner_enum.0.unwrap(),
1514			}))
1515		}
1516	}
1517
1518	impl Writeable for OuterStructRequiredEnum {
1519		fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1520			write_tlv_fields!(writer, {
1521				(0, InnerEnumV2::StructVariantB { field2: 0xdeadbeef }, required),
1522			});
1523			Ok(())
1524		}
1525	}
1526
1527	struct OuterOuterStruct {
1528		outer_struct: Option<OuterStructRequiredEnum>,
1529		other_field: u32,
1530	}
1531
1532	impl_writeable_tlv_based!(OuterOuterStruct, {
1533		(0, outer_struct, upgradable_option),
1534		(2, other_field, required),
1535	});
1536
1537
1538	#[test]
1539	fn upgradable_enum_required() {
1540		// Test downgrading from an `OuterOuterStruct` (i.e. test downgrading an
1541		// `upgradable_required` `InnerEnumV2` to an `InnerEnumV1`).
1542		//
1543		// Note that `OuterStructRequiredEnum` has a split write/read implementation that writes an
1544		// `InnerEnumV2::StructVariantB` irrespective of the value of `inner_enum`.
1545
1546		let dummy_inner_enum = InnerEnumV1::StructVariantA { field: 42 };
1547		let serialized_bytes = OuterOuterStruct {
1548			outer_struct: Some(OuterStructRequiredEnum { inner_enum: dummy_inner_enum }),
1549			other_field: 0x1bad1dea,
1550		}.encode();
1551		let mut s = Cursor::new(serialized_bytes);
1552
1553		let outer_outer_struct: OuterOuterStruct = Readable::read(&mut s).unwrap();
1554		assert!(outer_outer_struct.outer_struct.is_none());
1555		assert_eq!(outer_outer_struct.other_field, 0x1bad1dea);
1556	}
1557
1558	// BOLT TLV test cases
1559	fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedBigSize<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
1560		let mut s = Cursor::new(s);
1561		let mut tlv1: Option<HighZeroBytesDroppedBigSize<u64>> = None;
1562		let mut tlv2: Option<u64> = None;
1563		let mut tlv3: Option<(PublicKey, u64, u64)> = None;
1564		let mut tlv4: Option<u16> = None;
1565		decode_tlv_stream!(&mut s, {(1, tlv1, option), (2, tlv2, option), (3, tlv3, option), (254, tlv4, option)});
1566		Ok((tlv1, tlv2, tlv3, tlv4))
1567	}
1568
1569	#[test]
1570	fn bolt_tlv_bogus_stream() {
1571		macro_rules! do_test {
1572			($stream: expr, $reason: ident) => {
1573				if let Err(DecodeError::$reason) = tlv_reader_n1(&<Vec<u8>>::from_hex($stream).unwrap()[..]) {
1574				} else { panic!(); }
1575			}
1576		}
1577
1578		// TLVs from the BOLT test cases which should not decode as either n1 or n2
1579		do_test!(concat!("fd01"), ShortRead);
1580		do_test!(concat!("fd0001", "00"), InvalidValue);
1581		do_test!(concat!("fd0101"), ShortRead);
1582		do_test!(concat!("0f", "fd"), ShortRead);
1583		do_test!(concat!("0f", "fd26"), ShortRead);
1584		do_test!(concat!("0f", "fd2602"), ShortRead);
1585		do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
1586		do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
1587
1588		do_test!(concat!("12", "00"), UnknownRequiredFeature);
1589		do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
1590		do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
1591		do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
1592	}
1593
1594	#[test]
1595	fn bolt_tlv_bogus_n1_stream() {
1596		macro_rules! do_test {
1597			($stream: expr, $reason: ident) => {
1598				if let Err(DecodeError::$reason) = tlv_reader_n1(&<Vec<u8>>::from_hex($stream).unwrap()[..]) {
1599				} else { panic!(); }
1600			}
1601		}
1602
1603		// TLVs from the BOLT test cases which should not decode as n1
1604		do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
1605		do_test!(concat!("01", "01", "00"), InvalidValue);
1606		do_test!(concat!("01", "02", "0001"), InvalidValue);
1607		do_test!(concat!("01", "03", "000100"), InvalidValue);
1608		do_test!(concat!("01", "04", "00010000"), InvalidValue);
1609		do_test!(concat!("01", "05", "0001000000"), InvalidValue);
1610		do_test!(concat!("01", "06", "000100000000"), InvalidValue);
1611		do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
1612		do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
1613		do_test!(concat!("02", "07", "01010101010101"), ShortRead);
1614		do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
1615		do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
1616		do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
1617		do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
1618		do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
1619		do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
1620		do_test!(concat!("fd00fe", "00"), ShortRead);
1621		do_test!(concat!("fd00fe", "01", "01"), ShortRead);
1622		do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
1623		do_test!(concat!("00", "00"), UnknownRequiredFeature);
1624
1625		do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
1626		do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
1627		do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
1628		do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
1629
1630		// The last BOLT test modified to not require creating a new decoder for one trivial test.
1631		do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
1632	}
1633
1634	#[test]
1635	fn bolt_tlv_valid_n1_stream() {
1636		macro_rules! do_test {
1637			($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
1638				if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&<Vec<u8>>::from_hex($stream).unwrap()[..]) {
1639					assert_eq!(tlv1.map(|v| v.0), $tlv1);
1640					assert_eq!(tlv2, $tlv2);
1641					assert_eq!(tlv3, $tlv3);
1642					assert_eq!(tlv4, $tlv4);
1643				} else { panic!(); }
1644			}
1645		}
1646
1647		do_test!(concat!(""), None, None, None, None);
1648		do_test!(concat!("21", "00"), None, None, None, None);
1649		do_test!(concat!("fd0201", "00"), None, None, None, None);
1650		do_test!(concat!("fd00fd", "00"), None, None, None, None);
1651		do_test!(concat!("fd00ff", "00"), None, None, None, None);
1652		do_test!(concat!("fe02000001", "00"), None, None, None, None);
1653		do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
1654
1655		do_test!(concat!("01", "00"), Some(0), None, None, None);
1656		do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
1657		do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
1658		do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
1659		do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
1660		do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
1661		do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
1662		do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
1663		do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
1664		do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
1665		do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
1666			None, None, Some((
1667				PublicKey::from_slice(&<Vec<u8>>::from_hex("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
1668			None);
1669		do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
1670	}
1671
1672	fn do_simple_test_tlv_write() -> Result<(), io::Error> {
1673		let mut stream = VecWriter(Vec::new());
1674
1675		stream.0.clear();
1676		_encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
1677		assert_eq!(stream.0, <Vec<u8>>::from_hex("03010101").unwrap());
1678
1679		stream.0.clear();
1680		_encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
1681		assert_eq!(stream.0, <Vec<u8>>::from_hex("03010101").unwrap());
1682
1683		stream.0.clear();
1684		_encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
1685		assert_eq!(stream.0, <Vec<u8>>::from_hex("040402abcd").unwrap());
1686
1687		stream.0.clear();
1688		_encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
1689		assert_eq!(stream.0, <Vec<u8>>::from_hex("06fd00ff02abcd").unwrap());
1690
1691		stream.0.clear();
1692		_encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1693		assert_eq!(stream.0, <Vec<u8>>::from_hex("0e00080000000000000001fd00ff00").unwrap());
1694
1695		stream.0.clear();
1696		_encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1697		assert_eq!(stream.0, <Vec<u8>>::from_hex("0e00080000000000000001fd00ff00").unwrap());
1698
1699		Ok(())
1700	}
1701
1702	#[test]
1703	fn simple_test_tlv_write() {
1704		do_simple_test_tlv_write().unwrap();
1705	}
1706
1707	#[derive(Debug, Eq, PartialEq)]
1708	struct EmptyMsg {}
1709	impl_writeable_msg!(EmptyMsg, {}, {});
1710
1711	#[test]
1712	fn impl_writeable_msg_empty() {
1713		let msg = EmptyMsg {};
1714		let mut encoded_msg = msg.encode();
1715		assert!(encoded_msg.is_empty());
1716		let mut encoded_msg_stream = Cursor::new(&mut encoded_msg);
1717		let decoded_msg: EmptyMsg = Readable::read(&mut encoded_msg_stream).unwrap();
1718		assert_eq!(msg, decoded_msg);
1719	}
1720
1721	#[derive(Debug, PartialEq, Eq)]
1722	enum TuplesOnly {
1723		A(),
1724		B(u64),
1725	}
1726	impl_writeable_tlv_based_enum_upgradable!(TuplesOnly, (2, A) => {}, {3, B} => ());
1727
1728	#[test]
1729	fn test_impl_writeable_enum() {
1730		let a = TuplesOnly::A().encode();
1731		assert_eq!(TuplesOnly::read(&mut Cursor::new(&a)).unwrap(), Some(TuplesOnly::A()));
1732		let b42 = TuplesOnly::B(42).encode();
1733		assert_eq!(TuplesOnly::read(&mut Cursor::new(&b42)).unwrap(), Some(TuplesOnly::B(42)));
1734
1735		// Test unknown variants with 0-length data
1736		let unknown_variant = vec![41, 0];
1737		let mut none_read = Cursor::new(&unknown_variant);
1738		assert_eq!(TuplesOnly::read(&mut none_read).unwrap(), None);
1739		assert_eq!(none_read.position(), unknown_variant.len() as u64);
1740
1741		TuplesOnly::read(&mut Cursor::new(&vec![42, 0])).unwrap_err();
1742
1743		// Test unknown variants with data
1744		let unknown_data_variant = vec![41, 3, 42, 52, 62];
1745		let mut none_data_read = Cursor::new(&unknown_data_variant);
1746		assert_eq!(TuplesOnly::read(&mut none_data_read).unwrap(), None);
1747		assert_eq!(none_data_read.position(), unknown_data_variant.len() as u64);
1748	}
1749}