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 mut ret = $constr(len.0 as usize);
847				for _ in 0..len.0 {
848					let k = K::read(r)?;
849					let v_opt = V::read(r)?;
850					if let Some(v) = v_opt {
851						if ret.insert(k, v).is_some() {
852							return Err(DecodeError::InvalidValue);
853						}
854					}
855				}
856				Ok(ret)
857			}
858		}
859	}
860}
861
862impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
863impl_for_map!(HashMap, Hash, |len| hash_map_with_capacity(len));
864
865// HashSet
866impl<T> Writeable for HashSet<T>
867where T: Writeable + Eq + Hash
868{
869	#[inline]
870	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
871		CollectionLength(self.len() as u64).write(w)?;
872		for item in self.iter() {
873			item.write(w)?;
874		}
875		Ok(())
876	}
877}
878
879impl<T> Readable for HashSet<T>
880where T: Readable + Eq + Hash
881{
882	#[inline]
883	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
884		let len: CollectionLength = Readable::read(r)?;
885		let mut ret = hash_set_with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
886		for _ in 0..len.0 {
887			if !ret.insert(T::read(r)?) {
888				return Err(DecodeError::InvalidValue)
889			}
890		}
891		Ok(ret)
892	}
893}
894
895// Vectors
896macro_rules! impl_writeable_for_vec {
897	($ty: ty $(, $name: ident)*) => {
898		impl<$($name : Writeable),*> Writeable for Vec<$ty> {
899			#[inline]
900			fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
901				CollectionLength(self.len() as u64).write(w)?;
902				for elem in self.iter() {
903					elem.write(w)?;
904				}
905				Ok(())
906			}
907		}
908	}
909}
910macro_rules! impl_readable_for_vec {
911	($ty: ty $(, $name: ident)*) => {
912		impl<$($name : Readable),*> Readable for Vec<$ty> {
913			#[inline]
914			fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
915				let len: CollectionLength = Readable::read(r)?;
916				let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
917				for _ in 0..len.0 {
918					if let Some(val) = MaybeReadable::read(r)? {
919						ret.push(val);
920					}
921				}
922				Ok(ret)
923			}
924		}
925	}
926}
927macro_rules! impl_for_vec {
928	($ty: ty $(, $name: ident)*) => {
929		impl_writeable_for_vec!($ty $(, $name)*);
930		impl_readable_for_vec!($ty $(, $name)*);
931	}
932}
933
934// Alternatives to impl_writeable_for_vec/impl_readable_for_vec that add a length prefix to each
935// element in the Vec. Intended to be used when elements have variable lengths.
936macro_rules! impl_writeable_for_vec_with_element_length_prefix {
937	($ty: ty $(, $name: ident)*) => {
938		impl<$($name : Writeable),*> Writeable for Vec<$ty> {
939			#[inline]
940			fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
941				CollectionLength(self.len() as u64).write(w)?;
942				for elem in self.iter() {
943					CollectionLength(elem.serialized_length() as u64).write(w)?;
944					elem.write(w)?;
945				}
946				Ok(())
947			}
948		}
949	}
950}
951macro_rules! impl_readable_for_vec_with_element_length_prefix {
952	($ty: ty $(, $name: ident)*) => {
953		impl<$($name : Readable),*> Readable for Vec<$ty> {
954			#[inline]
955			fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
956				let len: CollectionLength = Readable::read(r)?;
957				let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
958				for _ in 0..len.0 {
959					let elem_len: CollectionLength = Readable::read(r)?;
960					let mut elem_reader = FixedLengthReader::new(r, elem_len.0);
961					if let Some(val) = MaybeReadable::read(&mut elem_reader)? {
962						ret.push(val);
963					}
964				}
965				Ok(ret)
966			}
967		}
968	}
969}
970macro_rules! impl_for_vec_with_element_length_prefix {
971	($ty: ty $(, $name: ident)*) => {
972		impl_writeable_for_vec_with_element_length_prefix!($ty $(, $name)*);
973		impl_readable_for_vec_with_element_length_prefix!($ty $(, $name)*);
974	}
975}
976
977impl Writeable for Vec<u8> {
978	#[inline]
979	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
980		CollectionLength(self.len() as u64).write(w)?;
981		w.write_all(&self)
982	}
983}
984
985impl Readable for Vec<u8> {
986	#[inline]
987	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
988		let mut len: CollectionLength = Readable::read(r)?;
989		let mut ret = Vec::new();
990		while len.0 > 0 {
991			let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
992			let readstart = ret.len();
993			ret.resize(readstart + readamt, 0);
994			r.read_exact(&mut ret[readstart..])?;
995			len.0 -= readamt as u64;
996		}
997		Ok(ret)
998	}
999}
1000
1001impl_for_vec!(ecdsa::Signature);
1002impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
1003impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
1004impl_for_vec!(crate::ln::channelmanager::PaymentClaimDetails);
1005impl_for_vec!(crate::ln::msgs::SocketAddress);
1006impl_for_vec!((A, B), A, B);
1007impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
1008impl_readable_for_vec!(crate::routing::router::BlindedTail);
1009impl_for_vec_with_element_length_prefix!(crate::ln::msgs::UpdateAddHTLC);
1010impl_writeable_for_vec_with_element_length_prefix!(&crate::ln::msgs::UpdateAddHTLC);
1011
1012impl Writeable for Vec<Witness> {
1013	#[inline]
1014	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1015		(self.len() as u16).write(w)?;
1016		for witness in self {
1017			(witness.size() as u16).write(w)?;
1018			witness.write(w)?;
1019		}
1020		Ok(())
1021	}
1022}
1023
1024impl Readable for Vec<Witness> {
1025	#[inline]
1026	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1027		let num_witnesses = <u16 as Readable>::read(r)? as usize;
1028		let mut witnesses = Vec::with_capacity(num_witnesses);
1029		for _ in 0..num_witnesses {
1030			// Even though the length of each witness can be inferred in its consensus-encoded form,
1031			// the spec includes a length prefix so that implementations don't have to deserialize
1032			//  each initially. We do that here anyway as in general we'll need to be able to make
1033			// assertions on some properties of the witnesses when receiving a message providing a list
1034			// of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
1035			let witness_len = <u16 as Readable>::read(r)? as usize;
1036			let witness = <Witness as Readable>::read(r)?;
1037			if witness.size() != witness_len {
1038				return Err(DecodeError::BadLengthDescriptor);
1039			}
1040			witnesses.push(witness);
1041		}
1042		Ok(witnesses)
1043	}
1044}
1045
1046impl Writeable for ScriptBuf {
1047	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1048		(self.len() as u16).write(w)?;
1049		w.write_all(self.as_bytes())
1050	}
1051}
1052
1053impl Readable for ScriptBuf {
1054	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1055		let len = <u16 as Readable>::read(r)? as usize;
1056		let mut buf = vec![0; len];
1057		r.read_exact(&mut buf)?;
1058		Ok(ScriptBuf::from(buf))
1059	}
1060}
1061
1062impl Writeable for PublicKey {
1063	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1064		self.serialize().write(w)
1065	}
1066	#[inline]
1067	fn serialized_length(&self) -> usize {
1068		PUBLIC_KEY_SIZE
1069	}
1070}
1071
1072impl Readable for PublicKey {
1073	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1074		let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
1075		match PublicKey::from_slice(&buf) {
1076			Ok(key) => Ok(key),
1077			Err(_) => return Err(DecodeError::InvalidValue),
1078		}
1079	}
1080}
1081
1082impl Writeable for SecretKey {
1083	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1084		let mut ser = [0; SECRET_KEY_SIZE];
1085		ser.copy_from_slice(&self[..]);
1086		ser.write(w)
1087	}
1088	#[inline]
1089	fn serialized_length(&self) -> usize {
1090		SECRET_KEY_SIZE
1091	}
1092}
1093
1094impl Readable for SecretKey {
1095	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1096		let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
1097		match SecretKey::from_slice(&buf) {
1098			Ok(key) => Ok(key),
1099			Err(_) => return Err(DecodeError::InvalidValue),
1100		}
1101	}
1102}
1103
1104#[cfg(taproot)]
1105impl Writeable for musig2::types::PublicNonce {
1106	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1107		self.serialize().write(w)
1108	}
1109}
1110
1111#[cfg(taproot)]
1112impl Readable for musig2::types::PublicNonce {
1113	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1114		let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
1115		musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
1116	}
1117}
1118
1119#[cfg(taproot)]
1120impl Writeable for PartialSignatureWithNonce {
1121	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1122		self.0.serialize().write(w)?;
1123		self.1.write(w)
1124	}
1125}
1126
1127#[cfg(taproot)]
1128impl Readable for PartialSignatureWithNonce {
1129	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1130		let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
1131		let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
1132		let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
1133		Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
1134	}
1135}
1136
1137impl Writeable for Hmac<Sha256> {
1138	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1139		w.write_all(&self[..])
1140	}
1141}
1142
1143impl Readable for Hmac<Sha256> {
1144	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1145		use bitcoin::hashes::Hash;
1146
1147		let buf: [u8; 32] = Readable::read(r)?;
1148		Ok(Hmac::<Sha256>::from_byte_array(buf))
1149	}
1150}
1151
1152impl Writeable for Sha256dHash {
1153	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1154		w.write_all(&self[..])
1155	}
1156}
1157
1158impl Readable for Sha256dHash {
1159	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1160		use bitcoin::hashes::Hash;
1161
1162		let buf: [u8; 32] = Readable::read(r)?;
1163		Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
1164	}
1165}
1166
1167impl Writeable for ecdsa::Signature {
1168	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1169		self.serialize_compact().write(w)
1170	}
1171}
1172
1173impl Readable for ecdsa::Signature {
1174	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1175		let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1176		match ecdsa::Signature::from_compact(&buf) {
1177			Ok(sig) => Ok(sig),
1178			Err(_) => return Err(DecodeError::InvalidValue),
1179		}
1180	}
1181}
1182
1183impl Writeable for schnorr::Signature {
1184	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1185		self.as_ref().write(w)
1186	}
1187}
1188
1189impl Readable for schnorr::Signature {
1190	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1191		let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1192		match schnorr::Signature::from_slice(&buf) {
1193			Ok(sig) => Ok(sig),
1194			Err(_) => return Err(DecodeError::InvalidValue),
1195		}
1196	}
1197}
1198
1199impl Writeable for PaymentPreimage {
1200	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1201		self.0.write(w)
1202	}
1203}
1204
1205impl Readable for PaymentPreimage {
1206	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1207		let buf: [u8; 32] = Readable::read(r)?;
1208		Ok(PaymentPreimage(buf))
1209	}
1210}
1211
1212impl Writeable for PaymentHash {
1213	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1214		self.0.write(w)
1215	}
1216}
1217
1218impl Readable for PaymentHash {
1219	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1220		let buf: [u8; 32] = Readable::read(r)?;
1221		Ok(PaymentHash(buf))
1222	}
1223}
1224
1225impl Writeable for PaymentSecret {
1226	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1227		self.0.write(w)
1228	}
1229}
1230
1231impl Readable for PaymentSecret {
1232	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1233		let buf: [u8; 32] = Readable::read(r)?;
1234		Ok(PaymentSecret(buf))
1235	}
1236}
1237
1238impl<T: Writeable> Writeable for Box<T> {
1239	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1240		T::write(&**self, w)
1241	}
1242}
1243
1244impl<T: Readable> Readable for Box<T> {
1245	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1246		Ok(Box::new(Readable::read(r)?))
1247	}
1248}
1249
1250impl<T: Writeable> Writeable for Option<T> {
1251	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1252		match *self {
1253			None => 0u8.write(w)?,
1254			Some(ref data) => {
1255				BigSize(data.serialized_length() as u64 + 1).write(w)?;
1256				data.write(w)?;
1257			}
1258		}
1259		Ok(())
1260	}
1261}
1262
1263impl<T: Readable> Readable for Option<T>
1264{
1265	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1266		let len: BigSize = Readable::read(r)?;
1267		match len.0 {
1268			0 => Ok(None),
1269			len => {
1270				let mut reader = FixedLengthReader::new(r, len - 1);
1271				Ok(Some(Readable::read(&mut reader)?))
1272			}
1273		}
1274	}
1275}
1276
1277impl Writeable for Amount {
1278	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1279		self.to_sat().write(w)
1280	}
1281}
1282
1283
1284impl Readable for Amount {
1285	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1286		let amount: u64 = Readable::read(r)?;
1287		Ok(Amount::from_sat(amount))
1288	}
1289}
1290
1291impl Writeable for Txid {
1292	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1293		w.write_all(&self[..])
1294	}
1295}
1296
1297impl Readable for Txid {
1298	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1299		use bitcoin::hashes::Hash;
1300
1301		let buf: [u8; 32] = Readable::read(r)?;
1302		Ok(Txid::from_slice(&buf[..]).unwrap())
1303	}
1304}
1305
1306impl Writeable for BlockHash {
1307	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1308		w.write_all(&self[..])
1309	}
1310}
1311
1312impl Readable for BlockHash {
1313	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1314		use bitcoin::hashes::Hash;
1315
1316		let buf: [u8; 32] = Readable::read(r)?;
1317		Ok(BlockHash::from_slice(&buf[..]).unwrap())
1318	}
1319}
1320
1321impl Writeable for ChainHash {
1322	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1323		w.write_all(self.as_bytes())
1324	}
1325}
1326
1327impl Readable for ChainHash {
1328	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1329		let buf: [u8; 32] = Readable::read(r)?;
1330		Ok(ChainHash::from(buf))
1331	}
1332}
1333
1334impl Writeable for OutPoint {
1335	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1336		self.txid.write(w)?;
1337		self.vout.write(w)?;
1338		Ok(())
1339	}
1340}
1341
1342impl Readable for OutPoint {
1343	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1344		let txid = Readable::read(r)?;
1345		let vout = Readable::read(r)?;
1346		Ok(OutPoint {
1347			txid,
1348			vout,
1349		})
1350	}
1351}
1352
1353macro_rules! impl_consensus_ser {
1354	($bitcoin_type: ty) => {
1355		impl Writeable for $bitcoin_type {
1356			fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1357				match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1358					Ok(_) => Ok(()),
1359					Err(e) => Err(e),
1360				}
1361			}
1362		}
1363
1364		impl Readable for $bitcoin_type {
1365			fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1366				let mut reader = BufReader::<_>::new(r);
1367				match consensus::encode::Decodable::consensus_decode(&mut reader) {
1368					Ok(t) => Ok(t),
1369					Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1370					Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind().into())),
1371					Err(_) => Err(DecodeError::InvalidValue),
1372				}
1373			}
1374		}
1375	}
1376}
1377impl_consensus_ser!(Transaction);
1378impl_consensus_ser!(TxOut);
1379impl_consensus_ser!(Witness);
1380
1381impl<T: Readable> Readable for Mutex<T> {
1382	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1383		let t: T = Readable::read(r)?;
1384		Ok(Mutex::new(t))
1385	}
1386}
1387impl<T: Writeable> Writeable for Mutex<T> {
1388	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1389		self.lock().unwrap().write(w)
1390	}
1391}
1392
1393impl<T: Readable> Readable for RwLock<T> {
1394	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1395		let t: T = Readable::read(r)?;
1396		Ok(RwLock::new(t))
1397	}
1398}
1399impl<T: Writeable> Writeable for RwLock<T> {
1400	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1401		self.read().unwrap().write(w)
1402	}
1403}
1404
1405macro_rules! impl_tuple_ser {
1406	($($i: ident : $type: tt),*) => {
1407		impl<$($type),*> Readable for ($($type),*)
1408		where $(
1409			$type: Readable,
1410		)*
1411		{
1412			fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1413				Ok(($(<$type as Readable>::read(r)?),*))
1414			}
1415		}
1416
1417		impl<$($type),*> Writeable for ($($type),*)
1418		where $(
1419			$type: Writeable,
1420		)*
1421		{
1422			fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1423				let ($($i),*) = self;
1424				$($i.write(w)?;)*
1425				Ok(())
1426			}
1427		}
1428	}
1429}
1430
1431impl_tuple_ser!(a: A, b: B);
1432impl_tuple_ser!(a: A, b: B, c: C);
1433impl_tuple_ser!(a: A, b: B, c: C, d: D);
1434impl_tuple_ser!(a: A, b: B, c: C, d: D, e: E);
1435impl_tuple_ser!(a: A, b: B, c: C, d: D, e: E, f: F);
1436impl_tuple_ser!(a: A, b: B, c: C, d: D, e: E, f: F, g: G);
1437
1438impl Writeable for () {
1439	fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1440		Ok(())
1441	}
1442}
1443impl Readable for () {
1444	fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1445		Ok(())
1446	}
1447}
1448
1449impl Writeable for String {
1450	#[inline]
1451	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1452		CollectionLength(self.len() as u64).write(w)?;
1453		w.write_all(self.as_bytes())
1454	}
1455}
1456impl Readable for String {
1457	#[inline]
1458	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1459		let v: Vec<u8> = Readable::read(r)?;
1460		let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1461		Ok(ret)
1462	}
1463}
1464
1465/// Represents a hostname for serialization purposes.
1466/// Only the character set and length will be validated.
1467/// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1468/// Its length is guaranteed to be representable by a single byte.
1469/// This serialization is used by [`BOLT 7`] hostnames.
1470///
1471/// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1472#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1473pub struct Hostname(String);
1474impl Hostname {
1475	/// Returns the length of the hostname.
1476	pub fn len(&self) -> u8 {
1477		(&self.0).len() as u8
1478	}
1479
1480	/// Check if the chars in `s` are allowed to be included in a [`Hostname`].
1481	pub(crate) fn str_is_valid_hostname(s: &str) -> bool {
1482		s.len() <= 255 &&
1483		s.chars().all(|c|
1484			c.is_ascii_alphanumeric() ||
1485			c == '.' || c == '_' || c == '-'
1486		)
1487	}
1488}
1489
1490impl core::fmt::Display for Hostname {
1491	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1492		write!(f, "{}", self.0)?;
1493		Ok(())
1494	}
1495}
1496impl Deref for Hostname {
1497	type Target = String;
1498
1499	fn deref(&self) -> &Self::Target {
1500		&self.0
1501	}
1502}
1503impl From<Hostname> for String {
1504	fn from(hostname: Hostname) -> Self {
1505		hostname.0
1506	}
1507}
1508impl TryFrom<Vec<u8>> for Hostname {
1509	type Error = ();
1510
1511	fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1512		if let Ok(s) = String::from_utf8(bytes) {
1513			Hostname::try_from(s)
1514		} else {
1515			Err(())
1516		}
1517	}
1518}
1519impl TryFrom<String> for Hostname {
1520	type Error = ();
1521
1522	fn try_from(s: String) -> Result<Self, Self::Error> {
1523		if Hostname::str_is_valid_hostname(&s) {
1524			Ok(Hostname(s))
1525		} else {
1526			Err(())
1527		}
1528	}
1529}
1530impl Writeable for Hostname {
1531	#[inline]
1532	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1533		self.len().write(w)?;
1534		w.write_all(self.as_bytes())
1535	}
1536}
1537impl Readable for Hostname {
1538	#[inline]
1539	fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1540		let len: u8 = Readable::read(r)?;
1541		let mut vec = Vec::with_capacity(len.into());
1542		vec.resize(len.into(), 0);
1543		r.read_exact(&mut vec)?;
1544		Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1545	}
1546}
1547
1548impl TryInto<Name> for Hostname {
1549	type Error = ();
1550	fn try_into(self) -> Result<Name, ()> {
1551		Name::try_from(self.0)
1552	}
1553}
1554
1555/// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1556impl Writeable for Duration {
1557	#[inline]
1558	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1559		self.as_secs().write(w)?;
1560		self.subsec_nanos().write(w)
1561	}
1562}
1563/// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1564impl Readable for Duration {
1565	#[inline]
1566	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1567		let secs = Readable::read(r)?;
1568		let nanos = Readable::read(r)?;
1569		Ok(Duration::new(secs, nanos))
1570	}
1571}
1572
1573/// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1574/// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1575///
1576/// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1577#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1578pub struct TransactionU16LenLimited(Transaction);
1579
1580impl TransactionU16LenLimited {
1581	/// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1582	/// serialized length is <= u16::MAX.
1583	pub fn new(transaction: Transaction) -> Result<Self, ()> {
1584		if transaction.serialized_length() > (u16::MAX as usize) {
1585			Err(())
1586		} else {
1587			Ok(Self(transaction))
1588		}
1589	}
1590
1591	/// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1592	pub fn into_transaction(self) -> Transaction {
1593		self.0
1594	}
1595
1596	/// Returns a reference to the contained `Transaction`
1597	pub fn as_transaction(&self) -> &Transaction {
1598		&self.0
1599	}
1600}
1601
1602impl Writeable for TransactionU16LenLimited {
1603	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1604		(self.0.serialized_length() as u16).write(w)?;
1605		self.0.write(w)
1606	}
1607}
1608
1609impl Readable for TransactionU16LenLimited {
1610	fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1611		let len = <u16 as Readable>::read(r)?;
1612		let mut tx_reader = FixedLengthReader::new(r, len as u64);
1613		let tx: Transaction = Readable::read(&mut tx_reader)?;
1614		if tx_reader.bytes_remain() {
1615			Err(DecodeError::BadLengthDescriptor)
1616		} else {
1617			Ok(Self(tx))
1618		}
1619	}
1620}
1621
1622impl Writeable for ClaimId {
1623	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1624		self.0.write(writer)
1625	}
1626}
1627
1628impl Readable for ClaimId {
1629	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1630		Ok(Self(Readable::read(reader)?))
1631	}
1632}
1633
1634#[cfg(test)]
1635mod tests {
1636	use bitcoin::hex::FromHex;
1637	use bitcoin::secp256k1::ecdsa;
1638	use crate::util::ser::{Readable, Hostname, Writeable};
1639	use crate::prelude::*;
1640
1641	#[test]
1642	fn hostname_conversion() {
1643		assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1644
1645		assert!(Hostname::try_from(String::from("\"")).is_err());
1646		assert!(Hostname::try_from(String::from("$")).is_err());
1647		assert!(Hostname::try_from(String::from("⚡")).is_err());
1648		let mut large_vec = Vec::with_capacity(256);
1649		large_vec.resize(256, b'A');
1650		assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1651	}
1652
1653	#[test]
1654	fn hostname_serialization() {
1655		let hostname = Hostname::try_from(String::from("test")).unwrap();
1656		let mut buf: Vec<u8> = Vec::new();
1657		hostname.write(&mut buf).unwrap();
1658		assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1659	}
1660
1661	#[test]
1662	/// Taproot will likely fill legacy signature fields with all 0s.
1663	/// This test ensures that doing so won't break serialization.
1664	fn null_signature_codec() {
1665		let buffer = vec![0u8; 64];
1666		let mut cursor = crate::io::Cursor::new(buffer.clone());
1667		let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1668		let serialization = signature.serialize_compact();
1669		assert_eq!(buffer, serialization.to_vec())
1670	}
1671
1672	#[test]
1673	fn bigsize_encoding_decoding() {
1674		let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1675		let bytes = vec![
1676			"00",
1677			"fc",
1678			"fd00fd",
1679			"fdffff",
1680			"fe00010000",
1681			"feffffffff",
1682			"ff0000000100000000",
1683			"ffffffffffffffffff"
1684		];
1685		for i in 0..=7 {
1686			let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(bytes[i]).unwrap());
1687			assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1688			let mut stream = super::VecWriter(Vec::new());
1689			super::BigSize(values[i]).write(&mut stream).unwrap();
1690			assert_eq!(stream.0, <Vec<u8>>::from_hex(bytes[i]).unwrap());
1691		}
1692		let err_bytes = vec![
1693			"fd00fc",
1694			"fe0000ffff",
1695			"ff00000000ffffffff",
1696			"fd00",
1697			"feffff",
1698			"ffffffffff",
1699			"fd",
1700			"fe",
1701			"ff",
1702			""
1703		];
1704		for i in 0..=9 {
1705			let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(err_bytes[i]).unwrap());
1706			if i < 3 {
1707				assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1708			} else {
1709				assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));
1710			}
1711		}
1712	}
1713}