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};
22 use core::convert::TryFrom;
25 use alloc::collections::BTreeMap;
27 use bitcoin::secp256k1::{PublicKey, SecretKey};
28 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE, SCHNORR_SIGNATURE_SIZE};
29 use bitcoin::secp256k1::ecdsa;
30 use bitcoin::secp256k1::schnorr;
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::marker::Sized;
39 use core::time::Duration;
40 use crate::chain::ClaimId;
41 use crate::ln::msgs::DecodeError;
43 use crate::ln::msgs::PartialSignatureWithNonce;
44 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
46 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
47 use crate::util::string::UntrustedString;
49 /// serialization buffer size
50 pub const MAX_BUF_SIZE: usize = 64 * 1024;
52 /// A simplified version of [`std::io::Write`] that exists largely for backwards compatibility.
53 /// An impl is provided for any type that also impls [`std::io::Write`].
55 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
57 /// Writes the given buf out. See std::io::Write::write_all for more
58 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
61 impl<W: Write> Writer for W {
63 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
64 <Self as io::Write>::write_all(self, buf)
68 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
69 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
71 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
75 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
76 self.0.write_all(buf)?;
80 fn flush(&mut self) -> Result<(), io::Error> {
85 pub(crate) struct VecWriter(pub Vec<u8>);
86 impl Writer for VecWriter {
88 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
89 self.0.extend_from_slice(buf);
94 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
95 /// of some data when serialized but don't yet need the full data.
97 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
98 pub struct LengthCalculatingWriter(pub usize);
99 impl Writer for LengthCalculatingWriter {
101 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
107 /// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
108 /// forward to ensure we always consume exactly the fixed length specified.
110 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
111 pub struct FixedLengthReader<'a, R: Read> {
116 impl<'a, R: Read> FixedLengthReader<'a, R> {
117 /// Returns a new [`FixedLengthReader`].
118 pub fn new(read: &'a mut R, total_bytes: u64) -> Self {
119 Self { read, bytes_read: 0, total_bytes }
122 /// Returns whether some bytes are remaining or not.
124 pub fn bytes_remain(&mut self) -> bool {
125 self.bytes_read != self.total_bytes
128 /// Consumes the remaining bytes.
130 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
131 copy(self, &mut sink()).unwrap();
132 if self.bytes_read != self.total_bytes {
133 Err(DecodeError::ShortRead)
139 impl<'a, R: Read> Read for FixedLengthReader<'a, R> {
141 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
142 if self.total_bytes == self.bytes_read {
145 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
146 match self.read.read(&mut dest[0..(read_len as usize)]) {
148 self.bytes_read += v as u64;
157 impl<'a, R: Read> LengthRead for FixedLengthReader<'a, R> {
159 fn total_bytes(&self) -> u64 {
164 /// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
165 /// between "EOF reached before we started" and "EOF reached mid-read".
167 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
168 pub struct ReadTrackingReader<R: Read> {
170 /// Returns whether we have read from this reader or not yet.
173 impl<R: Read> ReadTrackingReader<R> {
174 /// Returns a new [`ReadTrackingReader`].
175 pub fn new(read: R) -> Self {
176 Self { read, have_read: false }
179 impl<R: Read> Read for ReadTrackingReader<R> {
181 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
182 match self.read.read(dest) {
185 self.have_read = true;
193 /// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
195 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
196 pub trait Writeable {
197 /// Writes `self` out to the given [`Writer`].
198 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
200 /// Writes `self` out to a `Vec<u8>`.
201 fn encode(&self) -> Vec<u8> {
202 let len = self.serialized_length();
203 let mut msg = VecWriter(Vec::with_capacity(len));
204 self.write(&mut msg).unwrap();
205 // Note that objects with interior mutability may change size between when we called
206 // serialized_length and when we called write. That's okay, but shouldn't happen during
207 // testing as most of our tests are not threaded.
209 debug_assert_eq!(len, msg.0.len());
213 /// Writes `self` out to a `Vec<u8>`.
215 fn encode_with_len(&self) -> Vec<u8> {
216 let mut msg = VecWriter(Vec::new());
217 0u16.write(&mut msg).unwrap();
218 self.write(&mut msg).unwrap();
219 let len = msg.0.len();
220 debug_assert_eq!(len - 2, self.serialized_length());
221 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
225 /// Gets the length of this object after it has been serialized. This can be overridden to
226 /// optimize cases where we prepend an object with its length.
227 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
229 fn serialized_length(&self) -> usize {
230 let mut len_calc = LengthCalculatingWriter(0);
231 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
236 impl<'a, T: Writeable> Writeable for &'a T {
237 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
240 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
242 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
246 /// Reads a `Self` in from the given [`Read`].
247 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
250 /// A trait that various LDK types implement allowing them to be read in from a
251 /// [`Read`]` + `[`Seek`].
252 pub(crate) trait SeekReadable where Self: Sized {
253 /// Reads a `Self` in from the given [`Read`].
254 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
257 /// A trait that various higher-level LDK types implement allowing them to be read in
258 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
260 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
261 pub trait ReadableArgs<P>
264 /// Reads a `Self` in from the given [`Read`].
265 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
268 /// A [`std::io::Read`] that also provides the total bytes available to be read.
269 pub(crate) trait LengthRead: Read {
270 /// The total number of bytes available to be read.
271 fn total_bytes(&self) -> u64;
274 /// A trait that various higher-level LDK types implement allowing them to be read in
275 /// from a Read given some additional set of arguments which is required to deserialize, requiring
276 /// the implementer to provide the total length of the read.
277 pub(crate) trait LengthReadableArgs<P> where Self: Sized
279 /// Reads a `Self` in from the given [`LengthRead`].
280 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
283 /// A trait that various higher-level LDK types implement allowing them to be read in
284 /// from a [`Read`], requiring the implementer to provide the total length of the read.
285 pub(crate) trait LengthReadable where Self: Sized
287 /// Reads a `Self` in from the given [`LengthRead`].
288 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
291 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
293 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
294 pub trait MaybeReadable
297 /// Reads a `Self` in from the given [`Read`].
298 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
301 impl<T: Readable> MaybeReadable for T {
303 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
304 Ok(Some(Readable::read(reader)?))
308 /// Wrapper to read a required (non-optional) TLV record.
310 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
311 pub struct RequiredWrapper<T>(pub Option<T>);
312 impl<T: Readable> Readable for RequiredWrapper<T> {
314 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
315 Ok(Self(Some(Readable::read(reader)?)))
318 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
320 fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
321 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
324 /// When handling `default_values`, we want to map the default-value T directly
325 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
326 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
327 impl<T> From<T> for RequiredWrapper<T> {
328 fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
331 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
332 /// backwards compat.
334 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
335 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
336 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
338 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
339 let tlv = MaybeReadable::read(reader)?;
340 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
345 pub(crate) struct U48(pub u64);
346 impl Writeable for U48 {
348 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
349 writer.write_all(&be48_to_array(self.0))
352 impl Readable for U48 {
354 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
355 let mut buf = [0; 6];
356 reader.read_exact(&mut buf)?;
357 Ok(U48(slice_to_be48(&buf)))
361 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
362 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
364 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
365 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
366 /// you're looking for an example of a variable-length integer to use for your own project, move
367 /// along, this is a rather poor design.
368 #[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
369 pub struct BigSize(pub u64);
370 impl Writeable for BigSize {
372 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
375 (self.0 as u8).write(writer)
378 0xFDu8.write(writer)?;
379 (self.0 as u16).write(writer)
381 0x10000..=0xFFFFFFFF => {
382 0xFEu8.write(writer)?;
383 (self.0 as u32).write(writer)
386 0xFFu8.write(writer)?;
387 (self.0 as u64).write(writer)
392 impl Readable for BigSize {
394 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
395 let n: u8 = Readable::read(reader)?;
398 let x: u64 = Readable::read(reader)?;
400 Err(DecodeError::InvalidValue)
406 let x: u32 = Readable::read(reader)?;
408 Err(DecodeError::InvalidValue)
410 Ok(BigSize(x as u64))
414 let x: u16 = Readable::read(reader)?;
416 Err(DecodeError::InvalidValue)
418 Ok(BigSize(x as u64))
421 n => Ok(BigSize(n as u64))
426 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
427 /// primarily targets that, we must as well. However, because we may serialize objects that have
428 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
429 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
430 /// "read eight more bytes".
432 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
433 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
434 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
435 struct CollectionLength(pub u64);
436 impl Writeable for CollectionLength {
438 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
440 (self.0 as u16).write(writer)
442 0xffffu16.write(writer)?;
443 (self.0 - 0xffff).write(writer)
448 impl Readable for CollectionLength {
450 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
451 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
453 val = <u64 as Readable>::read(r)?
454 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
456 Ok(CollectionLength(val))
460 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
461 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
462 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
463 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
464 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
466 macro_rules! impl_writeable_primitive {
467 ($val_type:ty, $len: expr) => {
468 impl Writeable for $val_type {
470 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
471 writer.write_all(&self.to_be_bytes())
474 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
476 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
477 // Skip any full leading 0 bytes when writing (in BE):
478 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
481 impl Readable for $val_type {
483 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
484 let mut buf = [0; $len];
485 reader.read_exact(&mut buf)?;
486 Ok(<$val_type>::from_be_bytes(buf))
489 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
491 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
492 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
493 // the high bytes being dropped. To do so, we start reading into the middle of buf
494 // and then convert the appropriate number of bytes with extra high bytes out of
496 let mut buf = [0; $len*2];
497 let mut read_len = reader.read(&mut buf[$len..])?;
498 let mut total_read_len = read_len;
499 while read_len != 0 && total_read_len != $len {
500 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
501 total_read_len += read_len;
503 if total_read_len == 0 || buf[$len] != 0 {
504 let first_byte = $len - ($len - total_read_len);
505 let mut bytes = [0; $len];
506 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
507 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
509 // If the encoding had extra zero bytes, return a failure even though we know
510 // what they meant (as the TLV test vectors require this)
511 Err(DecodeError::InvalidValue)
515 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
516 fn from(val: $val_type) -> Self { Self(val) }
521 impl_writeable_primitive!(u128, 16);
522 impl_writeable_primitive!(u64, 8);
523 impl_writeable_primitive!(u32, 4);
524 impl_writeable_primitive!(u16, 2);
525 impl_writeable_primitive!(i64, 8);
526 impl_writeable_primitive!(i32, 4);
527 impl_writeable_primitive!(i16, 2);
528 impl_writeable_primitive!(i8, 1);
530 impl Writeable for u8 {
532 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
533 writer.write_all(&[*self])
536 impl Readable for u8 {
538 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
539 let mut buf = [0; 1];
540 reader.read_exact(&mut buf)?;
545 impl Writeable for bool {
547 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
548 writer.write_all(&[if *self {1} else {0}])
551 impl Readable for bool {
553 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
554 let mut buf = [0; 1];
555 reader.read_exact(&mut buf)?;
556 if buf[0] != 0 && buf[0] != 1 {
557 return Err(DecodeError::InvalidValue);
563 macro_rules! impl_array {
564 ($size:expr, $ty: ty) => (
565 impl Writeable for [$ty; $size] {
567 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
568 let mut out = [0; $size * core::mem::size_of::<$ty>()];
569 for (idx, v) in self.iter().enumerate() {
570 let startpos = idx * core::mem::size_of::<$ty>();
571 out[startpos..startpos + core::mem::size_of::<$ty>()].copy_from_slice(&v.to_be_bytes());
577 impl Readable for [$ty; $size] {
579 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
580 let mut buf = [0u8; $size * core::mem::size_of::<$ty>()];
581 r.read_exact(&mut buf)?;
582 let mut res = [0; $size];
583 for (idx, v) in res.iter_mut().enumerate() {
584 let startpos = idx * core::mem::size_of::<$ty>();
585 let mut arr = [0; core::mem::size_of::<$ty>()];
586 arr.copy_from_slice(&buf[startpos..startpos + core::mem::size_of::<$ty>()]);
587 *v = <$ty>::from_be_bytes(arr);
595 impl_array!(3, u8); // for rgb, ISO 4712 code
596 impl_array!(4, u8); // for IPv4
597 impl_array!(12, u8); // for OnionV2
598 impl_array!(16, u8); // for IPv6
599 impl_array!(32, u8); // for channel id & hmac
600 impl_array!(PUBLIC_KEY_SIZE, u8); // for PublicKey
601 impl_array!(64, u8); // for ecdsa::Signature and schnorr::Signature
602 impl_array!(66, u8); // for MuSig2 nonces
603 impl_array!(1300, u8); // for OnionPacket.hop_data
606 impl_array!(32, u16);
608 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
609 /// Used to prevent encoding the length twice.
611 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
612 pub struct WithoutLength<T>(pub T);
614 impl Writeable for WithoutLength<&String> {
616 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
617 w.write_all(self.0.as_bytes())
620 impl Readable for WithoutLength<String> {
622 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
623 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
624 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
627 impl<'a> From<&'a String> for WithoutLength<&'a String> {
628 fn from(s: &'a String) -> Self { Self(s) }
632 impl Writeable for WithoutLength<&UntrustedString> {
634 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
635 WithoutLength(&self.0.0).write(w)
638 impl Readable for WithoutLength<UntrustedString> {
640 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
641 let s: WithoutLength<String> = Readable::read(r)?;
642 Ok(Self(UntrustedString(s.0)))
646 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
648 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
649 for ref v in self.0.iter() {
656 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
658 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
659 let mut values = Vec::new();
661 let mut track_read = ReadTrackingReader::new(&mut reader);
662 match MaybeReadable::read(&mut track_read) {
663 Ok(Some(v)) => { values.push(v); },
665 // If we failed to read any bytes at all, we reached the end of our TLV
666 // stream and have simply exhausted all entries.
667 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
668 Err(e) => return Err(e),
674 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
675 fn from(v: &'a Vec<T>) -> Self { Self(v) }
678 impl Writeable for WithoutLength<&ScriptBuf> {
680 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
681 writer.write_all(self.0.as_bytes())
685 impl Readable for WithoutLength<ScriptBuf> {
687 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
688 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
689 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
694 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
696 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
698 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
699 for ref v in self.0.clone() {
707 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
708 fn eq(&self, other: &Self) -> bool {
709 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
713 macro_rules! impl_for_map {
714 ($ty: ident, $keybound: ident, $constr: expr) => {
715 impl<K, V> Writeable for $ty<K, V>
716 where K: Writeable + Eq + $keybound, V: Writeable
719 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
720 CollectionLength(self.len() as u64).write(w)?;
721 for (key, value) in self.iter() {
729 impl<K, V> Readable for $ty<K, V>
730 where K: Readable + Eq + $keybound, V: MaybeReadable
733 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
734 let len: CollectionLength = Readable::read(r)?;
735 let mut ret = $constr(len.0 as usize);
738 let v_opt = V::read(r)?;
739 if let Some(v) = v_opt {
740 if ret.insert(k, v).is_some() {
741 return Err(DecodeError::InvalidValue);
751 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
752 impl_for_map!(HashMap, Hash, |len| hash_map_with_capacity(len));
755 impl<T> Writeable for HashSet<T>
756 where T: Writeable + Eq + Hash
759 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
760 CollectionLength(self.len() as u64).write(w)?;
761 for item in self.iter() {
768 impl<T> Readable for HashSet<T>
769 where T: Readable + Eq + Hash
772 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
773 let len: CollectionLength = Readable::read(r)?;
774 let mut ret = hash_set_with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
776 if !ret.insert(T::read(r)?) {
777 return Err(DecodeError::InvalidValue)
785 macro_rules! impl_writeable_for_vec {
786 ($ty: ty $(, $name: ident)*) => {
787 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
789 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
790 CollectionLength(self.len() as u64).write(w)?;
791 for elem in self.iter() {
799 macro_rules! impl_readable_for_vec {
800 ($ty: ty $(, $name: ident)*) => {
801 impl<$($name : Readable),*> Readable for Vec<$ty> {
803 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
804 let len: CollectionLength = Readable::read(r)?;
805 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
807 if let Some(val) = MaybeReadable::read(r)? {
816 macro_rules! impl_for_vec {
817 ($ty: ty $(, $name: ident)*) => {
818 impl_writeable_for_vec!($ty $(, $name)*);
819 impl_readable_for_vec!($ty $(, $name)*);
823 // Alternatives to impl_writeable_for_vec/impl_readable_for_vec that add a length prefix to each
824 // element in the Vec. Intended to be used when elements have variable lengths.
825 macro_rules! impl_writeable_for_vec_with_element_length_prefix {
826 ($ty: ty $(, $name: ident)*) => {
827 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
829 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
830 CollectionLength(self.len() as u64).write(w)?;
831 for elem in self.iter() {
832 CollectionLength(elem.serialized_length() as u64).write(w)?;
840 macro_rules! impl_readable_for_vec_with_element_length_prefix {
841 ($ty: ty $(, $name: ident)*) => {
842 impl<$($name : Readable),*> Readable for Vec<$ty> {
844 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
845 let len: CollectionLength = Readable::read(r)?;
846 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
848 let elem_len: CollectionLength = Readable::read(r)?;
849 let mut elem_reader = FixedLengthReader::new(r, elem_len.0);
850 if let Some(val) = MaybeReadable::read(&mut elem_reader)? {
859 macro_rules! impl_for_vec_with_element_length_prefix {
860 ($ty: ty $(, $name: ident)*) => {
861 impl_writeable_for_vec_with_element_length_prefix!($ty $(, $name)*);
862 impl_readable_for_vec_with_element_length_prefix!($ty $(, $name)*);
866 impl Writeable for Vec<u8> {
868 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
869 CollectionLength(self.len() as u64).write(w)?;
874 impl Readable for Vec<u8> {
876 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
877 let mut len: CollectionLength = Readable::read(r)?;
878 let mut ret = Vec::new();
880 let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
881 let readstart = ret.len();
882 ret.resize(readstart + readamt, 0);
883 r.read_exact(&mut ret[readstart..])?;
884 len.0 -= readamt as u64;
890 impl_for_vec!(ecdsa::Signature);
891 impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
892 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
893 impl_for_vec!(crate::ln::msgs::SocketAddress);
894 impl_for_vec!((A, B), A, B);
895 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
896 impl_readable_for_vec!(crate::routing::router::BlindedTail);
897 impl_for_vec_with_element_length_prefix!(crate::ln::msgs::UpdateAddHTLC);
898 impl_writeable_for_vec_with_element_length_prefix!(&crate::ln::msgs::UpdateAddHTLC);
900 impl Writeable for Vec<Witness> {
902 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
903 (self.len() as u16).write(w)?;
904 for witness in self {
905 (witness.serialized_len() as u16).write(w)?;
912 impl Readable for Vec<Witness> {
914 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
915 let num_witnesses = <u16 as Readable>::read(r)? as usize;
916 let mut witnesses = Vec::with_capacity(num_witnesses);
917 for _ in 0..num_witnesses {
918 // Even though the length of each witness can be inferred in its consensus-encoded form,
919 // the spec includes a length prefix so that implementations don't have to deserialize
920 // each initially. We do that here anyway as in general we'll need to be able to make
921 // assertions on some properties of the witnesses when receiving a message providing a list
922 // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
923 let witness_len = <u16 as Readable>::read(r)? as usize;
924 let witness = <Witness as Readable>::read(r)?;
925 if witness.serialized_len() != witness_len {
926 return Err(DecodeError::BadLengthDescriptor);
928 witnesses.push(witness);
934 impl Writeable for ScriptBuf {
935 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
936 (self.len() as u16).write(w)?;
937 w.write_all(self.as_bytes())
941 impl Readable for ScriptBuf {
942 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
943 let len = <u16 as Readable>::read(r)? as usize;
944 let mut buf = vec![0; len];
945 r.read_exact(&mut buf)?;
946 Ok(ScriptBuf::from(buf))
950 impl Writeable for PublicKey {
951 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
952 self.serialize().write(w)
955 fn serialized_length(&self) -> usize {
960 impl Readable for PublicKey {
961 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
962 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
963 match PublicKey::from_slice(&buf) {
965 Err(_) => return Err(DecodeError::InvalidValue),
970 impl Writeable for SecretKey {
971 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
972 let mut ser = [0; SECRET_KEY_SIZE];
973 ser.copy_from_slice(&self[..]);
977 fn serialized_length(&self) -> usize {
982 impl Readable for SecretKey {
983 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
984 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
985 match SecretKey::from_slice(&buf) {
987 Err(_) => return Err(DecodeError::InvalidValue),
993 impl Writeable for musig2::types::PublicNonce {
994 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
995 self.serialize().write(w)
1000 impl Readable for musig2::types::PublicNonce {
1001 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1002 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
1003 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
1008 impl Writeable for PartialSignatureWithNonce {
1009 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1010 self.0.serialize().write(w)?;
1016 impl Readable for PartialSignatureWithNonce {
1017 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1018 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
1019 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
1020 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
1021 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
1025 impl Writeable for Sha256dHash {
1026 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1027 w.write_all(&self[..])
1031 impl Readable for Sha256dHash {
1032 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1033 use bitcoin::hashes::Hash;
1035 let buf: [u8; 32] = Readable::read(r)?;
1036 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
1040 impl Writeable for ecdsa::Signature {
1041 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1042 self.serialize_compact().write(w)
1046 impl Readable for ecdsa::Signature {
1047 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1048 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1049 match ecdsa::Signature::from_compact(&buf) {
1051 Err(_) => return Err(DecodeError::InvalidValue),
1056 impl Writeable for schnorr::Signature {
1057 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1058 self.as_ref().write(w)
1062 impl Readable for schnorr::Signature {
1063 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1064 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1065 match schnorr::Signature::from_slice(&buf) {
1067 Err(_) => return Err(DecodeError::InvalidValue),
1072 impl Writeable for PaymentPreimage {
1073 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1078 impl Readable for PaymentPreimage {
1079 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1080 let buf: [u8; 32] = Readable::read(r)?;
1081 Ok(PaymentPreimage(buf))
1085 impl Writeable for PaymentHash {
1086 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1091 impl Readable for PaymentHash {
1092 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1093 let buf: [u8; 32] = Readable::read(r)?;
1094 Ok(PaymentHash(buf))
1098 impl Writeable for PaymentSecret {
1099 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1104 impl Readable for PaymentSecret {
1105 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1106 let buf: [u8; 32] = Readable::read(r)?;
1107 Ok(PaymentSecret(buf))
1111 impl<T: Writeable> Writeable for Box<T> {
1112 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1113 T::write(&**self, w)
1117 impl<T: Readable> Readable for Box<T> {
1118 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1119 Ok(Box::new(Readable::read(r)?))
1123 impl<T: Writeable> Writeable for Option<T> {
1124 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1126 None => 0u8.write(w)?,
1128 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1136 impl<T: Readable> Readable for Option<T>
1138 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1139 let len: BigSize = Readable::read(r)?;
1143 let mut reader = FixedLengthReader::new(r, len - 1);
1144 Ok(Some(Readable::read(&mut reader)?))
1150 impl Writeable for Txid {
1151 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1152 w.write_all(&self[..])
1156 impl Readable for Txid {
1157 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1158 use bitcoin::hashes::Hash;
1160 let buf: [u8; 32] = Readable::read(r)?;
1161 Ok(Txid::from_slice(&buf[..]).unwrap())
1165 impl Writeable for BlockHash {
1166 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1167 w.write_all(&self[..])
1171 impl Readable for BlockHash {
1172 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1173 use bitcoin::hashes::Hash;
1175 let buf: [u8; 32] = Readable::read(r)?;
1176 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1180 impl Writeable for ChainHash {
1181 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1182 w.write_all(self.as_bytes())
1186 impl Readable for ChainHash {
1187 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1188 let buf: [u8; 32] = Readable::read(r)?;
1189 Ok(ChainHash::from(buf))
1193 impl Writeable for OutPoint {
1194 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1195 self.txid.write(w)?;
1196 self.vout.write(w)?;
1201 impl Readable for OutPoint {
1202 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1203 let txid = Readable::read(r)?;
1204 let vout = Readable::read(r)?;
1212 macro_rules! impl_consensus_ser {
1213 ($bitcoin_type: ty) => {
1214 impl Writeable for $bitcoin_type {
1215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1216 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1223 impl Readable for $bitcoin_type {
1224 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1225 match consensus::encode::Decodable::consensus_decode(r) {
1227 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1228 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1229 Err(_) => Err(DecodeError::InvalidValue),
1235 impl_consensus_ser!(Transaction);
1236 impl_consensus_ser!(TxOut);
1237 impl_consensus_ser!(Witness);
1239 impl<T: Readable> Readable for Mutex<T> {
1240 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1241 let t: T = Readable::read(r)?;
1245 impl<T: Writeable> Writeable for Mutex<T> {
1246 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1247 self.lock().unwrap().write(w)
1251 impl<T: Readable> Readable for RwLock<T> {
1252 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1253 let t: T = Readable::read(r)?;
1257 impl<T: Writeable> Writeable for RwLock<T> {
1258 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1259 self.read().unwrap().write(w)
1263 impl<A: Readable, B: Readable> Readable for (A, B) {
1264 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1265 let a: A = Readable::read(r)?;
1266 let b: B = Readable::read(r)?;
1270 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1271 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1277 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1278 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1279 let a: A = Readable::read(r)?;
1280 let b: B = Readable::read(r)?;
1281 let c: C = Readable::read(r)?;
1285 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1286 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1293 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1294 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1295 let a: A = Readable::read(r)?;
1296 let b: B = Readable::read(r)?;
1297 let c: C = Readable::read(r)?;
1298 let d: D = Readable::read(r)?;
1302 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1303 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1311 impl Writeable for () {
1312 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1316 impl Readable for () {
1317 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1322 impl Writeable for String {
1324 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1325 CollectionLength(self.len() as u64).write(w)?;
1326 w.write_all(self.as_bytes())
1329 impl Readable for String {
1331 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1332 let v: Vec<u8> = Readable::read(r)?;
1333 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1338 /// Represents a hostname for serialization purposes.
1339 /// Only the character set and length will be validated.
1340 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1341 /// Its length is guaranteed to be representable by a single byte.
1342 /// This serialization is used by [`BOLT 7`] hostnames.
1344 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1345 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
1346 pub struct Hostname(String);
1348 /// Returns the length of the hostname.
1349 pub fn len(&self) -> u8 {
1350 (&self.0).len() as u8
1354 impl core::fmt::Display for Hostname {
1355 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1356 write!(f, "{}", self.0)?;
1360 impl Deref for Hostname {
1361 type Target = String;
1363 fn deref(&self) -> &Self::Target {
1367 impl From<Hostname> for String {
1368 fn from(hostname: Hostname) -> Self {
1372 impl TryFrom<Vec<u8>> for Hostname {
1375 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1376 if let Ok(s) = String::from_utf8(bytes) {
1377 Hostname::try_from(s)
1383 impl TryFrom<String> for Hostname {
1386 fn try_from(s: String) -> Result<Self, Self::Error> {
1387 if s.len() <= 255 && s.chars().all(|c|
1388 c.is_ascii_alphanumeric() ||
1398 impl Writeable for Hostname {
1400 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1401 self.len().write(w)?;
1402 w.write_all(self.as_bytes())
1405 impl Readable for Hostname {
1407 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1408 let len: u8 = Readable::read(r)?;
1409 let mut vec = Vec::with_capacity(len.into());
1410 vec.resize(len.into(), 0);
1411 r.read_exact(&mut vec)?;
1412 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1416 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1417 impl Writeable for Duration {
1419 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1420 self.as_secs().write(w)?;
1421 self.subsec_nanos().write(w)
1424 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1425 impl Readable for Duration {
1427 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1428 let secs = Readable::read(r)?;
1429 let nanos = Readable::read(r)?;
1430 Ok(Duration::new(secs, nanos))
1434 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1435 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1437 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1438 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
1439 pub struct TransactionU16LenLimited(Transaction);
1441 impl TransactionU16LenLimited {
1442 /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1443 /// serialized length is <= u16::MAX.
1444 pub fn new(transaction: Transaction) -> Result<Self, ()> {
1445 if transaction.serialized_length() > (u16::MAX as usize) {
1448 Ok(Self(transaction))
1452 /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1453 pub fn into_transaction(self) -> Transaction {
1457 /// Returns a reference to the contained `Transaction`
1458 pub fn as_transaction(&self) -> &Transaction {
1463 impl Writeable for TransactionU16LenLimited {
1464 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1465 (self.0.serialized_length() as u16).write(w)?;
1470 impl Readable for TransactionU16LenLimited {
1471 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1472 let len = <u16 as Readable>::read(r)?;
1473 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1474 let tx: Transaction = Readable::read(&mut tx_reader)?;
1475 if tx_reader.bytes_remain() {
1476 Err(DecodeError::BadLengthDescriptor)
1483 impl Writeable for ClaimId {
1484 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1485 self.0.write(writer)
1489 impl Readable for ClaimId {
1490 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1491 Ok(Self(Readable::read(reader)?))
1497 use core::convert::TryFrom;
1498 use bitcoin::hashes::hex::FromHex;
1499 use bitcoin::secp256k1::ecdsa;
1500 use crate::util::ser::{Readable, Hostname, Writeable};
1503 fn hostname_conversion() {
1504 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1506 assert!(Hostname::try_from(String::from("\"")).is_err());
1507 assert!(Hostname::try_from(String::from("$")).is_err());
1508 assert!(Hostname::try_from(String::from("⚡")).is_err());
1509 let mut large_vec = Vec::with_capacity(256);
1510 large_vec.resize(256, b'A');
1511 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1515 fn hostname_serialization() {
1516 let hostname = Hostname::try_from(String::from("test")).unwrap();
1517 let mut buf: Vec<u8> = Vec::new();
1518 hostname.write(&mut buf).unwrap();
1519 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1523 /// Taproot will likely fill legacy signature fields with all 0s.
1524 /// This test ensures that doing so won't break serialization.
1525 fn null_signature_codec() {
1526 let buffer = vec![0u8; 64];
1527 let mut cursor = crate::io::Cursor::new(buffer.clone());
1528 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1529 let serialization = signature.serialize_compact();
1530 assert_eq!(buffer, serialization.to_vec())
1534 fn bigsize_encoding_decoding() {
1535 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1543 "ff0000000100000000",
1544 "ffffffffffffffffff"
1547 let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(bytes[i]).unwrap());
1548 assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1549 let mut stream = super::VecWriter(Vec::new());
1550 super::BigSize(values[i]).write(&mut stream).unwrap();
1551 assert_eq!(stream.0, <Vec<u8>>::from_hex(bytes[i]).unwrap());
1553 let err_bytes = vec![
1556 "ff00000000ffffffff",
1566 let mut stream = crate::io::Cursor::new(<Vec<u8>>::from_hex(err_bytes[i]).unwrap());
1568 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1570 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));