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