Skip to main content

lightning/util/
ser.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
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
8// licenses.
9
10//! A very simple serialization framework which is used to serialize/deserialize messages as well
11//! as [`ChannelManager`]s and [`ChannelMonitor`]s.
12//!
13//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
14//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
15
16use crate::io::{self, BufRead, Read, Write};
17use crate::io_extras::{copy, sink};
18use crate::ln::interactivetxs::{TxInMetadata, TxOutMetadata};
19use crate::ln::onion_utils::{HMAC_COUNT, HMAC_LEN, HOLD_TIME_LEN, MAX_HOPS};
20use crate::prelude::*;
21use crate::sync::{Mutex, RwLock};
22use core::cmp;
23use core::hash::Hash;
24use core::ops::Deref;
25use core::str::FromStr;
26
27use alloc::collections::BTreeMap;
28
29use bitcoin::absolute::LockTime as AbsoluteLockTime;
30use bitcoin::address::Address;
31use bitcoin::amount::{Amount, SignedAmount};
32use bitcoin::consensus::Encodable;
33use bitcoin::constants::ChainHash;
34use bitcoin::hash_types::{BlockHash, Txid};
35use bitcoin::hashes::hmac::Hmac;
36use bitcoin::hashes::sha256::Hash as Sha256;
37use bitcoin::hashes::sha256d::Hash as Sha256dHash;
38use bitcoin::script::{self, ScriptBuf};
39use bitcoin::secp256k1::constants::{
40	COMPACT_SIGNATURE_SIZE, PUBLIC_KEY_SIZE, SCHNORR_SIGNATURE_SIZE, SECRET_KEY_SIZE,
41};
42use bitcoin::secp256k1::ecdsa;
43use bitcoin::secp256k1::schnorr;
44use bitcoin::secp256k1::{PublicKey, SecretKey};
45use bitcoin::transaction::{OutPoint, Transaction, TxOut};
46use bitcoin::FeeRate;
47use bitcoin::{consensus, Sequence, TxIn, Weight, Witness};
48
49use dnssec_prover::rr::Name;
50
51use lightning_invoice::Bolt11Invoice;
52
53use crate::chain::ClaimId;
54use crate::ln::msgs::{DecodeError, SerialId};
55use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
56use crate::types::string::UntrustedString;
57use crate::util::byte_utils::{be48_to_array, slice_to_be48};
58
59use core::time::Duration;
60
61/// serialization buffer size
62pub const MAX_BUF_SIZE: usize = 64 * 1024;
63
64/// A simplified version of `std::io::Write` that exists largely for backwards compatibility.
65/// An impl is provided for any type that also impls `std::io::Write`.
66///
67/// This is not exported to bindings users as we only export serialization to/from byte arrays instead
68pub trait Writer {
69	/// Writes the given buf out. See std::io::Write::write_all for more
70	fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
71}
72
73impl<W: Write> Writer for W {
74	#[inline]
75	fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
76		<Self as io::Write>::write_all(self, buf)
77	}
78}
79
80// TODO: Drop this entirely if rust-bitcoin releases a version bump with https://github.com/rust-bitcoin/rust-bitcoin/pull/3173
81/// Wrap buffering support for implementations of Read.
82/// A [`Read`]er which keeps an internal buffer to avoid hitting the underlying stream directly for
83/// every read, implementing [`BufRead`].
84///
85/// In order to avoid reading bytes past the first object, and those bytes then ending up getting
86/// dropped, this BufReader operates in one-byte-increments.
87struct BufReader<'a, R: Read> {
88	inner: &'a mut R,
89	buf: [u8; 1],
90	is_consumed: bool,
91}
92
93impl<'a, R: Read> BufReader<'a, R> {
94	/// Creates a [`BufReader`] which will read from the given `inner`.
95	pub fn new(inner: &'a mut R) -> Self {
96		BufReader { inner, buf: [0; 1], is_consumed: true }
97	}
98}
99
100impl<'a, R: Read> Read for BufReader<'a, R> {
101	#[inline]
102	fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
103		if output.is_empty() {
104			return Ok(0);
105		}
106		let mut offset = 0;
107		if !self.is_consumed {
108			output[0] = self.buf[0];
109			self.is_consumed = true;
110			offset = 1;
111		}
112		self.inner.read(&mut output[offset..]).map(|len| len + offset)
113	}
114}
115
116impl<'a, R: Read> BufRead for BufReader<'a, R> {
117	#[inline]
118	fn fill_buf(&mut self) -> io::Result<&[u8]> {
119		debug_assert!(false, "rust-bitcoin doesn't actually use this");
120		if self.is_consumed {
121			let count = self.inner.read(&mut self.buf[..])?;
122			debug_assert!(count <= 1, "read gave us a garbage length");
123
124			// upon hitting EOF, assume the byte is already consumed
125			self.is_consumed = count == 0;
126		}
127
128		if self.is_consumed {
129			Ok(&[])
130		} else {
131			Ok(&self.buf[..])
132		}
133	}
134
135	#[inline]
136	fn consume(&mut self, amount: usize) {
137		debug_assert!(false, "rust-bitcoin doesn't actually use this");
138		if amount >= 1 {
139			debug_assert_eq!(amount, 1, "Can only consume one byte");
140			debug_assert!(!self.is_consumed, "Cannot consume more than had been read");
141			self.is_consumed = true;
142		}
143	}
144}
145
146pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
147impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
148	#[inline]
149	fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
150		self.0.write_all(buf)
151	}
152	#[inline]
153	fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
154		self.0.write_all(buf)?;
155		Ok(buf.len())
156	}
157	#[inline]
158	fn flush(&mut self) -> Result<(), io::Error> {
159		Ok(())
160	}
161}
162
163pub(crate) struct VecWriter(pub Vec<u8>);
164impl Writer for VecWriter {
165	#[inline]
166	fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
167		self.0.extend_from_slice(buf);
168		Ok(())
169	}
170}
171
172/// Writer that only tracks the amount of data written - useful if you need to calculate the length
173/// of some data when serialized but don't yet need the full data.
174///
175/// This is not exported to bindings users as manual TLV building is not currently supported in bindings
176pub struct LengthCalculatingWriter(pub usize);
177impl Writer for LengthCalculatingWriter {
178	#[inline]
179	fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
180		self.0 += buf.len();
181		Ok(())
182	}
183}
184
185/// Essentially `std::io::Take` but a bit simpler and with a method to walk the underlying stream
186/// forward to ensure we always consume exactly the fixed length specified.
187///
188/// This is not exported to bindings users as manual TLV building is not currently supported in bindings
189pub struct FixedLengthReader<'a, R: Read> {
190	read: &'a mut R,
191	bytes_read: u64,
192	total_bytes: u64,
193}
194impl<'a, R: Read> FixedLengthReader<'a, R> {
195	/// Returns a new [`FixedLengthReader`].
196	pub fn new(read: &'a mut R, total_bytes: u64) -> Self {
197		Self { read, bytes_read: 0, total_bytes }
198	}
199
200	/// Returns whether some bytes are remaining or not.
201	#[inline]
202	pub fn bytes_remain(&mut self) -> bool {
203		self.bytes_read != self.total_bytes
204	}
205
206	/// Consumes the remaining bytes.
207	#[inline]
208	pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
209		copy(self, &mut sink()).unwrap();
210		if self.bytes_read != self.total_bytes {
211			Err(DecodeError::ShortRead)
212		} else {
213			Ok(())
214		}
215	}
216}
217impl<'a, R: Read> Read for FixedLengthReader<'a, R> {
218	#[inline]
219	fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
220		if self.total_bytes == self.bytes_read {
221			Ok(0)
222		} else {
223			let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
224			match self.read.read(&mut dest[0..(read_len as usize)]) {
225				Ok(v) => {
226					self.bytes_read += v as u64;
227					Ok(v)
228				},
229				Err(e) => Err(e),
230			}
231		}
232	}
233}
234
235/// This is not exported to bindings users as reads are always from byte arrays, never streams, in
236/// bindings.
237impl<'a, R: Read> LengthLimitedRead for FixedLengthReader<'a, R> {
238	#[inline]
239	fn remaining_bytes(&self) -> u64 {
240		self.total_bytes.saturating_sub(self.bytes_read)
241	}
242}
243
244/// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
245/// between "EOF reached before we started" and "EOF reached mid-read".
246///
247/// This is not exported to bindings users as manual TLV building is not currently supported in bindings
248pub struct ReadTrackingReader<'a, R: Read> {
249	read: &'a mut R,
250	/// Returns whether we have read from this reader or not yet.
251	pub have_read: bool,
252}
253impl<'a, R: Read> ReadTrackingReader<'a, R> {
254	/// Returns a new [`ReadTrackingReader`].
255	pub fn new(read: &'a mut R) -> Self {
256		Self { read, have_read: false }
257	}
258}
259impl<'a, R: Read> Read for ReadTrackingReader<'a, R> {
260	#[inline]
261	fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
262		match self.read.read(dest) {
263			Ok(0) => Ok(0),
264			Ok(len) => {
265				self.have_read = true;
266				Ok(len)
267			},
268			Err(e) => Err(e),
269		}
270	}
271}
272
273/// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
274///
275/// This is not exported to bindings users as we only export serialization to/from byte arrays instead
276pub trait Writeable {
277	/// Writes `self` out to the given [`Writer`].
278	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
279
280	/// Writes `self` out to a `Vec<u8>`.
281	fn encode(&self) -> Vec<u8> {
282		let len = self.serialized_length();
283		let mut msg = VecWriter(Vec::with_capacity(len));
284		self.write(&mut msg).unwrap();
285		// Note that objects with interior mutability may change size between when we called
286		// serialized_length and when we called write. That's okay, but shouldn't happen during
287		// testing as most of our tests are not threaded.
288		#[cfg(test)]
289		debug_assert_eq!(len, msg.0.len());
290		msg.0
291	}
292
293	/// Writes `self` out to a `Vec<u8>`.
294	#[cfg(test)]
295	fn encode_with_len(&self) -> Vec<u8> {
296		let mut msg = VecWriter(Vec::new());
297		0u16.write(&mut msg).unwrap();
298		self.write(&mut msg).unwrap();
299		let len = msg.0.len();
300		debug_assert_eq!(len - 2, self.serialized_length());
301		msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
302		msg.0
303	}
304
305	/// Gets the length of this object after it has been serialized. This can be overridden to
306	/// optimize cases where we prepend an object with its length.
307	// Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
308	#[inline]
309	fn serialized_length(&self) -> usize {
310		let mut len_calc = LengthCalculatingWriter(0);
311		self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
312		len_calc.0
313	}
314}
315
316impl<'a, T: Writeable> Writeable for &'a T {
317	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
318		(*self).write(writer)
319	}
320}
321
322/// A trait that various LDK types implement allowing them to be read in from a [`Read`].
323///
324/// This is not exported to bindings users as we only export serialization to/from byte arrays instead
325pub trait Readable
326where
327	Self: Sized,
328{
329	/// Reads a `Self` in from the given [`Read`].
330	fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
331}
332
333/// A trait that various LDK types implement allowing them to be read in from a
334/// [`io::Cursor`].
335pub(crate) trait CursorReadable
336where
337	Self: Sized,
338{
339	/// Reads a `Self` in from the given [`Read`].
340	fn read<R: AsRef<[u8]>>(reader: &mut io::Cursor<R>) -> Result<Self, DecodeError>;
341}
342
343/// A trait that various higher-level LDK types implement allowing them to be read in
344/// from a [`Read`] given some additional set of arguments which is required to deserialize.
345///
346/// This is not exported to bindings users as we only export serialization to/from byte arrays instead
347pub trait ReadableArgs<P>
348where
349	Self: Sized,
350{
351	/// Reads a `Self` in from the given [`Read`].
352	fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
353}
354
355/// A [`io::Read`] that limits the amount of bytes that can be read. Implementations should ensure
356/// that the object being read will only consume a fixed number of bytes from the underlying
357/// [`io::Read`], see [`FixedLengthReader`] for an example.
358///
359/// This is not exported to bindings users as reads are always from byte arrays, never streams, in
360/// bindings.
361pub trait LengthLimitedRead: Read {
362	/// The number of bytes remaining to be read.
363	fn remaining_bytes(&self) -> u64;
364}
365
366impl LengthLimitedRead for &[u8] {
367	fn remaining_bytes(&self) -> u64 {
368		// The underlying `Read` implementation for slice updates the slice to point to the yet unread
369		// part.
370		self.len() as u64
371	}
372}
373
374/// Similar to [`LengthReadable`]. Useful when an additional set of arguments is required to
375/// deserialize.
376pub(crate) trait LengthReadableArgs<P>
377where
378	Self: Sized,
379{
380	/// Reads a `Self` in from the given [`LengthLimitedRead`].
381	fn read<R: LengthLimitedRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
382}
383
384/// A trait that allows the implementer to be read in from a [`LengthLimitedRead`], requiring the
385/// reader to limit the number of total bytes read from its underlying [`Read`]. Useful for structs
386/// that will always consume the entire provided [`Read`] when deserializing.
387///
388/// Any type that implements [`Readable`] also automatically has a [`LengthReadable`]
389/// implementation, but some types, most notably onion packets, only implement [`LengthReadable`].
390///
391/// This is not exported to bindings users as reads are always from byte arrays, never streams, in
392/// bindings.
393pub trait LengthReadable
394where
395	Self: Sized,
396{
397	/// Reads a `Self` in from the given [`LengthLimitedRead`].
398	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(
399		reader: &mut R,
400	) -> Result<Self, DecodeError>;
401}
402
403impl<T: Readable> LengthReadable for T {
404	#[inline]
405	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(
406		reader: &mut R,
407	) -> Result<T, DecodeError> {
408		Readable::read(reader)
409	}
410}
411
412/// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
413///
414/// This is not exported to bindings users as we only export serialization to/from byte arrays instead
415pub trait MaybeReadable
416where
417	Self: Sized,
418{
419	/// Reads a `Self` in from the given [`Read`].
420	fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
421}
422
423impl<T: Readable> MaybeReadable for T {
424	#[inline]
425	fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
426		Ok(Some(Readable::read(reader)?))
427	}
428}
429
430/// Wrapper to read a required (non-optional) TLV record.
431///
432/// This is not exported to bindings users as manual TLV building is not currently supported in bindings
433pub struct RequiredWrapper<T>(pub Option<T>);
434impl<T: LengthReadable> LengthReadable for RequiredWrapper<T> {
435	#[inline]
436	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(
437		reader: &mut R,
438	) -> Result<Self, DecodeError> {
439		Ok(Self(Some(LengthReadable::read_from_fixed_length_buffer(reader)?)))
440	}
441}
442impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
443	#[inline]
444	fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
445		Ok(Self(Some(ReadableArgs::read(reader, args)?)))
446	}
447}
448/// When handling `default_values`, we want to map the default-value T directly
449/// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
450/// well. Thus, we assume `Into<T> for T` does nothing and use that.
451impl<T> From<T> for RequiredWrapper<T> {
452	fn from(t: T) -> RequiredWrapper<T> {
453		RequiredWrapper(Some(t))
454	}
455}
456impl<T: Clone> Clone for RequiredWrapper<T> {
457	fn clone(&self) -> Self {
458		Self(self.0.clone())
459	}
460}
461impl<T: Copy> Copy for RequiredWrapper<T> {}
462
463/// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
464/// backwards compat.
465///
466/// This is not exported to bindings users as manual TLV building is not currently supported in bindings
467pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
468impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
469	#[inline]
470	fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
471		let tlv = MaybeReadable::read(reader)?;
472		if let Some(tlv) = tlv {
473			return Ok(Some(Self(Some(tlv))));
474		}
475		Ok(None)
476	}
477}
478
479pub(crate) struct U48(pub u64);
480impl Writeable for U48 {
481	#[inline]
482	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
483		writer.write_all(&be48_to_array(self.0))
484	}
485}
486impl Readable for U48 {
487	#[inline]
488	fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
489		let mut buf = [0; 6];
490		reader.read_exact(&mut buf)?;
491		Ok(U48(slice_to_be48(&buf)))
492	}
493}
494
495/// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
496/// variable-length integers except that it is serialized in big-endian instead of little-endian.
497///
498/// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
499/// encoded in several different ways, which we must check for at deserialization-time. Thus, if
500/// you're looking for an example of a variable-length integer to use for your own project, move
501/// along, this is a rather poor design.
502#[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
503pub struct BigSize(pub u64);
504impl Writeable for BigSize {
505	#[inline]
506	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
507		match self.0 {
508			0..=0xFC => (self.0 as u8).write(writer),
509			0xFD..=0xFFFF => {
510				0xFDu8.write(writer)?;
511				(self.0 as u16).write(writer)
512			},
513			0x10000..=0xFFFFFFFF => {
514				0xFEu8.write(writer)?;
515				(self.0 as u32).write(writer)
516			},
517			_ => {
518				0xFFu8.write(writer)?;
519				(self.0 as u64).write(writer)
520			},
521		}
522	}
523}
524impl Readable for BigSize {
525	#[inline]
526	fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
527		let n: u8 = Readable::read(reader)?;
528		match n {
529			0xFF => {
530				let x: u64 = Readable::read(reader)?;
531				if x < 0x100000000 {
532					Err(DecodeError::InvalidValue)
533				} else {
534					Ok(BigSize(x))
535				}
536			},
537			0xFE => {
538				let x: u32 = Readable::read(reader)?;
539				if x < 0x10000 {
540					Err(DecodeError::InvalidValue)
541				} else {
542					Ok(BigSize(x as u64))
543				}
544			},
545			0xFD => {
546				let x: u16 = Readable::read(reader)?;
547				if x < 0xFD {
548					Err(DecodeError::InvalidValue)
549				} else {
550					Ok(BigSize(x as u64))
551				}
552			},
553			n => Ok(BigSize(n as u64)),
554		}
555	}
556}
557
558/// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
559/// primarily targets that, we must as well. However, because we may serialize objects that have
560/// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
561/// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
562/// "read eight more bytes".
563///
564/// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
565/// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
566/// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
567pub struct CollectionLength(pub u64);
568impl Writeable for CollectionLength {
569	#[inline]
570	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
571		if self.0 < 0xffff {
572			(self.0 as u16).write(writer)
573		} else {
574			0xffffu16.write(writer)?;
575			(self.0 - 0xffff).write(writer)
576		}
577	}
578}
579
580impl Readable for CollectionLength {
581	#[inline]
582	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
583		let mut val: u64 = <u16 as Readable>::read(r)? as u64;
584		if val == 0xffff {
585			val =
586				<u64 as Readable>::read(r)?.checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
587		}
588		Ok(CollectionLength(val))
589	}
590}
591
592/// In TLV we occasionally send fields which only consist of, or potentially end with, a
593/// variable-length integer which is simply truncated by skipping high zero bytes. This type
594/// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
595#[cfg_attr(test, derive(PartialEq, Eq, Debug))]
596pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
597
598macro_rules! impl_writeable_primitive {
599	($val_type:ty, $len: expr) => {
600		impl Writeable for $val_type {
601			#[inline]
602			fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
603				writer.write_all(&self.to_be_bytes())
604			}
605		}
606		impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
607			#[inline]
608			fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
609				// Skip any full leading 0 bytes when writing (in BE):
610				writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros() / 8) as usize..$len])
611			}
612		}
613		impl Writeable for HighZeroBytesDroppedBigSize<&$val_type> {
614			#[inline]
615			fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
616				// Skip any full leading 0 bytes when writing (in BE):
617				writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros() / 8) as usize..$len])
618			}
619		}
620		impl Readable for $val_type {
621			#[inline]
622			fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
623				let mut buf = [0; $len];
624				reader.read_exact(&mut buf)?;
625				Ok(<$val_type>::from_be_bytes(buf))
626			}
627		}
628		impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
629			#[inline]
630			fn read<R: Read>(
631				reader: &mut R,
632			) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
633				// We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
634				// the high bytes being dropped. To do so, we start reading into the middle of buf
635				// and then convert the appropriate number of bytes with extra high bytes out of
636				// buf.
637				let mut buf = [0; $len * 2];
638				let mut read_len = reader.read(&mut buf[$len..])?;
639				let mut total_read_len = read_len;
640				while read_len != 0 && total_read_len != $len {
641					read_len = reader.read(&mut buf[($len + total_read_len)..])?;
642					total_read_len += read_len;
643				}
644				if total_read_len == 0 || buf[$len] != 0 {
645					let first_byte = $len - ($len - total_read_len);
646					let mut bytes = [0; $len];
647					bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
648					Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
649				} else {
650					// If the encoding had extra zero bytes, return a failure even though we know
651					// what they meant (as the TLV test vectors require this)
652					Err(DecodeError::InvalidValue)
653				}
654			}
655		}
656		impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
657			fn from(val: $val_type) -> Self {
658				Self(val)
659			}
660		}
661	};
662}
663
664impl_writeable_primitive!(u128, 16);
665impl_writeable_primitive!(u64, 8);
666impl_writeable_primitive!(u32, 4);
667impl_writeable_primitive!(u16, 2);
668impl_writeable_primitive!(i64, 8);
669impl_writeable_primitive!(i32, 4);
670impl_writeable_primitive!(i16, 2);
671impl_writeable_primitive!(i8, 1);
672
673impl Writeable for u8 {
674	#[inline]
675	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
676		writer.write_all(&[*self])
677	}
678}
679impl Readable for u8 {
680	#[inline]
681	fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
682		let mut buf = [0; 1];
683		reader.read_exact(&mut buf)?;
684		Ok(buf[0])
685	}
686}
687
688impl Writeable for bool {
689	#[inline]
690	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
691		writer.write_all(&[if *self { 1 } else { 0 }])
692	}
693}
694impl Readable for bool {
695	#[inline]
696	fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
697		let mut buf = [0; 1];
698		reader.read_exact(&mut buf)?;
699		if buf[0] != 0 && buf[0] != 1 {
700			return Err(DecodeError::InvalidValue);
701		}
702		Ok(buf[0] == 1)
703	}
704}
705
706macro_rules! impl_array {
707	($size:expr, $ty: ty) => {
708		impl Writeable for [$ty; $size] {
709			#[inline]
710			fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
711				let mut out = [0; $size * core::mem::size_of::<$ty>()];
712				for (idx, v) in self.iter().enumerate() {
713					let startpos = idx * core::mem::size_of::<$ty>();
714					out[startpos..startpos + core::mem::size_of::<$ty>()]
715						.copy_from_slice(&v.to_be_bytes());
716				}
717				w.write_all(&out)
718			}
719		}
720
721		impl Readable for [$ty; $size] {
722			#[inline]
723			fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
724				let mut buf = [0u8; $size * core::mem::size_of::<$ty>()];
725				r.read_exact(&mut buf)?;
726				let mut res = [0; $size];
727				for (idx, v) in res.iter_mut().enumerate() {
728					let startpos = idx * core::mem::size_of::<$ty>();
729					let mut arr = [0; core::mem::size_of::<$ty>()];
730					arr.copy_from_slice(&buf[startpos..startpos + core::mem::size_of::<$ty>()]);
731					*v = <$ty>::from_be_bytes(arr);
732				}
733				Ok(res)
734			}
735		}
736	};
737}
738
739impl_array!(3, u8); // for rgb, ISO 4217 code
740impl_array!(4, u8); // for IPv4
741impl_array!(12, u8); // for OnionV2
742impl_array!(16, u8); // for IPv6
743impl_array!(32, u8); // for channel id & hmac
744impl_array!(PUBLIC_KEY_SIZE, u8); // for PublicKey
745impl_array!(64, u8); // for ecdsa::Signature and schnorr::Signature
746impl_array!(1300, u8); // for OnionPacket.hop_data
747
748impl_array!(8, u16);
749impl_array!(32, u16);
750
751// Implement array serialization for attribution_data.
752impl_array!(MAX_HOPS * HOLD_TIME_LEN, u8);
753impl_array!(HMAC_LEN * HMAC_COUNT, u8);
754
755/// A type for variable-length values within TLV record where the length is encoded as part of the record.
756/// Used to prevent encoding the length twice.
757///
758/// This is not exported to bindings users as manual TLV building is not currently supported in bindings
759pub struct WithoutLength<T>(pub T);
760
761impl Writeable for WithoutLength<&&String> {
762	#[inline]
763	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
764		w.write_all(self.0.as_bytes())
765	}
766}
767
768impl Writeable for WithoutLength<&String> {
769	#[inline]
770	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
771		w.write_all(self.0.as_bytes())
772	}
773}
774
775impl LengthReadable for WithoutLength<String> {
776	#[inline]
777	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
778		let v: WithoutLength<Vec<u8>> = LengthReadable::read_from_fixed_length_buffer(r)?;
779		Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
780	}
781}
782impl<'a> From<&'a String> for WithoutLength<&'a String> {
783	fn from(s: &'a String) -> Self {
784		Self(s)
785	}
786}
787
788impl Writeable for UntrustedString {
789	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
790		self.0.write(w)
791	}
792}
793
794impl Readable for UntrustedString {
795	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
796		let s: String = Readable::read(r)?;
797		Ok(Self(s))
798	}
799}
800
801impl Writeable for WithoutLength<&UntrustedString> {
802	#[inline]
803	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
804		WithoutLength(&self.0 .0).write(w)
805	}
806}
807impl LengthReadable for WithoutLength<UntrustedString> {
808	#[inline]
809	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
810		let s: WithoutLength<String> = LengthReadable::read_from_fixed_length_buffer(r)?;
811		Ok(Self(UntrustedString(s.0)))
812	}
813}
814
815trait AsWriteableSlice {
816	type Inner: Writeable;
817	fn as_slice(&self) -> &[Self::Inner];
818}
819
820impl<T: Writeable> AsWriteableSlice for &Vec<T> {
821	type Inner = T;
822	fn as_slice(&self) -> &[T] {
823		&self
824	}
825}
826
827impl<T: Writeable> AsWriteableSlice for &&Vec<T> {
828	type Inner = T;
829	fn as_slice(&self) -> &[T] {
830		&self
831	}
832}
833
834impl<T: Writeable> AsWriteableSlice for &[T] {
835	type Inner = T;
836	fn as_slice(&self) -> &[T] {
837		&self
838	}
839}
840
841impl<S: AsWriteableSlice> Writeable for WithoutLength<S> {
842	#[inline]
843	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
844		for ref v in self.0.as_slice() {
845			v.write(writer)?;
846		}
847		Ok(())
848	}
849}
850
851impl<T: MaybeReadable> LengthReadable for WithoutLength<Vec<T>> {
852	#[inline]
853	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(
854		reader: &mut R,
855	) -> Result<Self, DecodeError> {
856		let mut values = Vec::new();
857		loop {
858			let mut track_read = ReadTrackingReader::new(reader);
859			match MaybeReadable::read(&mut track_read) {
860				Ok(Some(v)) => {
861					values.push(v);
862				},
863				Ok(None) => {},
864				// If we failed to read any bytes at all, we reached the end of our TLV
865				// stream and have simply exhausted all entries.
866				Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
867				Err(e) => return Err(e),
868			}
869		}
870		Ok(Self(values))
871	}
872}
873impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
874	fn from(v: &'a Vec<T>) -> Self {
875		Self(v)
876	}
877}
878
879impl Writeable for WithoutLength<&ScriptBuf> {
880	#[inline]
881	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
882		writer.write_all(self.0.as_bytes())
883	}
884}
885
886impl LengthReadable for WithoutLength<ScriptBuf> {
887	#[inline]
888	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
889		let v: WithoutLength<Vec<u8>> = LengthReadable::read_from_fixed_length_buffer(r)?;
890		Ok(WithoutLength(script::Builder::from(v.0).into_script()))
891	}
892}
893
894#[derive(Debug)]
895pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
896
897impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
898	#[inline]
899	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
900		for ref v in self.0.clone() {
901			v.write(writer)?;
902		}
903		Ok(())
904	}
905}
906
907#[cfg(test)]
908impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
909	fn eq(&self, other: &Self) -> bool {
910		self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
911	}
912}
913
914#[derive(Debug)]
915pub(crate) struct IterableOwned<I: Iterator<Item = T> + Clone, T>(pub I);
916
917impl<I: Iterator<Item = T> + Clone, T: Writeable> Writeable for IterableOwned<I, T> {
918	#[inline]
919	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
920		for ref v in self.0.clone() {
921			v.write(writer)?;
922		}
923		Ok(())
924	}
925}
926
927macro_rules! impl_for_map {
928	($ty: ident, $keybound: ident, $constr: expr) => {
929		impl<K, V> Writeable for $ty<K, V>
930		where
931			K: Writeable + Eq + $keybound,
932			V: Writeable,
933		{
934			#[inline]
935			fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
936				CollectionLength(self.len() as u64).write(w)?;
937				for (key, value) in self.iter() {
938					key.write(w)?;
939					value.write(w)?;
940				}
941				Ok(())
942			}
943		}
944
945		impl<K, V> Readable for $ty<K, V>
946		where
947			K: Readable + Eq + $keybound,
948			V: MaybeReadable,
949		{
950			#[inline]
951			fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
952				let len: CollectionLength = Readable::read(r)?;
953				let entry_size = ::core::mem::size_of::<K>() + ::core::mem::size_of::<V>();
954				let max_alloc = MAX_BUF_SIZE / (entry_size + 1);
955				let mut ret = $constr(cmp::min(len.0 as usize, max_alloc));
956				for _ in 0..len.0 {
957					let k = K::read(r)?;
958					let v_opt = V::read(r)?;
959					if let Some(v) = v_opt {
960						if ret.insert(k, v).is_some() {
961							return Err(DecodeError::InvalidValue);
962						}
963					}
964				}
965				Ok(ret)
966			}
967		}
968	};
969}
970
971impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
972impl_for_map!(HashMap, Hash, |len| hash_map_with_capacity(len));
973
974/// A wrapper used to serialize a `BTreeMap<u64, Vec<u8>>` with a few less bytes.
975pub(crate) struct BigSizeKeyedMap<T>(pub T);
976
977impl Writeable for BigSizeKeyedMap<&BTreeMap<u64, Vec<u8>>> {
978	#[inline]
979	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
980		BigSize(self.0.len() as u64).write(w)?;
981		for (key, value) in self.0.iter() {
982			BigSize(*key).write(w)?;
983			value.write(w)?;
984		}
985		Ok(())
986	}
987}
988
989impl LengthReadable for BigSizeKeyedMap<BTreeMap<u64, Vec<u8>>> {
990	#[inline]
991	fn read_from_fixed_length_buffer<R: LengthLimitedRead>(r: &mut R) -> Result<Self, DecodeError> {
992		let len: BigSize = Readable::read(r)?;
993		let mut ret = BTreeMap::new();
994		for _ in 0..len.0 {
995			let key: BigSize = Readable::read(r)?;
996			let value: Vec<u8> = Readable::read(r)?;
997			if ret.insert(key.0, value).is_some() {
998				return Err(DecodeError::InvalidValue);
999			}
1000		}
1001		Ok(BigSizeKeyedMap(ret))
1002	}
1003}
1004
1005// HashSet
1006impl<T> Writeable for HashSet<T>
1007where
1008	T: Writeable + Eq + Hash,
1009{
1010	#[inline]
1011	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1012		CollectionLength(self.len() as u64).write(w)?;
1013		for item in self.iter() {
1014			item.write(w)?;
1015		}
1016		Ok(())
1017	}
1018}
1019
1020impl<T> Readable for HashSet<T>
1021where
1022	T: Readable + Eq + Hash,
1023{
1024	#[inline]
1025	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1026		let len: CollectionLength = Readable::read(r)?;
1027		let mut ret = hash_set_with_capacity(cmp::min(
1028			len.0 as usize,
1029			MAX_BUF_SIZE / core::mem::size_of::<T>(),
1030		));
1031		for _ in 0..len.0 {
1032			if !ret.insert(T::read(r)?) {
1033				return Err(DecodeError::InvalidValue);
1034			}
1035		}
1036		Ok(ret)
1037	}
1038}
1039
1040/// Write number of items in a vec followed by each element, without writing a length-prefix for
1041/// each element.
1042#[macro_export]
1043macro_rules! impl_writeable_for_vec {
1044	($ty: ty $(, $name: ident)*) => {
1045		impl<$($name : Writeable),*> Writeable for Vec<$ty> {
1046			#[inline]
1047			fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1048				$crate::util::ser::CollectionLength(self.len() as u64).write(w)?;
1049				for elem in self.iter() {
1050					elem.write(w)?;
1051				}
1052				Ok(())
1053			}
1054		}
1055	}
1056}
1057/// Read the number of items in a vec followed by each element, without reading a length prefix for
1058/// each element.
1059///
1060/// Each element is read with `MaybeReadable`, meaning if an element cannot be read then it is
1061/// skipped without returning `DecodeError::InvalidValue`.
1062#[macro_export]
1063macro_rules! impl_readable_for_vec {
1064	($ty: ty $(, $name: ident)*) => {
1065		impl<$($name : Readable),*> Readable for Vec<$ty> {
1066			#[inline]
1067			fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
1068				let len: $crate::util::ser::CollectionLength = Readable::read(r)?;
1069				let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, $crate::util::ser::MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
1070				for _ in 0..len.0 {
1071					if let Some(val) = $crate::util::ser::MaybeReadable::read(r)? {
1072						ret.push(val);
1073					}
1074				}
1075				Ok(ret)
1076			}
1077		}
1078	}
1079}
1080macro_rules! impl_for_vec {
1081	($ty: ty $(, $name: ident)*) => {
1082		impl_writeable_for_vec!($ty $(, $name)*);
1083		impl_readable_for_vec!($ty $(, $name)*);
1084	}
1085}
1086
1087// Alternatives to impl_writeable_for_vec/impl_readable_for_vec that add a length prefix to each
1088// element in the Vec. Intended to be used when elements have variable lengths.
1089macro_rules! impl_writeable_for_vec_with_element_length_prefix {
1090	($ty: ty $(, $name: ident)*) => {
1091		impl<$($name : Writeable),*> Writeable for Vec<$ty> {
1092			#[inline]
1093			fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1094				CollectionLength(self.len() as u64).write(w)?;
1095				for elem in self.iter() {
1096					CollectionLength(elem.serialized_length() as u64).write(w)?;
1097					elem.write(w)?;
1098				}
1099				Ok(())
1100			}
1101		}
1102	}
1103}
1104macro_rules! impl_readable_for_vec_with_element_length_prefix {
1105	($ty: ty $(, $name: ident)*) => {
1106		impl<$($name : Readable),*> Readable for Vec<$ty> {
1107			#[inline]
1108			fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1109				let len: CollectionLength = Readable::read(r)?;
1110				let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
1111				for _ in 0..len.0 {
1112					let elem_len: CollectionLength = Readable::read(r)?;
1113					let mut elem_reader = FixedLengthReader::new(r, elem_len.0);
1114					ret.push(LengthReadable::read_from_fixed_length_buffer(&mut elem_reader)?);
1115				}
1116				Ok(ret)
1117			}
1118		}
1119	}
1120}
1121macro_rules! impl_for_vec_with_element_length_prefix {
1122	($ty: ty $(, $name: ident)*) => {
1123		impl_writeable_for_vec_with_element_length_prefix!($ty $(, $name)*);
1124		impl_readable_for_vec_with_element_length_prefix!($ty $(, $name)*);
1125	}
1126}
1127
1128impl Writeable for Vec<u8> {
1129	#[inline]
1130	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1131		CollectionLength(self.len() as u64).write(w)?;
1132		w.write_all(&self)
1133	}
1134}
1135
1136impl Readable for Vec<u8> {
1137	#[inline]
1138	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1139		let mut len: CollectionLength = Readable::read(r)?;
1140		let mut ret = Vec::new();
1141		while len.0 > 0 {
1142			let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
1143			let readstart = ret.len();
1144			ret.resize(readstart + readamt, 0);
1145			r.read_exact(&mut ret[readstart..])?;
1146			len.0 -= readamt as u64;
1147		}
1148		Ok(ret)
1149	}
1150}
1151
1152impl_for_vec!(ecdsa::Signature);
1153impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
1154impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
1155impl_for_vec!(crate::ln::channelmanager::PaymentClaimDetails);
1156impl_for_vec!(crate::ln::msgs::SocketAddress);
1157impl_for_vec!((A, B), A, B);
1158impl_for_vec!(OutPoint);
1159impl_for_vec!(ScriptBuf);
1160impl_for_vec!(SerialId);
1161impl_for_vec!(TxInMetadata);
1162impl_for_vec!(TxOutMetadata);
1163impl_for_vec!(crate::ln::our_peer_storage::PeerStorageMonitorHolder);
1164impl_for_vec!(crate::blinded_path::message::BlindedMessagePath);
1165impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
1166impl_readable_for_vec!(crate::routing::router::BlindedTail);
1167impl_for_vec!(crate::routing::router::TrampolineHop);
1168impl_for_vec_with_element_length_prefix!(crate::ln::msgs::UpdateAddHTLC);
1169impl_writeable_for_vec_with_element_length_prefix!(&crate::ln::msgs::UpdateAddHTLC);
1170impl_for_vec!(u32);
1171impl_for_vec!(crate::events::HTLCLocator);
1172impl_for_vec!(crate::ln::types::ChannelId);
1173
1174impl Writeable for Vec<Witness> {
1175	#[inline]
1176	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1177		(self.len() as u16).write(w)?;
1178		for witness in self {
1179			(witness.size() as u16).write(w)?;
1180			witness.write(w)?;
1181		}
1182		Ok(())
1183	}
1184}
1185
1186impl Readable for Vec<Witness> {
1187	#[inline]
1188	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1189		let num_witnesses = <u16 as Readable>::read(r)? as usize;
1190		let mut witnesses = Vec::with_capacity(num_witnesses);
1191		for _ in 0..num_witnesses {
1192			// Even though the length of each witness can be inferred in its consensus-encoded form,
1193			// the spec includes a length prefix so that implementations don't have to deserialize
1194			//  each initially. We do that here anyway as in general we'll need to be able to make
1195			// assertions on some properties of the witnesses when receiving a message providing a list
1196			// of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
1197			let witness_len = <u16 as Readable>::read(r)? as usize;
1198			let witness = <Witness as Readable>::read(r)?;
1199			if witness.size() != witness_len {
1200				return Err(DecodeError::BadLengthDescriptor);
1201			}
1202			witnesses.push(witness);
1203		}
1204		Ok(witnesses)
1205	}
1206}
1207
1208impl Writeable for ScriptBuf {
1209	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1210		(self.len() as u16).write(w)?;
1211		w.write_all(self.as_bytes())
1212	}
1213}
1214
1215impl Readable for ScriptBuf {
1216	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1217		let len = <u16 as Readable>::read(r)? as usize;
1218		let mut buf = vec![0; len];
1219		r.read_exact(&mut buf)?;
1220		Ok(ScriptBuf::from(buf))
1221	}
1222}
1223
1224impl Writeable for PublicKey {
1225	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1226		self.serialize().write(w)
1227	}
1228	#[inline]
1229	fn serialized_length(&self) -> usize {
1230		PUBLIC_KEY_SIZE
1231	}
1232}
1233
1234impl Readable for PublicKey {
1235	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1236		let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
1237		match PublicKey::from_slice(&buf) {
1238			Ok(key) => Ok(key),
1239			Err(_) => return Err(DecodeError::InvalidValue),
1240		}
1241	}
1242}
1243
1244impl Writeable for SecretKey {
1245	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1246		let mut ser = [0; SECRET_KEY_SIZE];
1247		ser.copy_from_slice(&self[..]);
1248		ser.write(w)
1249	}
1250	#[inline]
1251	fn serialized_length(&self) -> usize {
1252		SECRET_KEY_SIZE
1253	}
1254}
1255
1256impl Readable for SecretKey {
1257	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1258		let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
1259		match SecretKey::from_slice(&buf) {
1260			Ok(key) => Ok(key),
1261			Err(_) => return Err(DecodeError::InvalidValue),
1262		}
1263	}
1264}
1265
1266impl Writeable for Sha256 {
1267	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1268		w.write_all(&self[..])
1269	}
1270}
1271
1272impl Readable for Sha256 {
1273	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1274		use bitcoin::hashes::Hash;
1275
1276		let buf: [u8; 32] = Readable::read(r)?;
1277		Ok(Sha256::from_byte_array(buf))
1278	}
1279}
1280
1281impl Writeable for Hmac<Sha256> {
1282	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1283		w.write_all(&self[..])
1284	}
1285}
1286
1287impl Readable for Hmac<Sha256> {
1288	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1289		use bitcoin::hashes::Hash;
1290
1291		let buf: [u8; 32] = Readable::read(r)?;
1292		Ok(Hmac::<Sha256>::from_byte_array(buf))
1293	}
1294}
1295
1296impl Writeable for Sha256dHash {
1297	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1298		w.write_all(&self[..])
1299	}
1300}
1301
1302impl Readable for Sha256dHash {
1303	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1304		use bitcoin::hashes::Hash;
1305
1306		let buf: [u8; 32] = Readable::read(r)?;
1307		Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
1308	}
1309}
1310
1311impl Writeable for ecdsa::Signature {
1312	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1313		self.serialize_compact().write(w)
1314	}
1315}
1316
1317impl Readable for ecdsa::Signature {
1318	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1319		let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1320		match ecdsa::Signature::from_compact(&buf) {
1321			Ok(sig) => Ok(sig),
1322			Err(_) => return Err(DecodeError::InvalidValue),
1323		}
1324	}
1325}
1326
1327impl Writeable for schnorr::Signature {
1328	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1329		self.as_ref().write(w)
1330	}
1331}
1332
1333impl Readable for schnorr::Signature {
1334	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1335		let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1336		match schnorr::Signature::from_slice(&buf) {
1337			Ok(sig) => Ok(sig),
1338			Err(_) => return Err(DecodeError::InvalidValue),
1339		}
1340	}
1341}
1342
1343impl Writeable for PaymentPreimage {
1344	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1345		self.0.write(w)
1346	}
1347}
1348
1349impl Readable for PaymentPreimage {
1350	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1351		let buf: [u8; 32] = Readable::read(r)?;
1352		Ok(PaymentPreimage(buf))
1353	}
1354}
1355
1356impl Writeable for PaymentHash {
1357	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1358		self.0.write(w)
1359	}
1360}
1361
1362impl Readable for PaymentHash {
1363	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1364		let buf: [u8; 32] = Readable::read(r)?;
1365		Ok(PaymentHash(buf))
1366	}
1367}
1368
1369impl Writeable for PaymentSecret {
1370	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1371		self.0.write(w)
1372	}
1373}
1374
1375impl Readable for PaymentSecret {
1376	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1377		let buf: [u8; 32] = Readable::read(r)?;
1378		Ok(PaymentSecret(buf))
1379	}
1380}
1381
1382impl<T: Writeable> Writeable for Box<T> {
1383	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1384		T::write(&**self, w)
1385	}
1386}
1387
1388impl<T: Readable> Readable for Box<T> {
1389	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1390		Ok(Box::new(Readable::read(r)?))
1391	}
1392}
1393
1394impl<T: Writeable> Writeable for Option<T> {
1395	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1396		match *self {
1397			None => 0u8.write(w)?,
1398			Some(ref data) => {
1399				BigSize(data.serialized_length() as u64 + 1).write(w)?;
1400				data.write(w)?;
1401			},
1402		}
1403		Ok(())
1404	}
1405}
1406
1407impl<T: LengthReadable> Readable for Option<T> {
1408	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1409		let len: BigSize = Readable::read(r)?;
1410		match len.0 {
1411			0 => Ok(None),
1412			len => {
1413				let mut reader = FixedLengthReader::new(r, len - 1);
1414				Ok(Some(LengthReadable::read_from_fixed_length_buffer(&mut reader)?))
1415			},
1416		}
1417	}
1418}
1419
1420impl Writeable for AbsoluteLockTime {
1421	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1422		self.to_consensus_u32().write(w)
1423	}
1424}
1425
1426impl Readable for AbsoluteLockTime {
1427	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1428		let lock_time: u32 = Readable::read(r)?;
1429		Ok(AbsoluteLockTime::from_consensus(lock_time))
1430	}
1431}
1432
1433impl Writeable for Amount {
1434	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1435		self.to_sat().write(w)
1436	}
1437}
1438
1439impl Readable for Amount {
1440	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1441		let amount: u64 = Readable::read(r)?;
1442		Ok(Amount::from_sat(amount))
1443	}
1444}
1445
1446impl Writeable for SignedAmount {
1447	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1448		self.to_sat().write(w)
1449	}
1450}
1451
1452impl Readable for SignedAmount {
1453	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1454		let amount: i64 = Readable::read(r)?;
1455		Ok(SignedAmount::from_sat(amount))
1456	}
1457}
1458
1459impl Writeable for Weight {
1460	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1461		self.to_wu().write(w)
1462	}
1463}
1464
1465impl Readable for Weight {
1466	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1467		let wu: u64 = Readable::read(r)?;
1468		Ok(Weight::from_wu(wu))
1469	}
1470}
1471
1472impl Writeable for FeeRate {
1473	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1474		self.to_sat_per_kwu().write(w)
1475	}
1476}
1477
1478impl Readable for FeeRate {
1479	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1480		let sat_kwu: u64 = Readable::read(r)?;
1481		Ok(FeeRate::from_sat_per_kwu(sat_kwu))
1482	}
1483}
1484
1485impl Writeable for Txid {
1486	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1487		w.write_all(&self[..])
1488	}
1489}
1490
1491impl Readable for Txid {
1492	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1493		use bitcoin::hashes::Hash;
1494
1495		let buf: [u8; 32] = Readable::read(r)?;
1496		Ok(Txid::from_slice(&buf[..]).unwrap())
1497	}
1498}
1499
1500impl Writeable for BlockHash {
1501	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1502		w.write_all(&self[..])
1503	}
1504}
1505
1506impl Readable for BlockHash {
1507	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1508		use bitcoin::hashes::Hash;
1509
1510		let buf: [u8; 32] = Readable::read(r)?;
1511		Ok(BlockHash::from_slice(&buf[..]).unwrap())
1512	}
1513}
1514
1515impl Writeable for [Option<BlockHash>; 12] {
1516	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1517		for hash_opt in self {
1518			match hash_opt {
1519				Some(hash) => hash.write(w)?,
1520				None => ([0u8; 32]).write(w)?,
1521			}
1522		}
1523		Ok(())
1524	}
1525}
1526
1527impl Readable for [Option<BlockHash>; 12] {
1528	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1529		use bitcoin::hashes::Hash;
1530
1531		let mut res = [None; 12];
1532		for hash_opt in res.iter_mut() {
1533			let buf: [u8; 32] = Readable::read(r)?;
1534			if buf != [0; 32] {
1535				*hash_opt = Some(BlockHash::from_slice(&buf[..]).unwrap());
1536			}
1537		}
1538		Ok(res)
1539	}
1540}
1541
1542impl Writeable for ChainHash {
1543	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1544		w.write_all(self.as_bytes())
1545	}
1546}
1547
1548impl Readable for ChainHash {
1549	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1550		let buf: [u8; 32] = Readable::read(r)?;
1551		Ok(ChainHash::from(buf))
1552	}
1553}
1554
1555impl Writeable for OutPoint {
1556	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1557		self.txid.write(w)?;
1558		self.vout.write(w)?;
1559		Ok(())
1560	}
1561}
1562
1563impl Readable for OutPoint {
1564	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1565		let txid = Readable::read(r)?;
1566		let vout = Readable::read(r)?;
1567		Ok(OutPoint { txid, vout })
1568	}
1569}
1570
1571impl Writeable for Address {
1572	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1573		self.to_string().write(w)?;
1574		Ok(())
1575	}
1576}
1577
1578impl Readable for Address {
1579	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1580		let addr_string: String = Readable::read(r)?;
1581		let addr = Address::from_str(&addr_string)
1582			.map_err(|_| DecodeError::InvalidValue)?
1583			.assume_checked();
1584		Ok(addr)
1585	}
1586}
1587
1588impl Writeable for Bolt11Invoice {
1589	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1590		self.to_string().write(w)?;
1591		Ok(())
1592	}
1593}
1594
1595impl Readable for Bolt11Invoice {
1596	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1597		let invoice_string: String = Readable::read(r)?;
1598		let invoice =
1599			Bolt11Invoice::from_str(&invoice_string).map_err(|_| DecodeError::InvalidValue)?;
1600		Ok(invoice)
1601	}
1602}
1603
1604macro_rules! impl_consensus_ser {
1605	($bitcoin_type: ty) => {
1606		impl Writeable for $bitcoin_type {
1607			fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1608				match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1609					Ok(_) => Ok(()),
1610					Err(e) => Err(e),
1611				}
1612			}
1613		}
1614
1615		impl Readable for $bitcoin_type {
1616			fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1617				let mut reader = BufReader::<_>::new(r);
1618				match consensus::encode::Decodable::consensus_decode(&mut reader) {
1619					Ok(t) => Ok(t),
1620					Err(consensus::encode::Error::Io(ref e))
1621						if e.kind() == io::ErrorKind::UnexpectedEof =>
1622					{
1623						Err(DecodeError::ShortRead)
1624					},
1625					Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind().into())),
1626					Err(_) => Err(DecodeError::InvalidValue),
1627				}
1628			}
1629		}
1630	};
1631}
1632impl_consensus_ser!(Transaction);
1633impl_consensus_ser!(TxIn);
1634impl_consensus_ser!(TxOut);
1635impl_consensus_ser!(Witness);
1636impl_consensus_ser!(Sequence);
1637
1638impl<T: Readable> Readable for Mutex<T> {
1639	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1640		let t: T = Readable::read(r)?;
1641		Ok(Mutex::new(t))
1642	}
1643}
1644impl<T: Writeable> Writeable for Mutex<T> {
1645	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1646		self.lock().unwrap().write(w)
1647	}
1648}
1649
1650impl<T: Readable> Readable for RwLock<T> {
1651	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1652		let t: T = Readable::read(r)?;
1653		Ok(RwLock::new(t))
1654	}
1655}
1656impl<T: Writeable> Writeable for RwLock<T> {
1657	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1658		self.read().unwrap().write(w)
1659	}
1660}
1661
1662macro_rules! impl_tuple_ser {
1663	($($i: ident : $type: tt),*) => {
1664		impl<$($type),*> Readable for ($($type),*)
1665		where $(
1666			$type: Readable,
1667		)*
1668		{
1669			fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1670				Ok(($(<$type as Readable>::read(r)?),*))
1671			}
1672		}
1673
1674		impl<$($type),*> Writeable for ($($type),*)
1675		where $(
1676			$type: Writeable,
1677		)*
1678		{
1679			fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1680				let ($($i),*) = self;
1681				$($i.write(w)?;)*
1682				Ok(())
1683			}
1684		}
1685	}
1686}
1687
1688impl_tuple_ser!(a: A, b: B);
1689impl_tuple_ser!(a: A, b: B, c: C);
1690impl_tuple_ser!(a: A, b: B, c: C, d: D);
1691impl_tuple_ser!(a: A, b: B, c: C, d: D, e: E);
1692impl_tuple_ser!(a: A, b: B, c: C, d: D, e: E, f: F);
1693impl_tuple_ser!(a: A, b: B, c: C, d: D, e: E, f: F, g: G);
1694
1695impl Writeable for () {
1696	fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1697		Ok(())
1698	}
1699}
1700impl Readable for () {
1701	fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1702		Ok(())
1703	}
1704}
1705
1706impl Writeable for String {
1707	#[inline]
1708	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1709		self.as_str().write(w)
1710	}
1711}
1712
1713impl Writeable for &str {
1714	#[inline]
1715	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1716		CollectionLength(self.len() as u64).write(w)?;
1717		w.write_all(self.as_bytes())
1718	}
1719}
1720impl Readable for String {
1721	#[inline]
1722	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1723		let v: Vec<u8> = Readable::read(r)?;
1724		let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1725		Ok(ret)
1726	}
1727}
1728
1729/// Represents a hostname for serialization purposes.
1730/// Only the character set and length will be validated.
1731/// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1732/// Its length is guaranteed to be representable by a single byte.
1733/// This serialization is used by [`BOLT 7`] hostnames.
1734///
1735/// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1736#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1737pub struct Hostname(String);
1738impl Hostname {
1739	/// Returns the length of the hostname.
1740	pub fn len(&self) -> u8 {
1741		(&self.0).len() as u8
1742	}
1743
1744	/// Check if the chars in `s` are allowed to be included in a [`Hostname`].
1745	pub(crate) fn str_is_valid_hostname(s: &str) -> bool {
1746		s.len() <= 255
1747			&& s.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-')
1748	}
1749}
1750
1751impl core::fmt::Display for Hostname {
1752	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1753		write!(f, "{}", self.0)?;
1754		Ok(())
1755	}
1756}
1757impl Deref for Hostname {
1758	type Target = String;
1759
1760	fn deref(&self) -> &Self::Target {
1761		&self.0
1762	}
1763}
1764impl From<Hostname> for String {
1765	fn from(hostname: Hostname) -> Self {
1766		hostname.0
1767	}
1768}
1769impl TryFrom<Vec<u8>> for Hostname {
1770	type Error = ();
1771
1772	fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1773		if let Ok(s) = String::from_utf8(bytes) {
1774			Hostname::try_from(s)
1775		} else {
1776			Err(())
1777		}
1778	}
1779}
1780impl TryFrom<String> for Hostname {
1781	type Error = ();
1782
1783	fn try_from(s: String) -> Result<Self, Self::Error> {
1784		if Hostname::str_is_valid_hostname(&s) {
1785			Ok(Hostname(s))
1786		} else {
1787			Err(())
1788		}
1789	}
1790}
1791impl Writeable for Hostname {
1792	#[inline]
1793	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1794		self.len().write(w)?;
1795		w.write_all(self.as_bytes())
1796	}
1797}
1798impl Readable for Hostname {
1799	#[inline]
1800	fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1801		let len: u8 = Readable::read(r)?;
1802		let mut vec = Vec::with_capacity(len.into());
1803		vec.resize(len.into(), 0);
1804		r.read_exact(&mut vec)?;
1805		Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1806	}
1807}
1808
1809impl TryInto<Name> for Hostname {
1810	type Error = ();
1811	fn try_into(self) -> Result<Name, ()> {
1812		Name::try_from(self.0)
1813	}
1814}
1815
1816/// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1817impl Writeable for Duration {
1818	#[inline]
1819	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1820		self.as_secs().write(w)?;
1821		self.subsec_nanos().write(w)
1822	}
1823}
1824/// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1825impl Readable for Duration {
1826	#[inline]
1827	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1828		let secs = Readable::read(r)?;
1829		let nanos = Readable::read(r)?;
1830		// Duration::new panics if the nanosecond part in excess of a second, added to the second
1831		// part, overflows. To ensure this won't happen, we simply reject any case where there are
1832		// nanoseconds in excess of a second, which is invalid anyway.
1833		if nanos >= 1_000_000_000 {
1834			Err(DecodeError::InvalidValue)
1835		} else {
1836			Ok(Duration::new(secs, nanos))
1837		}
1838	}
1839}
1840
1841impl Writeable for ClaimId {
1842	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1843		self.0.write(writer)
1844	}
1845}
1846
1847impl Readable for ClaimId {
1848	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1849		Ok(Self(Readable::read(reader)?))
1850	}
1851}
1852
1853#[cfg(test)]
1854mod tests {
1855	use crate::prelude::*;
1856	use crate::util::ser::{Hostname, Readable, Writeable};
1857	use bitcoin::hex::FromHex;
1858	use bitcoin::secp256k1::ecdsa;
1859
1860	#[test]
1861	fn hostname_conversion() {
1862		assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1863
1864		assert!(Hostname::try_from(String::from("\"")).is_err());
1865		assert!(Hostname::try_from(String::from("$")).is_err());
1866		assert!(Hostname::try_from(String::from("⚡")).is_err());
1867		let mut large_vec = Vec::with_capacity(256);
1868		large_vec.resize(256, b'A');
1869		assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1870	}
1871
1872	#[test]
1873	fn hostname_serialization() {
1874		let hostname = Hostname::try_from(String::from("test")).unwrap();
1875		let mut buf: Vec<u8> = Vec::new();
1876		hostname.write(&mut buf).unwrap();
1877		assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1878	}
1879
1880	#[test]
1881	fn str_serialization_matches_string() {
1882		let s = "test";
1883		assert_eq!(s.encode(), s.to_string().encode());
1884	}
1885
1886	#[test]
1887	/// Taproot will likely fill legacy signature fields with all 0s.
1888	/// This test ensures that doing so won't break serialization.
1889	fn null_signature_codec() {
1890		let buffer = vec![0u8; 64];
1891		let mut cursor = crate::io::Cursor::new(buffer.clone());
1892		let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1893		let serialization = signature.serialize_compact();
1894		assert_eq!(buffer, serialization.to_vec())
1895	}
1896
1897	#[test]
1898	fn bigsize_encoding_decoding() {
1899		let values = [0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1900		let bytes = [
1901			"00",
1902			"fc",
1903			"fd00fd",
1904			"fdffff",
1905			"fe00010000",
1906			"feffffffff",
1907			"ff0000000100000000",
1908			"ffffffffffffffffff",
1909		];
1910		for i in 0..=7 {
1911			let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(bytes[i]).unwrap());
1912			assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1913			let mut stream = super::VecWriter(Vec::new());
1914			super::BigSize(values[i]).write(&mut stream).unwrap();
1915			assert_eq!(stream.0, <Vec<u8>>::from_hex(bytes[i]).unwrap());
1916		}
1917		let err_bytes = [
1918			"fd00fc",
1919			"fe0000ffff",
1920			"ff00000000ffffffff",
1921			"fd00",
1922			"feffff",
1923			"ffffffffff",
1924			"fd",
1925			"fe",
1926			"ff",
1927			"",
1928		];
1929		for i in 0..=9 {
1930			let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(err_bytes[i]).unwrap());
1931			if i < 3 {
1932				assert_eq!(
1933					super::BigSize::read(&mut stream).err(),
1934					Some(crate::ln::msgs::DecodeError::InvalidValue)
1935				);
1936			} else {
1937				assert_eq!(
1938					super::BigSize::read(&mut stream).err(),
1939					Some(crate::ln::msgs::DecodeError::ShortRead)
1940				);
1941			}
1942		}
1943	}
1944}