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 macro_rules! encode_tlv {
11 ($stream: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
12 encode_tlv!($stream, $type, $field, required)
14 ($stream: expr, $type: expr, $field: expr, required) => {
15 BigSize($type).write($stream)?;
16 BigSize($field.serialized_length() as u64).write($stream)?;
17 $field.write($stream)?;
19 ($stream: expr, $type: expr, $field: expr, vec_type) => {
20 encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required);
22 ($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
23 if let Some(ref field) = $optional_field {
24 BigSize($optional_type).write($stream)?;
25 BigSize(field.serialized_length() as u64).write($stream)?;
26 field.write($stream)?;
29 ($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
30 encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
32 ($stream: expr, $type: expr, $field: expr, (option, encoding: $fieldty: ty)) => {
33 encode_tlv!($stream, $type, $field, option);
37 macro_rules! encode_tlv_stream {
38 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
39 #[allow(unused_imports)]
41 ln::msgs::DecodeError,
47 encode_tlv!($stream, $type, $field, $fieldty);
50 #[allow(unused_mut, unused_variables, unused_assignments)]
51 #[cfg(debug_assertions)]
53 let mut last_seen: Option<u64> = None;
55 if let Some(t) = last_seen {
56 debug_assert!(t <= $type);
58 last_seen = Some($type);
64 macro_rules! get_varint_length_prefixed_tlv_length {
65 ($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
66 get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
68 ($len: expr, $type: expr, $field: expr, required) => {
69 BigSize($type).write(&mut $len).expect("No in-memory data may fail to serialize");
70 let field_len = $field.serialized_length();
71 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
74 ($len: expr, $type: expr, $field: expr, vec_type) => {
75 get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required);
77 ($len: expr, $optional_type: expr, $optional_field: expr, option) => {
78 if let Some(ref field) = $optional_field {
79 BigSize($optional_type).write(&mut $len).expect("No in-memory data may fail to serialize");
80 let field_len = field.serialized_length();
81 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
87 macro_rules! encode_varint_length_prefixed_tlv {
88 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
89 use $crate::util::ser::BigSize;
92 let mut len = $crate::util::ser::LengthCalculatingWriter(0);
94 get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
98 BigSize(len as u64).write($stream)?;
99 encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* });
103 macro_rules! check_tlv_order {
104 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
105 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
106 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
108 $field = $default.into();
111 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
112 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
113 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
115 return Err(DecodeError::InvalidValue);
118 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
121 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, vec_type) => {{
124 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, ignorable) => {{
127 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
130 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
135 macro_rules! check_missing_tlv {
136 ($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
137 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
138 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
139 if missing_req_type {
140 $field = $default.into();
143 ($last_seen_type: expr, $type: expr, $field: ident, required) => {{
144 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
145 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
146 if missing_req_type {
147 return Err(DecodeError::InvalidValue);
150 ($last_seen_type: expr, $type: expr, $field: ident, vec_type) => {{
153 ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
156 ($last_seen_type: expr, $type: expr, $field: ident, ignorable) => {{
159 ($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
162 ($last_seen_type: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
167 macro_rules! decode_tlv {
168 ($reader: expr, $field: ident, (default_value, $default: expr)) => {{
169 decode_tlv!($reader, $field, required)
171 ($reader: expr, $field: ident, required) => {{
172 $field = $crate::util::ser::Readable::read(&mut $reader)?;
174 ($reader: expr, $field: ident, vec_type) => {{
175 let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
178 ($reader: expr, $field: ident, option) => {{
179 $field = Some($crate::util::ser::Readable::read(&mut $reader)?);
181 ($reader: expr, $field: ident, ignorable) => {{
182 $field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
184 ($reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
185 $field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
187 ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {{
189 let field: $encoding<$fieldty> = ser::Readable::read(&mut $reader)?;
193 ($reader: expr, $field: ident, (option, encoding: $fieldty: ty)) => {{
194 decode_tlv!($reader, $field, option);
198 // `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
199 // If it is provided, it will be called with the custom type and the `FixedLengthReader` containing
200 // the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
201 // `Ok(false)` if the message type is unknown, and `Err(DecodeError)` if parsing fails.
202 macro_rules! decode_tlv_stream {
203 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
204 $(, $decode_custom_tlv: expr)?) => { {
205 let rewind = |_, _| { unreachable!() };
206 use core::ops::RangeBounds;
207 decode_tlv_stream_range!(
208 $stream, .., rewind, {$(($type, $field, $fieldty)),*} $(, $decode_custom_tlv)?
213 macro_rules! decode_tlv_stream_range {
214 ($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
215 $(, $decode_custom_tlv: expr)?) => { {
216 use $crate::ln::msgs::DecodeError;
217 let mut last_seen_type: Option<u64> = None;
218 let mut stream_ref = $stream;
220 use $crate::util::ser;
222 // First decode the type of this TLV:
223 let typ: ser::BigSize = {
224 // We track whether any bytes were read during the consensus_decode call to
225 // determine whether we should break or return ShortRead if we get an
226 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
227 // pass the TLV test vectors exactly, which requre this distinction.
228 let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
229 match <$crate::util::ser::BigSize as $crate::util::ser::Readable>::read(&mut tracking_reader) {
230 Err(DecodeError::ShortRead) => {
231 if !tracking_reader.have_read {
234 return Err(DecodeError::ShortRead);
237 Err(e) => return Err(e),
238 Ok(t) => if $range.contains(&t.0) { t } else {
239 drop(tracking_reader);
241 // Assumes the type id is minimally encoded, which is enforced on read.
242 use $crate::util::ser::Writeable;
243 let bytes_read = t.serialized_length();
244 $rewind(stream_ref, bytes_read);
250 // Types must be unique and monotonically increasing:
251 match last_seen_type {
252 Some(t) if typ.0 <= t => {
253 return Err(DecodeError::InvalidValue);
257 // As we read types, make sure we hit every required type:
259 check_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
261 last_seen_type = Some(typ.0);
263 // Finally, read the length and value itself:
264 let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
265 let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
268 decode_tlv!(s, $field, $fieldty);
269 if s.bytes_remain() {
270 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
271 return Err(DecodeError::InvalidValue);
276 if $decode_custom_tlv(t, &mut s)? {
277 // If a custom TLV was successfully read (i.e. decode_custom_tlv returns true),
278 // continue to the next TLV read.
284 return Err(DecodeError::UnknownRequiredFeature);
290 // Make sure we got to each required type after we've read every TLV:
292 check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
297 macro_rules! impl_writeable_msg {
298 ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
299 impl $crate::util::ser::Writeable for $st {
300 fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
301 $( self.$field.write(w)?; )*
302 encode_tlv_stream!(w, {$(($type, self.$tlvfield, $fieldty)),*});
306 impl $crate::util::ser::Readable for $st {
307 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
308 $(let $field = $crate::util::ser::Readable::read(r)?;)*
309 $(init_tlv_field_var!($tlvfield, $fieldty);)*
310 decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
320 macro_rules! impl_writeable {
321 ($st:ident, {$($field:ident),*}) => {
322 impl $crate::util::ser::Writeable for $st {
323 fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
324 $( self.$field.write(w)?; )*
329 fn serialized_length(&self) -> usize {
330 let mut len_calc = 0;
331 $( len_calc += self.$field.serialized_length(); )*
336 impl $crate::util::ser::Readable for $st {
337 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
339 $($field: $crate::util::ser::Readable::read(r)?),*
346 /// Write out two bytes to indicate the version of an object.
347 /// $this_version represents a unique version of a type. Incremented whenever the type's
348 /// serialization format has changed or has a new interpretation. Used by a type's
349 /// reader to determine how to interpret fields or if it can understand a serialized
351 /// $min_version_that_can_read_this is the minimum reader version which can understand this
352 /// serialized object. Previous versions will simply err with a
353 /// DecodeError::UnknownVersion.
355 /// Updates to either $this_version or $min_version_that_can_read_this should be included in
358 /// Both version fields can be specific to this type of object.
359 macro_rules! write_ver_prefix {
360 ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
361 $stream.write_all(&[$this_version; 1])?;
362 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
366 /// Writes out a suffix to an object which contains potentially backwards-compatible, optional
367 /// fields which old nodes can happily ignore.
369 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
370 /// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
372 /// This is the preferred method of adding new fields that old nodes can ignore and still function
374 macro_rules! write_tlv_fields {
375 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
376 encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
380 /// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
381 /// serialization logic for this object. This is compared against the
382 /// $min_version_that_can_read_this added by write_ver_prefix!().
383 macro_rules! read_ver_prefix {
384 ($stream: expr, $this_version: expr) => { {
385 let ver: u8 = Readable::read($stream)?;
386 let min_ver: u8 = Readable::read($stream)?;
387 if min_ver > $this_version {
388 return Err(DecodeError::UnknownVersion);
394 /// Reads a suffix added by write_tlv_fields.
395 macro_rules! read_tlv_fields {
396 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
397 let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
398 let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
399 decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
400 rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
404 macro_rules! init_tlv_based_struct_field {
405 ($field: ident, (default_value, $default: expr)) => {
408 ($field: ident, option) => {
411 ($field: ident, required) => {
414 ($field: ident, vec_type) => {
419 macro_rules! init_tlv_field_var {
420 ($field: ident, (default_value, $default: expr)) => {
421 let mut $field = $crate::util::ser::OptionDeserWrapper(None);
423 ($field: ident, required) => {
424 let mut $field = $crate::util::ser::OptionDeserWrapper(None);
426 ($field: ident, vec_type) => {
427 let mut $field = Some(Vec::new());
429 ($field: ident, option) => {
430 let mut $field = None;
434 /// Implements Readable/Writeable for a struct storing it as a set of TLVs
435 /// If $fieldty is `required`, then $field is a required field that is not an Option nor a Vec.
436 /// If $fieldty is `option`, then $field is optional field.
437 /// if $fieldty is `vec_type`, then $field is a Vec, which needs to have its individual elements
439 macro_rules! impl_writeable_tlv_based {
440 ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
441 impl $crate::util::ser::Writeable for $st {
442 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
443 write_tlv_fields!(writer, {
444 $(($type, self.$field, $fieldty)),*
450 fn serialized_length(&self) -> usize {
451 use $crate::util::ser::BigSize;
454 let mut len = $crate::util::ser::LengthCalculatingWriter(0);
456 get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
460 let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
461 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
466 impl $crate::util::ser::Readable for $st {
467 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
469 init_tlv_field_var!($field, $fieldty);
471 read_tlv_fields!(reader, {
472 $(($type, $field, $fieldty)),*
476 $field: init_tlv_based_struct_field!($field, $fieldty)
484 /// Defines a struct for a TLV stream and a similar struct using references for non-primitive types,
485 /// implementing [`Readable`] for the former and [`Writeable`] for the latter. Useful as an
486 /// intermediary format when reading or writing a type encoded as a TLV stream. Note that each field
487 /// representing a TLV record has its type wrapped with an [`Option`]. A tuple consisting of a type
488 /// and a serialization wrapper may be given in place of a type when custom serialization is
491 /// [`Readable`]: crate::util::ser::Readable
492 /// [`Writeable`]: crate::util::ser::Writeable
493 macro_rules! tlv_stream {
494 ($name:ident, $nameref:ident, $range:expr, {
495 $(($type:expr, $field:ident : $fieldty:tt)),* $(,)*
498 pub(crate) struct $name {
500 $field: Option<tlv_record_type!($fieldty)>,
504 pub(crate) struct $nameref<'a> {
506 pub(crate) $field: Option<tlv_record_ref_type!($fieldty)>,
510 impl<'a> $crate::util::ser::Writeable for $nameref<'a> {
511 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
512 encode_tlv_stream!(writer, {
513 $(($type, self.$field, (option, encoding: $fieldty))),*
519 impl $crate::util::ser::SeekReadable for $name {
520 fn read<R: $crate::io::Read + $crate::io::Seek>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
522 init_tlv_field_var!($field, option);
524 let rewind = |cursor: &mut R, offset: usize| {
525 cursor.seek($crate::io::SeekFrom::Current(-(offset as i64))).expect("");
527 decode_tlv_stream_range!(reader, $range, rewind, {
528 $(($type, $field, (option, encoding: $fieldty))),*
541 macro_rules! tlv_record_type {
542 (($type:ty, $wrapper:ident)) => { $type };
543 ($type:ty) => { $type };
546 macro_rules! tlv_record_ref_type {
549 ((u16, $wrapper: ident)) => { u16 };
550 ((u32, $wrapper: ident)) => { u32 };
551 ((u64, $wrapper: ident)) => { u64 };
552 (($type:ty, $wrapper:ident)) => { &'a $type };
553 ($type:ty) => { &'a $type };
556 macro_rules! _impl_writeable_tlv_based_enum_common {
557 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
558 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
560 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
561 impl $crate::util::ser::Writeable for $st {
562 fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
564 $($st::$variant_name { $(ref $field),* } => {
565 let id: u8 = $variant_id;
567 write_tlv_fields!(writer, {
568 $(($type, *$field, $fieldty)),*
571 $($st::$tuple_variant_name (ref field) => {
572 let id: u8 = $tuple_variant_id;
574 field.write(writer)?;
583 /// Implement MaybeReadable and Writeable for an enum, with struct variants stored as TLVs and
584 /// tuple variants stored directly.
586 /// This is largely identical to `impl_writeable_tlv_based_enum`, except that odd variants will
587 /// return `Ok(None)` instead of `Err(UnknownRequiredFeature)`. It should generally be preferred
588 /// when `MaybeReadable` is practical instead of just `Readable` as it provides an upgrade path for
589 /// new variants to be added which are simply ignored by existing clients.
590 macro_rules! impl_writeable_tlv_based_enum_upgradable {
591 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
592 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
595 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*)*) => {
596 _impl_writeable_tlv_based_enum_common!($st,
597 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
598 $($(($tuple_variant_id, $tuple_variant_name)),*)*);
600 impl $crate::util::ser::MaybeReadable for $st {
601 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
602 let id: u8 = $crate::util::ser::Readable::read(reader)?;
605 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
606 // in the same function body. Instead, we define a closure and call it.
609 init_tlv_field_var!($field, $fieldty);
611 read_tlv_fields!(reader, {
612 $(($type, $field, $fieldty)),*
614 Ok(Some($st::$variant_name {
616 $field: init_tlv_based_struct_field!($field, $fieldty)
622 $($($tuple_variant_id => {
623 Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
625 _ if id % 2 == 1 => Ok(None),
626 _ => Err(DecodeError::UnknownRequiredFeature),
634 /// Implement Readable and Writeable for an enum, with struct variants stored as TLVs and tuple
635 /// variants stored directly.
636 /// The format is, for example
637 /// impl_writeable_tlv_based_enum!(EnumName,
638 /// (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
639 /// (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, vec_type)};
640 /// (2, TupleVariantA), (3, TupleVariantB),
642 /// The type is written as a single byte, followed by any variant data.
643 /// Attempts to read an unknown type byte result in DecodeError::UnknownRequiredFeature.
644 macro_rules! impl_writeable_tlv_based_enum {
645 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
646 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
648 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
649 _impl_writeable_tlv_based_enum_common!($st,
650 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
651 $(($tuple_variant_id, $tuple_variant_name)),*);
653 impl $crate::util::ser::Readable for $st {
654 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
655 let id: u8 = $crate::util::ser::Readable::read(reader)?;
658 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
659 // in the same function body. Instead, we define a closure and call it.
662 init_tlv_field_var!($field, $fieldty);
664 read_tlv_fields!(reader, {
665 $(($type, $field, $fieldty)),*
667 Ok($st::$variant_name {
669 $field: init_tlv_based_struct_field!($field, $fieldty)
675 $($tuple_variant_id => {
676 Ok($st::$tuple_variant_name(Readable::read(reader)?))
679 Err(DecodeError::UnknownRequiredFeature)
689 use crate::io::{self, Cursor};
690 use crate::prelude::*;
691 use crate::ln::msgs::DecodeError;
692 use crate::util::ser::{Writeable, HighZeroBytesDroppedBigSize, VecWriter};
693 use bitcoin::secp256k1::PublicKey;
695 // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
696 // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
697 // work with so they're baked into the decoder. Thus, we have a few additional tests below
698 fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
699 let mut s = Cursor::new(s);
702 let mut c: Option<u32> = None;
703 decode_tlv_stream!(&mut s, {(2, a, required), (3, b, required), (4, c, option)});
708 fn tlv_v_short_read() {
709 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
710 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
711 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
717 fn tlv_types_out_of_order() {
718 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
719 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
722 // ...even if its some field we don't understand
723 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
724 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
730 fn tlv_req_type_missing_or_extra() {
731 // It's also bad if they included even fields we don't understand
732 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
733 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
736 // ... or if they're missing fields we need
737 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
738 concat!("0100", "0208deadbeef1badbeef")
741 // ... even if that field is even
742 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
743 concat!("0304deadbeef", "0500")
749 fn tlv_simple_good_cases() {
750 assert_eq!(tlv_reader(&::hex::decode(
751 concat!("0208deadbeef1badbeef", "03041bad1dea")
752 ).unwrap()[..]).unwrap(),
753 (0xdeadbeef1badbeef, 0x1bad1dea, None));
754 assert_eq!(tlv_reader(&::hex::decode(
755 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
756 ).unwrap()[..]).unwrap(),
757 (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
760 // BOLT TLV test cases
761 fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedBigSize<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
762 let mut s = Cursor::new(s);
763 let mut tlv1: Option<HighZeroBytesDroppedBigSize<u64>> = None;
764 let mut tlv2: Option<u64> = None;
765 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
766 let mut tlv4: Option<u16> = None;
767 decode_tlv_stream!(&mut s, {(1, tlv1, option), (2, tlv2, option), (3, tlv3, option), (254, tlv4, option)});
768 Ok((tlv1, tlv2, tlv3, tlv4))
772 fn bolt_tlv_bogus_stream() {
773 macro_rules! do_test {
774 ($stream: expr, $reason: ident) => {
775 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
780 // TLVs from the BOLT test cases which should not decode as either n1 or n2
781 do_test!(concat!("fd01"), ShortRead);
782 do_test!(concat!("fd0001", "00"), InvalidValue);
783 do_test!(concat!("fd0101"), ShortRead);
784 do_test!(concat!("0f", "fd"), ShortRead);
785 do_test!(concat!("0f", "fd26"), ShortRead);
786 do_test!(concat!("0f", "fd2602"), ShortRead);
787 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
788 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
790 do_test!(concat!("12", "00"), UnknownRequiredFeature);
791 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
792 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
793 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
797 fn bolt_tlv_bogus_n1_stream() {
798 macro_rules! do_test {
799 ($stream: expr, $reason: ident) => {
800 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
805 // TLVs from the BOLT test cases which should not decode as n1
806 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
807 do_test!(concat!("01", "01", "00"), InvalidValue);
808 do_test!(concat!("01", "02", "0001"), InvalidValue);
809 do_test!(concat!("01", "03", "000100"), InvalidValue);
810 do_test!(concat!("01", "04", "00010000"), InvalidValue);
811 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
812 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
813 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
814 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
815 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
816 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
817 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
818 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
819 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
820 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
821 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
822 do_test!(concat!("fd00fe", "00"), ShortRead);
823 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
824 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
825 do_test!(concat!("00", "00"), UnknownRequiredFeature);
827 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
828 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
829 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
830 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
832 // The last BOLT test modified to not require creating a new decoder for one trivial test.
833 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
837 fn bolt_tlv_valid_n1_stream() {
838 macro_rules! do_test {
839 ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
840 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
841 assert_eq!(tlv1.map(|v| v.0), $tlv1);
842 assert_eq!(tlv2, $tlv2);
843 assert_eq!(tlv3, $tlv3);
844 assert_eq!(tlv4, $tlv4);
849 do_test!(concat!(""), None, None, None, None);
850 do_test!(concat!("21", "00"), None, None, None, None);
851 do_test!(concat!("fd0201", "00"), None, None, None, None);
852 do_test!(concat!("fd00fd", "00"), None, None, None, None);
853 do_test!(concat!("fd00ff", "00"), None, None, None, None);
854 do_test!(concat!("fe02000001", "00"), None, None, None, None);
855 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
857 do_test!(concat!("01", "00"), Some(0), None, None, None);
858 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
859 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
860 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
861 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
862 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
863 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
864 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
865 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
866 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
867 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
869 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
871 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
874 fn do_simple_test_tlv_write() -> Result<(), io::Error> {
875 let mut stream = VecWriter(Vec::new());
878 encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
879 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
882 encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
883 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
886 encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
887 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
890 encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
891 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
894 encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
895 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
898 encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
899 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
905 fn simple_test_tlv_write() {
906 do_simple_test_tlv_write().unwrap();