1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A very simple serialization framework which is used to serialize/deserialize messages as well
11 //! as [`ChannelManager`]s and [`ChannelMonitor`]s.
13 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
14 //! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
16 use crate::prelude::*;
17 use crate::io::{self, Read, Seek, Write};
18 use crate::io_extras::{copy, sink};
20 use crate::sync::{Mutex, RwLock};
24 use alloc::collections::BTreeMap;
26 use bitcoin::secp256k1::{PublicKey, SecretKey};
27 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE, SCHNORR_SIGNATURE_SIZE};
28 use bitcoin::secp256k1::ecdsa;
29 use bitcoin::secp256k1::schnorr;
30 use bitcoin::blockdata::constants::ChainHash;
31 use bitcoin::blockdata::script::{self, ScriptBuf};
32 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
33 use bitcoin::{consensus, Witness};
34 use bitcoin::consensus::Encodable;
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hash_types::{Txid, BlockHash};
37 use core::time::Duration;
38 use crate::chain::ClaimId;
39 use crate::ln::msgs::DecodeError;
41 use crate::ln::msgs::PartialSignatureWithNonce;
42 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
44 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
45 use crate::util::string::UntrustedString;
47 /// serialization buffer size
48 pub const MAX_BUF_SIZE: usize = 64 * 1024;
50 /// A simplified version of [`std::io::Write`] that exists largely for backwards compatibility.
51 /// An impl is provided for any type that also impls [`std::io::Write`].
53 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
55 /// Writes the given buf out. See std::io::Write::write_all for more
56 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
59 impl<W: Write> Writer for W {
61 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
62 <Self as io::Write>::write_all(self, buf)
66 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
67 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
69 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
73 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
74 self.0.write_all(buf)?;
78 fn flush(&mut self) -> Result<(), io::Error> {
83 pub(crate) struct VecWriter(pub Vec<u8>);
84 impl Writer for VecWriter {
86 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
87 self.0.extend_from_slice(buf);
92 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
93 /// of some data when serialized but don't yet need the full data.
95 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
96 pub struct LengthCalculatingWriter(pub usize);
97 impl Writer for LengthCalculatingWriter {
99 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
105 /// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
106 /// forward to ensure we always consume exactly the fixed length specified.
108 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
109 pub struct FixedLengthReader<'a, R: Read> {
114 impl<'a, R: Read> FixedLengthReader<'a, R> {
115 /// Returns a new [`FixedLengthReader`].
116 pub fn new(read: &'a mut R, total_bytes: u64) -> Self {
117 Self { read, bytes_read: 0, total_bytes }
120 /// Returns whether some bytes are remaining or not.
122 pub fn bytes_remain(&mut self) -> bool {
123 self.bytes_read != self.total_bytes
126 /// Consumes the remaining bytes.
128 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
129 copy(self, &mut sink()).unwrap();
130 if self.bytes_read != self.total_bytes {
131 Err(DecodeError::ShortRead)
137 impl<'a, R: Read> Read for FixedLengthReader<'a, R> {
139 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
140 if self.total_bytes == self.bytes_read {
143 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
144 match self.read.read(&mut dest[0..(read_len as usize)]) {
146 self.bytes_read += v as u64;
155 impl<'a, R: Read> LengthRead for FixedLengthReader<'a, R> {
157 fn total_bytes(&self) -> u64 {
162 /// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
163 /// between "EOF reached before we started" and "EOF reached mid-read".
165 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
166 pub struct ReadTrackingReader<R: Read> {
168 /// Returns whether we have read from this reader or not yet.
171 impl<R: Read> ReadTrackingReader<R> {
172 /// Returns a new [`ReadTrackingReader`].
173 pub fn new(read: R) -> Self {
174 Self { read, have_read: false }
177 impl<R: Read> Read for ReadTrackingReader<R> {
179 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
180 match self.read.read(dest) {
183 self.have_read = true;
191 /// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
193 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
194 pub trait Writeable {
195 /// Writes `self` out to the given [`Writer`].
196 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
198 /// Writes `self` out to a `Vec<u8>`.
199 fn encode(&self) -> Vec<u8> {
200 let len = self.serialized_length();
201 let mut msg = VecWriter(Vec::with_capacity(len));
202 self.write(&mut msg).unwrap();
203 // Note that objects with interior mutability may change size between when we called
204 // serialized_length and when we called write. That's okay, but shouldn't happen during
205 // testing as most of our tests are not threaded.
207 debug_assert_eq!(len, msg.0.len());
211 /// Writes `self` out to a `Vec<u8>`.
213 fn encode_with_len(&self) -> Vec<u8> {
214 let mut msg = VecWriter(Vec::new());
215 0u16.write(&mut msg).unwrap();
216 self.write(&mut msg).unwrap();
217 let len = msg.0.len();
218 debug_assert_eq!(len - 2, self.serialized_length());
219 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
223 /// Gets the length of this object after it has been serialized. This can be overridden to
224 /// optimize cases where we prepend an object with its length.
225 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
227 fn serialized_length(&self) -> usize {
228 let mut len_calc = LengthCalculatingWriter(0);
229 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
234 impl<'a, T: Writeable> Writeable for &'a T {
235 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
238 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
240 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
244 /// Reads a `Self` in from the given [`Read`].
245 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
248 /// A trait that various LDK types implement allowing them to be read in from a
249 /// [`Read`]` + `[`Seek`].
250 pub(crate) trait SeekReadable where Self: Sized {
251 /// Reads a `Self` in from the given [`Read`].
252 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
255 /// A trait that various higher-level LDK types implement allowing them to be read in
256 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
258 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
259 pub trait ReadableArgs<P>
262 /// Reads a `Self` in from the given [`Read`].
263 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
266 /// A [`std::io::Read`] that also provides the total bytes available to be read.
267 pub(crate) trait LengthRead: Read {
268 /// The total number of bytes available to be read.
269 fn total_bytes(&self) -> u64;
272 /// A trait that various higher-level LDK types implement allowing them to be read in
273 /// from a Read given some additional set of arguments which is required to deserialize, requiring
274 /// the implementer to provide the total length of the read.
275 pub(crate) trait LengthReadableArgs<P> where Self: Sized
277 /// Reads a `Self` in from the given [`LengthRead`].
278 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
281 /// A trait that various higher-level LDK types implement allowing them to be read in
282 /// from a [`Read`], requiring the implementer to provide the total length of the read.
283 pub(crate) trait LengthReadable where Self: Sized
285 /// Reads a `Self` in from the given [`LengthRead`].
286 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
289 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
291 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
292 pub trait MaybeReadable
295 /// Reads a `Self` in from the given [`Read`].
296 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
299 impl<T: Readable> MaybeReadable for T {
301 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
302 Ok(Some(Readable::read(reader)?))
306 /// Wrapper to read a required (non-optional) TLV record.
308 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
309 pub struct RequiredWrapper<T>(pub Option<T>);
310 impl<T: Readable> Readable for RequiredWrapper<T> {
312 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
313 Ok(Self(Some(Readable::read(reader)?)))
316 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
318 fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
319 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
322 /// When handling `default_values`, we want to map the default-value T directly
323 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
324 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
325 impl<T> From<T> for RequiredWrapper<T> {
326 fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
329 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
330 /// backwards compat.
332 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
333 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
334 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
336 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
337 let tlv = MaybeReadable::read(reader)?;
338 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
343 pub(crate) struct U48(pub u64);
344 impl Writeable for U48 {
346 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
347 writer.write_all(&be48_to_array(self.0))
350 impl Readable for U48 {
352 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
353 let mut buf = [0; 6];
354 reader.read_exact(&mut buf)?;
355 Ok(U48(slice_to_be48(&buf)))
359 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
360 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
362 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
363 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
364 /// you're looking for an example of a variable-length integer to use for your own project, move
365 /// along, this is a rather poor design.
366 #[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
367 pub struct BigSize(pub u64);
368 impl Writeable for BigSize {
370 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
373 (self.0 as u8).write(writer)
376 0xFDu8.write(writer)?;
377 (self.0 as u16).write(writer)
379 0x10000..=0xFFFFFFFF => {
380 0xFEu8.write(writer)?;
381 (self.0 as u32).write(writer)
384 0xFFu8.write(writer)?;
385 (self.0 as u64).write(writer)
390 impl Readable for BigSize {
392 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
393 let n: u8 = Readable::read(reader)?;
396 let x: u64 = Readable::read(reader)?;
398 Err(DecodeError::InvalidValue)
404 let x: u32 = Readable::read(reader)?;
406 Err(DecodeError::InvalidValue)
408 Ok(BigSize(x as u64))
412 let x: u16 = Readable::read(reader)?;
414 Err(DecodeError::InvalidValue)
416 Ok(BigSize(x as u64))
419 n => Ok(BigSize(n as u64))
424 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
425 /// primarily targets that, we must as well. However, because we may serialize objects that have
426 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
427 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
428 /// "read eight more bytes".
430 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
431 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
432 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
433 struct CollectionLength(pub u64);
434 impl Writeable for CollectionLength {
436 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
438 (self.0 as u16).write(writer)
440 0xffffu16.write(writer)?;
441 (self.0 - 0xffff).write(writer)
446 impl Readable for CollectionLength {
448 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
449 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
451 val = <u64 as Readable>::read(r)?
452 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
454 Ok(CollectionLength(val))
458 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
459 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
460 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
461 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
462 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
464 macro_rules! impl_writeable_primitive {
465 ($val_type:ty, $len: expr) => {
466 impl Writeable for $val_type {
468 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
469 writer.write_all(&self.to_be_bytes())
472 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
474 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
475 // Skip any full leading 0 bytes when writing (in BE):
476 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
479 impl Readable for $val_type {
481 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
482 let mut buf = [0; $len];
483 reader.read_exact(&mut buf)?;
484 Ok(<$val_type>::from_be_bytes(buf))
487 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
489 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
490 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
491 // the high bytes being dropped. To do so, we start reading into the middle of buf
492 // and then convert the appropriate number of bytes with extra high bytes out of
494 let mut buf = [0; $len*2];
495 let mut read_len = reader.read(&mut buf[$len..])?;
496 let mut total_read_len = read_len;
497 while read_len != 0 && total_read_len != $len {
498 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
499 total_read_len += read_len;
501 if total_read_len == 0 || buf[$len] != 0 {
502 let first_byte = $len - ($len - total_read_len);
503 let mut bytes = [0; $len];
504 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
505 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
507 // If the encoding had extra zero bytes, return a failure even though we know
508 // what they meant (as the TLV test vectors require this)
509 Err(DecodeError::InvalidValue)
513 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
514 fn from(val: $val_type) -> Self { Self(val) }
519 impl_writeable_primitive!(u128, 16);
520 impl_writeable_primitive!(u64, 8);
521 impl_writeable_primitive!(u32, 4);
522 impl_writeable_primitive!(u16, 2);
523 impl_writeable_primitive!(i64, 8);
524 impl_writeable_primitive!(i32, 4);
525 impl_writeable_primitive!(i16, 2);
526 impl_writeable_primitive!(i8, 1);
528 impl Writeable for u8 {
530 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
531 writer.write_all(&[*self])
534 impl Readable for u8 {
536 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
537 let mut buf = [0; 1];
538 reader.read_exact(&mut buf)?;
543 impl Writeable for bool {
545 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
546 writer.write_all(&[if *self {1} else {0}])
549 impl Readable for bool {
551 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
552 let mut buf = [0; 1];
553 reader.read_exact(&mut buf)?;
554 if buf[0] != 0 && buf[0] != 1 {
555 return Err(DecodeError::InvalidValue);
561 macro_rules! impl_array {
562 ($size:expr, $ty: ty) => (
563 impl Writeable for [$ty; $size] {
565 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
566 let mut out = [0; $size * core::mem::size_of::<$ty>()];
567 for (idx, v) in self.iter().enumerate() {
568 let startpos = idx * core::mem::size_of::<$ty>();
569 out[startpos..startpos + core::mem::size_of::<$ty>()].copy_from_slice(&v.to_be_bytes());
575 impl Readable for [$ty; $size] {
577 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
578 let mut buf = [0u8; $size * core::mem::size_of::<$ty>()];
579 r.read_exact(&mut buf)?;
580 let mut res = [0; $size];
581 for (idx, v) in res.iter_mut().enumerate() {
582 let startpos = idx * core::mem::size_of::<$ty>();
583 let mut arr = [0; core::mem::size_of::<$ty>()];
584 arr.copy_from_slice(&buf[startpos..startpos + core::mem::size_of::<$ty>()]);
585 *v = <$ty>::from_be_bytes(arr);
593 impl_array!(3, u8); // for rgb, ISO 4712 code
594 impl_array!(4, u8); // for IPv4
595 impl_array!(12, u8); // for OnionV2
596 impl_array!(16, u8); // for IPv6
597 impl_array!(32, u8); // for channel id & hmac
598 impl_array!(PUBLIC_KEY_SIZE, u8); // for PublicKey
599 impl_array!(64, u8); // for ecdsa::Signature and schnorr::Signature
600 impl_array!(66, u8); // for MuSig2 nonces
601 impl_array!(1300, u8); // for OnionPacket.hop_data
604 impl_array!(32, u16);
606 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
607 /// Used to prevent encoding the length twice.
609 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
610 pub struct WithoutLength<T>(pub T);
612 impl Writeable for WithoutLength<&String> {
614 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
615 w.write_all(self.0.as_bytes())
618 impl Readable for WithoutLength<String> {
620 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
621 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
622 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
625 impl<'a> From<&'a String> for WithoutLength<&'a String> {
626 fn from(s: &'a String) -> Self { Self(s) }
630 impl Writeable for WithoutLength<&UntrustedString> {
632 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
633 WithoutLength(&self.0.0).write(w)
636 impl Readable for WithoutLength<UntrustedString> {
638 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
639 let s: WithoutLength<String> = Readable::read(r)?;
640 Ok(Self(UntrustedString(s.0)))
644 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
646 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
647 for ref v in self.0.iter() {
654 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
656 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
657 let mut values = Vec::new();
659 let mut track_read = ReadTrackingReader::new(&mut reader);
660 match MaybeReadable::read(&mut track_read) {
661 Ok(Some(v)) => { values.push(v); },
663 // If we failed to read any bytes at all, we reached the end of our TLV
664 // stream and have simply exhausted all entries.
665 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
666 Err(e) => return Err(e),
672 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
673 fn from(v: &'a Vec<T>) -> Self { Self(v) }
676 impl Writeable for WithoutLength<&ScriptBuf> {
678 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
679 writer.write_all(self.0.as_bytes())
683 impl Readable for WithoutLength<ScriptBuf> {
685 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
686 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
687 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
692 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
694 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
696 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
697 for ref v in self.0.clone() {
705 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
706 fn eq(&self, other: &Self) -> bool {
707 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
711 macro_rules! impl_for_map {
712 ($ty: ident, $keybound: ident, $constr: expr) => {
713 impl<K, V> Writeable for $ty<K, V>
714 where K: Writeable + Eq + $keybound, V: Writeable
717 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
718 CollectionLength(self.len() as u64).write(w)?;
719 for (key, value) in self.iter() {
727 impl<K, V> Readable for $ty<K, V>
728 where K: Readable + Eq + $keybound, V: MaybeReadable
731 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
732 let len: CollectionLength = Readable::read(r)?;
733 let mut ret = $constr(len.0 as usize);
736 let v_opt = V::read(r)?;
737 if let Some(v) = v_opt {
738 if ret.insert(k, v).is_some() {
739 return Err(DecodeError::InvalidValue);
749 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
750 impl_for_map!(HashMap, Hash, |len| hash_map_with_capacity(len));
753 impl<T> Writeable for HashSet<T>
754 where T: Writeable + Eq + Hash
757 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
758 CollectionLength(self.len() as u64).write(w)?;
759 for item in self.iter() {
766 impl<T> Readable for HashSet<T>
767 where T: Readable + Eq + Hash
770 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
771 let len: CollectionLength = Readable::read(r)?;
772 let mut ret = hash_set_with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
774 if !ret.insert(T::read(r)?) {
775 return Err(DecodeError::InvalidValue)
783 macro_rules! impl_writeable_for_vec {
784 ($ty: ty $(, $name: ident)*) => {
785 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
787 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
788 CollectionLength(self.len() as u64).write(w)?;
789 for elem in self.iter() {
797 macro_rules! impl_readable_for_vec {
798 ($ty: ty $(, $name: ident)*) => {
799 impl<$($name : Readable),*> Readable for Vec<$ty> {
801 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
802 let len: CollectionLength = Readable::read(r)?;
803 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
805 if let Some(val) = MaybeReadable::read(r)? {
814 macro_rules! impl_for_vec {
815 ($ty: ty $(, $name: ident)*) => {
816 impl_writeable_for_vec!($ty $(, $name)*);
817 impl_readable_for_vec!($ty $(, $name)*);
821 // Alternatives to impl_writeable_for_vec/impl_readable_for_vec that add a length prefix to each
822 // element in the Vec. Intended to be used when elements have variable lengths.
823 macro_rules! impl_writeable_for_vec_with_element_length_prefix {
824 ($ty: ty $(, $name: ident)*) => {
825 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
827 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
828 CollectionLength(self.len() as u64).write(w)?;
829 for elem in self.iter() {
830 CollectionLength(elem.serialized_length() as u64).write(w)?;
838 macro_rules! impl_readable_for_vec_with_element_length_prefix {
839 ($ty: ty $(, $name: ident)*) => {
840 impl<$($name : Readable),*> Readable for Vec<$ty> {
842 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
843 let len: CollectionLength = Readable::read(r)?;
844 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
846 let elem_len: CollectionLength = Readable::read(r)?;
847 let mut elem_reader = FixedLengthReader::new(r, elem_len.0);
848 if let Some(val) = MaybeReadable::read(&mut elem_reader)? {
857 macro_rules! impl_for_vec_with_element_length_prefix {
858 ($ty: ty $(, $name: ident)*) => {
859 impl_writeable_for_vec_with_element_length_prefix!($ty $(, $name)*);
860 impl_readable_for_vec_with_element_length_prefix!($ty $(, $name)*);
864 impl Writeable for Vec<u8> {
866 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
867 CollectionLength(self.len() as u64).write(w)?;
872 impl Readable for Vec<u8> {
874 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
875 let mut len: CollectionLength = Readable::read(r)?;
876 let mut ret = Vec::new();
878 let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
879 let readstart = ret.len();
880 ret.resize(readstart + readamt, 0);
881 r.read_exact(&mut ret[readstart..])?;
882 len.0 -= readamt as u64;
888 impl_for_vec!(ecdsa::Signature);
889 impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
890 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
891 impl_for_vec!(crate::ln::msgs::SocketAddress);
892 impl_for_vec!((A, B), A, B);
893 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
894 impl_readable_for_vec!(crate::routing::router::BlindedTail);
895 impl_for_vec_with_element_length_prefix!(crate::ln::msgs::UpdateAddHTLC);
896 impl_writeable_for_vec_with_element_length_prefix!(&crate::ln::msgs::UpdateAddHTLC);
898 impl Writeable for Vec<Witness> {
900 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
901 (self.len() as u16).write(w)?;
902 for witness in self {
903 (witness.serialized_len() as u16).write(w)?;
910 impl Readable for Vec<Witness> {
912 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
913 let num_witnesses = <u16 as Readable>::read(r)? as usize;
914 let mut witnesses = Vec::with_capacity(num_witnesses);
915 for _ in 0..num_witnesses {
916 // Even though the length of each witness can be inferred in its consensus-encoded form,
917 // the spec includes a length prefix so that implementations don't have to deserialize
918 // each initially. We do that here anyway as in general we'll need to be able to make
919 // assertions on some properties of the witnesses when receiving a message providing a list
920 // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
921 let witness_len = <u16 as Readable>::read(r)? as usize;
922 let witness = <Witness as Readable>::read(r)?;
923 if witness.serialized_len() != witness_len {
924 return Err(DecodeError::BadLengthDescriptor);
926 witnesses.push(witness);
932 impl Writeable for ScriptBuf {
933 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
934 (self.len() as u16).write(w)?;
935 w.write_all(self.as_bytes())
939 impl Readable for ScriptBuf {
940 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
941 let len = <u16 as Readable>::read(r)? as usize;
942 let mut buf = vec![0; len];
943 r.read_exact(&mut buf)?;
944 Ok(ScriptBuf::from(buf))
948 impl Writeable for PublicKey {
949 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
950 self.serialize().write(w)
953 fn serialized_length(&self) -> usize {
958 impl Readable for PublicKey {
959 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
960 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
961 match PublicKey::from_slice(&buf) {
963 Err(_) => return Err(DecodeError::InvalidValue),
968 impl Writeable for SecretKey {
969 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
970 let mut ser = [0; SECRET_KEY_SIZE];
971 ser.copy_from_slice(&self[..]);
975 fn serialized_length(&self) -> usize {
980 impl Readable for SecretKey {
981 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
982 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
983 match SecretKey::from_slice(&buf) {
985 Err(_) => return Err(DecodeError::InvalidValue),
991 impl Writeable for musig2::types::PublicNonce {
992 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
993 self.serialize().write(w)
998 impl Readable for musig2::types::PublicNonce {
999 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1000 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
1001 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
1006 impl Writeable for PartialSignatureWithNonce {
1007 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1008 self.0.serialize().write(w)?;
1014 impl Readable for PartialSignatureWithNonce {
1015 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1016 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
1017 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
1018 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
1019 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
1023 impl Writeable for Sha256dHash {
1024 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1025 w.write_all(&self[..])
1029 impl Readable for Sha256dHash {
1030 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1031 use bitcoin::hashes::Hash;
1033 let buf: [u8; 32] = Readable::read(r)?;
1034 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
1038 impl Writeable for ecdsa::Signature {
1039 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1040 self.serialize_compact().write(w)
1044 impl Readable for ecdsa::Signature {
1045 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1046 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1047 match ecdsa::Signature::from_compact(&buf) {
1049 Err(_) => return Err(DecodeError::InvalidValue),
1054 impl Writeable for schnorr::Signature {
1055 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1056 self.as_ref().write(w)
1060 impl Readable for schnorr::Signature {
1061 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1062 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1063 match schnorr::Signature::from_slice(&buf) {
1065 Err(_) => return Err(DecodeError::InvalidValue),
1070 impl Writeable for PaymentPreimage {
1071 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1076 impl Readable for PaymentPreimage {
1077 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1078 let buf: [u8; 32] = Readable::read(r)?;
1079 Ok(PaymentPreimage(buf))
1083 impl Writeable for PaymentHash {
1084 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1089 impl Readable for PaymentHash {
1090 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1091 let buf: [u8; 32] = Readable::read(r)?;
1092 Ok(PaymentHash(buf))
1096 impl Writeable for PaymentSecret {
1097 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1102 impl Readable for PaymentSecret {
1103 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1104 let buf: [u8; 32] = Readable::read(r)?;
1105 Ok(PaymentSecret(buf))
1109 impl<T: Writeable> Writeable for Box<T> {
1110 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1111 T::write(&**self, w)
1115 impl<T: Readable> Readable for Box<T> {
1116 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1117 Ok(Box::new(Readable::read(r)?))
1121 impl<T: Writeable> Writeable for Option<T> {
1122 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1124 None => 0u8.write(w)?,
1126 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1134 impl<T: Readable> Readable for Option<T>
1136 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1137 let len: BigSize = Readable::read(r)?;
1141 let mut reader = FixedLengthReader::new(r, len - 1);
1142 Ok(Some(Readable::read(&mut reader)?))
1148 impl Writeable for Txid {
1149 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1150 w.write_all(&self[..])
1154 impl Readable for Txid {
1155 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1156 use bitcoin::hashes::Hash;
1158 let buf: [u8; 32] = Readable::read(r)?;
1159 Ok(Txid::from_slice(&buf[..]).unwrap())
1163 impl Writeable for BlockHash {
1164 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1165 w.write_all(&self[..])
1169 impl Readable for BlockHash {
1170 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1171 use bitcoin::hashes::Hash;
1173 let buf: [u8; 32] = Readable::read(r)?;
1174 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1178 impl Writeable for ChainHash {
1179 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1180 w.write_all(self.as_bytes())
1184 impl Readable for ChainHash {
1185 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1186 let buf: [u8; 32] = Readable::read(r)?;
1187 Ok(ChainHash::from(buf))
1191 impl Writeable for OutPoint {
1192 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1193 self.txid.write(w)?;
1194 self.vout.write(w)?;
1199 impl Readable for OutPoint {
1200 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1201 let txid = Readable::read(r)?;
1202 let vout = Readable::read(r)?;
1210 macro_rules! impl_consensus_ser {
1211 ($bitcoin_type: ty) => {
1212 impl Writeable for $bitcoin_type {
1213 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1214 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1221 impl Readable for $bitcoin_type {
1222 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1223 match consensus::encode::Decodable::consensus_decode(r) {
1225 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1226 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1227 Err(_) => Err(DecodeError::InvalidValue),
1233 impl_consensus_ser!(Transaction);
1234 impl_consensus_ser!(TxOut);
1235 impl_consensus_ser!(Witness);
1237 impl<T: Readable> Readable for Mutex<T> {
1238 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1239 let t: T = Readable::read(r)?;
1243 impl<T: Writeable> Writeable for Mutex<T> {
1244 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1245 self.lock().unwrap().write(w)
1249 impl<T: Readable> Readable for RwLock<T> {
1250 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1251 let t: T = Readable::read(r)?;
1255 impl<T: Writeable> Writeable for RwLock<T> {
1256 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1257 self.read().unwrap().write(w)
1261 impl<A: Readable, B: Readable> Readable for (A, B) {
1262 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1263 let a: A = Readable::read(r)?;
1264 let b: B = Readable::read(r)?;
1268 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1269 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1275 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1276 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1277 let a: A = Readable::read(r)?;
1278 let b: B = Readable::read(r)?;
1279 let c: C = Readable::read(r)?;
1283 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1284 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1291 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1292 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1293 let a: A = Readable::read(r)?;
1294 let b: B = Readable::read(r)?;
1295 let c: C = Readable::read(r)?;
1296 let d: D = Readable::read(r)?;
1300 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1301 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1309 impl Writeable for () {
1310 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1314 impl Readable for () {
1315 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1320 impl Writeable for String {
1322 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1323 CollectionLength(self.len() as u64).write(w)?;
1324 w.write_all(self.as_bytes())
1327 impl Readable for String {
1329 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1330 let v: Vec<u8> = Readable::read(r)?;
1331 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1336 /// Represents a hostname for serialization purposes.
1337 /// Only the character set and length will be validated.
1338 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1339 /// Its length is guaranteed to be representable by a single byte.
1340 /// This serialization is used by [`BOLT 7`] hostnames.
1342 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1343 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
1344 pub struct Hostname(String);
1346 /// Returns the length of the hostname.
1347 pub fn len(&self) -> u8 {
1348 (&self.0).len() as u8
1352 impl core::fmt::Display for Hostname {
1353 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1354 write!(f, "{}", self.0)?;
1358 impl Deref for Hostname {
1359 type Target = String;
1361 fn deref(&self) -> &Self::Target {
1365 impl From<Hostname> for String {
1366 fn from(hostname: Hostname) -> Self {
1370 impl TryFrom<Vec<u8>> for Hostname {
1373 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1374 if let Ok(s) = String::from_utf8(bytes) {
1375 Hostname::try_from(s)
1381 impl TryFrom<String> for Hostname {
1384 fn try_from(s: String) -> Result<Self, Self::Error> {
1385 if s.len() <= 255 && s.chars().all(|c|
1386 c.is_ascii_alphanumeric() ||
1396 impl Writeable for Hostname {
1398 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1399 self.len().write(w)?;
1400 w.write_all(self.as_bytes())
1403 impl Readable for Hostname {
1405 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1406 let len: u8 = Readable::read(r)?;
1407 let mut vec = Vec::with_capacity(len.into());
1408 vec.resize(len.into(), 0);
1409 r.read_exact(&mut vec)?;
1410 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1414 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1415 impl Writeable for Duration {
1417 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1418 self.as_secs().write(w)?;
1419 self.subsec_nanos().write(w)
1422 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1423 impl Readable for Duration {
1425 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1426 let secs = Readable::read(r)?;
1427 let nanos = Readable::read(r)?;
1428 Ok(Duration::new(secs, nanos))
1432 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1433 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1435 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1436 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
1437 pub struct TransactionU16LenLimited(Transaction);
1439 impl TransactionU16LenLimited {
1440 /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1441 /// serialized length is <= u16::MAX.
1442 pub fn new(transaction: Transaction) -> Result<Self, ()> {
1443 if transaction.serialized_length() > (u16::MAX as usize) {
1446 Ok(Self(transaction))
1450 /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1451 pub fn into_transaction(self) -> Transaction {
1455 /// Returns a reference to the contained `Transaction`
1456 pub fn as_transaction(&self) -> &Transaction {
1461 impl Writeable for TransactionU16LenLimited {
1462 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1463 (self.0.serialized_length() as u16).write(w)?;
1468 impl Readable for TransactionU16LenLimited {
1469 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1470 let len = <u16 as Readable>::read(r)?;
1471 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1472 let tx: Transaction = Readable::read(&mut tx_reader)?;
1473 if tx_reader.bytes_remain() {
1474 Err(DecodeError::BadLengthDescriptor)
1481 impl Writeable for ClaimId {
1482 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1483 self.0.write(writer)
1487 impl Readable for ClaimId {
1488 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1489 Ok(Self(Readable::read(reader)?))
1495 use bitcoin::hashes::hex::FromHex;
1496 use bitcoin::secp256k1::ecdsa;
1497 use crate::util::ser::{Readable, Hostname, Writeable};
1498 use crate::prelude::*;
1501 fn hostname_conversion() {
1502 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1504 assert!(Hostname::try_from(String::from("\"")).is_err());
1505 assert!(Hostname::try_from(String::from("$")).is_err());
1506 assert!(Hostname::try_from(String::from("⚡")).is_err());
1507 let mut large_vec = Vec::with_capacity(256);
1508 large_vec.resize(256, b'A');
1509 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1513 fn hostname_serialization() {
1514 let hostname = Hostname::try_from(String::from("test")).unwrap();
1515 let mut buf: Vec<u8> = Vec::new();
1516 hostname.write(&mut buf).unwrap();
1517 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1521 /// Taproot will likely fill legacy signature fields with all 0s.
1522 /// This test ensures that doing so won't break serialization.
1523 fn null_signature_codec() {
1524 let buffer = vec![0u8; 64];
1525 let mut cursor = crate::io::Cursor::new(buffer.clone());
1526 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1527 let serialization = signature.serialize_compact();
1528 assert_eq!(buffer, serialization.to_vec())
1532 fn bigsize_encoding_decoding() {
1533 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1541 "ff0000000100000000",
1542 "ffffffffffffffffff"
1545 let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(bytes[i]).unwrap());
1546 assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1547 let mut stream = super::VecWriter(Vec::new());
1548 super::BigSize(values[i]).write(&mut stream).unwrap();
1549 assert_eq!(stream.0, <Vec<u8>>::from_hex(bytes[i]).unwrap());
1551 let err_bytes = vec![
1554 "ff00000000ffffffff",
1564 let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(err_bytes[i]).unwrap());
1566 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1568 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));