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 //! A very simple serialization framework which is used to serialize/deserialize messages as well
11 //! as [`ChannelManager`]s and [`ChannelMonitor`]s.
13 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
14 //! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
16 use crate::prelude::*;
17 use crate::io::{self, Read, Seek, Write};
18 use crate::io_extras::{copy, sink};
20 use crate::sync::{Mutex, RwLock};
22 use core::convert::TryFrom;
25 use alloc::collections::BTreeMap;
27 use bitcoin::secp256k1::{PublicKey, SecretKey};
28 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE, SCHNORR_SIGNATURE_SIZE};
29 use bitcoin::secp256k1::ecdsa;
30 use bitcoin::secp256k1::schnorr;
31 use bitcoin::blockdata::constants::ChainHash;
32 use bitcoin::blockdata::script::{self, Script};
33 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
34 use bitcoin::{consensus, Witness};
35 use bitcoin::consensus::Encodable;
36 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
37 use bitcoin::hash_types::{Txid, BlockHash};
38 use core::marker::Sized;
39 use core::time::Duration;
40 use crate::chain::ClaimId;
41 use crate::ln::msgs::DecodeError;
43 use crate::ln::msgs::PartialSignatureWithNonce;
44 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
46 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
47 use crate::util::string::UntrustedString;
49 /// serialization buffer size
50 pub const MAX_BUF_SIZE: usize = 64 * 1024;
52 /// A simplified version of [`std::io::Write`] that exists largely for backwards compatibility.
53 /// An impl is provided for any type that also impls [`std::io::Write`].
55 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
57 /// Writes the given buf out. See std::io::Write::write_all for more
58 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
61 impl<W: Write> Writer for W {
63 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
64 <Self as io::Write>::write_all(self, buf)
68 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
69 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
71 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
75 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
76 self.0.write_all(buf)?;
80 fn flush(&mut self) -> Result<(), io::Error> {
85 pub(crate) struct VecWriter(pub Vec<u8>);
86 impl Writer for VecWriter {
88 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
89 self.0.extend_from_slice(buf);
94 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
95 /// of some data when serialized but don't yet need the full data.
97 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
98 pub struct LengthCalculatingWriter(pub usize);
99 impl Writer for LengthCalculatingWriter {
101 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
107 /// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
108 /// forward to ensure we always consume exactly the fixed length specified.
110 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
111 pub struct FixedLengthReader<R: Read> {
116 impl<R: Read> FixedLengthReader<R> {
117 /// Returns a new [`FixedLengthReader`].
118 pub fn new(read: R, total_bytes: u64) -> Self {
119 Self { read, bytes_read: 0, total_bytes }
122 /// Returns whether some bytes are remaining or not.
124 pub fn bytes_remain(&mut self) -> bool {
125 self.bytes_read != self.total_bytes
128 /// Consumes the remaining bytes.
130 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
131 copy(self, &mut sink()).unwrap();
132 if self.bytes_read != self.total_bytes {
133 Err(DecodeError::ShortRead)
139 impl<R: Read> Read for FixedLengthReader<R> {
141 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
142 if self.total_bytes == self.bytes_read {
145 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
146 match self.read.read(&mut dest[0..(read_len as usize)]) {
148 self.bytes_read += v as u64;
157 impl<R: Read> LengthRead for FixedLengthReader<R> {
159 fn total_bytes(&self) -> u64 {
164 /// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
165 /// between "EOF reached before we started" and "EOF reached mid-read".
167 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
168 pub struct ReadTrackingReader<R: Read> {
170 /// Returns whether we have read from this reader or not yet.
173 impl<R: Read> ReadTrackingReader<R> {
174 /// Returns a new [`ReadTrackingReader`].
175 pub fn new(read: R) -> Self {
176 Self { read, have_read: false }
179 impl<R: Read> Read for ReadTrackingReader<R> {
181 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
182 match self.read.read(dest) {
185 self.have_read = true;
193 /// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
195 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
196 pub trait Writeable {
197 /// Writes `self` out to the given [`Writer`].
198 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
200 /// Writes `self` out to a `Vec<u8>`.
201 fn encode(&self) -> Vec<u8> {
202 let len = self.serialized_length();
203 let mut msg = VecWriter(Vec::with_capacity(len));
204 self.write(&mut msg).unwrap();
205 // Note that objects with interior mutability may change size between when we called
206 // serialized_length and when we called write. That's okay, but shouldn't happen during
207 // testing as most of our tests are not threaded.
209 debug_assert_eq!(len, msg.0.len());
213 /// Writes `self` out to a `Vec<u8>`.
215 fn encode_with_len(&self) -> Vec<u8> {
216 let mut msg = VecWriter(Vec::new());
217 0u16.write(&mut msg).unwrap();
218 self.write(&mut msg).unwrap();
219 let len = msg.0.len();
220 debug_assert_eq!(len - 2, self.serialized_length());
221 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
225 /// Gets the length of this object after it has been serialized. This can be overridden to
226 /// optimize cases where we prepend an object with its length.
227 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
229 fn serialized_length(&self) -> usize {
230 let mut len_calc = LengthCalculatingWriter(0);
231 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
236 impl<'a, T: Writeable> Writeable for &'a T {
237 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
240 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
242 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
246 /// Reads a `Self` in from the given [`Read`].
247 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
250 /// A trait that various LDK types implement allowing them to be read in from a
251 /// [`Read`]` + `[`Seek`].
252 pub(crate) trait SeekReadable where Self: Sized {
253 /// Reads a `Self` in from the given [`Read`].
254 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
257 /// A trait that various higher-level LDK types implement allowing them to be read in
258 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
260 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
261 pub trait ReadableArgs<P>
264 /// Reads a `Self` in from the given [`Read`].
265 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
268 /// A [`std::io::Read`] that also provides the total bytes available to be read.
269 pub(crate) trait LengthRead: Read {
270 /// The total number of bytes available to be read.
271 fn total_bytes(&self) -> u64;
274 /// A trait that various higher-level LDK types implement allowing them to be read in
275 /// from a Read given some additional set of arguments which is required to deserialize, requiring
276 /// the implementer to provide the total length of the read.
277 pub(crate) trait LengthReadableArgs<P> where Self: Sized
279 /// Reads a `Self` in from the given [`LengthRead`].
280 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
283 /// A trait that various higher-level LDK types implement allowing them to be read in
284 /// from a [`Read`], requiring the implementer to provide the total length of the read.
285 pub(crate) trait LengthReadable where Self: Sized
287 /// Reads a `Self` in from the given [`LengthRead`].
288 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
291 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
293 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
294 pub trait MaybeReadable
297 /// Reads a `Self` in from the given [`Read`].
298 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
301 impl<T: Readable> MaybeReadable for T {
303 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
304 Ok(Some(Readable::read(reader)?))
308 /// Wrapper to read a required (non-optional) TLV record.
310 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
311 pub struct RequiredWrapper<T>(pub Option<T>);
312 impl<T: Readable> Readable for RequiredWrapper<T> {
314 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
315 Ok(Self(Some(Readable::read(reader)?)))
318 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
320 fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
321 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
324 /// When handling `default_values`, we want to map the default-value T directly
325 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
326 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
327 impl<T> From<T> for RequiredWrapper<T> {
328 fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
331 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
332 /// backwards compat.
334 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
335 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
336 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
338 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
339 let tlv = MaybeReadable::read(reader)?;
340 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
345 pub(crate) struct U48(pub u64);
346 impl Writeable for U48 {
348 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
349 writer.write_all(&be48_to_array(self.0))
352 impl Readable for U48 {
354 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
355 let mut buf = [0; 6];
356 reader.read_exact(&mut buf)?;
357 Ok(U48(slice_to_be48(&buf)))
361 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
362 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
364 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
365 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
366 /// you're looking for an example of a variable-length integer to use for your own project, move
367 /// along, this is a rather poor design.
368 #[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
369 pub struct BigSize(pub u64);
370 impl Writeable for BigSize {
372 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
375 (self.0 as u8).write(writer)
378 0xFDu8.write(writer)?;
379 (self.0 as u16).write(writer)
381 0x10000...0xFFFFFFFF => {
382 0xFEu8.write(writer)?;
383 (self.0 as u32).write(writer)
386 0xFFu8.write(writer)?;
387 (self.0 as u64).write(writer)
392 impl Readable for BigSize {
394 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
395 let n: u8 = Readable::read(reader)?;
398 let x: u64 = Readable::read(reader)?;
400 Err(DecodeError::InvalidValue)
406 let x: u32 = Readable::read(reader)?;
408 Err(DecodeError::InvalidValue)
410 Ok(BigSize(x as u64))
414 let x: u16 = Readable::read(reader)?;
416 Err(DecodeError::InvalidValue)
418 Ok(BigSize(x as u64))
421 n => Ok(BigSize(n as u64))
426 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
427 /// primarily targets that, we must as well. However, because we may serialize objects that have
428 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
429 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
430 /// "read eight more bytes".
432 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
433 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
434 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
435 struct CollectionLength(pub u64);
436 impl Writeable for CollectionLength {
438 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
440 (self.0 as u16).write(writer)
442 0xffffu16.write(writer)?;
443 (self.0 - 0xffff).write(writer)
448 impl Readable for CollectionLength {
450 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
451 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
453 val = <u64 as Readable>::read(r)?
454 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
456 Ok(CollectionLength(val))
460 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
461 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
462 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
463 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
464 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
466 macro_rules! impl_writeable_primitive {
467 ($val_type:ty, $len: expr) => {
468 impl Writeable for $val_type {
470 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
471 writer.write_all(&self.to_be_bytes())
474 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
476 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
477 // Skip any full leading 0 bytes when writing (in BE):
478 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
481 impl Readable for $val_type {
483 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
484 let mut buf = [0; $len];
485 reader.read_exact(&mut buf)?;
486 Ok(<$val_type>::from_be_bytes(buf))
489 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
491 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
492 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
493 // the high bytes being dropped. To do so, we start reading into the middle of buf
494 // and then convert the appropriate number of bytes with extra high bytes out of
496 let mut buf = [0; $len*2];
497 let mut read_len = reader.read(&mut buf[$len..])?;
498 let mut total_read_len = read_len;
499 while read_len != 0 && total_read_len != $len {
500 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
501 total_read_len += read_len;
503 if total_read_len == 0 || buf[$len] != 0 {
504 let first_byte = $len - ($len - total_read_len);
505 let mut bytes = [0; $len];
506 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
507 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
509 // If the encoding had extra zero bytes, return a failure even though we know
510 // what they meant (as the TLV test vectors require this)
511 Err(DecodeError::InvalidValue)
515 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
516 fn from(val: $val_type) -> Self { Self(val) }
521 impl_writeable_primitive!(u128, 16);
522 impl_writeable_primitive!(u64, 8);
523 impl_writeable_primitive!(u32, 4);
524 impl_writeable_primitive!(u16, 2);
525 impl_writeable_primitive!(i64, 8);
526 impl_writeable_primitive!(i32, 4);
527 impl_writeable_primitive!(i16, 2);
528 impl_writeable_primitive!(i8, 1);
530 impl Writeable for u8 {
532 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
533 writer.write_all(&[*self])
536 impl Readable for u8 {
538 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
539 let mut buf = [0; 1];
540 reader.read_exact(&mut buf)?;
545 impl Writeable for bool {
547 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
548 writer.write_all(&[if *self {1} else {0}])
551 impl Readable for bool {
553 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
554 let mut buf = [0; 1];
555 reader.read_exact(&mut buf)?;
556 if buf[0] != 0 && buf[0] != 1 {
557 return Err(DecodeError::InvalidValue);
563 macro_rules! impl_array {
564 ($size:expr, $ty: ty) => (
565 impl Writeable for [$ty; $size] {
567 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
568 let mut out = [0; $size * core::mem::size_of::<$ty>()];
569 for (idx, v) in self.iter().enumerate() {
570 let startpos = idx * core::mem::size_of::<$ty>();
571 out[startpos..startpos + core::mem::size_of::<$ty>()].copy_from_slice(&v.to_be_bytes());
577 impl Readable for [$ty; $size] {
579 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
580 let mut buf = [0u8; $size * core::mem::size_of::<$ty>()];
581 r.read_exact(&mut buf)?;
582 let mut res = [0; $size];
583 for (idx, v) in res.iter_mut().enumerate() {
584 let startpos = idx * core::mem::size_of::<$ty>();
585 let mut arr = [0; core::mem::size_of::<$ty>()];
586 arr.copy_from_slice(&buf[startpos..startpos + core::mem::size_of::<$ty>()]);
587 *v = <$ty>::from_be_bytes(arr);
595 impl_array!(3, u8); // for rgb, ISO 4712 code
596 impl_array!(4, u8); // for IPv4
597 impl_array!(12, u8); // for OnionV2
598 impl_array!(16, u8); // for IPv6
599 impl_array!(32, u8); // for channel id & hmac
600 impl_array!(PUBLIC_KEY_SIZE, u8); // for PublicKey
601 impl_array!(64, u8); // for ecdsa::Signature and schnorr::Signature
602 impl_array!(66, u8); // for MuSig2 nonces
603 impl_array!(1300, u8); // for OnionPacket.hop_data
606 impl_array!(32, u16);
608 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
609 /// Used to prevent encoding the length twice.
611 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
612 pub struct WithoutLength<T>(pub T);
614 impl Writeable for WithoutLength<&String> {
616 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
617 w.write_all(self.0.as_bytes())
620 impl Readable for WithoutLength<String> {
622 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
623 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
624 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
627 impl<'a> From<&'a String> for WithoutLength<&'a String> {
628 fn from(s: &'a String) -> Self { Self(s) }
632 impl Writeable for WithoutLength<&UntrustedString> {
634 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
635 WithoutLength(&self.0.0).write(w)
638 impl Readable for WithoutLength<UntrustedString> {
640 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
641 let s: WithoutLength<String> = Readable::read(r)?;
642 Ok(Self(UntrustedString(s.0)))
646 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
648 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
649 for ref v in self.0.iter() {
656 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
658 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
659 let mut values = Vec::new();
661 let mut track_read = ReadTrackingReader::new(&mut reader);
662 match MaybeReadable::read(&mut track_read) {
663 Ok(Some(v)) => { values.push(v); },
665 // If we failed to read any bytes at all, we reached the end of our TLV
666 // stream and have simply exhausted all entries.
667 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
668 Err(e) => return Err(e),
674 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
675 fn from(v: &'a Vec<T>) -> Self { Self(v) }
678 impl Writeable for WithoutLength<&Script> {
680 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
681 writer.write_all(self.0.as_bytes())
685 impl Readable for WithoutLength<Script> {
687 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
688 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
689 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
694 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
696 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
698 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
699 for ref v in self.0.clone() {
707 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
708 fn eq(&self, other: &Self) -> bool {
709 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
713 macro_rules! impl_for_map {
714 ($ty: ident, $keybound: ident, $constr: expr) => {
715 impl<K, V> Writeable for $ty<K, V>
716 where K: Writeable + Eq + $keybound, V: Writeable
719 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
720 CollectionLength(self.len() as u64).write(w)?;
721 for (key, value) in self.iter() {
729 impl<K, V> Readable for $ty<K, V>
730 where K: Readable + Eq + $keybound, V: MaybeReadable
733 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
734 let len: CollectionLength = Readable::read(r)?;
735 let mut ret = $constr(len.0 as usize);
738 let v_opt = V::read(r)?;
739 if let Some(v) = v_opt {
740 if ret.insert(k, v).is_some() {
741 return Err(DecodeError::InvalidValue);
751 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
752 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
755 impl<T> Writeable for HashSet<T>
756 where T: Writeable + Eq + Hash
759 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
760 CollectionLength(self.len() as u64).write(w)?;
761 for item in self.iter() {
768 impl<T> Readable for HashSet<T>
769 where T: Readable + Eq + Hash
772 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
773 let len: CollectionLength = Readable::read(r)?;
774 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
776 if !ret.insert(T::read(r)?) {
777 return Err(DecodeError::InvalidValue)
785 macro_rules! impl_writeable_for_vec {
786 ($ty: ty $(, $name: ident)*) => {
787 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
789 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
790 CollectionLength(self.len() as u64).write(w)?;
791 for elem in self.iter() {
799 macro_rules! impl_readable_for_vec {
800 ($ty: ty $(, $name: ident)*) => {
801 impl<$($name : Readable),*> Readable for Vec<$ty> {
803 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
804 let len: CollectionLength = Readable::read(r)?;
805 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
807 if let Some(val) = MaybeReadable::read(r)? {
816 macro_rules! impl_for_vec {
817 ($ty: ty $(, $name: ident)*) => {
818 impl_writeable_for_vec!($ty $(, $name)*);
819 impl_readable_for_vec!($ty $(, $name)*);
823 impl Writeable for Vec<u8> {
825 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
826 CollectionLength(self.len() as u64).write(w)?;
831 impl Readable for Vec<u8> {
833 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
834 let mut len: CollectionLength = Readable::read(r)?;
835 let mut ret = Vec::new();
837 let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
838 let readstart = ret.len();
839 ret.resize(readstart + readamt, 0);
840 r.read_exact(&mut ret[readstart..])?;
841 len.0 -= readamt as u64;
847 impl_for_vec!(ecdsa::Signature);
848 impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
849 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
850 impl_for_vec!((A, B), A, B);
851 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
852 impl_readable_for_vec!(crate::routing::router::BlindedTail);
854 impl Writeable for Vec<Witness> {
856 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
857 (self.len() as u16).write(w)?;
858 for witness in self {
859 (witness.serialized_len() as u16).write(w)?;
866 impl Readable for Vec<Witness> {
868 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
869 let num_witnesses = <u16 as Readable>::read(r)? as usize;
870 let mut witnesses = Vec::with_capacity(num_witnesses);
871 for _ in 0..num_witnesses {
872 // Even though the length of each witness can be inferred in its consensus-encoded form,
873 // the spec includes a length prefix so that implementations don't have to deserialize
874 // each initially. We do that here anyway as in general we'll need to be able to make
875 // assertions on some properties of the witnesses when receiving a message providing a list
876 // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
877 let witness_len = <u16 as Readable>::read(r)? as usize;
878 let witness = <Witness as Readable>::read(r)?;
879 if witness.serialized_len() != witness_len {
880 return Err(DecodeError::BadLengthDescriptor);
882 witnesses.push(witness);
888 impl Writeable for Script {
889 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
890 (self.len() as u16).write(w)?;
891 w.write_all(self.as_bytes())
895 impl Readable for Script {
896 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
897 let len = <u16 as Readable>::read(r)? as usize;
898 let mut buf = vec![0; len];
899 r.read_exact(&mut buf)?;
900 Ok(Script::from(buf))
904 impl Writeable for PublicKey {
905 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
906 self.serialize().write(w)
909 fn serialized_length(&self) -> usize {
914 impl Readable for PublicKey {
915 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
916 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
917 match PublicKey::from_slice(&buf) {
919 Err(_) => return Err(DecodeError::InvalidValue),
924 impl Writeable for SecretKey {
925 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
926 let mut ser = [0; SECRET_KEY_SIZE];
927 ser.copy_from_slice(&self[..]);
931 fn serialized_length(&self) -> usize {
936 impl Readable for SecretKey {
937 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
938 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
939 match SecretKey::from_slice(&buf) {
941 Err(_) => return Err(DecodeError::InvalidValue),
947 impl Writeable for musig2::types::PublicNonce {
948 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
949 self.serialize().write(w)
954 impl Readable for musig2::types::PublicNonce {
955 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
956 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
957 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
962 impl Writeable for PartialSignatureWithNonce {
963 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
964 self.0.serialize().write(w)?;
970 impl Readable for PartialSignatureWithNonce {
971 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
972 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
973 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
974 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
975 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
979 impl Writeable for Sha256dHash {
980 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
981 w.write_all(&self[..])
985 impl Readable for Sha256dHash {
986 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
987 use bitcoin::hashes::Hash;
989 let buf: [u8; 32] = Readable::read(r)?;
990 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
994 impl Writeable for ecdsa::Signature {
995 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
996 self.serialize_compact().write(w)
1000 impl Readable for ecdsa::Signature {
1001 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1002 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1003 match ecdsa::Signature::from_compact(&buf) {
1005 Err(_) => return Err(DecodeError::InvalidValue),
1010 impl Writeable for schnorr::Signature {
1011 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1012 self.as_ref().write(w)
1016 impl Readable for schnorr::Signature {
1017 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1018 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1019 match schnorr::Signature::from_slice(&buf) {
1021 Err(_) => return Err(DecodeError::InvalidValue),
1026 impl Writeable for PaymentPreimage {
1027 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1032 impl Readable for PaymentPreimage {
1033 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1034 let buf: [u8; 32] = Readable::read(r)?;
1035 Ok(PaymentPreimage(buf))
1039 impl Writeable for PaymentHash {
1040 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1045 impl Readable for PaymentHash {
1046 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1047 let buf: [u8; 32] = Readable::read(r)?;
1048 Ok(PaymentHash(buf))
1052 impl Writeable for PaymentSecret {
1053 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1058 impl Readable for PaymentSecret {
1059 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1060 let buf: [u8; 32] = Readable::read(r)?;
1061 Ok(PaymentSecret(buf))
1065 impl<T: Writeable> Writeable for Box<T> {
1066 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1067 T::write(&**self, w)
1071 impl<T: Readable> Readable for Box<T> {
1072 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1073 Ok(Box::new(Readable::read(r)?))
1077 impl<T: Writeable> Writeable for Option<T> {
1078 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1080 None => 0u8.write(w)?,
1082 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1090 impl<T: Readable> Readable for Option<T>
1092 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1093 let len: BigSize = Readable::read(r)?;
1097 let mut reader = FixedLengthReader::new(r, len - 1);
1098 Ok(Some(Readable::read(&mut reader)?))
1104 impl Writeable for Txid {
1105 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1106 w.write_all(&self[..])
1110 impl Readable for Txid {
1111 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1112 use bitcoin::hashes::Hash;
1114 let buf: [u8; 32] = Readable::read(r)?;
1115 Ok(Txid::from_slice(&buf[..]).unwrap())
1119 impl Writeable for BlockHash {
1120 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1121 w.write_all(&self[..])
1125 impl Readable for BlockHash {
1126 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1127 use bitcoin::hashes::Hash;
1129 let buf: [u8; 32] = Readable::read(r)?;
1130 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1134 impl Writeable for ChainHash {
1135 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1136 w.write_all(self.as_bytes())
1140 impl Readable for ChainHash {
1141 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1142 let buf: [u8; 32] = Readable::read(r)?;
1143 Ok(ChainHash::from(&buf[..]))
1147 impl Writeable for OutPoint {
1148 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1149 self.txid.write(w)?;
1150 self.vout.write(w)?;
1155 impl Readable for OutPoint {
1156 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1157 let txid = Readable::read(r)?;
1158 let vout = Readable::read(r)?;
1166 macro_rules! impl_consensus_ser {
1167 ($bitcoin_type: ty) => {
1168 impl Writeable for $bitcoin_type {
1169 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1170 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1177 impl Readable for $bitcoin_type {
1178 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1179 match consensus::encode::Decodable::consensus_decode(r) {
1181 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1182 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1183 Err(_) => Err(DecodeError::InvalidValue),
1189 impl_consensus_ser!(Transaction);
1190 impl_consensus_ser!(TxOut);
1191 impl_consensus_ser!(Witness);
1193 impl<T: Readable> Readable for Mutex<T> {
1194 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1195 let t: T = Readable::read(r)?;
1199 impl<T: Writeable> Writeable for Mutex<T> {
1200 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1201 self.lock().unwrap().write(w)
1205 impl<T: Readable> Readable for RwLock<T> {
1206 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1207 let t: T = Readable::read(r)?;
1211 impl<T: Writeable> Writeable for RwLock<T> {
1212 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1213 self.read().unwrap().write(w)
1217 impl<A: Readable, B: Readable> Readable for (A, B) {
1218 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1219 let a: A = Readable::read(r)?;
1220 let b: B = Readable::read(r)?;
1224 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1225 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1231 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1232 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1233 let a: A = Readable::read(r)?;
1234 let b: B = Readable::read(r)?;
1235 let c: C = Readable::read(r)?;
1239 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1240 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1247 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1248 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1249 let a: A = Readable::read(r)?;
1250 let b: B = Readable::read(r)?;
1251 let c: C = Readable::read(r)?;
1252 let d: D = Readable::read(r)?;
1256 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1257 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1265 impl Writeable for () {
1266 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1270 impl Readable for () {
1271 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1276 impl Writeable for String {
1278 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1279 CollectionLength(self.len() as u64).write(w)?;
1280 w.write_all(self.as_bytes())
1283 impl Readable for String {
1285 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1286 let v: Vec<u8> = Readable::read(r)?;
1287 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1292 /// Represents a hostname for serialization purposes.
1293 /// Only the character set and length will be validated.
1294 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1295 /// Its length is guaranteed to be representable by a single byte.
1296 /// This serialization is used by [`BOLT 7`] hostnames.
1298 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1299 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
1300 pub struct Hostname(String);
1302 /// Returns the length of the hostname.
1303 pub fn len(&self) -> u8 {
1304 (&self.0).len() as u8
1308 impl core::fmt::Display for Hostname {
1309 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1310 write!(f, "{}", self.0)?;
1314 impl Deref for Hostname {
1315 type Target = String;
1317 fn deref(&self) -> &Self::Target {
1321 impl From<Hostname> for String {
1322 fn from(hostname: Hostname) -> Self {
1326 impl TryFrom<Vec<u8>> for Hostname {
1329 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1330 if let Ok(s) = String::from_utf8(bytes) {
1331 Hostname::try_from(s)
1337 impl TryFrom<String> for Hostname {
1340 fn try_from(s: String) -> Result<Self, Self::Error> {
1341 if s.len() <= 255 && s.chars().all(|c|
1342 c.is_ascii_alphanumeric() ||
1352 impl Writeable for Hostname {
1354 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1355 self.len().write(w)?;
1356 w.write_all(self.as_bytes())
1359 impl Readable for Hostname {
1361 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1362 let len: u8 = Readable::read(r)?;
1363 let mut vec = Vec::with_capacity(len.into());
1364 vec.resize(len.into(), 0);
1365 r.read_exact(&mut vec)?;
1366 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1370 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1371 impl Writeable for Duration {
1373 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1374 self.as_secs().write(w)?;
1375 self.subsec_nanos().write(w)
1378 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1379 impl Readable for Duration {
1381 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1382 let secs = Readable::read(r)?;
1383 let nanos = Readable::read(r)?;
1384 Ok(Duration::new(secs, nanos))
1388 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1389 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1391 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1392 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
1393 pub struct TransactionU16LenLimited(Transaction);
1395 impl TransactionU16LenLimited {
1396 /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1397 /// serialized length is <= u16::MAX.
1398 pub fn new(transaction: Transaction) -> Result<Self, ()> {
1399 if transaction.serialized_length() > (u16::MAX as usize) {
1402 Ok(Self(transaction))
1406 /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1407 pub fn into_transaction(self) -> Transaction {
1412 impl Writeable for TransactionU16LenLimited {
1413 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1414 (self.0.serialized_length() as u16).write(w)?;
1419 impl Readable for TransactionU16LenLimited {
1420 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1421 let len = <u16 as Readable>::read(r)?;
1422 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1423 let tx: Transaction = Readable::read(&mut tx_reader)?;
1424 if tx_reader.bytes_remain() {
1425 Err(DecodeError::BadLengthDescriptor)
1432 impl Writeable for ClaimId {
1433 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1434 self.0.write(writer)
1438 impl Readable for ClaimId {
1439 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1440 Ok(Self(Readable::read(reader)?))
1446 use core::convert::TryFrom;
1447 use bitcoin::secp256k1::ecdsa;
1448 use crate::util::ser::{Readable, Hostname, Writeable};
1451 fn hostname_conversion() {
1452 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1454 assert!(Hostname::try_from(String::from("\"")).is_err());
1455 assert!(Hostname::try_from(String::from("$")).is_err());
1456 assert!(Hostname::try_from(String::from("⚡")).is_err());
1457 let mut large_vec = Vec::with_capacity(256);
1458 large_vec.resize(256, b'A');
1459 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1463 fn hostname_serialization() {
1464 let hostname = Hostname::try_from(String::from("test")).unwrap();
1465 let mut buf: Vec<u8> = Vec::new();
1466 hostname.write(&mut buf).unwrap();
1467 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1471 /// Taproot will likely fill legacy signature fields with all 0s.
1472 /// This test ensures that doing so won't break serialization.
1473 fn null_signature_codec() {
1474 let buffer = vec![0u8; 64];
1475 let mut cursor = crate::io::Cursor::new(buffer.clone());
1476 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1477 let serialization = signature.serialize_compact();
1478 assert_eq!(buffer, serialization.to_vec())
1482 fn bigsize_encoding_decoding() {
1483 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1491 "ff0000000100000000",
1492 "ffffffffffffffffff"
1495 let mut stream = crate::io::Cursor::new(::hex::decode(bytes[i]).unwrap());
1496 assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1497 let mut stream = super::VecWriter(Vec::new());
1498 super::BigSize(values[i]).write(&mut stream).unwrap();
1499 assert_eq!(stream.0, ::hex::decode(bytes[i]).unwrap());
1501 let err_bytes = vec![
1504 "ff00000000ffffffff",
1514 let mut stream = crate::io::Cursor::new(::hex::decode(err_bytes[i]).unwrap());
1516 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1518 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));