1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Some macros that implement [`Readable`]/[`Writeable`] traits for lightning messages.
11 //! They also handle serialization and deserialization of TLVs.
13 //! [`Readable`]: crate::util::ser::Readable
14 //! [`Writeable`]: crate::util::ser::Writeable
16 // There are quite a few TLV serialization "types" which behave differently. We currently only
17 // publicly document the `optional` and `required` types, not supporting anything else publicly and
18 // changing them at will.
20 // Some of the other types include:
21 // * (default_value, $default) - reads optionally, reading $default if no TLV is present
22 // * (static_value, $value) - ignores any TLVs, always using $value
23 // * required_vec - reads into a Vec without a length prefix, failing if no TLV is present.
24 // * optional_vec - reads into an Option<Vec> without a length prefix, continuing if no TLV is
25 // present. Writes from a Vec directly, only if any elements are present. Note
26 // that the struct deserialization macros return a Vec, not an Option.
27 // * upgradable_option - reads via MaybeReadable.
28 // * upgradable_required - reads via MaybeReadable, requiring a TLV be present but may return None
29 // if MaybeReadable::read() returns None.
31 /// Implements serialization for a single TLV record.
32 /// This is exported for use by other exported macros, do not use directly.
35 macro_rules! _encode_tlv {
36 ($stream: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
37 $crate::_encode_tlv!($stream, $type, $field, required)
39 ($stream: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
40 let _ = &$field; // Ensure we "use" the $field
42 ($stream: expr, $type: expr, $field: expr, required) => {
43 BigSize($type).write($stream)?;
44 BigSize($field.serialized_length() as u64).write($stream)?;
45 $field.write($stream)?;
47 ($stream: expr, $type: expr, $field: expr, required_vec) => {
48 $crate::_encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required);
50 ($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
51 if let Some(ref field) = $optional_field {
52 BigSize($optional_type).write($stream)?;
53 BigSize(field.serialized_length() as u64).write($stream)?;
54 field.write($stream)?;
57 ($stream: expr, $type: expr, $field: expr, optional_vec) => {
58 if !$field.is_empty() {
59 $crate::_encode_tlv!($stream, $type, $field, required_vec);
62 ($stream: expr, $type: expr, $field: expr, upgradable_required) => {
63 $crate::_encode_tlv!($stream, $type, $field, required);
65 ($stream: expr, $type: expr, $field: expr, upgradable_option) => {
66 $crate::_encode_tlv!($stream, $type, $field, option);
68 ($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
69 $crate::_encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
71 ($stream: expr, $type: expr, $field: expr, (option, encoding: $fieldty: ty)) => {
72 $crate::_encode_tlv!($stream, $type, $field, option);
74 ($stream: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
75 // Just a read-mapped type
76 $crate::_encode_tlv!($stream, $type, $field, option);
80 /// Panics if the last seen TLV type is not numerically less than the TLV type currently being checked.
81 /// This is exported for use by other exported macros, do not use directly.
84 macro_rules! _check_encoded_tlv_order {
85 ($last_type: expr, $type: expr, (static_value, $value: expr)) => { };
86 ($last_type: expr, $type: expr, $fieldty: tt) => {
87 if let Some(t) = $last_type {
88 #[allow(unused_comparisons)] // Note that $type may be 0 making the following comparison always false
89 (debug_assert!(t < $type))
91 $last_type = Some($type);
95 /// Implements the TLVs serialization part in a [`Writeable`] implementation of a struct.
97 /// This should be called inside a method which returns `Result<_, `[`io::Error`]`>`, such as
98 /// [`Writeable::write`]. It will only return an `Err` if the stream `Err`s or [`Writeable::write`]
99 /// on one of the fields `Err`s.
101 /// `$stream` must be a `&mut `[`Writer`] which will receive the bytes for each TLV in the stream.
103 /// Fields MUST be sorted in `$type`-order.
105 /// Note that the lightning TLV requirements require that a single type not appear more than once,
106 /// that TLVs are sorted in type-ascending order, and that any even types be understood by the
109 /// Any `option` fields which have a value of `None` will not be serialized at all.
113 /// # use lightning::encode_tlv_stream;
114 /// # fn write<W: lightning::util::ser::Writer> (stream: &mut W) -> Result<(), lightning::io::Error> {
115 /// let mut required_value = 0u64;
116 /// let mut optional_value: Option<u64> = None;
117 /// encode_tlv_stream!(stream, {
118 /// (0, required_value, required),
119 /// (1, Some(42u64), option),
120 /// (2, optional_value, option),
122 /// // At this point `required_value` has been written as a TLV of type 0, `42u64` has been written
123 /// // as a TLV of type 1 (indicating the reader may ignore it if it is not understood), and *no*
124 /// // TLV is written with type 2.
129 /// [`Writeable`]: crate::util::ser::Writeable
130 /// [`io::Error`]: crate::io::Error
131 /// [`Writeable::write`]: crate::util::ser::Writeable::write
132 /// [`Writer`]: crate::util::ser::Writer
134 macro_rules! encode_tlv_stream {
135 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
136 $crate::_encode_tlv_stream!($stream, {$(($type, $field, $fieldty)),*})
140 /// Implementation of [`encode_tlv_stream`].
141 /// This is exported for use by other exported macros, do not use directly.
144 macro_rules! _encode_tlv_stream {
145 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
146 $crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, &[])
148 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}, $extra_tlvs: expr) => { {
149 #[allow(unused_imports)]
151 ln::msgs::DecodeError,
154 util::ser::Writeable,
158 $crate::_encode_tlv!($stream, $type, $field, $fieldty);
160 for tlv in $extra_tlvs {
161 let (typ, value): &(u64, Vec<u8>) = tlv;
162 $crate::_encode_tlv!($stream, *typ, *value, required_vec);
165 #[allow(unused_mut, unused_variables, unused_assignments)]
166 #[cfg(debug_assertions)]
168 let mut last_seen: Option<u64> = None;
170 $crate::_check_encoded_tlv_order!(last_seen, $type, $fieldty);
172 for tlv in $extra_tlvs {
173 let (typ, _): &(u64, Vec<u8>) = tlv;
174 $crate::_check_encoded_tlv_order!(last_seen, *typ, required_vec);
180 /// Adds the length of the serialized field to a [`LengthCalculatingWriter`].
181 /// This is exported for use by other exported macros, do not use directly.
183 /// [`LengthCalculatingWriter`]: crate::util::ser::LengthCalculatingWriter
186 macro_rules! _get_varint_length_prefixed_tlv_length {
187 ($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
188 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
190 ($len: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
192 ($len: expr, $type: expr, $field: expr, required) => {
193 BigSize($type).write(&mut $len).expect("No in-memory data may fail to serialize");
194 let field_len = $field.serialized_length();
195 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
198 ($len: expr, $type: expr, $field: expr, required_vec) => {
199 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required);
201 ($len: expr, $optional_type: expr, $optional_field: expr, option) => {
202 if let Some(ref field) = $optional_field {
203 BigSize($optional_type).write(&mut $len).expect("No in-memory data may fail to serialize");
204 let field_len = field.serialized_length();
205 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
209 ($len: expr, $type: expr, $field: expr, optional_vec) => {
210 if !$field.is_empty() {
211 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required_vec);
214 ($len: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
215 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
217 ($len: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
218 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field.map(|f| $encoding(f)), option);
220 ($len: expr, $type: expr, $field: expr, upgradable_required) => {
221 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required);
223 ($len: expr, $type: expr, $field: expr, upgradable_option) => {
224 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
228 /// See the documentation of [`write_tlv_fields`].
229 /// This is exported for use by other exported macros, do not use directly.
232 macro_rules! _encode_varint_length_prefixed_tlv {
233 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
234 _encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*}, &[])
236 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}, $extra_tlvs: expr) => { {
237 use $crate::util::ser::BigSize;
241 let mut len = $crate::util::ser::LengthCalculatingWriter(0);
243 $crate::_get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
245 for tlv in $extra_tlvs {
246 let (typ, value): &(u64, Vec<u8>) = tlv;
247 $crate::_get_varint_length_prefixed_tlv_length!(len, *typ, *value, required_vec);
251 BigSize(len as u64).write($stream)?;
252 $crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, $extra_tlvs);
256 /// Errors if there are missing required TLV types between the last seen type and the type currently being processed.
257 /// This is exported for use by other exported macros, do not use directly.
260 macro_rules! _check_decoded_tlv_order {
261 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
262 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
263 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
265 $field = $default.into();
268 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (static_value, $value: expr)) => {
270 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
271 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
272 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
274 return Err(DecodeError::InvalidValue);
277 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
278 $crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
280 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
283 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required_vec) => {{
284 $crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
286 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, optional_vec) => {{
289 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_required) => {{
290 _check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required)
292 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_option) => {{
295 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
298 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
303 /// Errors if there are missing required TLV types after the last seen type.
304 /// This is exported for use by other exported macros, do not use directly.
307 macro_rules! _check_missing_tlv {
308 ($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
309 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
310 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
311 if missing_req_type {
312 $field = $default.into();
315 ($last_seen_type: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
318 ($last_seen_type: expr, $type: expr, $field: ident, required) => {{
319 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
320 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
321 if missing_req_type {
322 return Err(DecodeError::InvalidValue);
325 ($last_seen_type: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
326 $crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
328 ($last_seen_type: expr, $type: expr, $field: ident, required_vec) => {{
329 $crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
331 ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
334 ($last_seen_type: expr, $type: expr, $field: ident, optional_vec) => {{
337 ($last_seen_type: expr, $type: expr, $field: ident, upgradable_required) => {{
338 _check_missing_tlv!($last_seen_type, $type, $field, required)
340 ($last_seen_type: expr, $type: expr, $field: ident, upgradable_option) => {{
343 ($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
346 ($last_seen_type: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
351 /// Implements deserialization for a single TLV record.
352 /// This is exported for use by other exported macros, do not use directly.
355 macro_rules! _decode_tlv {
356 ($reader: expr, $field: ident, (default_value, $default: expr)) => {{
357 $crate::_decode_tlv!($reader, $field, required)
359 ($reader: expr, $field: ident, (static_value, $value: expr)) => {{
361 ($reader: expr, $field: ident, required) => {{
362 $field = $crate::util::ser::Readable::read(&mut $reader)?;
364 ($reader: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
365 $field = $trait::read(&mut $reader $(, $read_arg)*)?;
367 ($reader: expr, $field: ident, required_vec) => {{
368 let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
371 ($reader: expr, $field: ident, option) => {{
372 $field = Some($crate::util::ser::Readable::read(&mut $reader)?);
374 ($reader: expr, $field: ident, optional_vec) => {{
375 let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
378 // `upgradable_required` indicates we're reading a required TLV that may have been upgraded
379 // without backwards compat. We'll error if the field is missing, and return `Ok(None)` if the
380 // field is present but we can no longer understand it.
381 // Note that this variant can only be used within a `MaybeReadable` read.
382 ($reader: expr, $field: ident, upgradable_required) => {{
383 $field = match $crate::util::ser::MaybeReadable::read(&mut $reader)? {
388 // `upgradable_option` indicates we're reading an Option-al TLV that may have been upgraded
389 // without backwards compat. $field will be None if the TLV is missing or if the field is present
390 // but we can no longer understand it.
391 ($reader: expr, $field: ident, upgradable_option) => {{
392 $field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
394 ($reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
395 $field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
397 ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident, $encoder:ty))) => {{
398 $crate::_decode_tlv!($reader, $field, (option, encoding: ($fieldty, $encoding)));
400 ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {{
402 let field: $encoding<$fieldty> = ser::Readable::read(&mut $reader)?;
406 ($reader: expr, $field: ident, (option, encoding: $fieldty: ty)) => {{
407 $crate::_decode_tlv!($reader, $field, option);
411 /// Checks if `$val` matches `$type`.
412 /// This is exported for use by other exported macros, do not use directly.
415 macro_rules! _decode_tlv_stream_match_check {
416 ($val: ident, $type: expr, (static_value, $value: expr)) => { false };
417 ($val: ident, $type: expr, $fieldty: tt) => { $val == $type }
420 /// Implements the TLVs deserialization part in a [`Readable`] implementation of a struct.
422 /// This should be called inside a method which returns `Result<_, `[`DecodeError`]`>`, such as
423 /// [`Readable::read`]. It will either return an `Err` or ensure all `required` fields have been
424 /// read and optionally read `optional` fields.
426 /// `$stream` must be a [`Read`] and will be fully consumed, reading until no more bytes remain
427 /// (i.e. it returns [`DecodeError::ShortRead`]).
429 /// Fields MUST be sorted in `$type`-order.
431 /// Note that the lightning TLV requirements require that a single type not appear more than once,
432 /// that TLVs are sorted in type-ascending order, and that any even types be understood by the
437 /// # use lightning::decode_tlv_stream;
438 /// # fn read<R: lightning::io::Read> (stream: R) -> Result<(), lightning::ln::msgs::DecodeError> {
439 /// let mut required_value = 0u64;
440 /// let mut optional_value: Option<u64> = None;
441 /// decode_tlv_stream!(stream, {
442 /// (0, required_value, required),
443 /// (2, optional_value, option),
445 /// // At this point, `required_value` has been overwritten with the TLV with type 0.
446 /// // `optional_value` may have been overwritten, setting it to `Some` if a TLV with type 2 was
452 /// [`Readable`]: crate::util::ser::Readable
453 /// [`DecodeError`]: crate::ln::msgs::DecodeError
454 /// [`Readable::read`]: crate::util::ser::Readable::read
455 /// [`Read`]: crate::io::Read
456 /// [`DecodeError::ShortRead`]: crate::ln::msgs::DecodeError::ShortRead
458 macro_rules! decode_tlv_stream {
459 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
460 let rewind = |_, _| { unreachable!() };
461 $crate::_decode_tlv_stream_range!($stream, .., rewind, {$(($type, $field, $fieldty)),*});
465 /// Similar to [`decode_tlv_stream`] with a custom TLV decoding capabilities.
467 /// `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
468 /// If it is provided, it will be called with the custom type and the [`FixedLengthReader`] containing
469 /// the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
470 /// `Ok(false)` if the message type is unknown, and `Err(`[`DecodeError`]`)` if parsing fails.
472 /// [`FixedLengthReader`]: crate::util::ser::FixedLengthReader
473 /// [`DecodeError`]: crate::ln::msgs::DecodeError
474 macro_rules! decode_tlv_stream_with_custom_tlv_decode {
475 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
476 $(, $decode_custom_tlv: expr)?) => { {
477 let rewind = |_, _| { unreachable!() };
478 _decode_tlv_stream_range!(
479 $stream, .., rewind, {$(($type, $field, $fieldty)),*} $(, $decode_custom_tlv)?
486 macro_rules! _decode_tlv_stream_range {
487 ($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
488 $(, $decode_custom_tlv: expr)?) => { {
489 use $crate::ln::msgs::DecodeError;
490 let mut last_seen_type: Option<u64> = None;
491 let mut stream_ref = $stream;
493 use $crate::util::ser;
495 // First decode the type of this TLV:
496 let typ: ser::BigSize = {
497 // We track whether any bytes were read during the consensus_decode call to
498 // determine whether we should break or return ShortRead if we get an
499 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
500 // pass the TLV test vectors exactly, which require this distinction.
501 let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
502 match <$crate::util::ser::BigSize as $crate::util::ser::Readable>::read(&mut tracking_reader) {
503 Err(DecodeError::ShortRead) => {
504 if !tracking_reader.have_read {
507 return Err(DecodeError::ShortRead);
510 Err(e) => return Err(e),
511 Ok(t) => if core::ops::RangeBounds::contains(&$range, &t.0) { t } else {
512 drop(tracking_reader);
514 // Assumes the type id is minimally encoded, which is enforced on read.
515 use $crate::util::ser::Writeable;
516 let bytes_read = t.serialized_length();
517 $rewind(stream_ref, bytes_read);
523 // Types must be unique and monotonically increasing:
524 match last_seen_type {
525 Some(t) if typ.0 <= t => {
526 return Err(DecodeError::InvalidValue);
530 // As we read types, make sure we hit every required type between `last_seen_type` and `typ`:
532 $crate::_check_decoded_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
534 last_seen_type = Some(typ.0);
536 // Finally, read the length and value itself:
537 let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
538 let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
540 $(_t if $crate::_decode_tlv_stream_match_check!(_t, $type, $fieldty) => {
541 $crate::_decode_tlv!(s, $field, $fieldty);
542 if s.bytes_remain() {
543 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
544 return Err(DecodeError::InvalidValue);
549 if $decode_custom_tlv(t, &mut s)? {
550 // If a custom TLV was successfully read (i.e. decode_custom_tlv returns true),
551 // continue to the next TLV read.
557 return Err(DecodeError::UnknownRequiredFeature);
563 // Make sure we got to each required type after we've read every TLV:
565 $crate::_check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
570 /// Implements [`Readable`]/[`Writeable`] for a message struct that may include non-TLV and
571 /// TLV-encoded parts.
573 /// This is useful to implement a [`CustomMessageReader`].
575 /// Currently `$fieldty` may only be `option`, i.e., `$tlvfield` is optional field.
579 /// # use lightning::impl_writeable_msg;
580 /// struct MyCustomMessage {
581 /// pub field_1: u32,
582 /// pub field_2: bool,
583 /// pub field_3: String,
584 /// pub tlv_optional_integer: Option<u32>,
587 /// impl_writeable_msg!(MyCustomMessage, {
592 /// (1, tlv_optional_integer, option),
596 /// [`Readable`]: crate::util::ser::Readable
597 /// [`Writeable`]: crate::util::ser::Writeable
598 /// [`CustomMessageReader`]: crate::ln::wire::CustomMessageReader
600 macro_rules! impl_writeable_msg {
601 ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
602 impl $crate::util::ser::Writeable for $st {
603 fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
604 $( self.$field.write(w)?; )*
605 $crate::encode_tlv_stream!(w, {$(($type, self.$tlvfield.as_ref(), $fieldty)),*});
609 impl $crate::util::ser::Readable for $st {
610 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
611 $(let $field = $crate::util::ser::Readable::read(r)?;)*
612 $($crate::_init_tlv_field_var!($tlvfield, $fieldty);)*
613 $crate::decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
623 macro_rules! impl_writeable {
624 ($st:ident, {$($field:ident),*}) => {
625 impl $crate::util::ser::Writeable for $st {
626 fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
627 $( self.$field.write(w)?; )*
632 fn serialized_length(&self) -> usize {
633 let mut len_calc = 0;
634 $( len_calc += self.$field.serialized_length(); )*
639 impl $crate::util::ser::Readable for $st {
640 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
642 $($field: $crate::util::ser::Readable::read(r)?),*
649 /// Write out two bytes to indicate the version of an object.
651 /// $this_version represents a unique version of a type. Incremented whenever the type's
652 /// serialization format has changed or has a new interpretation. Used by a type's reader to
653 /// determine how to interpret fields or if it can understand a serialized object.
655 /// $min_version_that_can_read_this is the minimum reader version which can understand this
656 /// serialized object. Previous versions will simply err with a [`DecodeError::UnknownVersion`].
658 /// Updates to either `$this_version` or `$min_version_that_can_read_this` should be included in
661 /// Both version fields can be specific to this type of object.
663 /// [`DecodeError::UnknownVersion`]: crate::ln::msgs::DecodeError::UnknownVersion
664 macro_rules! write_ver_prefix {
665 ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
666 $stream.write_all(&[$this_version; 1])?;
667 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
671 /// Writes out a suffix to an object as a length-prefixed TLV stream which contains potentially
672 /// backwards-compatible, optional fields which old nodes can happily ignore.
674 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
675 /// [`DecodeError::UnknownRequiredFeature`] error, with unknown odd fields ignored.
677 /// This is the preferred method of adding new fields that old nodes can ignore and still function
680 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
682 macro_rules! write_tlv_fields {
683 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
684 $crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
688 /// Reads a prefix added by [`write_ver_prefix`], above. Takes the current version of the
689 /// serialization logic for this object. This is compared against the
690 /// `$min_version_that_can_read_this` added by [`write_ver_prefix`].
691 macro_rules! read_ver_prefix {
692 ($stream: expr, $this_version: expr) => { {
693 let ver: u8 = Readable::read($stream)?;
694 let min_ver: u8 = Readable::read($stream)?;
695 if min_ver > $this_version {
696 return Err(DecodeError::UnknownVersion);
702 /// Reads a suffix added by [`write_tlv_fields`].
704 /// [`write_tlv_fields`]: crate::write_tlv_fields
706 macro_rules! read_tlv_fields {
707 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
708 let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
709 let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
710 $crate::decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
711 rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
715 /// Initializes the struct fields.
717 /// This is exported for use by other exported macros, do not use directly.
720 macro_rules! _init_tlv_based_struct_field {
721 ($field: ident, (default_value, $default: expr)) => {
724 ($field: ident, (static_value, $value: expr)) => {
727 ($field: ident, option) => {
730 ($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
731 $crate::_init_tlv_based_struct_field!($field, option)
733 ($field: ident, upgradable_required) => {
736 ($field: ident, upgradable_option) => {
739 ($field: ident, required) => {
742 ($field: ident, required_vec) => {
745 ($field: ident, optional_vec) => {
750 /// Initializes the variable we are going to read the TLV into.
752 /// This is exported for use by other exported macros, do not use directly.
755 macro_rules! _init_tlv_field_var {
756 ($field: ident, (default_value, $default: expr)) => {
757 let mut $field = $crate::util::ser::RequiredWrapper(None);
759 ($field: ident, (static_value, $value: expr)) => {
762 ($field: ident, required) => {
763 let mut $field = $crate::util::ser::RequiredWrapper(None);
765 ($field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {
766 $crate::_init_tlv_field_var!($field, required);
768 ($field: ident, required_vec) => {
769 let mut $field = Vec::new();
771 ($field: ident, option) => {
772 let mut $field = None;
774 ($field: ident, optional_vec) => {
775 let mut $field = Some(Vec::new());
777 ($field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
778 $crate::_init_tlv_field_var!($field, option);
780 ($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
781 $crate::_init_tlv_field_var!($field, option);
783 ($field: ident, upgradable_required) => {
784 let mut $field = $crate::util::ser::UpgradableRequired(None);
786 ($field: ident, upgradable_option) => {
787 let mut $field = None;
791 /// Equivalent to running [`_init_tlv_field_var`] then [`read_tlv_fields`].
793 /// This is exported for use by other exported macros, do not use directly.
796 macro_rules! _init_and_read_tlv_fields {
797 ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
799 $crate::_init_tlv_field_var!($field, $fieldty);
802 $crate::read_tlv_fields!($reader, {
803 $(($type, $field, $fieldty)),*
808 /// Implements [`Readable`]/[`Writeable`] for a struct storing it as a set of TLVs
809 /// If `$fieldty` is `required`, then `$field` is a required field that is not an [`Option`] nor a [`Vec`].
810 /// If `$fieldty` is `(default_value, $default)`, then `$field` will be set to `$default` if not present.
811 /// If `$fieldty` is `option`, then `$field` is optional field.
812 /// If `$fieldty` is `optional_vec`, then `$field` is a [`Vec`], which needs to have its individual elements serialized.
813 /// Note that for `optional_vec` no bytes are written if the vec is empty
817 /// # use lightning::{impl_writeable_tlv_based, _encode_varint_length_prefixed_tlv};
818 /// # extern crate alloc;
819 /// struct LightningMessage {
820 /// tlv_integer: u32,
821 /// tlv_default_integer: u32,
822 /// tlv_optional_integer: Option<u32>,
823 /// tlv_vec_type_integer: Vec<u32>,
826 /// impl_writeable_tlv_based!(LightningMessage, {
827 /// (0, tlv_integer, required),
828 /// (1, tlv_default_integer, (default_value, 7)),
829 /// (2, tlv_optional_integer, option),
830 /// (3, tlv_vec_type_integer, optional_vec),
834 /// [`Readable`]: crate::util::ser::Readable
835 /// [`Writeable`]: crate::util::ser::Writeable
837 macro_rules! impl_writeable_tlv_based {
838 ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
839 impl $crate::util::ser::Writeable for $st {
840 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
841 $crate::write_tlv_fields!(writer, {
842 $(($type, self.$field, $fieldty)),*
848 fn serialized_length(&self) -> usize {
849 use $crate::util::ser::BigSize;
852 let mut len = $crate::util::ser::LengthCalculatingWriter(0);
854 $crate::_get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
858 let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
859 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
864 impl $crate::util::ser::Readable for $st {
865 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
866 $crate::_init_and_read_tlv_fields!(reader, {
867 $(($type, $field, $fieldty)),*
871 $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
879 /// Defines a struct for a TLV stream and a similar struct using references for non-primitive types,
880 /// implementing [`Readable`] for the former and [`Writeable`] for the latter. Useful as an
881 /// intermediary format when reading or writing a type encoded as a TLV stream. Note that each field
882 /// representing a TLV record has its type wrapped with an [`Option`]. A tuple consisting of a type
883 /// and a serialization wrapper may be given in place of a type when custom serialization is
886 /// [`Readable`]: crate::util::ser::Readable
887 /// [`Writeable`]: crate::util::ser::Writeable
888 macro_rules! tlv_stream {
889 ($name:ident, $nameref:ident, $range:expr, {
890 $(($type:expr, $field:ident : $fieldty:tt)),* $(,)*
893 pub(super) struct $name {
895 pub(super) $field: Option<tlv_record_type!($fieldty)>,
899 #[cfg_attr(test, derive(PartialEq))]
901 pub(super) struct $nameref<'a> {
903 pub(super) $field: Option<tlv_record_ref_type!($fieldty)>,
907 impl<'a> $crate::util::ser::Writeable for $nameref<'a> {
908 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
909 encode_tlv_stream!(writer, {
910 $(($type, self.$field, (option, encoding: $fieldty))),*
916 impl $crate::util::ser::SeekReadable for $name {
917 fn read<R: $crate::io::Read + $crate::io::Seek>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
919 _init_tlv_field_var!($field, option);
921 let rewind = |cursor: &mut R, offset: usize| {
922 cursor.seek($crate::io::SeekFrom::Current(-(offset as i64))).expect("");
924 _decode_tlv_stream_range!(reader, $range, rewind, {
925 $(($type, $field, (option, encoding: $fieldty))),*
938 macro_rules! tlv_record_type {
939 (($type:ty, $wrapper:ident)) => { $type };
940 (($type:ty, $wrapper:ident, $encoder:ty)) => { $type };
941 ($type:ty) => { $type };
944 macro_rules! tlv_record_ref_type {
947 ((u16, $wrapper: ident)) => { u16 };
948 ((u32, $wrapper: ident)) => { u32 };
949 ((u64, $wrapper: ident)) => { u64 };
950 (($type:ty, $wrapper:ident)) => { &'a $type };
951 (($type:ty, $wrapper:ident, $encoder:ty)) => { $encoder };
952 ($type:ty) => { &'a $type };
957 macro_rules! _impl_writeable_tlv_based_enum_common {
958 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
959 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
961 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
962 impl $crate::util::ser::Writeable for $st {
963 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
965 $($st::$variant_name { $(ref $field),* } => {
966 let id: u8 = $variant_id;
968 $crate::write_tlv_fields!(writer, {
969 $(($type, *$field, $fieldty)),*
972 $($st::$tuple_variant_name (ref field) => {
973 let id: u8 = $tuple_variant_id;
975 field.write(writer)?;
984 /// Implement [`Readable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and tuple
985 /// variants stored directly.
986 /// The format is, for example
988 /// impl_writeable_tlv_based_enum!(EnumName,
989 /// (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
990 /// (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, optional_vec)};
991 /// (2, TupleVariantA), (3, TupleVariantB),
994 /// The type is written as a single byte, followed by any variant data.
995 /// Attempts to read an unknown type byte result in [`DecodeError::UnknownRequiredFeature`].
997 /// [`Readable`]: crate::util::ser::Readable
998 /// [`Writeable`]: crate::util::ser::Writeable
999 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
1001 macro_rules! impl_writeable_tlv_based_enum {
1002 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
1003 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1005 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
1006 $crate::_impl_writeable_tlv_based_enum_common!($st,
1007 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
1008 $(($tuple_variant_id, $tuple_variant_name)),*);
1010 impl $crate::util::ser::Readable for $st {
1011 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
1012 let id: u8 = $crate::util::ser::Readable::read(reader)?;
1015 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
1016 // in the same function body. Instead, we define a closure and call it.
1018 $crate::_init_and_read_tlv_fields!(reader, {
1019 $(($type, $field, $fieldty)),*
1021 Ok($st::$variant_name {
1023 $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1029 $($tuple_variant_id => {
1030 Ok($st::$tuple_variant_name($crate::util::ser::Readable::read(reader)?))
1033 Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature)
1041 /// Implement [`MaybeReadable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and
1042 /// tuple variants stored directly.
1044 /// This is largely identical to [`impl_writeable_tlv_based_enum`], except that odd variants will
1045 /// return `Ok(None)` instead of `Err(`[`DecodeError::UnknownRequiredFeature`]`)`. It should generally be preferred
1046 /// when [`MaybeReadable`] is practical instead of just [`Readable`] as it provides an upgrade path for
1047 /// new variants to be added which are simply ignored by existing clients.
1049 /// [`MaybeReadable`]: crate::util::ser::MaybeReadable
1050 /// [`Writeable`]: crate::util::ser::Writeable
1051 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
1052 /// [`Readable`]: crate::util::ser::Readable
1054 macro_rules! impl_writeable_tlv_based_enum_upgradable {
1055 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
1056 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1059 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*)*) => {
1060 $crate::_impl_writeable_tlv_based_enum_common!($st,
1061 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
1062 $($(($tuple_variant_id, $tuple_variant_name)),*)*);
1064 impl $crate::util::ser::MaybeReadable for $st {
1065 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
1066 let id: u8 = $crate::util::ser::Readable::read(reader)?;
1069 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
1070 // in the same function body. Instead, we define a closure and call it.
1072 $crate::_init_and_read_tlv_fields!(reader, {
1073 $(($type, $field, $fieldty)),*
1075 Ok(Some($st::$variant_name {
1077 $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1083 $($($tuple_variant_id => {
1084 Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
1086 _ if id % 2 == 1 => Ok(None),
1087 _ => Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature),
1096 use crate::io::{self, Cursor};
1097 use crate::prelude::*;
1098 use crate::ln::msgs::DecodeError;
1099 use crate::util::ser::{Writeable, HighZeroBytesDroppedBigSize, VecWriter};
1100 use bitcoin::secp256k1::PublicKey;
1102 // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
1103 // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
1104 // work with so they're baked into the decoder. Thus, we have a few additional tests below
1105 fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
1106 let mut s = Cursor::new(s);
1109 let mut c: Option<u32> = None;
1110 decode_tlv_stream!(&mut s, {(2, a, required), (3, b, required), (4, c, option)});
1115 fn tlv_v_short_read() {
1116 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
1117 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
1118 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
1120 } else { panic!(); }
1124 fn tlv_types_out_of_order() {
1125 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
1126 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
1128 } else { panic!(); }
1129 // ...even if its some field we don't understand
1130 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
1131 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
1133 } else { panic!(); }
1137 fn tlv_req_type_missing_or_extra() {
1138 // It's also bad if they included even fields we don't understand
1139 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
1140 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
1142 } else { panic!(); }
1143 // ... or if they're missing fields we need
1144 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
1145 concat!("0100", "0208deadbeef1badbeef")
1147 } else { panic!(); }
1148 // ... even if that field is even
1149 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
1150 concat!("0304deadbeef", "0500")
1152 } else { panic!(); }
1156 fn tlv_simple_good_cases() {
1157 assert_eq!(tlv_reader(&::hex::decode(
1158 concat!("0208deadbeef1badbeef", "03041bad1dea")
1159 ).unwrap()[..]).unwrap(),
1160 (0xdeadbeef1badbeef, 0x1bad1dea, None));
1161 assert_eq!(tlv_reader(&::hex::decode(
1162 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
1163 ).unwrap()[..]).unwrap(),
1164 (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
1167 #[derive(Debug, PartialEq)]
1168 struct TestUpgradable {
1174 fn upgradable_tlv_reader(s: &[u8]) -> Result<Option<TestUpgradable>, DecodeError> {
1175 let mut s = Cursor::new(s);
1178 let mut c: Option<u32> = None;
1179 decode_tlv_stream!(&mut s, {(2, a, upgradable_required), (3, b, upgradable_required), (4, c, upgradable_option)});
1180 Ok(Some(TestUpgradable { a, b, c, }))
1184 fn upgradable_tlv_simple_good_cases() {
1185 assert_eq!(upgradable_tlv_reader(&::hex::decode(
1186 concat!("0204deadbeef", "03041bad1dea", "0404deadbeef")
1187 ).unwrap()[..]).unwrap(),
1188 Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: Some(0xdeadbeef) }));
1190 assert_eq!(upgradable_tlv_reader(&::hex::decode(
1191 concat!("0204deadbeef", "03041bad1dea")
1192 ).unwrap()[..]).unwrap(),
1193 Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: None}));
1197 fn missing_required_upgradable() {
1198 if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&::hex::decode(
1199 concat!("0100", "0204deadbeef")
1201 } else { panic!(); }
1202 if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&::hex::decode(
1203 concat!("0100", "03041bad1dea")
1205 } else { panic!(); }
1208 // BOLT TLV test cases
1209 fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedBigSize<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
1210 let mut s = Cursor::new(s);
1211 let mut tlv1: Option<HighZeroBytesDroppedBigSize<u64>> = None;
1212 let mut tlv2: Option<u64> = None;
1213 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
1214 let mut tlv4: Option<u16> = None;
1215 decode_tlv_stream!(&mut s, {(1, tlv1, option), (2, tlv2, option), (3, tlv3, option), (254, tlv4, option)});
1216 Ok((tlv1, tlv2, tlv3, tlv4))
1220 fn bolt_tlv_bogus_stream() {
1221 macro_rules! do_test {
1222 ($stream: expr, $reason: ident) => {
1223 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
1224 } else { panic!(); }
1228 // TLVs from the BOLT test cases which should not decode as either n1 or n2
1229 do_test!(concat!("fd01"), ShortRead);
1230 do_test!(concat!("fd0001", "00"), InvalidValue);
1231 do_test!(concat!("fd0101"), ShortRead);
1232 do_test!(concat!("0f", "fd"), ShortRead);
1233 do_test!(concat!("0f", "fd26"), ShortRead);
1234 do_test!(concat!("0f", "fd2602"), ShortRead);
1235 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
1236 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
1238 do_test!(concat!("12", "00"), UnknownRequiredFeature);
1239 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
1240 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
1241 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
1245 fn bolt_tlv_bogus_n1_stream() {
1246 macro_rules! do_test {
1247 ($stream: expr, $reason: ident) => {
1248 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
1249 } else { panic!(); }
1253 // TLVs from the BOLT test cases which should not decode as n1
1254 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
1255 do_test!(concat!("01", "01", "00"), InvalidValue);
1256 do_test!(concat!("01", "02", "0001"), InvalidValue);
1257 do_test!(concat!("01", "03", "000100"), InvalidValue);
1258 do_test!(concat!("01", "04", "00010000"), InvalidValue);
1259 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
1260 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
1261 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
1262 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
1263 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
1264 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
1265 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
1266 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
1267 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
1268 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
1269 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
1270 do_test!(concat!("fd00fe", "00"), ShortRead);
1271 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
1272 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
1273 do_test!(concat!("00", "00"), UnknownRequiredFeature);
1275 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
1276 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
1277 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
1278 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
1280 // The last BOLT test modified to not require creating a new decoder for one trivial test.
1281 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
1285 fn bolt_tlv_valid_n1_stream() {
1286 macro_rules! do_test {
1287 ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
1288 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
1289 assert_eq!(tlv1.map(|v| v.0), $tlv1);
1290 assert_eq!(tlv2, $tlv2);
1291 assert_eq!(tlv3, $tlv3);
1292 assert_eq!(tlv4, $tlv4);
1293 } else { panic!(); }
1297 do_test!(concat!(""), None, None, None, None);
1298 do_test!(concat!("21", "00"), None, None, None, None);
1299 do_test!(concat!("fd0201", "00"), None, None, None, None);
1300 do_test!(concat!("fd00fd", "00"), None, None, None, None);
1301 do_test!(concat!("fd00ff", "00"), None, None, None, None);
1302 do_test!(concat!("fe02000001", "00"), None, None, None, None);
1303 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
1305 do_test!(concat!("01", "00"), Some(0), None, None, None);
1306 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
1307 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
1308 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
1309 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
1310 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
1311 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
1312 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
1313 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
1314 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
1315 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
1317 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
1319 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
1322 fn do_simple_test_tlv_write() -> Result<(), io::Error> {
1323 let mut stream = VecWriter(Vec::new());
1326 _encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
1327 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
1330 _encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
1331 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
1334 _encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
1335 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
1338 _encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
1339 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
1342 _encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1343 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
1346 _encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1347 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
1353 fn simple_test_tlv_write() {
1354 do_simple_test_tlv_write().unwrap();