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, ::util::ser::VecWriteWrapper(&$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)?;
31 macro_rules! encode_tlv_stream {
32 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
33 #[allow(unused_imports)]
35 ln::msgs::DecodeError,
41 encode_tlv!($stream, $type, $field, $fieldty);
44 #[allow(unused_mut, unused_variables, unused_assignments)]
45 #[cfg(debug_assertions)]
47 let mut last_seen: Option<u64> = None;
49 if let Some(t) = last_seen {
50 debug_assert!(t <= $type);
52 last_seen = Some($type);
58 macro_rules! get_varint_length_prefixed_tlv_length {
59 ($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
60 get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
62 ($len: expr, $type: expr, $field: expr, required) => {
63 BigSize($type).write(&mut $len).expect("No in-memory data may fail to serialize");
64 let field_len = $field.serialized_length();
65 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
68 ($len: expr, $type: expr, $field: expr, vec_type) => {
69 get_varint_length_prefixed_tlv_length!($len, $type, ::util::ser::VecWriteWrapper(&$field), required);
71 ($len: expr, $optional_type: expr, $optional_field: expr, option) => {
72 if let Some(ref field) = $optional_field {
73 BigSize($optional_type).write(&mut $len).expect("No in-memory data may fail to serialize");
74 let field_len = field.serialized_length();
75 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
81 macro_rules! encode_varint_length_prefixed_tlv {
82 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
83 use util::ser::BigSize;
86 let mut len = ::util::ser::LengthCalculatingWriter(0);
88 get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
92 BigSize(len as u64).write($stream)?;
93 encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* });
97 macro_rules! check_tlv_order {
98 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
99 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
100 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
105 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
106 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
107 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
109 return Err(DecodeError::InvalidValue);
112 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
115 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, vec_type) => {{
118 ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, ignorable) => {{
123 macro_rules! check_missing_tlv {
124 ($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
125 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
126 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
127 if missing_req_type {
131 ($last_seen_type: expr, $type: expr, $field: ident, required) => {{
132 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
133 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
134 if missing_req_type {
135 return Err(DecodeError::InvalidValue);
138 ($last_seen_type: expr, $type: expr, $field: ident, vec_type) => {{
141 ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
144 ($last_seen_type: expr, $type: expr, $field: ident, ignorable) => {{
149 macro_rules! decode_tlv {
150 ($reader: expr, $field: ident, (default_value, $default: expr)) => {{
151 decode_tlv!($reader, $field, required)
153 ($reader: expr, $field: ident, required) => {{
154 $field = ser::Readable::read(&mut $reader)?;
156 ($reader: expr, $field: ident, vec_type) => {{
157 let f: ::util::ser::VecReadWrapper<_> = ser::Readable::read(&mut $reader)?;
160 ($reader: expr, $field: ident, option) => {{
161 $field = Some(ser::Readable::read(&mut $reader)?);
163 ($reader: expr, $field: ident, ignorable) => {{
164 $field = ser::MaybeReadable::read(&mut $reader)?;
168 macro_rules! decode_tlv_stream {
169 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
170 use ln::msgs::DecodeError;
171 let mut last_seen_type: Option<u64> = None;
172 let mut stream_ref = $stream;
176 // First decode the type of this TLV:
177 let typ: ser::BigSize = {
178 // We track whether any bytes were read during the consensus_decode call to
179 // determine whether we should break or return ShortRead if we get an
180 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
181 // pass the TLV test vectors exactly, which requre this distinction.
182 let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
183 match ser::Readable::read(&mut tracking_reader) {
184 Err(DecodeError::ShortRead) => {
185 if !tracking_reader.have_read {
188 return Err(DecodeError::ShortRead);
191 Err(e) => return Err(e),
196 // Types must be unique and monotonically increasing:
197 match last_seen_type {
198 Some(t) if typ.0 <= t => {
199 return Err(DecodeError::InvalidValue);
203 // As we read types, make sure we hit every required type:
205 check_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
207 last_seen_type = Some(typ.0);
209 // Finally, read the length and value itself:
210 let length: ser::BigSize = ser::Readable::read(&mut stream_ref)?;
211 let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
214 decode_tlv!(s, $field, $fieldty);
215 if s.bytes_remain() {
216 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
217 return Err(DecodeError::InvalidValue);
221 return Err(DecodeError::UnknownRequiredFeature);
227 // Make sure we got to each required type after we've read every TLV:
229 check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
234 macro_rules! impl_writeable_msg {
235 ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
236 impl ::util::ser::Writeable for $st {
237 fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
238 $( self.$field.write(w)?; )*
239 encode_tlv_stream!(w, {$(($type, self.$tlvfield, $fieldty)),*});
243 impl ::util::ser::Readable for $st {
244 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
245 $(let $field = ::util::ser::Readable::read(r)?;)*
246 $(init_tlv_field_var!($tlvfield, $fieldty);)*
247 decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
257 macro_rules! impl_writeable {
258 ($st:ident, {$($field:ident),*}) => {
259 impl ::util::ser::Writeable for $st {
260 fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
261 $( self.$field.write(w)?; )*
266 fn serialized_length(&self) -> usize {
267 let mut len_calc = 0;
268 $( len_calc += self.$field.serialized_length(); )*
273 impl ::util::ser::Readable for $st {
274 fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
276 $($field: ::util::ser::Readable::read(r)?),*
283 /// Write out two bytes to indicate the version of an object.
284 /// $this_version represents a unique version of a type. Incremented whenever the type's
285 /// serialization format has changed or has a new interpretation. Used by a type's
286 /// reader to determine how to interpret fields or if it can understand a serialized
288 /// $min_version_that_can_read_this is the minimum reader version which can understand this
289 /// serialized object. Previous versions will simply err with a
290 /// DecodeError::UnknownVersion.
292 /// Updates to either $this_version or $min_version_that_can_read_this should be included in
295 /// Both version fields can be specific to this type of object.
296 macro_rules! write_ver_prefix {
297 ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
298 $stream.write_all(&[$this_version; 1])?;
299 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
303 /// Writes out a suffix to an object which contains potentially backwards-compatible, optional
304 /// fields which old nodes can happily ignore.
306 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
307 /// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
309 /// This is the preferred method of adding new fields that old nodes can ignore and still function
311 macro_rules! write_tlv_fields {
312 ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
313 encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
317 /// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
318 /// serialization logic for this object. This is compared against the
319 /// $min_version_that_can_read_this added by write_ver_prefix!().
320 macro_rules! read_ver_prefix {
321 ($stream: expr, $this_version: expr) => { {
322 let ver: u8 = Readable::read($stream)?;
323 let min_ver: u8 = Readable::read($stream)?;
324 if min_ver > $this_version {
325 return Err(DecodeError::UnknownVersion);
331 /// Reads a suffix added by write_tlv_fields.
332 macro_rules! read_tlv_fields {
333 ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
334 let tlv_len: ::util::ser::BigSize = ::util::ser::Readable::read($stream)?;
335 let mut rd = ::util::ser::FixedLengthReader::new($stream, tlv_len.0);
336 decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
337 rd.eat_remaining().map_err(|_| ::ln::msgs::DecodeError::ShortRead)?;
341 macro_rules! init_tlv_based_struct_field {
342 ($field: ident, (default_value, $default: expr)) => {
345 ($field: ident, option) => {
348 ($field: ident, required) => {
351 ($field: ident, vec_type) => {
356 macro_rules! init_tlv_field_var {
357 ($field: ident, (default_value, $default: expr)) => {
358 let mut $field = $default;
360 ($field: ident, required) => {
361 let mut $field = ::util::ser::OptionDeserWrapper(None);
363 ($field: ident, vec_type) => {
364 let mut $field = Some(Vec::new());
366 ($field: ident, option) => {
367 let mut $field = None;
371 /// Implements Readable/Writeable for a struct storing it as a set of TLVs
372 /// If $fieldty is `required`, then $field is a required field that is not an Option nor a Vec.
373 /// If $fieldty is `option`, then $field is optional field.
374 /// if $fieldty is `vec_type`, then $field is a Vec, which needs to have its individual elements
376 macro_rules! impl_writeable_tlv_based {
377 ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
378 impl ::util::ser::Writeable for $st {
379 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
380 write_tlv_fields!(writer, {
381 $(($type, self.$field, $fieldty)),*
387 fn serialized_length(&self) -> usize {
388 use util::ser::BigSize;
391 let mut len = ::util::ser::LengthCalculatingWriter(0);
393 get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
397 let mut len_calc = ::util::ser::LengthCalculatingWriter(0);
398 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
403 impl ::util::ser::Readable for $st {
404 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
406 init_tlv_field_var!($field, $fieldty);
408 read_tlv_fields!(reader, {
409 $(($type, $field, $fieldty)),*
413 $field: init_tlv_based_struct_field!($field, $fieldty)
421 macro_rules! _impl_writeable_tlv_based_enum_common {
422 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
423 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
425 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
426 impl ::util::ser::Writeable for $st {
427 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
429 $($st::$variant_name { $(ref $field),* } => {
430 let id: u8 = $variant_id;
432 write_tlv_fields!(writer, {
433 $(($type, $field, $fieldty)),*
436 $($st::$tuple_variant_name (ref field) => {
437 let id: u8 = $tuple_variant_id;
439 field.write(writer)?;
448 /// Implement MaybeReadable and Writeable for an enum, with struct variants stored as TLVs and
449 /// tuple variants stored directly.
451 /// This is largely identical to `impl_writeable_tlv_based_enum`, except that odd variants will
452 /// return `Ok(None)` instead of `Err(UnknownRequiredFeature)`. It should generally be preferred
453 /// when `MaybeReadable` is practical instead of just `Readable` as it provides an upgrade path for
454 /// new variants to be added which are simply ignored by existing clients.
455 macro_rules! impl_writeable_tlv_based_enum_upgradable {
456 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
457 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
460 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*)*) => {
461 _impl_writeable_tlv_based_enum_common!($st,
462 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
463 $($(($tuple_variant_id, $tuple_variant_name)),*)*);
465 impl ::util::ser::MaybeReadable for $st {
466 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, ::ln::msgs::DecodeError> {
467 let id: u8 = ::util::ser::Readable::read(reader)?;
470 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
471 // in the same function body. Instead, we define a closure and call it.
474 init_tlv_field_var!($field, $fieldty);
476 read_tlv_fields!(reader, {
477 $(($type, $field, $fieldty)),*
479 Ok(Some($st::$variant_name {
481 $field: init_tlv_based_struct_field!($field, $fieldty)
487 $($($tuple_variant_id => {
488 Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
490 _ if id % 2 == 1 => Ok(None),
491 _ => Err(DecodeError::UnknownRequiredFeature),
499 /// Implement Readable and Writeable for an enum, with struct variants stored as TLVs and tuple
500 /// variants stored directly.
501 /// The format is, for example
502 /// impl_writeable_tlv_based_enum!(EnumName,
503 /// (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
504 /// (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, vec_type)};
505 /// (2, TupleVariantA), (3, TupleVariantB),
507 /// The type is written as a single byte, followed by any variant data.
508 /// Attempts to read an unknown type byte result in DecodeError::UnknownRequiredFeature.
509 macro_rules! impl_writeable_tlv_based_enum {
510 ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
511 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
513 $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
514 _impl_writeable_tlv_based_enum_common!($st,
515 $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
516 $(($tuple_variant_id, $tuple_variant_name)),*);
518 impl ::util::ser::Readable for $st {
519 fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
520 let id: u8 = ::util::ser::Readable::read(reader)?;
523 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
524 // in the same function body. Instead, we define a closure and call it.
527 init_tlv_field_var!($field, $fieldty);
529 read_tlv_fields!(reader, {
530 $(($type, $field, $fieldty)),*
532 Ok($st::$variant_name {
534 $field: init_tlv_based_struct_field!($field, $fieldty)
540 $($tuple_variant_id => {
541 Ok($st::$tuple_variant_name(Readable::read(reader)?))
544 Err(DecodeError::UnknownRequiredFeature)
554 use io::{self, Cursor};
556 use ln::msgs::DecodeError;
557 use util::ser::{Writeable, HighZeroBytesDroppedVarInt, VecWriter};
558 use bitcoin::secp256k1::PublicKey;
560 // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
561 // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
562 // work with so they're baked into the decoder. Thus, we have a few additional tests below
563 fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
564 let mut s = Cursor::new(s);
567 let mut c: Option<u32> = None;
568 decode_tlv_stream!(&mut s, {(2, a, required), (3, b, required), (4, c, option)});
573 fn tlv_v_short_read() {
574 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
575 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
576 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
582 fn tlv_types_out_of_order() {
583 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
584 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
587 // ...even if its some field we don't understand
588 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
589 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
595 fn tlv_req_type_missing_or_extra() {
596 // It's also bad if they included even fields we don't understand
597 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
598 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
601 // ... or if they're missing fields we need
602 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
603 concat!("0100", "0208deadbeef1badbeef")
606 // ... even if that field is even
607 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
608 concat!("0304deadbeef", "0500")
614 fn tlv_simple_good_cases() {
615 assert_eq!(tlv_reader(&::hex::decode(
616 concat!("0208deadbeef1badbeef", "03041bad1dea")
617 ).unwrap()[..]).unwrap(),
618 (0xdeadbeef1badbeef, 0x1bad1dea, None));
619 assert_eq!(tlv_reader(&::hex::decode(
620 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
621 ).unwrap()[..]).unwrap(),
622 (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
625 // BOLT TLV test cases
626 fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedVarInt<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
627 let mut s = Cursor::new(s);
628 let mut tlv1: Option<HighZeroBytesDroppedVarInt<u64>> = None;
629 let mut tlv2: Option<u64> = None;
630 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
631 let mut tlv4: Option<u16> = None;
632 decode_tlv_stream!(&mut s, {(1, tlv1, option), (2, tlv2, option), (3, tlv3, option), (254, tlv4, option)});
633 Ok((tlv1, tlv2, tlv3, tlv4))
637 fn bolt_tlv_bogus_stream() {
638 macro_rules! do_test {
639 ($stream: expr, $reason: ident) => {
640 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
645 // TLVs from the BOLT test cases which should not decode as either n1 or n2
646 do_test!(concat!("fd01"), ShortRead);
647 do_test!(concat!("fd0001", "00"), InvalidValue);
648 do_test!(concat!("fd0101"), ShortRead);
649 do_test!(concat!("0f", "fd"), ShortRead);
650 do_test!(concat!("0f", "fd26"), ShortRead);
651 do_test!(concat!("0f", "fd2602"), ShortRead);
652 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
653 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
655 do_test!(concat!("12", "00"), UnknownRequiredFeature);
656 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
657 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
658 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
662 fn bolt_tlv_bogus_n1_stream() {
663 macro_rules! do_test {
664 ($stream: expr, $reason: ident) => {
665 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
670 // TLVs from the BOLT test cases which should not decode as n1
671 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
672 do_test!(concat!("01", "01", "00"), InvalidValue);
673 do_test!(concat!("01", "02", "0001"), InvalidValue);
674 do_test!(concat!("01", "03", "000100"), InvalidValue);
675 do_test!(concat!("01", "04", "00010000"), InvalidValue);
676 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
677 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
678 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
679 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
680 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
681 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
682 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
683 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
684 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
685 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
686 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
687 do_test!(concat!("fd00fe", "00"), ShortRead);
688 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
689 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
690 do_test!(concat!("00", "00"), UnknownRequiredFeature);
692 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
693 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
694 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
695 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
697 // The last BOLT test modified to not require creating a new decoder for one trivial test.
698 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
702 fn bolt_tlv_valid_n1_stream() {
703 macro_rules! do_test {
704 ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
705 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
706 assert_eq!(tlv1.map(|v| v.0), $tlv1);
707 assert_eq!(tlv2, $tlv2);
708 assert_eq!(tlv3, $tlv3);
709 assert_eq!(tlv4, $tlv4);
714 do_test!(concat!(""), None, None, None, None);
715 do_test!(concat!("21", "00"), None, None, None, None);
716 do_test!(concat!("fd0201", "00"), None, None, None, None);
717 do_test!(concat!("fd00fd", "00"), None, None, None, None);
718 do_test!(concat!("fd00ff", "00"), None, None, None, None);
719 do_test!(concat!("fe02000001", "00"), None, None, None, None);
720 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
722 do_test!(concat!("01", "00"), Some(0), None, None, None);
723 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
724 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
725 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
726 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
727 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
728 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
729 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
730 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
731 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
732 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
734 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
736 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
739 fn do_simple_test_tlv_write() -> Result<(), io::Error> {
740 let mut stream = VecWriter(Vec::new());
743 encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
744 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
747 encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
748 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
751 encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
752 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
755 encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
756 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
759 encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedVarInt(0u64), required)});
760 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
763 encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedVarInt(0u64), required)});
764 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
770 fn simple_test_tlv_write() {
771 do_simple_test_tlv_write().unwrap();