ser_macros: rename check_tlv_order
[rust-lightning] / lightning / src / 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 macro_rules! encode_tlv {
11         ($stream: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
12                 encode_tlv!($stream, $type, $field, required)
13         };
14         ($stream: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
15                 let _ = &$field; // Ensure we "use" the $field
16         };
17         ($stream: expr, $type: expr, $field: expr, required) => {
18                 BigSize($type).write($stream)?;
19                 BigSize($field.serialized_length() as u64).write($stream)?;
20                 $field.write($stream)?;
21         };
22         ($stream: expr, $type: expr, $field: expr, vec_type) => {
23                 encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required);
24         };
25         ($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
26                 if let Some(ref field) = $optional_field {
27                         BigSize($optional_type).write($stream)?;
28                         BigSize(field.serialized_length() as u64).write($stream)?;
29                         field.write($stream)?;
30                 }
31         };
32         ($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
33                 encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
34         };
35         ($stream: expr, $type: expr, $field: expr, (option, encoding: $fieldty: ty)) => {
36                 encode_tlv!($stream, $type, $field, option);
37         };
38 }
39
40
41 macro_rules! check_encoded_tlv_order {
42         ($last_type: expr, $type: expr, (static_value, $value: expr)) => { };
43         ($last_type: expr, $type: expr, $fieldty: tt) => {
44                 if let Some(t) = $last_type {
45                         debug_assert!(t <= $type);
46                 }
47                 $last_type = Some($type);
48         };
49 }
50
51 macro_rules! encode_tlv_stream {
52         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
53                 #[allow(unused_imports)]
54                 use $crate::{
55                         ln::msgs::DecodeError,
56                         util::ser,
57                         util::ser::BigSize,
58                 };
59
60                 $(
61                         encode_tlv!($stream, $type, $field, $fieldty);
62                 )*
63
64                 #[allow(unused_mut, unused_variables, unused_assignments)]
65                 #[cfg(debug_assertions)]
66                 {
67                         let mut last_seen: Option<u64> = None;
68                         $(
69                                 check_encoded_tlv_order!(last_seen, $type, $fieldty);
70                         )*
71                 }
72         } }
73 }
74
75 macro_rules! get_varint_length_prefixed_tlv_length {
76         ($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
77                 get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
78         };
79         ($len: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
80         };
81         ($len: expr, $type: expr, $field: expr, required) => {
82                 BigSize($type).write(&mut $len).expect("No in-memory data may fail to serialize");
83                 let field_len = $field.serialized_length();
84                 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
85                 $len.0 += field_len;
86         };
87         ($len: expr, $type: expr, $field: expr, vec_type) => {
88                 get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required);
89         };
90         ($len: expr, $optional_type: expr, $optional_field: expr, option) => {
91                 if let Some(ref field) = $optional_field {
92                         BigSize($optional_type).write(&mut $len).expect("No in-memory data may fail to serialize");
93                         let field_len = field.serialized_length();
94                         BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
95                         $len.0 += field_len;
96                 }
97         };
98 }
99
100 macro_rules! encode_varint_length_prefixed_tlv {
101         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
102                 use $crate::util::ser::BigSize;
103                 let len = {
104                         #[allow(unused_mut)]
105                         let mut len = $crate::util::ser::LengthCalculatingWriter(0);
106                         $(
107                                 get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
108                         )*
109                         len.0
110                 };
111                 BigSize(len as u64).write($stream)?;
112                 encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* });
113         } }
114 }
115
116 macro_rules! check_decoded_tlv_order {
117         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
118                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
119                 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
120                 if invalid_order {
121                         $field = $default.into();
122                 }
123         }};
124         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (static_value, $value: expr)) => {
125         };
126         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
127                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
128                 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
129                 if invalid_order {
130                         return Err(DecodeError::InvalidValue);
131                 }
132         }};
133         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
134                 // no-op
135         }};
136         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, vec_type) => {{
137                 // no-op
138         }};
139         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, ignorable) => {{
140                 // no-op
141         }};
142         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
143                 // no-op
144         }};
145         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
146                 // no-op
147         }};
148 }
149
150 macro_rules! check_missing_tlv {
151         ($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
152                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
153                 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
154                 if missing_req_type {
155                         $field = $default.into();
156                 }
157         }};
158         ($last_seen_type: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
159                 $field = $value;
160         };
161         ($last_seen_type: expr, $type: expr, $field: ident, required) => {{
162                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
163                 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
164                 if missing_req_type {
165                         return Err(DecodeError::InvalidValue);
166                 }
167         }};
168         ($last_seen_type: expr, $type: expr, $field: ident, vec_type) => {{
169                 // no-op
170         }};
171         ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
172                 // no-op
173         }};
174         ($last_seen_type: expr, $type: expr, $field: ident, ignorable) => {{
175                 // no-op
176         }};
177         ($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
178                 // no-op
179         }};
180         ($last_seen_type: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
181                 // no-op
182         }};
183 }
184
185 macro_rules! decode_tlv {
186         ($reader: expr, $field: ident, (default_value, $default: expr)) => {{
187                 decode_tlv!($reader, $field, required)
188         }};
189         ($reader: expr, $field: ident, (static_value, $value: expr)) => {{
190         }};
191         ($reader: expr, $field: ident, required) => {{
192                 $field = $crate::util::ser::Readable::read(&mut $reader)?;
193         }};
194         ($reader: expr, $field: ident, vec_type) => {{
195                 let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
196                 $field = Some(f.0);
197         }};
198         ($reader: expr, $field: ident, option) => {{
199                 $field = Some($crate::util::ser::Readable::read(&mut $reader)?);
200         }};
201         ($reader: expr, $field: ident, ignorable) => {{
202                 $field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
203         }};
204         ($reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
205                 $field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
206         }};
207         ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {{
208                 $field = {
209                         let field: $encoding<$fieldty> = ser::Readable::read(&mut $reader)?;
210                         Some(field.0)
211                 };
212         }};
213         ($reader: expr, $field: ident, (option, encoding: $fieldty: ty)) => {{
214                 decode_tlv!($reader, $field, option);
215         }};
216 }
217
218 macro_rules! _decode_tlv_stream_match_check {
219         ($val: ident, $type: expr, (static_value, $value: expr)) => { false };
220         ($val: ident, $type: expr, $fieldty: tt) => { $val == $type }
221 }
222
223 // `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
224 // If it is provided, it will be called with the custom type and the `FixedLengthReader` containing
225 // the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
226 // `Ok(false)` if the message type is unknown, and `Err(DecodeError)` if parsing fails.
227 macro_rules! decode_tlv_stream {
228         ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
229          $(, $decode_custom_tlv: expr)?) => { {
230                 let rewind = |_, _| { unreachable!() };
231                 use core::ops::RangeBounds;
232                 decode_tlv_stream_range!(
233                         $stream, .., rewind, {$(($type, $field, $fieldty)),*} $(, $decode_custom_tlv)?
234                 );
235         } }
236 }
237
238 macro_rules! decode_tlv_stream_range {
239         ($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
240          $(, $decode_custom_tlv: expr)?) => { {
241                 use $crate::ln::msgs::DecodeError;
242                 let mut last_seen_type: Option<u64> = None;
243                 let mut stream_ref = $stream;
244                 'tlv_read: loop {
245                         use $crate::util::ser;
246
247                         // First decode the type of this TLV:
248                         let typ: ser::BigSize = {
249                                 // We track whether any bytes were read during the consensus_decode call to
250                                 // determine whether we should break or return ShortRead if we get an
251                                 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
252                                 // pass the TLV test vectors exactly, which requre this distinction.
253                                 let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
254                                 match <$crate::util::ser::BigSize as $crate::util::ser::Readable>::read(&mut tracking_reader) {
255                                         Err(DecodeError::ShortRead) => {
256                                                 if !tracking_reader.have_read {
257                                                         break 'tlv_read;
258                                                 } else {
259                                                         return Err(DecodeError::ShortRead);
260                                                 }
261                                         },
262                                         Err(e) => return Err(e),
263                                         Ok(t) => if $range.contains(&t.0) { t } else {
264                                                 drop(tracking_reader);
265
266                                                 // Assumes the type id is minimally encoded, which is enforced on read.
267                                                 use $crate::util::ser::Writeable;
268                                                 let bytes_read = t.serialized_length();
269                                                 $rewind(stream_ref, bytes_read);
270                                                 break 'tlv_read;
271                                         },
272                                 }
273                         };
274
275                         // Types must be unique and monotonically increasing:
276                         match last_seen_type {
277                                 Some(t) if typ.0 <= t => {
278                                         return Err(DecodeError::InvalidValue);
279                                 },
280                                 _ => {},
281                         }
282                         // As we read types, make sure we hit every required type:
283                         $({
284                                 check_decoded_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
285                         })*
286                         last_seen_type = Some(typ.0);
287
288                         // Finally, read the length and value itself:
289                         let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
290                         let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
291                         match typ.0 {
292                                 $(_t if _decode_tlv_stream_match_check!(_t, $type, $fieldty) => {
293                                         decode_tlv!(s, $field, $fieldty);
294                                         if s.bytes_remain() {
295                                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
296                                                 return Err(DecodeError::InvalidValue);
297                                         }
298                                 },)*
299                                 t => {
300                                         $(
301                                                 if $decode_custom_tlv(t, &mut s)? {
302                                                         // If a custom TLV was successfully read (i.e. decode_custom_tlv returns true),
303                                                         // continue to the next TLV read.
304                                                         s.eat_remaining()?;
305                                                         continue 'tlv_read;
306                                                 }
307                                         )?
308                                         if t % 2 == 0 {
309                                                 return Err(DecodeError::UnknownRequiredFeature);
310                                         }
311                                 }
312                         }
313                         s.eat_remaining()?;
314                 }
315                 // Make sure we got to each required type after we've read every TLV:
316                 $({
317                         check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
318                 })*
319         } }
320 }
321
322 macro_rules! impl_writeable_msg {
323         ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
324                 impl $crate::util::ser::Writeable for $st {
325                         fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
326                                 $( self.$field.write(w)?; )*
327                                 encode_tlv_stream!(w, {$(($type, self.$tlvfield, $fieldty)),*});
328                                 Ok(())
329                         }
330                 }
331                 impl $crate::util::ser::Readable for $st {
332                         fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
333                                 $(let $field = $crate::util::ser::Readable::read(r)?;)*
334                                 $(init_tlv_field_var!($tlvfield, $fieldty);)*
335                                 decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
336                                 Ok(Self {
337                                         $($field),*,
338                                         $($tlvfield),*
339                                 })
340                         }
341                 }
342         }
343 }
344
345 macro_rules! impl_writeable {
346         ($st:ident, {$($field:ident),*}) => {
347                 impl $crate::util::ser::Writeable for $st {
348                         fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
349                                 $( self.$field.write(w)?; )*
350                                 Ok(())
351                         }
352
353                         #[inline]
354                         fn serialized_length(&self) -> usize {
355                                 let mut len_calc = 0;
356                                 $( len_calc += self.$field.serialized_length(); )*
357                                 return len_calc;
358                         }
359                 }
360
361                 impl $crate::util::ser::Readable for $st {
362                         fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
363                                 Ok(Self {
364                                         $($field: $crate::util::ser::Readable::read(r)?),*
365                                 })
366                         }
367                 }
368         }
369 }
370
371 /// Write out two bytes to indicate the version of an object.
372 /// $this_version represents a unique version of a type. Incremented whenever the type's
373 ///               serialization format has changed or has a new interpretation. Used by a type's
374 ///               reader to determine how to interpret fields or if it can understand a serialized
375 ///               object.
376 /// $min_version_that_can_read_this is the minimum reader version which can understand this
377 ///                                 serialized object. Previous versions will simply err with a
378 ///                                 DecodeError::UnknownVersion.
379 ///
380 /// Updates to either $this_version or $min_version_that_can_read_this should be included in
381 /// release notes.
382 ///
383 /// Both version fields can be specific to this type of object.
384 macro_rules! write_ver_prefix {
385         ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
386                 $stream.write_all(&[$this_version; 1])?;
387                 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
388         }
389 }
390
391 /// Writes out a suffix to an object which contains potentially backwards-compatible, optional
392 /// fields which old nodes can happily ignore.
393 ///
394 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
395 /// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
396 ///
397 /// This is the preferred method of adding new fields that old nodes can ignore and still function
398 /// correctly.
399 macro_rules! write_tlv_fields {
400         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
401                 encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
402         }
403 }
404
405 /// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
406 /// serialization logic for this object. This is compared against the
407 /// $min_version_that_can_read_this added by write_ver_prefix!().
408 macro_rules! read_ver_prefix {
409         ($stream: expr, $this_version: expr) => { {
410                 let ver: u8 = Readable::read($stream)?;
411                 let min_ver: u8 = Readable::read($stream)?;
412                 if min_ver > $this_version {
413                         return Err(DecodeError::UnknownVersion);
414                 }
415                 ver
416         } }
417 }
418
419 /// Reads a suffix added by write_tlv_fields.
420 macro_rules! read_tlv_fields {
421         ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
422                 let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
423                 let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
424                 decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
425                 rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
426         } }
427 }
428
429 macro_rules! init_tlv_based_struct_field {
430         ($field: ident, (default_value, $default: expr)) => {
431                 $field.0.unwrap()
432         };
433         ($field: ident, (static_value, $value: expr)) => {
434                 $field
435         };
436         ($field: ident, option) => {
437                 $field
438         };
439         ($field: ident, required) => {
440                 $field.0.unwrap()
441         };
442         ($field: ident, vec_type) => {
443                 $field.unwrap()
444         };
445 }
446
447 macro_rules! init_tlv_field_var {
448         ($field: ident, (default_value, $default: expr)) => {
449                 let mut $field = $crate::util::ser::OptionDeserWrapper(None);
450         };
451         ($field: ident, (static_value, $value: expr)) => {
452                 let $field;
453         };
454         ($field: ident, required) => {
455                 let mut $field = $crate::util::ser::OptionDeserWrapper(None);
456         };
457         ($field: ident, vec_type) => {
458                 let mut $field = Some(Vec::new());
459         };
460         ($field: ident, option) => {
461                 let mut $field = None;
462         };
463 }
464
465 macro_rules! init_and_read_tlv_fields {
466         ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
467                 $(
468                         init_tlv_field_var!($field, $fieldty);
469                 )*
470
471                 read_tlv_fields!($reader, {
472                         $(($type, $field, $fieldty)),*
473                 });
474         }
475 }
476
477 /// Implements Readable/Writeable for a struct storing it as a set of TLVs
478 /// If $fieldty is `required`, then $field is a required field that is not an Option nor a Vec.
479 /// If $fieldty is `option`, then $field is optional field.
480 /// if $fieldty is `vec_type`, then $field is a Vec, which needs to have its individual elements
481 /// serialized.
482 macro_rules! impl_writeable_tlv_based {
483         ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
484                 impl $crate::util::ser::Writeable for $st {
485                         fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
486                                 write_tlv_fields!(writer, {
487                                         $(($type, self.$field, $fieldty)),*
488                                 });
489                                 Ok(())
490                         }
491
492                         #[inline]
493                         fn serialized_length(&self) -> usize {
494                                 use $crate::util::ser::BigSize;
495                                 let len = {
496                                         #[allow(unused_mut)]
497                                         let mut len = $crate::util::ser::LengthCalculatingWriter(0);
498                                         $(
499                                                 get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
500                                         )*
501                                         len.0
502                                 };
503                                 let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
504                                 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
505                                 len + len_calc.0
506                         }
507                 }
508
509                 impl $crate::util::ser::Readable for $st {
510                         fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
511                                 init_and_read_tlv_fields!(reader, {
512                                         $(($type, $field, $fieldty)),*
513                                 });
514                                 Ok(Self {
515                                         $(
516                                                 $field: init_tlv_based_struct_field!($field, $fieldty)
517                                         ),*
518                                 })
519                         }
520                 }
521         }
522 }
523
524 /// Defines a struct for a TLV stream and a similar struct using references for non-primitive types,
525 /// implementing [`Readable`] for the former and [`Writeable`] for the latter. Useful as an
526 /// intermediary format when reading or writing a type encoded as a TLV stream. Note that each field
527 /// representing a TLV record has its type wrapped with an [`Option`]. A tuple consisting of a type
528 /// and a serialization wrapper may be given in place of a type when custom serialization is
529 /// required.
530 ///
531 /// [`Readable`]: crate::util::ser::Readable
532 /// [`Writeable`]: crate::util::ser::Writeable
533 macro_rules! tlv_stream {
534         ($name:ident, $nameref:ident, $range:expr, {
535                 $(($type:expr, $field:ident : $fieldty:tt)),* $(,)*
536         }) => {
537                 #[derive(Debug)]
538                 pub(super) struct $name {
539                         $(
540                                 pub(super) $field: Option<tlv_record_type!($fieldty)>,
541                         )*
542                 }
543
544                 #[derive(Debug, PartialEq)]
545                 pub(super) struct $nameref<'a> {
546                         $(
547                                 pub(super) $field: Option<tlv_record_ref_type!($fieldty)>,
548                         )*
549                 }
550
551                 impl<'a> $crate::util::ser::Writeable for $nameref<'a> {
552                         fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
553                                 encode_tlv_stream!(writer, {
554                                         $(($type, self.$field, (option, encoding: $fieldty))),*
555                                 });
556                                 Ok(())
557                         }
558                 }
559
560                 impl $crate::util::ser::SeekReadable for $name {
561                         fn read<R: $crate::io::Read + $crate::io::Seek>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
562                                 $(
563                                         init_tlv_field_var!($field, option);
564                                 )*
565                                 let rewind = |cursor: &mut R, offset: usize| {
566                                         cursor.seek($crate::io::SeekFrom::Current(-(offset as i64))).expect("");
567                                 };
568                                 decode_tlv_stream_range!(reader, $range, rewind, {
569                                         $(($type, $field, (option, encoding: $fieldty))),*
570                                 });
571
572                                 Ok(Self {
573                                         $(
574                                                 $field: $field
575                                         ),*
576                                 })
577                         }
578                 }
579         }
580 }
581
582 macro_rules! tlv_record_type {
583         (($type:ty, $wrapper:ident)) => { $type };
584         ($type:ty) => { $type };
585 }
586
587 macro_rules! tlv_record_ref_type {
588         (char) => { char };
589         (u8) => { u8 };
590         ((u16, $wrapper: ident)) => { u16 };
591         ((u32, $wrapper: ident)) => { u32 };
592         ((u64, $wrapper: ident)) => { u64 };
593         (($type:ty, $wrapper:ident)) => { &'a $type };
594         ($type:ty) => { &'a $type };
595 }
596
597 macro_rules! _impl_writeable_tlv_based_enum_common {
598         ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
599                 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
600         ),* $(,)*;
601         $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*) => {
602                 impl $crate::util::ser::Writeable for $st {
603                         fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
604                                 match self {
605                                         $($st::$variant_name { $(ref $field),* } => {
606                                                 let id: u8 = $variant_id;
607                                                 id.write(writer)?;
608                                                 write_tlv_fields!(writer, {
609                                                         $(($type, *$field, $fieldty)),*
610                                                 });
611                                         }),*
612                                         $($st::$tuple_variant_name (ref field) => {
613                                                 let id: u8 = $tuple_variant_id;
614                                                 id.write(writer)?;
615                                                 field.write(writer)?;
616                                         }),*
617                                 }
618                                 Ok(())
619                         }
620                 }
621         }
622 }
623
624 /// Implement MaybeReadable and Writeable for an enum, with struct variants stored as TLVs and
625 /// tuple variants stored directly.
626 ///
627 /// This is largely identical to `impl_writeable_tlv_based_enum`, except that odd variants will
628 /// return `Ok(None)` instead of `Err(UnknownRequiredFeature)`. It should generally be preferred
629 /// when `MaybeReadable` is practical instead of just `Readable` as it provides an upgrade path for
630 /// new variants to be added which are simply ignored by existing clients.
631 macro_rules! impl_writeable_tlv_based_enum_upgradable {
632         ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
633                 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
634         ),* $(,)*
635         $(;
636         $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*)*) => {
637                 _impl_writeable_tlv_based_enum_common!($st,
638                         $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
639                         $($(($tuple_variant_id, $tuple_variant_name)),*)*);
640
641                 impl $crate::util::ser::MaybeReadable for $st {
642                         fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
643                                 let id: u8 = $crate::util::ser::Readable::read(reader)?;
644                                 match id {
645                                         $($variant_id => {
646                                                 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
647                                                 // in the same function body. Instead, we define a closure and call it.
648                                                 let f = || {
649                                                         init_and_read_tlv_fields!(reader, {
650                                                                 $(($type, $field, $fieldty)),*
651                                                         });
652                                                         Ok(Some($st::$variant_name {
653                                                                 $(
654                                                                         $field: init_tlv_based_struct_field!($field, $fieldty)
655                                                                 ),*
656                                                         }))
657                                                 };
658                                                 f()
659                                         }),*
660                                         $($($tuple_variant_id => {
661                                                 Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
662                                         }),*)*
663                                         _ if id % 2 == 1 => Ok(None),
664                                         _ => Err(DecodeError::UnknownRequiredFeature),
665                                 }
666                         }
667                 }
668
669         }
670 }
671
672 /// Implement Readable and Writeable for an enum, with struct variants stored as TLVs and tuple
673 /// variants stored directly.
674 /// The format is, for example
675 /// impl_writeable_tlv_based_enum!(EnumName,
676 ///   (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
677 ///   (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, vec_type)};
678 ///   (2, TupleVariantA), (3, TupleVariantB),
679 /// );
680 /// The type is written as a single byte, followed by any variant data.
681 /// Attempts to read an unknown type byte result in DecodeError::UnknownRequiredFeature.
682 macro_rules! impl_writeable_tlv_based_enum {
683         ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
684                 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
685         ),* $(,)*;
686         $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*) => {
687                 _impl_writeable_tlv_based_enum_common!($st,
688                         $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
689                         $(($tuple_variant_id, $tuple_variant_name)),*);
690
691                 impl $crate::util::ser::Readable for $st {
692                         fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
693                                 let id: u8 = $crate::util::ser::Readable::read(reader)?;
694                                 match id {
695                                         $($variant_id => {
696                                                 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
697                                                 // in the same function body. Instead, we define a closure and call it.
698                                                 let f = || {
699                                                         init_and_read_tlv_fields!(reader, {
700                                                                 $(($type, $field, $fieldty)),*
701                                                         });
702                                                         Ok($st::$variant_name {
703                                                                 $(
704                                                                         $field: init_tlv_based_struct_field!($field, $fieldty)
705                                                                 ),*
706                                                         })
707                                                 };
708                                                 f()
709                                         }),*
710                                         $($tuple_variant_id => {
711                                                 Ok($st::$tuple_variant_name(Readable::read(reader)?))
712                                         }),*
713                                         _ => {
714                                                 Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature)
715                                         },
716                                 }
717                         }
718                 }
719         }
720 }
721
722 #[cfg(test)]
723 mod tests {
724         use crate::io::{self, Cursor};
725         use crate::prelude::*;
726         use crate::ln::msgs::DecodeError;
727         use crate::util::ser::{Writeable, HighZeroBytesDroppedBigSize, VecWriter};
728         use bitcoin::secp256k1::PublicKey;
729
730         // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
731         // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
732         // work with so they're baked into the decoder. Thus, we have a few additional tests below
733         fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
734                 let mut s = Cursor::new(s);
735                 let mut a: u64 = 0;
736                 let mut b: u32 = 0;
737                 let mut c: Option<u32> = None;
738                 decode_tlv_stream!(&mut s, {(2, a, required), (3, b, required), (4, c, option)});
739                 Ok((a, b, c))
740         }
741
742         #[test]
743         fn tlv_v_short_read() {
744                 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
745                 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
746                                 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
747                                 ).unwrap()[..]) {
748                 } else { panic!(); }
749         }
750
751         #[test]
752         fn tlv_types_out_of_order() {
753                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
754                                 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
755                                 ).unwrap()[..]) {
756                 } else { panic!(); }
757                 // ...even if its some field we don't understand
758                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
759                                 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
760                                 ).unwrap()[..]) {
761                 } else { panic!(); }
762         }
763
764         #[test]
765         fn tlv_req_type_missing_or_extra() {
766                 // It's also bad if they included even fields we don't understand
767                 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
768                                 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
769                                 ).unwrap()[..]) {
770                 } else { panic!(); }
771                 // ... or if they're missing fields we need
772                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
773                                 concat!("0100", "0208deadbeef1badbeef")
774                                 ).unwrap()[..]) {
775                 } else { panic!(); }
776                 // ... even if that field is even
777                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
778                                 concat!("0304deadbeef", "0500")
779                                 ).unwrap()[..]) {
780                 } else { panic!(); }
781         }
782
783         #[test]
784         fn tlv_simple_good_cases() {
785                 assert_eq!(tlv_reader(&::hex::decode(
786                                 concat!("0208deadbeef1badbeef", "03041bad1dea")
787                                 ).unwrap()[..]).unwrap(),
788                         (0xdeadbeef1badbeef, 0x1bad1dea, None));
789                 assert_eq!(tlv_reader(&::hex::decode(
790                                 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
791                                 ).unwrap()[..]).unwrap(),
792                         (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
793         }
794
795         // BOLT TLV test cases
796         fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedBigSize<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
797                 let mut s = Cursor::new(s);
798                 let mut tlv1: Option<HighZeroBytesDroppedBigSize<u64>> = None;
799                 let mut tlv2: Option<u64> = None;
800                 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
801                 let mut tlv4: Option<u16> = None;
802                 decode_tlv_stream!(&mut s, {(1, tlv1, option), (2, tlv2, option), (3, tlv3, option), (254, tlv4, option)});
803                 Ok((tlv1, tlv2, tlv3, tlv4))
804         }
805
806         #[test]
807         fn bolt_tlv_bogus_stream() {
808                 macro_rules! do_test {
809                         ($stream: expr, $reason: ident) => {
810                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
811                                 } else { panic!(); }
812                         }
813                 }
814
815                 // TLVs from the BOLT test cases which should not decode as either n1 or n2
816                 do_test!(concat!("fd01"), ShortRead);
817                 do_test!(concat!("fd0001", "00"), InvalidValue);
818                 do_test!(concat!("fd0101"), ShortRead);
819                 do_test!(concat!("0f", "fd"), ShortRead);
820                 do_test!(concat!("0f", "fd26"), ShortRead);
821                 do_test!(concat!("0f", "fd2602"), ShortRead);
822                 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
823                 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
824
825                 do_test!(concat!("12", "00"), UnknownRequiredFeature);
826                 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
827                 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
828                 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
829         }
830
831         #[test]
832         fn bolt_tlv_bogus_n1_stream() {
833                 macro_rules! do_test {
834                         ($stream: expr, $reason: ident) => {
835                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
836                                 } else { panic!(); }
837                         }
838                 }
839
840                 // TLVs from the BOLT test cases which should not decode as n1
841                 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
842                 do_test!(concat!("01", "01", "00"), InvalidValue);
843                 do_test!(concat!("01", "02", "0001"), InvalidValue);
844                 do_test!(concat!("01", "03", "000100"), InvalidValue);
845                 do_test!(concat!("01", "04", "00010000"), InvalidValue);
846                 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
847                 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
848                 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
849                 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
850                 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
851                 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
852                 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
853                 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
854                 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
855                 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
856                 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
857                 do_test!(concat!("fd00fe", "00"), ShortRead);
858                 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
859                 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
860                 do_test!(concat!("00", "00"), UnknownRequiredFeature);
861
862                 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
863                 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
864                 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
865                 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
866
867                 // The last BOLT test modified to not require creating a new decoder for one trivial test.
868                 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
869         }
870
871         #[test]
872         fn bolt_tlv_valid_n1_stream() {
873                 macro_rules! do_test {
874                         ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
875                                 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
876                                         assert_eq!(tlv1.map(|v| v.0), $tlv1);
877                                         assert_eq!(tlv2, $tlv2);
878                                         assert_eq!(tlv3, $tlv3);
879                                         assert_eq!(tlv4, $tlv4);
880                                 } else { panic!(); }
881                         }
882                 }
883
884                 do_test!(concat!(""), None, None, None, None);
885                 do_test!(concat!("21", "00"), None, None, None, None);
886                 do_test!(concat!("fd0201", "00"), None, None, None, None);
887                 do_test!(concat!("fd00fd", "00"), None, None, None, None);
888                 do_test!(concat!("fd00ff", "00"), None, None, None, None);
889                 do_test!(concat!("fe02000001", "00"), None, None, None, None);
890                 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
891
892                 do_test!(concat!("01", "00"), Some(0), None, None, None);
893                 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
894                 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
895                 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
896                 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
897                 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
898                 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
899                 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
900                 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
901                 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
902                 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
903                         None, None, Some((
904                                 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
905                         None);
906                 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
907         }
908
909         fn do_simple_test_tlv_write() -> Result<(), io::Error> {
910                 let mut stream = VecWriter(Vec::new());
911
912                 stream.0.clear();
913                 encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
914                 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
915
916                 stream.0.clear();
917                 encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
918                 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
919
920                 stream.0.clear();
921                 encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
922                 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
923
924                 stream.0.clear();
925                 encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
926                 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
927
928                 stream.0.clear();
929                 encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
930                 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
931
932                 stream.0.clear();
933                 encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
934                 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
935
936                 Ok(())
937         }
938
939         #[test]
940         fn simple_test_tlv_write() {
941                 do_simple_test_tlv_write().unwrap();
942         }
943 }