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