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::amount::Amount;
31 use bitcoin::blockdata::constants::ChainHash;
32 use bitcoin::blockdata::script::{self, ScriptBuf};
33 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
34 use bitcoin::{consensus, Witness};
35 use bitcoin::consensus::Encodable;
36 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
37 use bitcoin::hash_types::{Txid, BlockHash};
38 use core::time::Duration;
39 use crate::chain::ClaimId;
40 use crate::ln::msgs::DecodeError;
42 use crate::ln::msgs::PartialSignatureWithNonce;
43 use crate::ln::types::{PaymentPreimage, PaymentHash, PaymentSecret};
45 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
46 use crate::util::string::UntrustedString;
48 /// serialization buffer size
49 pub const MAX_BUF_SIZE: usize = 64 * 1024;
51 /// A simplified version of [`std::io::Write`] that exists largely for backwards compatibility.
52 /// An impl is provided for any type that also impls [`std::io::Write`].
54 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
56 /// Writes the given buf out. See std::io::Write::write_all for more
57 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
60 impl<W: Write> Writer for W {
62 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
63 <Self as io::Write>::write_all(self, buf)
67 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
68 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
70 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
74 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
75 self.0.write_all(buf)?;
79 fn flush(&mut self) -> Result<(), io::Error> {
84 pub(crate) struct VecWriter(pub Vec<u8>);
85 impl Writer for VecWriter {
87 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
88 self.0.extend_from_slice(buf);
93 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
94 /// of some data when serialized but don't yet need the full data.
96 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
97 pub struct LengthCalculatingWriter(pub usize);
98 impl Writer for LengthCalculatingWriter {
100 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
106 /// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
107 /// forward to ensure we always consume exactly the fixed length specified.
109 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
110 pub struct FixedLengthReader<'a, R: Read> {
115 impl<'a, R: Read> FixedLengthReader<'a, R> {
116 /// Returns a new [`FixedLengthReader`].
117 pub fn new(read: &'a mut R, total_bytes: u64) -> Self {
118 Self { read, bytes_read: 0, total_bytes }
121 /// Returns whether some bytes are remaining or not.
123 pub fn bytes_remain(&mut self) -> bool {
124 self.bytes_read != self.total_bytes
127 /// Consumes the remaining bytes.
129 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
130 copy(self, &mut sink()).unwrap();
131 if self.bytes_read != self.total_bytes {
132 Err(DecodeError::ShortRead)
138 impl<'a, R: Read> Read for FixedLengthReader<'a, R> {
140 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
141 if self.total_bytes == self.bytes_read {
144 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
145 match self.read.read(&mut dest[0..(read_len as usize)]) {
147 self.bytes_read += v as u64;
156 impl<'a, R: Read> LengthRead for FixedLengthReader<'a, R> {
158 fn total_bytes(&self) -> u64 {
163 /// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
164 /// between "EOF reached before we started" and "EOF reached mid-read".
166 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
167 pub struct ReadTrackingReader<R: Read> {
169 /// Returns whether we have read from this reader or not yet.
172 impl<R: Read> ReadTrackingReader<R> {
173 /// Returns a new [`ReadTrackingReader`].
174 pub fn new(read: R) -> Self {
175 Self { read, have_read: false }
178 impl<R: Read> Read for ReadTrackingReader<R> {
180 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
181 match self.read.read(dest) {
184 self.have_read = true;
192 /// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
194 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
195 pub trait Writeable {
196 /// Writes `self` out to the given [`Writer`].
197 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
199 /// Writes `self` out to a `Vec<u8>`.
200 fn encode(&self) -> Vec<u8> {
201 let len = self.serialized_length();
202 let mut msg = VecWriter(Vec::with_capacity(len));
203 self.write(&mut msg).unwrap();
204 // Note that objects with interior mutability may change size between when we called
205 // serialized_length and when we called write. That's okay, but shouldn't happen during
206 // testing as most of our tests are not threaded.
208 debug_assert_eq!(len, msg.0.len());
212 /// Writes `self` out to a `Vec<u8>`.
214 fn encode_with_len(&self) -> Vec<u8> {
215 let mut msg = VecWriter(Vec::new());
216 0u16.write(&mut msg).unwrap();
217 self.write(&mut msg).unwrap();
218 let len = msg.0.len();
219 debug_assert_eq!(len - 2, self.serialized_length());
220 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
224 /// Gets the length of this object after it has been serialized. This can be overridden to
225 /// optimize cases where we prepend an object with its length.
226 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
228 fn serialized_length(&self) -> usize {
229 let mut len_calc = LengthCalculatingWriter(0);
230 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
235 impl<'a, T: Writeable> Writeable for &'a T {
236 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
239 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
241 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
245 /// Reads a `Self` in from the given [`Read`].
246 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
249 /// A trait that various LDK types implement allowing them to be read in from a
250 /// [`Read`]` + `[`Seek`].
251 pub(crate) trait SeekReadable where Self: Sized {
252 /// Reads a `Self` in from the given [`Read`].
253 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
256 /// A trait that various higher-level LDK types implement allowing them to be read in
257 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
259 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
260 pub trait ReadableArgs<P>
263 /// Reads a `Self` in from the given [`Read`].
264 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
267 /// A [`std::io::Read`] that also provides the total bytes available to be read.
268 pub(crate) trait LengthRead: Read {
269 /// The total number of bytes available to be read.
270 fn total_bytes(&self) -> u64;
273 /// A trait that various higher-level LDK types implement allowing them to be read in
274 /// from a Read given some additional set of arguments which is required to deserialize, requiring
275 /// the implementer to provide the total length of the read.
276 pub(crate) trait LengthReadableArgs<P> where Self: Sized
278 /// Reads a `Self` in from the given [`LengthRead`].
279 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
282 /// A trait that various higher-level LDK types implement allowing them to be read in
283 /// from a [`Read`], requiring the implementer to provide the total length of the read.
284 pub(crate) trait LengthReadable where Self: Sized
286 /// Reads a `Self` in from the given [`LengthRead`].
287 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
290 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
292 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
293 pub trait MaybeReadable
296 /// Reads a `Self` in from the given [`Read`].
297 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
300 impl<T: Readable> MaybeReadable for T {
302 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
303 Ok(Some(Readable::read(reader)?))
307 /// Wrapper to read a required (non-optional) TLV record.
309 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
310 pub struct RequiredWrapper<T>(pub Option<T>);
311 impl<T: Readable> Readable for RequiredWrapper<T> {
313 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
314 Ok(Self(Some(Readable::read(reader)?)))
317 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
319 fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
320 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
323 /// When handling `default_values`, we want to map the default-value T directly
324 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
325 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
326 impl<T> From<T> for RequiredWrapper<T> {
327 fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
330 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
331 /// backwards compat.
333 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
334 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
335 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
337 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
338 let tlv = MaybeReadable::read(reader)?;
339 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
344 pub(crate) struct U48(pub u64);
345 impl Writeable for U48 {
347 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
348 writer.write_all(&be48_to_array(self.0))
351 impl Readable for U48 {
353 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
354 let mut buf = [0; 6];
355 reader.read_exact(&mut buf)?;
356 Ok(U48(slice_to_be48(&buf)))
360 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
361 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
363 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
364 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
365 /// you're looking for an example of a variable-length integer to use for your own project, move
366 /// along, this is a rather poor design.
367 #[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
368 pub struct BigSize(pub u64);
369 impl Writeable for BigSize {
371 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
374 (self.0 as u8).write(writer)
377 0xFDu8.write(writer)?;
378 (self.0 as u16).write(writer)
380 0x10000..=0xFFFFFFFF => {
381 0xFEu8.write(writer)?;
382 (self.0 as u32).write(writer)
385 0xFFu8.write(writer)?;
386 (self.0 as u64).write(writer)
391 impl Readable for BigSize {
393 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
394 let n: u8 = Readable::read(reader)?;
397 let x: u64 = Readable::read(reader)?;
399 Err(DecodeError::InvalidValue)
405 let x: u32 = Readable::read(reader)?;
407 Err(DecodeError::InvalidValue)
409 Ok(BigSize(x as u64))
413 let x: u16 = Readable::read(reader)?;
415 Err(DecodeError::InvalidValue)
417 Ok(BigSize(x as u64))
420 n => Ok(BigSize(n as u64))
425 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
426 /// primarily targets that, we must as well. However, because we may serialize objects that have
427 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
428 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
429 /// "read eight more bytes".
431 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
432 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
433 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
434 struct CollectionLength(pub u64);
435 impl Writeable for CollectionLength {
437 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
439 (self.0 as u16).write(writer)
441 0xffffu16.write(writer)?;
442 (self.0 - 0xffff).write(writer)
447 impl Readable for CollectionLength {
449 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
450 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
452 val = <u64 as Readable>::read(r)?
453 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
455 Ok(CollectionLength(val))
459 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
460 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
461 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
462 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
463 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
465 macro_rules! impl_writeable_primitive {
466 ($val_type:ty, $len: expr) => {
467 impl Writeable for $val_type {
469 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
470 writer.write_all(&self.to_be_bytes())
473 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
475 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
476 // Skip any full leading 0 bytes when writing (in BE):
477 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
480 impl Readable for $val_type {
482 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
483 let mut buf = [0; $len];
484 reader.read_exact(&mut buf)?;
485 Ok(<$val_type>::from_be_bytes(buf))
488 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
490 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
491 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
492 // the high bytes being dropped. To do so, we start reading into the middle of buf
493 // and then convert the appropriate number of bytes with extra high bytes out of
495 let mut buf = [0; $len*2];
496 let mut read_len = reader.read(&mut buf[$len..])?;
497 let mut total_read_len = read_len;
498 while read_len != 0 && total_read_len != $len {
499 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
500 total_read_len += read_len;
502 if total_read_len == 0 || buf[$len] != 0 {
503 let first_byte = $len - ($len - total_read_len);
504 let mut bytes = [0; $len];
505 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
506 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
508 // If the encoding had extra zero bytes, return a failure even though we know
509 // what they meant (as the TLV test vectors require this)
510 Err(DecodeError::InvalidValue)
514 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
515 fn from(val: $val_type) -> Self { Self(val) }
520 impl_writeable_primitive!(u128, 16);
521 impl_writeable_primitive!(u64, 8);
522 impl_writeable_primitive!(u32, 4);
523 impl_writeable_primitive!(u16, 2);
524 impl_writeable_primitive!(i64, 8);
525 impl_writeable_primitive!(i32, 4);
526 impl_writeable_primitive!(i16, 2);
527 impl_writeable_primitive!(i8, 1);
529 impl Writeable for u8 {
531 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
532 writer.write_all(&[*self])
535 impl Readable for u8 {
537 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
538 let mut buf = [0; 1];
539 reader.read_exact(&mut buf)?;
544 impl Writeable for bool {
546 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
547 writer.write_all(&[if *self {1} else {0}])
550 impl Readable for bool {
552 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
553 let mut buf = [0; 1];
554 reader.read_exact(&mut buf)?;
555 if buf[0] != 0 && buf[0] != 1 {
556 return Err(DecodeError::InvalidValue);
562 macro_rules! impl_array {
563 ($size:expr, $ty: ty) => (
564 impl Writeable for [$ty; $size] {
566 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
567 let mut out = [0; $size * core::mem::size_of::<$ty>()];
568 for (idx, v) in self.iter().enumerate() {
569 let startpos = idx * core::mem::size_of::<$ty>();
570 out[startpos..startpos + core::mem::size_of::<$ty>()].copy_from_slice(&v.to_be_bytes());
576 impl Readable for [$ty; $size] {
578 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
579 let mut buf = [0u8; $size * core::mem::size_of::<$ty>()];
580 r.read_exact(&mut buf)?;
581 let mut res = [0; $size];
582 for (idx, v) in res.iter_mut().enumerate() {
583 let startpos = idx * core::mem::size_of::<$ty>();
584 let mut arr = [0; core::mem::size_of::<$ty>()];
585 arr.copy_from_slice(&buf[startpos..startpos + core::mem::size_of::<$ty>()]);
586 *v = <$ty>::from_be_bytes(arr);
594 impl_array!(3, u8); // for rgb, ISO 4712 code
595 impl_array!(4, u8); // for IPv4
596 impl_array!(12, u8); // for OnionV2
597 impl_array!(16, u8); // for IPv6
598 impl_array!(32, u8); // for channel id & hmac
599 impl_array!(PUBLIC_KEY_SIZE, u8); // for PublicKey
600 impl_array!(64, u8); // for ecdsa::Signature and schnorr::Signature
601 impl_array!(66, u8); // for MuSig2 nonces
602 impl_array!(1300, u8); // for OnionPacket.hop_data
605 impl_array!(32, u16);
607 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
608 /// Used to prevent encoding the length twice.
610 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
611 pub struct WithoutLength<T>(pub T);
613 impl Writeable for WithoutLength<&String> {
615 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
616 w.write_all(self.0.as_bytes())
619 impl Readable for WithoutLength<String> {
621 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
622 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
623 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
626 impl<'a> From<&'a String> for WithoutLength<&'a String> {
627 fn from(s: &'a String) -> Self { Self(s) }
631 impl Writeable for WithoutLength<&UntrustedString> {
633 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
634 WithoutLength(&self.0.0).write(w)
637 impl Readable for WithoutLength<UntrustedString> {
639 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
640 let s: WithoutLength<String> = Readable::read(r)?;
641 Ok(Self(UntrustedString(s.0)))
645 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
647 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
648 for ref v in self.0.iter() {
655 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
657 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
658 let mut values = Vec::new();
660 let mut track_read = ReadTrackingReader::new(&mut reader);
661 match MaybeReadable::read(&mut track_read) {
662 Ok(Some(v)) => { values.push(v); },
664 // If we failed to read any bytes at all, we reached the end of our TLV
665 // stream and have simply exhausted all entries.
666 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
667 Err(e) => return Err(e),
673 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
674 fn from(v: &'a Vec<T>) -> Self { Self(v) }
677 impl Writeable for WithoutLength<&ScriptBuf> {
679 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
680 writer.write_all(self.0.as_bytes())
684 impl Readable for WithoutLength<ScriptBuf> {
686 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
687 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
688 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
693 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
695 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
697 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
698 for ref v in self.0.clone() {
706 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
707 fn eq(&self, other: &Self) -> bool {
708 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
712 macro_rules! impl_for_map {
713 ($ty: ident, $keybound: ident, $constr: expr) => {
714 impl<K, V> Writeable for $ty<K, V>
715 where K: Writeable + Eq + $keybound, V: Writeable
718 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
719 CollectionLength(self.len() as u64).write(w)?;
720 for (key, value) in self.iter() {
728 impl<K, V> Readable for $ty<K, V>
729 where K: Readable + Eq + $keybound, V: MaybeReadable
732 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
733 let len: CollectionLength = Readable::read(r)?;
734 let mut ret = $constr(len.0 as usize);
737 let v_opt = V::read(r)?;
738 if let Some(v) = v_opt {
739 if ret.insert(k, v).is_some() {
740 return Err(DecodeError::InvalidValue);
750 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
751 impl_for_map!(HashMap, Hash, |len| hash_map_with_capacity(len));
754 impl<T> Writeable for HashSet<T>
755 where T: Writeable + Eq + Hash
758 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
759 CollectionLength(self.len() as u64).write(w)?;
760 for item in self.iter() {
767 impl<T> Readable for HashSet<T>
768 where T: Readable + Eq + Hash
771 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
772 let len: CollectionLength = Readable::read(r)?;
773 let mut ret = hash_set_with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
775 if !ret.insert(T::read(r)?) {
776 return Err(DecodeError::InvalidValue)
784 macro_rules! impl_writeable_for_vec {
785 ($ty: ty $(, $name: ident)*) => {
786 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
788 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
789 CollectionLength(self.len() as u64).write(w)?;
790 for elem in self.iter() {
798 macro_rules! impl_readable_for_vec {
799 ($ty: ty $(, $name: ident)*) => {
800 impl<$($name : Readable),*> Readable for Vec<$ty> {
802 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
803 let len: CollectionLength = Readable::read(r)?;
804 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
806 if let Some(val) = MaybeReadable::read(r)? {
815 macro_rules! impl_for_vec {
816 ($ty: ty $(, $name: ident)*) => {
817 impl_writeable_for_vec!($ty $(, $name)*);
818 impl_readable_for_vec!($ty $(, $name)*);
822 // Alternatives to impl_writeable_for_vec/impl_readable_for_vec that add a length prefix to each
823 // element in the Vec. Intended to be used when elements have variable lengths.
824 macro_rules! impl_writeable_for_vec_with_element_length_prefix {
825 ($ty: ty $(, $name: ident)*) => {
826 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
828 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
829 CollectionLength(self.len() as u64).write(w)?;
830 for elem in self.iter() {
831 CollectionLength(elem.serialized_length() as u64).write(w)?;
839 macro_rules! impl_readable_for_vec_with_element_length_prefix {
840 ($ty: ty $(, $name: ident)*) => {
841 impl<$($name : Readable),*> Readable for Vec<$ty> {
843 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
844 let len: CollectionLength = Readable::read(r)?;
845 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
847 let elem_len: CollectionLength = Readable::read(r)?;
848 let mut elem_reader = FixedLengthReader::new(r, elem_len.0);
849 if let Some(val) = MaybeReadable::read(&mut elem_reader)? {
858 macro_rules! impl_for_vec_with_element_length_prefix {
859 ($ty: ty $(, $name: ident)*) => {
860 impl_writeable_for_vec_with_element_length_prefix!($ty $(, $name)*);
861 impl_readable_for_vec_with_element_length_prefix!($ty $(, $name)*);
865 impl Writeable for Vec<u8> {
867 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
868 CollectionLength(self.len() as u64).write(w)?;
873 impl Readable for Vec<u8> {
875 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
876 let mut len: CollectionLength = Readable::read(r)?;
877 let mut ret = Vec::new();
879 let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
880 let readstart = ret.len();
881 ret.resize(readstart + readamt, 0);
882 r.read_exact(&mut ret[readstart..])?;
883 len.0 -= readamt as u64;
889 impl_for_vec!(ecdsa::Signature);
890 impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
891 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
892 impl_for_vec!(crate::ln::msgs::SocketAddress);
893 impl_for_vec!((A, B), A, B);
894 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
895 impl_readable_for_vec!(crate::routing::router::BlindedTail);
896 impl_for_vec_with_element_length_prefix!(crate::ln::msgs::UpdateAddHTLC);
897 impl_writeable_for_vec_with_element_length_prefix!(&crate::ln::msgs::UpdateAddHTLC);
899 impl Writeable for Vec<Witness> {
901 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
902 (self.len() as u16).write(w)?;
903 for witness in self {
904 (witness.size() as u16).write(w)?;
911 impl Readable for Vec<Witness> {
913 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
914 let num_witnesses = <u16 as Readable>::read(r)? as usize;
915 let mut witnesses = Vec::with_capacity(num_witnesses);
916 for _ in 0..num_witnesses {
917 // Even though the length of each witness can be inferred in its consensus-encoded form,
918 // the spec includes a length prefix so that implementations don't have to deserialize
919 // each initially. We do that here anyway as in general we'll need to be able to make
920 // assertions on some properties of the witnesses when receiving a message providing a list
921 // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
922 let witness_len = <u16 as Readable>::read(r)? as usize;
923 let witness = <Witness as Readable>::read(r)?;
924 if witness.size() != witness_len {
925 return Err(DecodeError::BadLengthDescriptor);
927 witnesses.push(witness);
933 impl Writeable for ScriptBuf {
934 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
935 (self.len() as u16).write(w)?;
936 w.write_all(self.as_bytes())
940 impl Readable for ScriptBuf {
941 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
942 let len = <u16 as Readable>::read(r)? as usize;
943 let mut buf = vec![0; len];
944 r.read_exact(&mut buf)?;
945 Ok(ScriptBuf::from(buf))
949 impl Writeable for PublicKey {
950 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
951 self.serialize().write(w)
954 fn serialized_length(&self) -> usize {
959 impl Readable for PublicKey {
960 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
961 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
962 match PublicKey::from_slice(&buf) {
964 Err(_) => return Err(DecodeError::InvalidValue),
969 impl Writeable for SecretKey {
970 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
971 let mut ser = [0; SECRET_KEY_SIZE];
972 ser.copy_from_slice(&self[..]);
976 fn serialized_length(&self) -> usize {
981 impl Readable for SecretKey {
982 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
983 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
984 match SecretKey::from_slice(&buf) {
986 Err(_) => return Err(DecodeError::InvalidValue),
992 impl Writeable for musig2::types::PublicNonce {
993 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
994 self.serialize().write(w)
999 impl Readable for musig2::types::PublicNonce {
1000 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1001 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
1002 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
1007 impl Writeable for PartialSignatureWithNonce {
1008 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1009 self.0.serialize().write(w)?;
1015 impl Readable for PartialSignatureWithNonce {
1016 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1017 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
1018 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
1019 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
1020 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
1024 impl Writeable for Sha256dHash {
1025 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1026 w.write_all(&self[..])
1030 impl Readable for Sha256dHash {
1031 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1032 use bitcoin::hashes::Hash;
1034 let buf: [u8; 32] = Readable::read(r)?;
1035 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
1039 impl Writeable for ecdsa::Signature {
1040 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1041 self.serialize_compact().write(w)
1045 impl Readable for ecdsa::Signature {
1046 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1047 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1048 match ecdsa::Signature::from_compact(&buf) {
1050 Err(_) => return Err(DecodeError::InvalidValue),
1055 impl Writeable for schnorr::Signature {
1056 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1057 self.as_ref().write(w)
1061 impl Readable for schnorr::Signature {
1062 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1063 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1064 match schnorr::Signature::from_slice(&buf) {
1066 Err(_) => return Err(DecodeError::InvalidValue),
1071 impl Writeable for PaymentPreimage {
1072 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1077 impl Readable for PaymentPreimage {
1078 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1079 let buf: [u8; 32] = Readable::read(r)?;
1080 Ok(PaymentPreimage(buf))
1084 impl Writeable for PaymentHash {
1085 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1090 impl Readable for PaymentHash {
1091 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1092 let buf: [u8; 32] = Readable::read(r)?;
1093 Ok(PaymentHash(buf))
1097 impl Writeable for PaymentSecret {
1098 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1103 impl Readable for PaymentSecret {
1104 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1105 let buf: [u8; 32] = Readable::read(r)?;
1106 Ok(PaymentSecret(buf))
1110 impl<T: Writeable> Writeable for Box<T> {
1111 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1112 T::write(&**self, w)
1116 impl<T: Readable> Readable for Box<T> {
1117 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1118 Ok(Box::new(Readable::read(r)?))
1122 impl<T: Writeable> Writeable for Option<T> {
1123 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1125 None => 0u8.write(w)?,
1127 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1135 impl<T: Readable> Readable for Option<T>
1137 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1138 let len: BigSize = Readable::read(r)?;
1142 let mut reader = FixedLengthReader::new(r, len - 1);
1143 Ok(Some(Readable::read(&mut reader)?))
1149 impl Writeable for Amount {
1150 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1151 self.to_sat().write(w)
1156 impl Readable for Amount {
1157 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1158 let amount: u64 = Readable::read(r)?;
1159 Ok(Amount::from_sat(amount))
1163 impl Writeable for Txid {
1164 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1165 w.write_all(&self[..])
1169 impl Readable for Txid {
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(Txid::from_slice(&buf[..]).unwrap())
1178 impl Writeable for BlockHash {
1179 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1180 w.write_all(&self[..])
1184 impl Readable for BlockHash {
1185 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1186 use bitcoin::hashes::Hash;
1188 let buf: [u8; 32] = Readable::read(r)?;
1189 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1193 impl Writeable for ChainHash {
1194 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1195 w.write_all(self.as_bytes())
1199 impl Readable for ChainHash {
1200 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1201 let buf: [u8; 32] = Readable::read(r)?;
1202 Ok(ChainHash::from(buf))
1206 impl Writeable for OutPoint {
1207 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1208 self.txid.write(w)?;
1209 self.vout.write(w)?;
1214 impl Readable for OutPoint {
1215 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1216 let txid = Readable::read(r)?;
1217 let vout = Readable::read(r)?;
1225 macro_rules! impl_consensus_ser {
1226 ($bitcoin_type: ty) => {
1227 impl Writeable for $bitcoin_type {
1228 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1229 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1236 impl Readable for $bitcoin_type {
1237 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1238 match consensus::encode::Decodable::consensus_decode(r) {
1240 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1241 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1242 Err(_) => Err(DecodeError::InvalidValue),
1248 impl_consensus_ser!(Transaction);
1249 impl_consensus_ser!(TxOut);
1250 impl_consensus_ser!(Witness);
1252 impl<T: Readable> Readable for Mutex<T> {
1253 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1254 let t: T = Readable::read(r)?;
1258 impl<T: Writeable> Writeable for Mutex<T> {
1259 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1260 self.lock().unwrap().write(w)
1264 impl<T: Readable> Readable for RwLock<T> {
1265 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1266 let t: T = Readable::read(r)?;
1270 impl<T: Writeable> Writeable for RwLock<T> {
1271 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1272 self.read().unwrap().write(w)
1276 impl<A: Readable, B: Readable> Readable for (A, B) {
1277 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1278 let a: A = Readable::read(r)?;
1279 let b: B = Readable::read(r)?;
1283 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1284 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1290 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1291 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1292 let a: A = Readable::read(r)?;
1293 let b: B = Readable::read(r)?;
1294 let c: C = Readable::read(r)?;
1298 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1299 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1306 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1307 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1308 let a: A = Readable::read(r)?;
1309 let b: B = Readable::read(r)?;
1310 let c: C = Readable::read(r)?;
1311 let d: D = Readable::read(r)?;
1315 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1316 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1324 impl Writeable for () {
1325 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1329 impl Readable for () {
1330 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1335 impl Writeable for String {
1337 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1338 CollectionLength(self.len() as u64).write(w)?;
1339 w.write_all(self.as_bytes())
1342 impl Readable for String {
1344 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1345 let v: Vec<u8> = Readable::read(r)?;
1346 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1351 /// Represents a hostname for serialization purposes.
1352 /// Only the character set and length will be validated.
1353 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1354 /// Its length is guaranteed to be representable by a single byte.
1355 /// This serialization is used by [`BOLT 7`] hostnames.
1357 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1358 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
1359 pub struct Hostname(String);
1361 /// Returns the length of the hostname.
1362 pub fn len(&self) -> u8 {
1363 (&self.0).len() as u8
1367 impl core::fmt::Display for Hostname {
1368 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1369 write!(f, "{}", self.0)?;
1373 impl Deref for Hostname {
1374 type Target = String;
1376 fn deref(&self) -> &Self::Target {
1380 impl From<Hostname> for String {
1381 fn from(hostname: Hostname) -> Self {
1385 impl TryFrom<Vec<u8>> for Hostname {
1388 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1389 if let Ok(s) = String::from_utf8(bytes) {
1390 Hostname::try_from(s)
1396 impl TryFrom<String> for Hostname {
1399 fn try_from(s: String) -> Result<Self, Self::Error> {
1400 if s.len() <= 255 && s.chars().all(|c|
1401 c.is_ascii_alphanumeric() ||
1411 impl Writeable for Hostname {
1413 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1414 self.len().write(w)?;
1415 w.write_all(self.as_bytes())
1418 impl Readable for Hostname {
1420 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1421 let len: u8 = Readable::read(r)?;
1422 let mut vec = Vec::with_capacity(len.into());
1423 vec.resize(len.into(), 0);
1424 r.read_exact(&mut vec)?;
1425 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1429 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1430 impl Writeable for Duration {
1432 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1433 self.as_secs().write(w)?;
1434 self.subsec_nanos().write(w)
1437 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1438 impl Readable for Duration {
1440 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1441 let secs = Readable::read(r)?;
1442 let nanos = Readable::read(r)?;
1443 Ok(Duration::new(secs, nanos))
1447 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1448 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1450 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1451 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
1452 pub struct TransactionU16LenLimited(Transaction);
1454 impl TransactionU16LenLimited {
1455 /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1456 /// serialized length is <= u16::MAX.
1457 pub fn new(transaction: Transaction) -> Result<Self, ()> {
1458 if transaction.serialized_length() > (u16::MAX as usize) {
1461 Ok(Self(transaction))
1465 /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1466 pub fn into_transaction(self) -> Transaction {
1470 /// Returns a reference to the contained `Transaction`
1471 pub fn as_transaction(&self) -> &Transaction {
1476 impl Writeable for TransactionU16LenLimited {
1477 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1478 (self.0.serialized_length() as u16).write(w)?;
1483 impl Readable for TransactionU16LenLimited {
1484 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1485 let len = <u16 as Readable>::read(r)?;
1486 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1487 let tx: Transaction = Readable::read(&mut tx_reader)?;
1488 if tx_reader.bytes_remain() {
1489 Err(DecodeError::BadLengthDescriptor)
1496 impl Writeable for ClaimId {
1497 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1498 self.0.write(writer)
1502 impl Readable for ClaimId {
1503 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1504 Ok(Self(Readable::read(reader)?))
1510 use bitcoin::hashes::hex::FromHex;
1511 use bitcoin::secp256k1::ecdsa;
1512 use crate::util::ser::{Readable, Hostname, Writeable};
1513 use crate::prelude::*;
1516 fn hostname_conversion() {
1517 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1519 assert!(Hostname::try_from(String::from("\"")).is_err());
1520 assert!(Hostname::try_from(String::from("$")).is_err());
1521 assert!(Hostname::try_from(String::from("⚡")).is_err());
1522 let mut large_vec = Vec::with_capacity(256);
1523 large_vec.resize(256, b'A');
1524 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1528 fn hostname_serialization() {
1529 let hostname = Hostname::try_from(String::from("test")).unwrap();
1530 let mut buf: Vec<u8> = Vec::new();
1531 hostname.write(&mut buf).unwrap();
1532 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1536 /// Taproot will likely fill legacy signature fields with all 0s.
1537 /// This test ensures that doing so won't break serialization.
1538 fn null_signature_codec() {
1539 let buffer = vec![0u8; 64];
1540 let mut cursor = crate::io::Cursor::new(buffer.clone());
1541 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1542 let serialization = signature.serialize_compact();
1543 assert_eq!(buffer, serialization.to_vec())
1547 fn bigsize_encoding_decoding() {
1548 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1556 "ff0000000100000000",
1557 "ffffffffffffffffff"
1560 let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(bytes[i]).unwrap());
1561 assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1562 let mut stream = super::VecWriter(Vec::new());
1563 super::BigSize(values[i]).write(&mut stream).unwrap();
1564 assert_eq!(stream.0, <Vec<u8>>::from_hex(bytes[i]).unwrap());
1566 let err_bytes = vec![
1569 "ff00000000ffffffff",
1579 let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(err_bytes[i]).unwrap());
1581 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1583 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));