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;
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, Script};
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::ln::msgs::DecodeError;
42 use crate::ln::msgs::PartialSignatureWithNonce;
43 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
45 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
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<R: Read> {
114 impl<R: Read> FixedLengthReader<R> {
115 /// Returns a new [`FixedLengthReader`].
116 pub fn new(read: 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<R: Read> Read for FixedLengthReader<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<R: Read> LengthRead for FixedLengthReader<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 mut msg = VecWriter(Vec::new());
201 self.write(&mut msg).unwrap();
205 /// Writes `self` out to a `Vec<u8>`.
207 fn encode_with_len(&self) -> Vec<u8> {
208 let mut msg = VecWriter(Vec::new());
209 0u16.write(&mut msg).unwrap();
210 self.write(&mut msg).unwrap();
211 let len = msg.0.len();
212 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
216 /// Gets the length of this object after it has been serialized. This can be overridden to
217 /// optimize cases where we prepend an object with its length.
218 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
220 fn serialized_length(&self) -> usize {
221 let mut len_calc = LengthCalculatingWriter(0);
222 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
227 impl<'a, T: Writeable> Writeable for &'a T {
228 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
231 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
233 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
237 /// Reads a `Self` in from the given [`Read`].
238 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
241 /// A trait that various LDK types implement allowing them to be read in from a
242 /// [`Read`]` + `[`Seek`].
243 pub(crate) trait SeekReadable where Self: Sized {
244 /// Reads a `Self` in from the given [`Read`].
245 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
248 /// A trait that various higher-level LDK types implement allowing them to be read in
249 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
251 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
252 pub trait ReadableArgs<P>
255 /// Reads a `Self` in from the given [`Read`].
256 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
259 /// A [`std::io::Read`] that also provides the total bytes available to be read.
260 pub(crate) trait LengthRead: Read {
261 /// The total number of bytes available to be read.
262 fn total_bytes(&self) -> u64;
265 /// A trait that various higher-level LDK types implement allowing them to be read in
266 /// from a Read given some additional set of arguments which is required to deserialize, requiring
267 /// the implementer to provide the total length of the read.
268 pub(crate) trait LengthReadableArgs<P> where Self: Sized
270 /// Reads a `Self` in from the given [`LengthRead`].
271 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
274 /// A trait that various higher-level LDK types implement allowing them to be read in
275 /// from a [`Read`], requiring the implementer to provide the total length of the read.
276 pub(crate) trait LengthReadable where Self: Sized
278 /// Reads a `Self` in from the given [`LengthRead`].
279 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
282 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
284 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
285 pub trait MaybeReadable
288 /// Reads a `Self` in from the given [`Read`].
289 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
292 impl<T: Readable> MaybeReadable for T {
294 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
295 Ok(Some(Readable::read(reader)?))
299 /// Wrapper to read a required (non-optional) TLV record.
301 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
302 pub struct RequiredWrapper<T>(pub Option<T>);
303 impl<T: Readable> Readable for RequiredWrapper<T> {
305 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
306 Ok(Self(Some(Readable::read(reader)?)))
309 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
311 fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
312 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
315 /// When handling `default_values`, we want to map the default-value T directly
316 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
317 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
318 impl<T> From<T> for RequiredWrapper<T> {
319 fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
322 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
323 /// backwards compat.
325 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
326 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
327 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
329 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
330 let tlv = MaybeReadable::read(reader)?;
331 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
336 pub(crate) struct U48(pub u64);
337 impl Writeable for U48 {
339 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
340 writer.write_all(&be48_to_array(self.0))
343 impl Readable for U48 {
345 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
346 let mut buf = [0; 6];
347 reader.read_exact(&mut buf)?;
348 Ok(U48(slice_to_be48(&buf)))
352 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
353 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
355 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
356 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
357 /// you're looking for an example of a variable-length integer to use for your own project, move
358 /// along, this is a rather poor design.
359 pub struct BigSize(pub u64);
360 impl Writeable for BigSize {
362 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
365 (self.0 as u8).write(writer)
368 0xFDu8.write(writer)?;
369 (self.0 as u16).write(writer)
371 0x10000...0xFFFFFFFF => {
372 0xFEu8.write(writer)?;
373 (self.0 as u32).write(writer)
376 0xFFu8.write(writer)?;
377 (self.0 as u64).write(writer)
382 impl Readable for BigSize {
384 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
385 let n: u8 = Readable::read(reader)?;
388 let x: u64 = Readable::read(reader)?;
390 Err(DecodeError::InvalidValue)
396 let x: u32 = Readable::read(reader)?;
398 Err(DecodeError::InvalidValue)
400 Ok(BigSize(x as u64))
404 let x: u16 = Readable::read(reader)?;
406 Err(DecodeError::InvalidValue)
408 Ok(BigSize(x as u64))
411 n => Ok(BigSize(n as u64))
416 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
417 /// primarily targets that, we must as well. However, because we may serialize objects that have
418 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
419 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
420 /// "read eight more bytes".
422 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
423 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
424 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
425 struct CollectionLength(pub u64);
426 impl Writeable for CollectionLength {
428 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
430 (self.0 as u16).write(writer)
432 0xffffu16.write(writer)?;
433 (self.0 - 0xffff).write(writer)
438 impl Readable for CollectionLength {
440 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
441 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
443 val = <u64 as Readable>::read(r)?
444 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
446 Ok(CollectionLength(val))
450 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
451 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
452 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
453 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
454 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
456 macro_rules! impl_writeable_primitive {
457 ($val_type:ty, $len: expr) => {
458 impl Writeable for $val_type {
460 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
461 writer.write_all(&self.to_be_bytes())
464 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
466 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
467 // Skip any full leading 0 bytes when writing (in BE):
468 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
471 impl Readable for $val_type {
473 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
474 let mut buf = [0; $len];
475 reader.read_exact(&mut buf)?;
476 Ok(<$val_type>::from_be_bytes(buf))
479 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
481 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
482 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
483 // the high bytes being dropped. To do so, we start reading into the middle of buf
484 // and then convert the appropriate number of bytes with extra high bytes out of
486 let mut buf = [0; $len*2];
487 let mut read_len = reader.read(&mut buf[$len..])?;
488 let mut total_read_len = read_len;
489 while read_len != 0 && total_read_len != $len {
490 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
491 total_read_len += read_len;
493 if total_read_len == 0 || buf[$len] != 0 {
494 let first_byte = $len - ($len - total_read_len);
495 let mut bytes = [0; $len];
496 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
497 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
499 // If the encoding had extra zero bytes, return a failure even though we know
500 // what they meant (as the TLV test vectors require this)
501 Err(DecodeError::InvalidValue)
505 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
506 fn from(val: $val_type) -> Self { Self(val) }
511 impl_writeable_primitive!(u128, 16);
512 impl_writeable_primitive!(u64, 8);
513 impl_writeable_primitive!(u32, 4);
514 impl_writeable_primitive!(u16, 2);
515 impl_writeable_primitive!(i64, 8);
516 impl_writeable_primitive!(i32, 4);
517 impl_writeable_primitive!(i16, 2);
518 impl_writeable_primitive!(i8, 1);
520 impl Writeable for u8 {
522 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
523 writer.write_all(&[*self])
526 impl Readable for u8 {
528 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
529 let mut buf = [0; 1];
530 reader.read_exact(&mut buf)?;
535 impl Writeable for bool {
537 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
538 writer.write_all(&[if *self {1} else {0}])
541 impl Readable for bool {
543 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
544 let mut buf = [0; 1];
545 reader.read_exact(&mut buf)?;
546 if buf[0] != 0 && buf[0] != 1 {
547 return Err(DecodeError::InvalidValue);
554 macro_rules! impl_array {
556 impl Writeable for [u8; $size]
559 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
564 impl Readable for [u8; $size]
567 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
568 let mut buf = [0u8; $size];
569 r.read_exact(&mut buf)?;
576 impl_array!(3); // for rgb, ISO 4712 code
577 impl_array!(4); // for IPv4
578 impl_array!(12); // for OnionV2
579 impl_array!(16); // for IPv6
580 impl_array!(32); // for channel id & hmac
581 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
582 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
583 impl_array!(66); // for MuSig2 nonces
584 impl_array!(1300); // for OnionPacket.hop_data
586 impl Writeable for [u16; 8] {
588 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
589 for v in self.iter() {
590 w.write_all(&v.to_be_bytes())?
596 impl Readable for [u16; 8] {
598 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
599 let mut buf = [0u8; 16];
600 r.read_exact(&mut buf)?;
601 let mut res = [0u16; 8];
602 for (idx, v) in res.iter_mut().enumerate() {
603 *v = (buf[idx*2] as u16) << 8 | (buf[idx*2 + 1] as u16)
609 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
610 /// Used to prevent encoding the length twice.
612 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
613 pub struct WithoutLength<T>(pub T);
615 impl Writeable for WithoutLength<&String> {
617 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
618 w.write_all(self.0.as_bytes())
621 impl Readable for WithoutLength<String> {
623 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
624 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
625 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
628 impl<'a> From<&'a String> for WithoutLength<&'a String> {
629 fn from(s: &'a String) -> Self { Self(s) }
632 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
634 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
635 for ref v in self.0.iter() {
642 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
644 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
645 let mut values = Vec::new();
647 let mut track_read = ReadTrackingReader::new(&mut reader);
648 match MaybeReadable::read(&mut track_read) {
649 Ok(Some(v)) => { values.push(v); },
651 // If we failed to read any bytes at all, we reached the end of our TLV
652 // stream and have simply exhausted all entries.
653 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
654 Err(e) => return Err(e),
660 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
661 fn from(v: &'a Vec<T>) -> Self { Self(v) }
664 impl Writeable for WithoutLength<&Script> {
666 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
667 writer.write_all(self.0.as_bytes())
671 impl Readable for WithoutLength<Script> {
673 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
674 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
675 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
680 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
682 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
684 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
685 for ref v in self.0.clone() {
693 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
694 fn eq(&self, other: &Self) -> bool {
695 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
699 macro_rules! impl_for_map {
700 ($ty: ident, $keybound: ident, $constr: expr) => {
701 impl<K, V> Writeable for $ty<K, V>
702 where K: Writeable + Eq + $keybound, V: Writeable
705 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
706 CollectionLength(self.len() as u64).write(w)?;
707 for (key, value) in self.iter() {
715 impl<K, V> Readable for $ty<K, V>
716 where K: Readable + Eq + $keybound, V: MaybeReadable
719 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
720 let len: CollectionLength = Readable::read(r)?;
721 let mut ret = $constr(len.0 as usize);
724 let v_opt = V::read(r)?;
725 if let Some(v) = v_opt {
726 if ret.insert(k, v).is_some() {
727 return Err(DecodeError::InvalidValue);
737 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
738 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
741 impl<T> Writeable for HashSet<T>
742 where T: Writeable + Eq + Hash
745 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
746 CollectionLength(self.len() as u64).write(w)?;
747 for item in self.iter() {
754 impl<T> Readable for HashSet<T>
755 where T: Readable + Eq + Hash
758 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
759 let len: CollectionLength = Readable::read(r)?;
760 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
762 if !ret.insert(T::read(r)?) {
763 return Err(DecodeError::InvalidValue)
771 macro_rules! impl_writeable_for_vec {
772 ($ty: ty $(, $name: ident)*) => {
773 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
775 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
776 CollectionLength(self.len() as u64).write(w)?;
777 for elem in self.iter() {
785 macro_rules! impl_readable_for_vec {
786 ($ty: ty $(, $name: ident)*) => {
787 impl<$($name : Readable),*> Readable for Vec<$ty> {
789 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
790 let len: CollectionLength = Readable::read(r)?;
791 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
793 if let Some(val) = MaybeReadable::read(r)? {
802 macro_rules! impl_for_vec {
803 ($ty: ty $(, $name: ident)*) => {
804 impl_writeable_for_vec!($ty $(, $name)*);
805 impl_readable_for_vec!($ty $(, $name)*);
809 impl Writeable for Vec<u8> {
811 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
812 CollectionLength(self.len() as u64).write(w)?;
817 impl Readable for Vec<u8> {
819 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
820 let mut len: CollectionLength = Readable::read(r)?;
821 let mut ret = Vec::new();
823 let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
824 let readstart = ret.len();
825 ret.resize(readstart + readamt, 0);
826 r.read_exact(&mut ret[readstart..])?;
827 len.0 -= readamt as u64;
833 impl_for_vec!(ecdsa::Signature);
834 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
835 impl_for_vec!((A, B), A, B);
836 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
837 impl_readable_for_vec!(crate::routing::router::BlindedTail);
839 impl Writeable for Vec<Witness> {
841 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
842 (self.len() as u16).write(w)?;
843 for witness in self {
844 (witness.serialized_len() as u16).write(w)?;
851 impl Readable for Vec<Witness> {
853 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
854 let num_witnesses = <u16 as Readable>::read(r)? as usize;
855 let mut witnesses = Vec::with_capacity(num_witnesses);
856 for _ in 0..num_witnesses {
857 // Even though the length of each witness can be inferred in its consensus-encoded form,
858 // the spec includes a length prefix so that implementations don't have to deserialize
859 // each initially. We do that here anyway as in general we'll need to be able to make
860 // assertions on some properties of the witnesses when receiving a message providing a list
861 // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
862 let witness_len = <u16 as Readable>::read(r)? as usize;
863 let witness = <Witness as Readable>::read(r)?;
864 if witness.serialized_len() != witness_len {
865 return Err(DecodeError::BadLengthDescriptor);
867 witnesses.push(witness);
873 impl Writeable for Script {
874 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
875 (self.len() as u16).write(w)?;
876 w.write_all(self.as_bytes())
880 impl Readable for Script {
881 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
882 let len = <u16 as Readable>::read(r)? as usize;
883 let mut buf = vec![0; len];
884 r.read_exact(&mut buf)?;
885 Ok(Script::from(buf))
889 impl Writeable for PublicKey {
890 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
891 self.serialize().write(w)
894 fn serialized_length(&self) -> usize {
899 impl Readable for PublicKey {
900 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
901 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
902 match PublicKey::from_slice(&buf) {
904 Err(_) => return Err(DecodeError::InvalidValue),
909 impl Writeable for SecretKey {
910 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
911 let mut ser = [0; SECRET_KEY_SIZE];
912 ser.copy_from_slice(&self[..]);
916 fn serialized_length(&self) -> usize {
921 impl Readable for SecretKey {
922 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
923 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
924 match SecretKey::from_slice(&buf) {
926 Err(_) => return Err(DecodeError::InvalidValue),
932 impl Writeable for musig2::types::PublicNonce {
933 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
934 self.serialize().write(w)
939 impl Readable for musig2::types::PublicNonce {
940 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
941 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
942 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
947 impl Writeable for PartialSignatureWithNonce {
948 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
949 self.0.serialize().write(w)?;
955 impl Readable for PartialSignatureWithNonce {
956 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
957 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
958 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
959 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
960 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
964 impl Writeable for Sha256dHash {
965 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
966 w.write_all(&self[..])
970 impl Readable for Sha256dHash {
971 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
972 use bitcoin::hashes::Hash;
974 let buf: [u8; 32] = Readable::read(r)?;
975 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
979 impl Writeable for ecdsa::Signature {
980 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
981 self.serialize_compact().write(w)
985 impl Readable for ecdsa::Signature {
986 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
987 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
988 match ecdsa::Signature::from_compact(&buf) {
990 Err(_) => return Err(DecodeError::InvalidValue),
995 impl Writeable for schnorr::Signature {
996 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
997 self.as_ref().write(w)
1001 impl Readable for schnorr::Signature {
1002 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1003 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1004 match schnorr::Signature::from_slice(&buf) {
1006 Err(_) => return Err(DecodeError::InvalidValue),
1011 impl Writeable for PaymentPreimage {
1012 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1017 impl Readable for PaymentPreimage {
1018 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1019 let buf: [u8; 32] = Readable::read(r)?;
1020 Ok(PaymentPreimage(buf))
1024 impl Writeable for PaymentHash {
1025 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1030 impl Readable for PaymentHash {
1031 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1032 let buf: [u8; 32] = Readable::read(r)?;
1033 Ok(PaymentHash(buf))
1037 impl Writeable for PaymentSecret {
1038 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1043 impl Readable for PaymentSecret {
1044 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1045 let buf: [u8; 32] = Readable::read(r)?;
1046 Ok(PaymentSecret(buf))
1050 impl<T: Writeable> Writeable for Box<T> {
1051 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1052 T::write(&**self, w)
1056 impl<T: Readable> Readable for Box<T> {
1057 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1058 Ok(Box::new(Readable::read(r)?))
1062 impl<T: Writeable> Writeable for Option<T> {
1063 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1065 None => 0u8.write(w)?,
1067 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1075 impl<T: Readable> Readable for Option<T>
1077 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1078 let len: BigSize = Readable::read(r)?;
1082 let mut reader = FixedLengthReader::new(r, len - 1);
1083 Ok(Some(Readable::read(&mut reader)?))
1089 impl Writeable for Txid {
1090 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1091 w.write_all(&self[..])
1095 impl Readable for Txid {
1096 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1097 use bitcoin::hashes::Hash;
1099 let buf: [u8; 32] = Readable::read(r)?;
1100 Ok(Txid::from_slice(&buf[..]).unwrap())
1104 impl Writeable for BlockHash {
1105 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1106 w.write_all(&self[..])
1110 impl Readable for BlockHash {
1111 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1112 use bitcoin::hashes::Hash;
1114 let buf: [u8; 32] = Readable::read(r)?;
1115 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1119 impl Writeable for ChainHash {
1120 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1121 w.write_all(self.as_bytes())
1125 impl Readable for ChainHash {
1126 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1127 let buf: [u8; 32] = Readable::read(r)?;
1128 Ok(ChainHash::from(&buf[..]))
1132 impl Writeable for OutPoint {
1133 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1134 self.txid.write(w)?;
1135 self.vout.write(w)?;
1140 impl Readable for OutPoint {
1141 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1142 let txid = Readable::read(r)?;
1143 let vout = Readable::read(r)?;
1151 macro_rules! impl_consensus_ser {
1152 ($bitcoin_type: ty) => {
1153 impl Writeable for $bitcoin_type {
1154 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1155 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1162 impl Readable for $bitcoin_type {
1163 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1164 match consensus::encode::Decodable::consensus_decode(r) {
1166 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1167 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1168 Err(_) => Err(DecodeError::InvalidValue),
1174 impl_consensus_ser!(Transaction);
1175 impl_consensus_ser!(TxOut);
1176 impl_consensus_ser!(Witness);
1178 impl<T: Readable> Readable for Mutex<T> {
1179 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1180 let t: T = Readable::read(r)?;
1184 impl<T: Writeable> Writeable for Mutex<T> {
1185 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1186 self.lock().unwrap().write(w)
1190 impl<A: Readable, B: Readable> Readable for (A, B) {
1191 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1192 let a: A = Readable::read(r)?;
1193 let b: B = Readable::read(r)?;
1197 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1198 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1204 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1205 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1206 let a: A = Readable::read(r)?;
1207 let b: B = Readable::read(r)?;
1208 let c: C = Readable::read(r)?;
1212 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1213 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1220 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1221 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1222 let a: A = Readable::read(r)?;
1223 let b: B = Readable::read(r)?;
1224 let c: C = Readable::read(r)?;
1225 let d: D = Readable::read(r)?;
1229 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1230 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1238 impl Writeable for () {
1239 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1243 impl Readable for () {
1244 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1249 impl Writeable for String {
1251 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1252 CollectionLength(self.len() as u64).write(w)?;
1253 w.write_all(self.as_bytes())
1256 impl Readable for String {
1258 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1259 let v: Vec<u8> = Readable::read(r)?;
1260 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1265 /// Represents a hostname for serialization purposes.
1266 /// Only the character set and length will be validated.
1267 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1268 /// Its length is guaranteed to be representable by a single byte.
1269 /// This serialization is used by [`BOLT 7`] hostnames.
1271 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1272 #[derive(Clone, Debug, PartialEq, Eq)]
1273 pub struct Hostname(String);
1275 /// Returns the length of the hostname.
1276 pub fn len(&self) -> u8 {
1277 (&self.0).len() as u8
1280 impl Deref for Hostname {
1281 type Target = String;
1283 fn deref(&self) -> &Self::Target {
1287 impl From<Hostname> for String {
1288 fn from(hostname: Hostname) -> Self {
1292 impl TryFrom<Vec<u8>> for Hostname {
1295 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1296 if let Ok(s) = String::from_utf8(bytes) {
1297 Hostname::try_from(s)
1303 impl TryFrom<String> for Hostname {
1306 fn try_from(s: String) -> Result<Self, Self::Error> {
1307 if s.len() <= 255 && s.chars().all(|c|
1308 c.is_ascii_alphanumeric() ||
1318 impl Writeable for Hostname {
1320 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1321 self.len().write(w)?;
1322 w.write_all(self.as_bytes())
1325 impl Readable for Hostname {
1327 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1328 let len: u8 = Readable::read(r)?;
1329 let mut vec = Vec::with_capacity(len.into());
1330 vec.resize(len.into(), 0);
1331 r.read_exact(&mut vec)?;
1332 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1336 impl Writeable for Duration {
1338 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1339 self.as_secs().write(w)?;
1340 self.subsec_nanos().write(w)
1343 impl Readable for Duration {
1345 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1346 let secs = Readable::read(r)?;
1347 let nanos = Readable::read(r)?;
1348 Ok(Duration::new(secs, nanos))
1352 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1353 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1355 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1356 #[derive(Clone, Debug, PartialEq, Eq)]
1357 pub struct TransactionU16LenLimited(Transaction);
1359 impl TransactionU16LenLimited {
1360 /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1361 /// serialized length is <= u16::MAX.
1362 pub fn new(transaction: Transaction) -> Result<Self, ()> {
1363 if transaction.serialized_length() > (u16::MAX as usize) {
1366 Ok(Self(transaction))
1370 /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1371 pub fn into_transaction(self) -> Transaction {
1376 impl Writeable for TransactionU16LenLimited {
1377 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1378 (self.0.serialized_length() as u16).write(w)?;
1383 impl Readable for TransactionU16LenLimited {
1384 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1385 let len = <u16 as Readable>::read(r)?;
1386 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1387 let tx: Transaction = Readable::read(&mut tx_reader)?;
1388 if tx_reader.bytes_remain() {
1389 Err(DecodeError::BadLengthDescriptor)
1398 use core::convert::TryFrom;
1399 use bitcoin::secp256k1::ecdsa;
1400 use crate::util::ser::{Readable, Hostname, Writeable};
1403 fn hostname_conversion() {
1404 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1406 assert!(Hostname::try_from(String::from("\"")).is_err());
1407 assert!(Hostname::try_from(String::from("$")).is_err());
1408 assert!(Hostname::try_from(String::from("⚡")).is_err());
1409 let mut large_vec = Vec::with_capacity(256);
1410 large_vec.resize(256, b'A');
1411 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1415 fn hostname_serialization() {
1416 let hostname = Hostname::try_from(String::from("test")).unwrap();
1417 let mut buf: Vec<u8> = Vec::new();
1418 hostname.write(&mut buf).unwrap();
1419 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1423 /// Taproot will likely fill legacy signature fields with all 0s.
1424 /// This test ensures that doing so won't break serialization.
1425 fn null_signature_codec() {
1426 let buffer = vec![0u8; 64];
1427 let mut cursor = crate::io::Cursor::new(buffer.clone());
1428 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1429 let serialization = signature.serialize_compact();
1430 assert_eq!(buffer, serialization.to_vec())
1434 fn bigsize_encoding_decoding() {
1435 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1443 "ff0000000100000000",
1444 "ffffffffffffffffff"
1447 let mut stream = crate::io::Cursor::new(::hex::decode(bytes[i]).unwrap());
1448 assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1449 let mut stream = super::VecWriter(Vec::new());
1450 super::BigSize(values[i]).write(&mut stream).unwrap();
1451 assert_eq!(stream.0, ::hex::decode(bytes[i]).unwrap());
1453 let err_bytes = vec![
1456 "ff00000000ffffffff",
1466 let mut stream = crate::io::Cursor::new(::hex::decode(err_bytes[i]).unwrap());
1468 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1470 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));