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 $crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*}, &[])
236 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}, $extra_tlvs: expr) => { {
238 use $crate::util::ser::BigSize;
242 let mut len = $crate::util::ser::LengthCalculatingWriter(0);
244 $crate::_get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
246 for tlv in $extra_tlvs {
247 let (typ, value): &(u64, Vec<u8>) = tlv;
248 $crate::_get_varint_length_prefixed_tlv_length!(len, *typ, *value, required_vec);
252 BigSize(len as u64).write($stream)?;
253 $crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, $extra_tlvs);
257 /// Errors if there are missing required TLV types between the last seen type and the type currently being processed.
258 /// This is exported for use by other exported macros, do not use directly.
261 macro_rules! _check_decoded_tlv_order {
262 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
263 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
264 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
266 $field = $default.into();
269 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (static_value, $value: expr)) => {
271 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
272 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
273 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
275 return Err(DecodeError::InvalidValue);
278 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
279 $crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
281 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
284 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required_vec) => {{
285 $crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
287 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, optional_vec) => {{
290 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_required) => {{
291 _check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required)
293 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_option) => {{
296 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
299 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
304 /// Errors if there are missing required TLV types after the last seen type.
305 /// This is exported for use by other exported macros, do not use directly.
308 macro_rules! _check_missing_tlv {
309 ($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
310 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
311 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
312 if missing_req_type {
313 $field = $default.into();
316 ($last_seen_type: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
319 ($last_seen_type: expr, $type: expr, $field: ident, required) => {{
320 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
321 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
322 if missing_req_type {
323 return Err(DecodeError::InvalidValue);
326 ($last_seen_type: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
327 $crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
329 ($last_seen_type: expr, $type: expr, $field: ident, required_vec) => {{
330 $crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
332 ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
335 ($last_seen_type: expr, $type: expr, $field: ident, optional_vec) => {{
338 ($last_seen_type: expr, $type: expr, $field: ident, upgradable_required) => {{
339 _check_missing_tlv!($last_seen_type, $type, $field, required)
341 ($last_seen_type: expr, $type: expr, $field: ident, upgradable_option) => {{
344 ($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
347 ($last_seen_type: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
352 /// Implements deserialization for a single TLV record.
353 /// This is exported for use by other exported macros, do not use directly.
356 macro_rules! _decode_tlv {
357 ($reader: expr, $field: ident, (default_value, $default: expr)) => {{
358 $crate::_decode_tlv!($reader, $field, required)
360 ($reader: expr, $field: ident, (static_value, $value: expr)) => {{
362 ($reader: expr, $field: ident, required) => {{
363 $field = $crate::util::ser::Readable::read(&mut $reader)?;
365 ($reader: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
366 $field = $trait::read(&mut $reader $(, $read_arg)*)?;
368 ($reader: expr, $field: ident, required_vec) => {{
369 let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
372 ($reader: expr, $field: ident, option) => {{
373 $field = Some($crate::util::ser::Readable::read(&mut $reader)?);
375 ($reader: expr, $field: ident, optional_vec) => {{
376 let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
379 // `upgradable_required` indicates we're reading a required TLV that may have been upgraded
380 // without backwards compat. We'll error if the field is missing, and return `Ok(None)` if the
381 // field is present but we can no longer understand it.
382 // Note that this variant can only be used within a `MaybeReadable` read.
383 ($reader: expr, $field: ident, upgradable_required) => {{
384 $field = match $crate::util::ser::MaybeReadable::read(&mut $reader)? {
389 // `upgradable_option` indicates we're reading an Option-al TLV that may have been upgraded
390 // without backwards compat. $field will be None if the TLV is missing or if the field is present
391 // but we can no longer understand it.
392 ($reader: expr, $field: ident, upgradable_option) => {{
393 $field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
395 ($reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
396 $field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
398 ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident, $encoder:ty))) => {{
399 $crate::_decode_tlv!($reader, $field, (option, encoding: ($fieldty, $encoding)));
401 ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {{
403 let field: $encoding<$fieldty> = ser::Readable::read(&mut $reader)?;
407 ($reader: expr, $field: ident, (option, encoding: $fieldty: ty)) => {{
408 $crate::_decode_tlv!($reader, $field, option);
412 /// Checks if `$val` matches `$type`.
413 /// This is exported for use by other exported macros, do not use directly.
416 macro_rules! _decode_tlv_stream_match_check {
417 ($val: ident, $type: expr, (static_value, $value: expr)) => { false };
418 ($val: ident, $type: expr, $fieldty: tt) => { $val == $type }
421 /// Implements the TLVs deserialization part in a [`Readable`] implementation of a struct.
423 /// This should be called inside a method which returns `Result<_, `[`DecodeError`]`>`, such as
424 /// [`Readable::read`]. It will either return an `Err` or ensure all `required` fields have been
425 /// read and optionally read `optional` fields.
427 /// `$stream` must be a [`Read`] and will be fully consumed, reading until no more bytes remain
428 /// (i.e. it returns [`DecodeError::ShortRead`]).
430 /// Fields MUST be sorted in `$type`-order.
432 /// Note that the lightning TLV requirements require that a single type not appear more than once,
433 /// that TLVs are sorted in type-ascending order, and that any even types be understood by the
438 /// # use lightning::decode_tlv_stream;
439 /// # fn read<R: lightning::io::Read> (stream: R) -> Result<(), lightning::ln::msgs::DecodeError> {
440 /// let mut required_value = 0u64;
441 /// let mut optional_value: Option<u64> = None;
442 /// decode_tlv_stream!(stream, {
443 /// (0, required_value, required),
444 /// (2, optional_value, option),
446 /// // At this point, `required_value` has been overwritten with the TLV with type 0.
447 /// // `optional_value` may have been overwritten, setting it to `Some` if a TLV with type 2 was
453 /// [`Readable`]: crate::util::ser::Readable
454 /// [`DecodeError`]: crate::ln::msgs::DecodeError
455 /// [`Readable::read`]: crate::util::ser::Readable::read
456 /// [`Read`]: crate::io::Read
457 /// [`DecodeError::ShortRead`]: crate::ln::msgs::DecodeError::ShortRead
459 macro_rules! decode_tlv_stream {
460 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
461 let rewind = |_, _| { unreachable!() };
462 $crate::_decode_tlv_stream_range!($stream, .., rewind, {$(($type, $field, $fieldty)),*});
466 /// Similar to [`decode_tlv_stream`] with a custom TLV decoding capabilities.
468 /// `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
469 /// If it is provided, it will be called with the custom type and the [`FixedLengthReader`] containing
470 /// the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
471 /// `Ok(false)` if the message type is unknown, and `Err(`[`DecodeError`]`)` if parsing fails.
473 /// [`FixedLengthReader`]: crate::util::ser::FixedLengthReader
474 /// [`DecodeError`]: crate::ln::msgs::DecodeError
475 macro_rules! decode_tlv_stream_with_custom_tlv_decode {
476 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
477 $(, $decode_custom_tlv: expr)?) => { {
478 let rewind = |_, _| { unreachable!() };
479 _decode_tlv_stream_range!(
480 $stream, .., rewind, {$(($type, $field, $fieldty)),*} $(, $decode_custom_tlv)?
487 macro_rules! _decode_tlv_stream_range {
488 ($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
489 $(, $decode_custom_tlv: expr)?) => { {
490 use $crate::ln::msgs::DecodeError;
491 let mut last_seen_type: Option<u64> = None;
492 let mut stream_ref = $stream;
494 use $crate::util::ser;
496 // First decode the type of this TLV:
497 let typ: ser::BigSize = {
498 // We track whether any bytes were read during the consensus_decode call to
499 // determine whether we should break or return ShortRead if we get an
500 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
501 // pass the TLV test vectors exactly, which require this distinction.
502 let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
503 match <$crate::util::ser::BigSize as $crate::util::ser::Readable>::read(&mut tracking_reader) {
504 Err(DecodeError::ShortRead) => {
505 if !tracking_reader.have_read {
508 return Err(DecodeError::ShortRead);
511 Err(e) => return Err(e),
512 Ok(t) => if core::ops::RangeBounds::contains(&$range, &t.0) { t } else {
513 drop(tracking_reader);
515 // Assumes the type id is minimally encoded, which is enforced on read.
516 use $crate::util::ser::Writeable;
517 let bytes_read = t.serialized_length();
518 $rewind(stream_ref, bytes_read);
524 // Types must be unique and monotonically increasing:
525 match last_seen_type {
526 Some(t) if typ.0 <= t => {
527 return Err(DecodeError::InvalidValue);
531 // As we read types, make sure we hit every required type between `last_seen_type` and `typ`:
533 $crate::_check_decoded_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
535 last_seen_type = Some(typ.0);
537 // Finally, read the length and value itself:
538 let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
539 let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
541 $(_t if $crate::_decode_tlv_stream_match_check!(_t, $type, $fieldty) => {
542 $crate::_decode_tlv!(s, $field, $fieldty);
543 if s.bytes_remain() {
544 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
545 return Err(DecodeError::InvalidValue);
550 if $decode_custom_tlv(t, &mut s)? {
551 // If a custom TLV was successfully read (i.e. decode_custom_tlv returns true),
552 // continue to the next TLV read.
558 return Err(DecodeError::UnknownRequiredFeature);
564 // Make sure we got to each required type after we've read every TLV:
566 $crate::_check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
571 /// Implements [`Readable`]/[`Writeable`] for a message struct that may include non-TLV and
572 /// TLV-encoded parts.
574 /// This is useful to implement a [`CustomMessageReader`].
576 /// Currently `$fieldty` may only be `option`, i.e., `$tlvfield` is optional field.
580 /// # use lightning::impl_writeable_msg;
581 /// struct MyCustomMessage {
582 /// pub field_1: u32,
583 /// pub field_2: bool,
584 /// pub field_3: String,
585 /// pub tlv_optional_integer: Option<u32>,
588 /// impl_writeable_msg!(MyCustomMessage, {
593 /// (1, tlv_optional_integer, option),
597 /// [`Readable`]: crate::util::ser::Readable
598 /// [`Writeable`]: crate::util::ser::Writeable
599 /// [`CustomMessageReader`]: crate::ln::wire::CustomMessageReader
601 macro_rules! impl_writeable_msg {
602 ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
603 impl $crate::util::ser::Writeable for $st {
604 fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
605 $( self.$field.write(w)?; )*
606 $crate::encode_tlv_stream!(w, {$(($type, self.$tlvfield.as_ref(), $fieldty)),*});
610 impl $crate::util::ser::Readable for $st {
611 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
612 $(let $field = $crate::util::ser::Readable::read(r)?;)*
613 $($crate::_init_tlv_field_var!($tlvfield, $fieldty);)*
614 $crate::decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
624 macro_rules! impl_writeable {
625 ($st:ident, {$($field:ident),*}) => {
626 impl $crate::util::ser::Writeable for $st {
627 fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
628 $( self.$field.write(w)?; )*
633 fn serialized_length(&self) -> usize {
634 let mut len_calc = 0;
635 $( len_calc += self.$field.serialized_length(); )*
640 impl $crate::util::ser::Readable for $st {
641 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
643 $($field: $crate::util::ser::Readable::read(r)?),*
650 /// Write out two bytes to indicate the version of an object.
652 /// $this_version represents a unique version of a type. Incremented whenever the type's
653 /// serialization format has changed or has a new interpretation. Used by a type's reader to
654 /// determine how to interpret fields or if it can understand a serialized object.
656 /// $min_version_that_can_read_this is the minimum reader version which can understand this
657 /// serialized object. Previous versions will simply err with a [`DecodeError::UnknownVersion`].
659 /// Updates to either `$this_version` or `$min_version_that_can_read_this` should be included in
662 /// Both version fields can be specific to this type of object.
664 /// [`DecodeError::UnknownVersion`]: crate::ln::msgs::DecodeError::UnknownVersion
665 macro_rules! write_ver_prefix {
666 ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
667 $stream.write_all(&[$this_version; 1])?;
668 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
672 /// Writes out a suffix to an object as a length-prefixed TLV stream which contains potentially
673 /// backwards-compatible, optional fields which old nodes can happily ignore.
675 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
676 /// [`DecodeError::UnknownRequiredFeature`] error, with unknown odd fields ignored.
678 /// This is the preferred method of adding new fields that old nodes can ignore and still function
681 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
683 macro_rules! write_tlv_fields {
684 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
685 $crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
689 /// Reads a prefix added by [`write_ver_prefix`], above. Takes the current version of the
690 /// serialization logic for this object. This is compared against the
691 /// `$min_version_that_can_read_this` added by [`write_ver_prefix`].
692 macro_rules! read_ver_prefix {
693 ($stream: expr, $this_version: expr) => { {
694 let ver: u8 = Readable::read($stream)?;
695 let min_ver: u8 = Readable::read($stream)?;
696 if min_ver > $this_version {
697 return Err(DecodeError::UnknownVersion);
703 /// Reads a suffix added by [`write_tlv_fields`].
705 /// [`write_tlv_fields`]: crate::write_tlv_fields
707 macro_rules! read_tlv_fields {
708 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
709 let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
710 let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
711 $crate::decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
712 rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
716 /// Initializes the struct fields.
718 /// This is exported for use by other exported macros, do not use directly.
721 macro_rules! _init_tlv_based_struct_field {
722 ($field: ident, (default_value, $default: expr)) => {
725 ($field: ident, (static_value, $value: expr)) => {
728 ($field: ident, option) => {
731 ($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
732 $crate::_init_tlv_based_struct_field!($field, option)
734 ($field: ident, upgradable_required) => {
737 ($field: ident, upgradable_option) => {
740 ($field: ident, required) => {
743 ($field: ident, required_vec) => {
746 ($field: ident, optional_vec) => {
751 /// Initializes the variable we are going to read the TLV into.
753 /// This is exported for use by other exported macros, do not use directly.
756 macro_rules! _init_tlv_field_var {
757 ($field: ident, (default_value, $default: expr)) => {
758 let mut $field = $crate::util::ser::RequiredWrapper(None);
760 ($field: ident, (static_value, $value: expr)) => {
763 ($field: ident, required) => {
764 let mut $field = $crate::util::ser::RequiredWrapper(None);
766 ($field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {
767 $crate::_init_tlv_field_var!($field, required);
769 ($field: ident, required_vec) => {
770 let mut $field = Vec::new();
772 ($field: ident, option) => {
773 let mut $field = None;
775 ($field: ident, optional_vec) => {
776 let mut $field = Some(Vec::new());
778 ($field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
779 $crate::_init_tlv_field_var!($field, option);
781 ($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
782 $crate::_init_tlv_field_var!($field, option);
784 ($field: ident, upgradable_required) => {
785 let mut $field = $crate::util::ser::UpgradableRequired(None);
787 ($field: ident, upgradable_option) => {
788 let mut $field = None;
792 /// Equivalent to running [`_init_tlv_field_var`] then [`read_tlv_fields`].
794 /// If any unused values are read, their type MUST be specified or else `rustc` will read them as an
797 /// This is exported for use by other exported macros, do not use directly.
800 macro_rules! _init_and_read_len_prefixed_tlv_fields {
801 ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
803 $crate::_init_tlv_field_var!($field, $fieldty);
806 $crate::read_tlv_fields!($reader, {
807 $(($type, $field, $fieldty)),*
812 /// Equivalent to running [`_init_tlv_field_var`] then [`decode_tlv_stream`].
814 /// If any unused values are read, their type MUST be specified or else `rustc` will read them as an
816 macro_rules! _init_and_read_tlv_stream {
817 ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
819 $crate::_init_tlv_field_var!($field, $fieldty);
822 $crate::decode_tlv_stream!($reader, {
823 $(($type, $field, $fieldty)),*
828 /// Implements [`Readable`]/[`Writeable`] for a struct storing it as a set of TLVs
829 /// If `$fieldty` is `required`, then `$field` is a required field that is not an [`Option`] nor a [`Vec`].
830 /// If `$fieldty` is `(default_value, $default)`, then `$field` will be set to `$default` if not present.
831 /// If `$fieldty` is `option`, then `$field` is optional field.
832 /// If `$fieldty` is `optional_vec`, then `$field` is a [`Vec`], which needs to have its individual elements serialized.
833 /// Note that for `optional_vec` no bytes are written if the vec is empty
837 /// # use lightning::impl_writeable_tlv_based;
838 /// struct LightningMessage {
839 /// tlv_integer: u32,
840 /// tlv_default_integer: u32,
841 /// tlv_optional_integer: Option<u32>,
842 /// tlv_vec_type_integer: Vec<u32>,
845 /// impl_writeable_tlv_based!(LightningMessage, {
846 /// (0, tlv_integer, required),
847 /// (1, tlv_default_integer, (default_value, 7)),
848 /// (2, tlv_optional_integer, option),
849 /// (3, tlv_vec_type_integer, optional_vec),
853 /// [`Readable`]: crate::util::ser::Readable
854 /// [`Writeable`]: crate::util::ser::Writeable
856 macro_rules! impl_writeable_tlv_based {
857 ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
858 impl $crate::util::ser::Writeable for $st {
859 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
860 $crate::write_tlv_fields!(writer, {
861 $(($type, self.$field, $fieldty)),*
867 fn serialized_length(&self) -> usize {
868 use $crate::util::ser::BigSize;
871 let mut len = $crate::util::ser::LengthCalculatingWriter(0);
873 $crate::_get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
877 let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
878 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
883 impl $crate::util::ser::Readable for $st {
884 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
885 $crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
886 $(($type, $field, $fieldty)),*
890 $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
898 /// Defines a struct for a TLV stream and a similar struct using references for non-primitive types,
899 /// implementing [`Readable`] for the former and [`Writeable`] for the latter. Useful as an
900 /// intermediary format when reading or writing a type encoded as a TLV stream. Note that each field
901 /// representing a TLV record has its type wrapped with an [`Option`]. A tuple consisting of a type
902 /// and a serialization wrapper may be given in place of a type when custom serialization is
905 /// [`Readable`]: crate::util::ser::Readable
906 /// [`Writeable`]: crate::util::ser::Writeable
907 macro_rules! tlv_stream {
908 ($name:ident, $nameref:ident, $range:expr, {
909 $(($type:expr, $field:ident : $fieldty:tt)),* $(,)*
912 pub(super) struct $name {
914 pub(super) $field: Option<tlv_record_type!($fieldty)>,
918 #[cfg_attr(test, derive(PartialEq))]
920 pub(crate) struct $nameref<'a> {
922 pub(super) $field: Option<tlv_record_ref_type!($fieldty)>,
926 impl<'a> $crate::util::ser::Writeable for $nameref<'a> {
927 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
928 encode_tlv_stream!(writer, {
929 $(($type, self.$field, (option, encoding: $fieldty))),*
935 impl $crate::util::ser::SeekReadable for $name {
936 fn read<R: $crate::io::Read + $crate::io::Seek>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
938 _init_tlv_field_var!($field, option);
940 let rewind = |cursor: &mut R, offset: usize| {
941 cursor.seek($crate::io::SeekFrom::Current(-(offset as i64))).expect("");
943 _decode_tlv_stream_range!(reader, $range, rewind, {
944 $(($type, $field, (option, encoding: $fieldty))),*
957 macro_rules! tlv_record_type {
958 (($type:ty, $wrapper:ident)) => { $type };
959 (($type:ty, $wrapper:ident, $encoder:ty)) => { $type };
960 ($type:ty) => { $type };
963 macro_rules! tlv_record_ref_type {
966 ((u16, $wrapper: ident)) => { u16 };
967 ((u32, $wrapper: ident)) => { u32 };
968 ((u64, $wrapper: ident)) => { u64 };
969 (($type:ty, $wrapper:ident)) => { &'a $type };
970 (($type:ty, $wrapper:ident, $encoder:ty)) => { $encoder };
971 ($type:ty) => { &'a $type };
976 macro_rules! _impl_writeable_tlv_based_enum_common {
977 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
978 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
980 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
981 impl $crate::util::ser::Writeable for $st {
982 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
984 $($st::$variant_name { $(ref $field),* } => {
985 let id: u8 = $variant_id;
987 $crate::write_tlv_fields!(writer, {
988 $(($type, *$field, $fieldty)),*
991 $($st::$tuple_variant_name (ref field) => {
992 let id: u8 = $tuple_variant_id;
994 field.write(writer)?;
1003 /// Implement [`Readable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and tuple
1004 /// variants stored directly.
1005 /// The format is, for example
1007 /// impl_writeable_tlv_based_enum!(EnumName,
1008 /// (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
1009 /// (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, optional_vec)};
1010 /// (2, TupleVariantA), (3, TupleVariantB),
1013 /// The type is written as a single byte, followed by any variant data.
1014 /// Attempts to read an unknown type byte result in [`DecodeError::UnknownRequiredFeature`].
1016 /// [`Readable`]: crate::util::ser::Readable
1017 /// [`Writeable`]: crate::util::ser::Writeable
1018 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
1020 macro_rules! impl_writeable_tlv_based_enum {
1021 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
1022 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1024 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
1025 $crate::_impl_writeable_tlv_based_enum_common!($st,
1026 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
1027 $(($tuple_variant_id, $tuple_variant_name)),*);
1029 impl $crate::util::ser::Readable for $st {
1030 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
1031 let id: u8 = $crate::util::ser::Readable::read(reader)?;
1034 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
1035 // in the same function body. Instead, we define a closure and call it.
1037 $crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
1038 $(($type, $field, $fieldty)),*
1040 Ok($st::$variant_name {
1042 $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1048 $($tuple_variant_id => {
1049 Ok($st::$tuple_variant_name($crate::util::ser::Readable::read(reader)?))
1052 Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature)
1060 /// Implement [`MaybeReadable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and
1061 /// tuple variants stored directly.
1063 /// This is largely identical to [`impl_writeable_tlv_based_enum`], except that odd variants will
1064 /// return `Ok(None)` instead of `Err(`[`DecodeError::UnknownRequiredFeature`]`)`. It should generally be preferred
1065 /// when [`MaybeReadable`] is practical instead of just [`Readable`] as it provides an upgrade path for
1066 /// new variants to be added which are simply ignored by existing clients.
1068 /// [`MaybeReadable`]: crate::util::ser::MaybeReadable
1069 /// [`Writeable`]: crate::util::ser::Writeable
1070 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
1071 /// [`Readable`]: crate::util::ser::Readable
1073 macro_rules! impl_writeable_tlv_based_enum_upgradable {
1074 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
1075 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1078 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*)*) => {
1079 $crate::_impl_writeable_tlv_based_enum_common!($st,
1080 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
1081 $($(($tuple_variant_id, $tuple_variant_name)),*)*);
1083 impl $crate::util::ser::MaybeReadable for $st {
1084 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
1085 let id: u8 = $crate::util::ser::Readable::read(reader)?;
1088 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
1089 // in the same function body. Instead, we define a closure and call it.
1091 $crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
1092 $(($type, $field, $fieldty)),*
1094 Ok(Some($st::$variant_name {
1096 $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1102 $($($tuple_variant_id => {
1103 Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
1105 _ if id % 2 == 1 => Ok(None),
1106 _ => Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature),
1115 use crate::io::{self, Cursor};
1116 use crate::prelude::*;
1117 use crate::ln::msgs::DecodeError;
1118 use crate::util::ser::{Writeable, HighZeroBytesDroppedBigSize, VecWriter};
1119 use bitcoin::hashes::hex::FromHex;
1120 use bitcoin::secp256k1::PublicKey;
1122 // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
1123 // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
1124 // work with so they're baked into the decoder. Thus, we have a few additional tests below
1125 fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
1126 let mut s = Cursor::new(s);
1129 let mut c: Option<u32> = None;
1130 decode_tlv_stream!(&mut s, {(2, a, required), (3, b, required), (4, c, option)});
1135 fn tlv_v_short_read() {
1136 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
1137 if let Err(DecodeError::ShortRead) = tlv_reader(&<Vec<u8>>::from_hex(
1138 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
1140 } else { panic!(); }
1144 fn tlv_types_out_of_order() {
1145 if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1146 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
1148 } else { panic!(); }
1149 // ...even if its some field we don't understand
1150 if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1151 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
1153 } else { panic!(); }
1157 fn tlv_req_type_missing_or_extra() {
1158 // It's also bad if they included even fields we don't understand
1159 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&<Vec<u8>>::from_hex(
1160 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
1162 } else { panic!(); }
1163 // ... or if they're missing fields we need
1164 if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1165 concat!("0100", "0208deadbeef1badbeef")
1167 } else { panic!(); }
1168 // ... even if that field is even
1169 if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1170 concat!("0304deadbeef", "0500")
1172 } else { panic!(); }
1176 fn tlv_simple_good_cases() {
1177 assert_eq!(tlv_reader(&<Vec<u8>>::from_hex(
1178 concat!("0208deadbeef1badbeef", "03041bad1dea")
1179 ).unwrap()[..]).unwrap(),
1180 (0xdeadbeef1badbeef, 0x1bad1dea, None));
1181 assert_eq!(tlv_reader(&<Vec<u8>>::from_hex(
1182 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
1183 ).unwrap()[..]).unwrap(),
1184 (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
1187 #[derive(Debug, PartialEq)]
1188 struct TestUpgradable {
1194 fn upgradable_tlv_reader(s: &[u8]) -> Result<Option<TestUpgradable>, DecodeError> {
1195 let mut s = Cursor::new(s);
1198 let mut c: Option<u32> = None;
1199 decode_tlv_stream!(&mut s, {(2, a, upgradable_required), (3, b, upgradable_required), (4, c, upgradable_option)});
1200 Ok(Some(TestUpgradable { a, b, c, }))
1204 fn upgradable_tlv_simple_good_cases() {
1205 assert_eq!(upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1206 concat!("0204deadbeef", "03041bad1dea", "0404deadbeef")
1207 ).unwrap()[..]).unwrap(),
1208 Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: Some(0xdeadbeef) }));
1210 assert_eq!(upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1211 concat!("0204deadbeef", "03041bad1dea")
1212 ).unwrap()[..]).unwrap(),
1213 Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: None}));
1217 fn missing_required_upgradable() {
1218 if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1219 concat!("0100", "0204deadbeef")
1221 } else { panic!(); }
1222 if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1223 concat!("0100", "03041bad1dea")
1225 } else { panic!(); }
1228 // BOLT TLV test cases
1229 fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedBigSize<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
1230 let mut s = Cursor::new(s);
1231 let mut tlv1: Option<HighZeroBytesDroppedBigSize<u64>> = None;
1232 let mut tlv2: Option<u64> = None;
1233 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
1234 let mut tlv4: Option<u16> = None;
1235 decode_tlv_stream!(&mut s, {(1, tlv1, option), (2, tlv2, option), (3, tlv3, option), (254, tlv4, option)});
1236 Ok((tlv1, tlv2, tlv3, tlv4))
1240 fn bolt_tlv_bogus_stream() {
1241 macro_rules! do_test {
1242 ($stream: expr, $reason: ident) => {
1243 if let Err(DecodeError::$reason) = tlv_reader_n1(&<Vec<u8>>::from_hex($stream).unwrap()[..]) {
1244 } else { panic!(); }
1248 // TLVs from the BOLT test cases which should not decode as either n1 or n2
1249 do_test!(concat!("fd01"), ShortRead);
1250 do_test!(concat!("fd0001", "00"), InvalidValue);
1251 do_test!(concat!("fd0101"), ShortRead);
1252 do_test!(concat!("0f", "fd"), ShortRead);
1253 do_test!(concat!("0f", "fd26"), ShortRead);
1254 do_test!(concat!("0f", "fd2602"), ShortRead);
1255 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
1256 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
1258 do_test!(concat!("12", "00"), UnknownRequiredFeature);
1259 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
1260 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
1261 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
1265 fn bolt_tlv_bogus_n1_stream() {
1266 macro_rules! do_test {
1267 ($stream: expr, $reason: ident) => {
1268 if let Err(DecodeError::$reason) = tlv_reader_n1(&<Vec<u8>>::from_hex($stream).unwrap()[..]) {
1269 } else { panic!(); }
1273 // TLVs from the BOLT test cases which should not decode as n1
1274 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
1275 do_test!(concat!("01", "01", "00"), InvalidValue);
1276 do_test!(concat!("01", "02", "0001"), InvalidValue);
1277 do_test!(concat!("01", "03", "000100"), InvalidValue);
1278 do_test!(concat!("01", "04", "00010000"), InvalidValue);
1279 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
1280 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
1281 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
1282 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
1283 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
1284 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
1285 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
1286 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
1287 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
1288 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
1289 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
1290 do_test!(concat!("fd00fe", "00"), ShortRead);
1291 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
1292 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
1293 do_test!(concat!("00", "00"), UnknownRequiredFeature);
1295 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
1296 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
1297 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
1298 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
1300 // The last BOLT test modified to not require creating a new decoder for one trivial test.
1301 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
1305 fn bolt_tlv_valid_n1_stream() {
1306 macro_rules! do_test {
1307 ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
1308 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&<Vec<u8>>::from_hex($stream).unwrap()[..]) {
1309 assert_eq!(tlv1.map(|v| v.0), $tlv1);
1310 assert_eq!(tlv2, $tlv2);
1311 assert_eq!(tlv3, $tlv3);
1312 assert_eq!(tlv4, $tlv4);
1313 } else { panic!(); }
1317 do_test!(concat!(""), None, None, None, None);
1318 do_test!(concat!("21", "00"), None, None, None, None);
1319 do_test!(concat!("fd0201", "00"), None, None, None, None);
1320 do_test!(concat!("fd00fd", "00"), None, None, None, None);
1321 do_test!(concat!("fd00ff", "00"), None, None, None, None);
1322 do_test!(concat!("fe02000001", "00"), None, None, None, None);
1323 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
1325 do_test!(concat!("01", "00"), Some(0), None, None, None);
1326 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
1327 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
1328 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
1329 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
1330 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
1331 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
1332 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
1333 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
1334 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
1335 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
1337 PublicKey::from_slice(&<Vec<u8>>::from_hex("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
1339 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
1342 fn do_simple_test_tlv_write() -> Result<(), io::Error> {
1343 let mut stream = VecWriter(Vec::new());
1346 _encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
1347 assert_eq!(stream.0, <Vec<u8>>::from_hex("03010101").unwrap());
1350 _encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
1351 assert_eq!(stream.0, <Vec<u8>>::from_hex("03010101").unwrap());
1354 _encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
1355 assert_eq!(stream.0, <Vec<u8>>::from_hex("040402abcd").unwrap());
1358 _encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
1359 assert_eq!(stream.0, <Vec<u8>>::from_hex("06fd00ff02abcd").unwrap());
1362 _encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1363 assert_eq!(stream.0, <Vec<u8>>::from_hex("0e00080000000000000001fd00ff00").unwrap());
1366 _encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1367 assert_eq!(stream.0, <Vec<u8>>::from_hex("0e00080000000000000001fd00ff00").unwrap());
1373 fn simple_test_tlv_write() {
1374 do_simple_test_tlv_write().unwrap();