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