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::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<R: Read> {
116 impl<R: Read> FixedLengthReader<R> {
117 /// Returns a new [`FixedLengthReader`].
118 pub fn new(read: 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<R: Read> Read for FixedLengthReader<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<R: Read> LengthRead for FixedLengthReader<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 mut msg = VecWriter(Vec::new());
203 self.write(&mut msg).unwrap();
207 /// Writes `self` out to a `Vec<u8>`.
209 fn encode_with_len(&self) -> Vec<u8> {
210 let mut msg = VecWriter(Vec::new());
211 0u16.write(&mut msg).unwrap();
212 self.write(&mut msg).unwrap();
213 let len = msg.0.len();
214 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
218 /// Gets the length of this object after it has been serialized. This can be overridden to
219 /// optimize cases where we prepend an object with its length.
220 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
222 fn serialized_length(&self) -> usize {
223 let mut len_calc = LengthCalculatingWriter(0);
224 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
229 impl<'a, T: Writeable> Writeable for &'a T {
230 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
233 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
235 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
239 /// Reads a `Self` in from the given [`Read`].
240 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
243 /// A trait that various LDK types implement allowing them to be read in from a
244 /// [`Read`]` + `[`Seek`].
245 pub(crate) trait SeekReadable where Self: Sized {
246 /// Reads a `Self` in from the given [`Read`].
247 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
250 /// A trait that various higher-level LDK types implement allowing them to be read in
251 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
253 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
254 pub trait ReadableArgs<P>
257 /// Reads a `Self` in from the given [`Read`].
258 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
261 /// A [`std::io::Read`] that also provides the total bytes available to be read.
262 pub(crate) trait LengthRead: Read {
263 /// The total number of bytes available to be read.
264 fn total_bytes(&self) -> u64;
267 /// A trait that various higher-level LDK types implement allowing them to be read in
268 /// from a Read given some additional set of arguments which is required to deserialize, requiring
269 /// the implementer to provide the total length of the read.
270 pub(crate) trait LengthReadableArgs<P> where Self: Sized
272 /// Reads a `Self` in from the given [`LengthRead`].
273 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
276 /// A trait that various higher-level LDK types implement allowing them to be read in
277 /// from a [`Read`], requiring the implementer to provide the total length of the read.
278 pub(crate) trait LengthReadable where Self: Sized
280 /// Reads a `Self` in from the given [`LengthRead`].
281 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
284 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
286 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
287 pub trait MaybeReadable
290 /// Reads a `Self` in from the given [`Read`].
291 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
294 impl<T: Readable> MaybeReadable for T {
296 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
297 Ok(Some(Readable::read(reader)?))
301 /// Wrapper to read a required (non-optional) TLV record.
303 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
304 pub struct RequiredWrapper<T>(pub Option<T>);
305 impl<T: Readable> Readable for RequiredWrapper<T> {
307 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
308 Ok(Self(Some(Readable::read(reader)?)))
311 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
313 fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
314 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
317 /// When handling `default_values`, we want to map the default-value T directly
318 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
319 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
320 impl<T> From<T> for RequiredWrapper<T> {
321 fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
324 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
325 /// backwards compat.
327 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
328 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
329 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
331 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
332 let tlv = MaybeReadable::read(reader)?;
333 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
338 pub(crate) struct U48(pub u64);
339 impl Writeable for U48 {
341 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
342 writer.write_all(&be48_to_array(self.0))
345 impl Readable for U48 {
347 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
348 let mut buf = [0; 6];
349 reader.read_exact(&mut buf)?;
350 Ok(U48(slice_to_be48(&buf)))
354 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
355 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
357 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
358 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
359 /// you're looking for an example of a variable-length integer to use for your own project, move
360 /// along, this is a rather poor design.
361 pub struct BigSize(pub u64);
362 impl Writeable for BigSize {
364 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
367 (self.0 as u8).write(writer)
370 0xFDu8.write(writer)?;
371 (self.0 as u16).write(writer)
373 0x10000...0xFFFFFFFF => {
374 0xFEu8.write(writer)?;
375 (self.0 as u32).write(writer)
378 0xFFu8.write(writer)?;
379 (self.0 as u64).write(writer)
384 impl Readable for BigSize {
386 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
387 let n: u8 = Readable::read(reader)?;
390 let x: u64 = Readable::read(reader)?;
392 Err(DecodeError::InvalidValue)
398 let x: u32 = Readable::read(reader)?;
400 Err(DecodeError::InvalidValue)
402 Ok(BigSize(x as u64))
406 let x: u16 = Readable::read(reader)?;
408 Err(DecodeError::InvalidValue)
410 Ok(BigSize(x as u64))
413 n => Ok(BigSize(n as u64))
418 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
419 /// primarily targets that, we must as well. However, because we may serialize objects that have
420 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
421 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
422 /// "read eight more bytes".
424 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
425 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
426 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
427 struct CollectionLength(pub u64);
428 impl Writeable for CollectionLength {
430 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
432 (self.0 as u16).write(writer)
434 0xffffu16.write(writer)?;
435 (self.0 - 0xffff).write(writer)
440 impl Readable for CollectionLength {
442 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
443 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
445 val = <u64 as Readable>::read(r)?
446 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
448 Ok(CollectionLength(val))
452 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
453 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
454 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
455 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
456 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
458 macro_rules! impl_writeable_primitive {
459 ($val_type:ty, $len: expr) => {
460 impl Writeable for $val_type {
462 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
463 writer.write_all(&self.to_be_bytes())
466 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
468 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
469 // Skip any full leading 0 bytes when writing (in BE):
470 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
473 impl Readable for $val_type {
475 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
476 let mut buf = [0; $len];
477 reader.read_exact(&mut buf)?;
478 Ok(<$val_type>::from_be_bytes(buf))
481 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
483 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
484 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
485 // the high bytes being dropped. To do so, we start reading into the middle of buf
486 // and then convert the appropriate number of bytes with extra high bytes out of
488 let mut buf = [0; $len*2];
489 let mut read_len = reader.read(&mut buf[$len..])?;
490 let mut total_read_len = read_len;
491 while read_len != 0 && total_read_len != $len {
492 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
493 total_read_len += read_len;
495 if total_read_len == 0 || buf[$len] != 0 {
496 let first_byte = $len - ($len - total_read_len);
497 let mut bytes = [0; $len];
498 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
499 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
501 // If the encoding had extra zero bytes, return a failure even though we know
502 // what they meant (as the TLV test vectors require this)
503 Err(DecodeError::InvalidValue)
507 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
508 fn from(val: $val_type) -> Self { Self(val) }
513 impl_writeable_primitive!(u128, 16);
514 impl_writeable_primitive!(u64, 8);
515 impl_writeable_primitive!(u32, 4);
516 impl_writeable_primitive!(u16, 2);
517 impl_writeable_primitive!(i64, 8);
518 impl_writeable_primitive!(i32, 4);
519 impl_writeable_primitive!(i16, 2);
520 impl_writeable_primitive!(i8, 1);
522 impl Writeable for u8 {
524 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
525 writer.write_all(&[*self])
528 impl Readable for u8 {
530 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
531 let mut buf = [0; 1];
532 reader.read_exact(&mut buf)?;
537 impl Writeable for bool {
539 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
540 writer.write_all(&[if *self {1} else {0}])
543 impl Readable for bool {
545 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
546 let mut buf = [0; 1];
547 reader.read_exact(&mut buf)?;
548 if buf[0] != 0 && buf[0] != 1 {
549 return Err(DecodeError::InvalidValue);
556 macro_rules! impl_array {
558 impl Writeable for [u8; $size]
561 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
566 impl Readable for [u8; $size]
569 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
570 let mut buf = [0u8; $size];
571 r.read_exact(&mut buf)?;
578 impl_array!(3); // for rgb, ISO 4712 code
579 impl_array!(4); // for IPv4
580 impl_array!(12); // for OnionV2
581 impl_array!(16); // for IPv6
582 impl_array!(32); // for channel id & hmac
583 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
584 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
585 impl_array!(66); // for MuSig2 nonces
586 impl_array!(1300); // for OnionPacket.hop_data
588 impl Writeable for [u16; 8] {
590 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
591 for v in self.iter() {
592 w.write_all(&v.to_be_bytes())?
598 impl Readable for [u16; 8] {
600 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
601 let mut buf = [0u8; 16];
602 r.read_exact(&mut buf)?;
603 let mut res = [0u16; 8];
604 for (idx, v) in res.iter_mut().enumerate() {
605 *v = (buf[idx*2] as u16) << 8 | (buf[idx*2 + 1] as u16)
611 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
612 /// Used to prevent encoding the length twice.
614 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
615 pub struct WithoutLength<T>(pub T);
617 impl Writeable for WithoutLength<&String> {
619 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
620 w.write_all(self.0.as_bytes())
623 impl Readable for WithoutLength<String> {
625 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
626 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
627 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
630 impl<'a> From<&'a String> for WithoutLength<&'a String> {
631 fn from(s: &'a String) -> Self { Self(s) }
635 impl Writeable for WithoutLength<&UntrustedString> {
637 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
638 WithoutLength(&self.0.0).write(w)
641 impl Readable for WithoutLength<UntrustedString> {
643 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
644 let s: WithoutLength<String> = Readable::read(r)?;
645 Ok(Self(UntrustedString(s.0)))
649 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
651 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
652 for ref v in self.0.iter() {
659 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
661 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
662 let mut values = Vec::new();
664 let mut track_read = ReadTrackingReader::new(&mut reader);
665 match MaybeReadable::read(&mut track_read) {
666 Ok(Some(v)) => { values.push(v); },
668 // If we failed to read any bytes at all, we reached the end of our TLV
669 // stream and have simply exhausted all entries.
670 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
671 Err(e) => return Err(e),
677 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
678 fn from(v: &'a Vec<T>) -> Self { Self(v) }
681 impl Writeable for WithoutLength<&Script> {
683 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
684 writer.write_all(self.0.as_bytes())
688 impl Readable for WithoutLength<Script> {
690 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
691 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
692 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
697 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
699 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
701 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
702 for ref v in self.0.clone() {
710 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
711 fn eq(&self, other: &Self) -> bool {
712 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
716 macro_rules! impl_for_map {
717 ($ty: ident, $keybound: ident, $constr: expr) => {
718 impl<K, V> Writeable for $ty<K, V>
719 where K: Writeable + Eq + $keybound, V: Writeable
722 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
723 CollectionLength(self.len() as u64).write(w)?;
724 for (key, value) in self.iter() {
732 impl<K, V> Readable for $ty<K, V>
733 where K: Readable + Eq + $keybound, V: MaybeReadable
736 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
737 let len: CollectionLength = Readable::read(r)?;
738 let mut ret = $constr(len.0 as usize);
741 let v_opt = V::read(r)?;
742 if let Some(v) = v_opt {
743 if ret.insert(k, v).is_some() {
744 return Err(DecodeError::InvalidValue);
754 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
755 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
758 impl<T> Writeable for HashSet<T>
759 where T: Writeable + Eq + Hash
762 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
763 CollectionLength(self.len() as u64).write(w)?;
764 for item in self.iter() {
771 impl<T> Readable for HashSet<T>
772 where T: Readable + Eq + Hash
775 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
776 let len: CollectionLength = Readable::read(r)?;
777 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
779 if !ret.insert(T::read(r)?) {
780 return Err(DecodeError::InvalidValue)
788 macro_rules! impl_writeable_for_vec {
789 ($ty: ty $(, $name: ident)*) => {
790 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
792 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
793 CollectionLength(self.len() as u64).write(w)?;
794 for elem in self.iter() {
802 macro_rules! impl_readable_for_vec {
803 ($ty: ty $(, $name: ident)*) => {
804 impl<$($name : Readable),*> Readable for Vec<$ty> {
806 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
807 let len: CollectionLength = Readable::read(r)?;
808 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
810 if let Some(val) = MaybeReadable::read(r)? {
819 macro_rules! impl_for_vec {
820 ($ty: ty $(, $name: ident)*) => {
821 impl_writeable_for_vec!($ty $(, $name)*);
822 impl_readable_for_vec!($ty $(, $name)*);
826 impl Writeable for Vec<u8> {
828 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
829 CollectionLength(self.len() as u64).write(w)?;
834 impl Readable for Vec<u8> {
836 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
837 let mut len: CollectionLength = Readable::read(r)?;
838 let mut ret = Vec::new();
840 let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
841 let readstart = ret.len();
842 ret.resize(readstart + readamt, 0);
843 r.read_exact(&mut ret[readstart..])?;
844 len.0 -= readamt as u64;
850 impl_for_vec!(ecdsa::Signature);
851 impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
852 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
853 impl_for_vec!((A, B), A, B);
854 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
855 impl_readable_for_vec!(crate::routing::router::BlindedTail);
857 impl Writeable for Vec<Witness> {
859 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
860 (self.len() as u16).write(w)?;
861 for witness in self {
862 (witness.serialized_len() as u16).write(w)?;
869 impl Readable for Vec<Witness> {
871 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
872 let num_witnesses = <u16 as Readable>::read(r)? as usize;
873 let mut witnesses = Vec::with_capacity(num_witnesses);
874 for _ in 0..num_witnesses {
875 // Even though the length of each witness can be inferred in its consensus-encoded form,
876 // the spec includes a length prefix so that implementations don't have to deserialize
877 // each initially. We do that here anyway as in general we'll need to be able to make
878 // assertions on some properties of the witnesses when receiving a message providing a list
879 // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
880 let witness_len = <u16 as Readable>::read(r)? as usize;
881 let witness = <Witness as Readable>::read(r)?;
882 if witness.serialized_len() != witness_len {
883 return Err(DecodeError::BadLengthDescriptor);
885 witnesses.push(witness);
891 impl Writeable for Script {
892 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
893 (self.len() as u16).write(w)?;
894 w.write_all(self.as_bytes())
898 impl Readable for Script {
899 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
900 let len = <u16 as Readable>::read(r)? as usize;
901 let mut buf = vec![0; len];
902 r.read_exact(&mut buf)?;
903 Ok(Script::from(buf))
907 impl Writeable for PublicKey {
908 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
909 self.serialize().write(w)
912 fn serialized_length(&self) -> usize {
917 impl Readable for PublicKey {
918 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
919 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
920 match PublicKey::from_slice(&buf) {
922 Err(_) => return Err(DecodeError::InvalidValue),
927 impl Writeable for SecretKey {
928 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
929 let mut ser = [0; SECRET_KEY_SIZE];
930 ser.copy_from_slice(&self[..]);
934 fn serialized_length(&self) -> usize {
939 impl Readable for SecretKey {
940 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
941 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
942 match SecretKey::from_slice(&buf) {
944 Err(_) => return Err(DecodeError::InvalidValue),
950 impl Writeable for musig2::types::PublicNonce {
951 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
952 self.serialize().write(w)
957 impl Readable for musig2::types::PublicNonce {
958 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
959 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
960 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
965 impl Writeable for PartialSignatureWithNonce {
966 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
967 self.0.serialize().write(w)?;
973 impl Readable for PartialSignatureWithNonce {
974 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
975 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
976 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
977 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
978 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
982 impl Writeable for Sha256dHash {
983 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
984 w.write_all(&self[..])
988 impl Readable for Sha256dHash {
989 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
990 use bitcoin::hashes::Hash;
992 let buf: [u8; 32] = Readable::read(r)?;
993 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
997 impl Writeable for ecdsa::Signature {
998 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
999 self.serialize_compact().write(w)
1003 impl Readable for ecdsa::Signature {
1004 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1005 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1006 match ecdsa::Signature::from_compact(&buf) {
1008 Err(_) => return Err(DecodeError::InvalidValue),
1013 impl Writeable for schnorr::Signature {
1014 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1015 self.as_ref().write(w)
1019 impl Readable for schnorr::Signature {
1020 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1021 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1022 match schnorr::Signature::from_slice(&buf) {
1024 Err(_) => return Err(DecodeError::InvalidValue),
1029 impl Writeable for PaymentPreimage {
1030 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1035 impl Readable for PaymentPreimage {
1036 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1037 let buf: [u8; 32] = Readable::read(r)?;
1038 Ok(PaymentPreimage(buf))
1042 impl Writeable for PaymentHash {
1043 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1048 impl Readable for PaymentHash {
1049 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1050 let buf: [u8; 32] = Readable::read(r)?;
1051 Ok(PaymentHash(buf))
1055 impl Writeable for PaymentSecret {
1056 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1061 impl Readable for PaymentSecret {
1062 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1063 let buf: [u8; 32] = Readable::read(r)?;
1064 Ok(PaymentSecret(buf))
1068 impl<T: Writeable> Writeable for Box<T> {
1069 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1070 T::write(&**self, w)
1074 impl<T: Readable> Readable for Box<T> {
1075 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1076 Ok(Box::new(Readable::read(r)?))
1080 impl<T: Writeable> Writeable for Option<T> {
1081 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1083 None => 0u8.write(w)?,
1085 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1093 impl<T: Readable> Readable for Option<T>
1095 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1096 let len: BigSize = Readable::read(r)?;
1100 let mut reader = FixedLengthReader::new(r, len - 1);
1101 Ok(Some(Readable::read(&mut reader)?))
1107 impl Writeable for Txid {
1108 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1109 w.write_all(&self[..])
1113 impl Readable for Txid {
1114 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1115 use bitcoin::hashes::Hash;
1117 let buf: [u8; 32] = Readable::read(r)?;
1118 Ok(Txid::from_slice(&buf[..]).unwrap())
1122 impl Writeable for BlockHash {
1123 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1124 w.write_all(&self[..])
1128 impl Readable for BlockHash {
1129 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1130 use bitcoin::hashes::Hash;
1132 let buf: [u8; 32] = Readable::read(r)?;
1133 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1137 impl Writeable for ChainHash {
1138 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1139 w.write_all(self.as_bytes())
1143 impl Readable for ChainHash {
1144 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1145 let buf: [u8; 32] = Readable::read(r)?;
1146 Ok(ChainHash::from(&buf[..]))
1150 impl Writeable for OutPoint {
1151 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1152 self.txid.write(w)?;
1153 self.vout.write(w)?;
1158 impl Readable for OutPoint {
1159 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1160 let txid = Readable::read(r)?;
1161 let vout = Readable::read(r)?;
1169 macro_rules! impl_consensus_ser {
1170 ($bitcoin_type: ty) => {
1171 impl Writeable for $bitcoin_type {
1172 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1173 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1180 impl Readable for $bitcoin_type {
1181 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1182 match consensus::encode::Decodable::consensus_decode(r) {
1184 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1185 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1186 Err(_) => Err(DecodeError::InvalidValue),
1192 impl_consensus_ser!(Transaction);
1193 impl_consensus_ser!(TxOut);
1194 impl_consensus_ser!(Witness);
1196 impl<T: Readable> Readable for Mutex<T> {
1197 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1198 let t: T = Readable::read(r)?;
1202 impl<T: Writeable> Writeable for Mutex<T> {
1203 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1204 self.lock().unwrap().write(w)
1208 impl<A: Readable, B: Readable> Readable for (A, B) {
1209 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1210 let a: A = Readable::read(r)?;
1211 let b: B = Readable::read(r)?;
1215 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1216 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1222 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1223 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1224 let a: A = Readable::read(r)?;
1225 let b: B = Readable::read(r)?;
1226 let c: C = Readable::read(r)?;
1230 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1231 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1238 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1239 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1240 let a: A = Readable::read(r)?;
1241 let b: B = Readable::read(r)?;
1242 let c: C = Readable::read(r)?;
1243 let d: D = Readable::read(r)?;
1247 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1248 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1256 impl Writeable for () {
1257 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1261 impl Readable for () {
1262 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1267 impl Writeable for String {
1269 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1270 CollectionLength(self.len() as u64).write(w)?;
1271 w.write_all(self.as_bytes())
1274 impl Readable for String {
1276 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1277 let v: Vec<u8> = Readable::read(r)?;
1278 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1283 /// Represents a hostname for serialization purposes.
1284 /// Only the character set and length will be validated.
1285 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1286 /// Its length is guaranteed to be representable by a single byte.
1287 /// This serialization is used by [`BOLT 7`] hostnames.
1289 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1290 #[derive(Clone, Debug, PartialEq, Eq)]
1291 pub struct Hostname(String);
1293 /// Returns the length of the hostname.
1294 pub fn len(&self) -> u8 {
1295 (&self.0).len() as u8
1298 impl Deref for Hostname {
1299 type Target = String;
1301 fn deref(&self) -> &Self::Target {
1305 impl From<Hostname> for String {
1306 fn from(hostname: Hostname) -> Self {
1310 impl TryFrom<Vec<u8>> for Hostname {
1313 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1314 if let Ok(s) = String::from_utf8(bytes) {
1315 Hostname::try_from(s)
1321 impl TryFrom<String> for Hostname {
1324 fn try_from(s: String) -> Result<Self, Self::Error> {
1325 if s.len() <= 255 && s.chars().all(|c|
1326 c.is_ascii_alphanumeric() ||
1336 impl Writeable for Hostname {
1338 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1339 self.len().write(w)?;
1340 w.write_all(self.as_bytes())
1343 impl Readable for Hostname {
1345 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1346 let len: u8 = Readable::read(r)?;
1347 let mut vec = Vec::with_capacity(len.into());
1348 vec.resize(len.into(), 0);
1349 r.read_exact(&mut vec)?;
1350 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1354 impl Writeable for Duration {
1356 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1357 self.as_secs().write(w)?;
1358 self.subsec_nanos().write(w)
1361 impl Readable for Duration {
1363 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1364 let secs = Readable::read(r)?;
1365 let nanos = Readable::read(r)?;
1366 Ok(Duration::new(secs, nanos))
1370 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1371 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1373 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1374 #[derive(Clone, Debug, PartialEq, Eq)]
1375 pub struct TransactionU16LenLimited(Transaction);
1377 impl TransactionU16LenLimited {
1378 /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1379 /// serialized length is <= u16::MAX.
1380 pub fn new(transaction: Transaction) -> Result<Self, ()> {
1381 if transaction.serialized_length() > (u16::MAX as usize) {
1384 Ok(Self(transaction))
1388 /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1389 pub fn into_transaction(self) -> Transaction {
1394 impl Writeable for TransactionU16LenLimited {
1395 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1396 (self.0.serialized_length() as u16).write(w)?;
1401 impl Readable for TransactionU16LenLimited {
1402 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1403 let len = <u16 as Readable>::read(r)?;
1404 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1405 let tx: Transaction = Readable::read(&mut tx_reader)?;
1406 if tx_reader.bytes_remain() {
1407 Err(DecodeError::BadLengthDescriptor)
1414 impl Writeable for ClaimId {
1415 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1416 self.0.write(writer)
1420 impl Readable for ClaimId {
1421 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1422 Ok(Self(Readable::read(reader)?))
1428 use core::convert::TryFrom;
1429 use bitcoin::secp256k1::ecdsa;
1430 use crate::util::ser::{Readable, Hostname, Writeable};
1433 fn hostname_conversion() {
1434 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1436 assert!(Hostname::try_from(String::from("\"")).is_err());
1437 assert!(Hostname::try_from(String::from("$")).is_err());
1438 assert!(Hostname::try_from(String::from("⚡")).is_err());
1439 let mut large_vec = Vec::with_capacity(256);
1440 large_vec.resize(256, b'A');
1441 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1445 fn hostname_serialization() {
1446 let hostname = Hostname::try_from(String::from("test")).unwrap();
1447 let mut buf: Vec<u8> = Vec::new();
1448 hostname.write(&mut buf).unwrap();
1449 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1453 /// Taproot will likely fill legacy signature fields with all 0s.
1454 /// This test ensures that doing so won't break serialization.
1455 fn null_signature_codec() {
1456 let buffer = vec![0u8; 64];
1457 let mut cursor = crate::io::Cursor::new(buffer.clone());
1458 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1459 let serialization = signature.serialize_compact();
1460 assert_eq!(buffer, serialization.to_vec())
1464 fn bigsize_encoding_decoding() {
1465 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1473 "ff0000000100000000",
1474 "ffffffffffffffffff"
1477 let mut stream = crate::io::Cursor::new(::hex::decode(bytes[i]).unwrap());
1478 assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1479 let mut stream = super::VecWriter(Vec::new());
1480 super::BigSize(values[i]).write(&mut stream).unwrap();
1481 assert_eq!(stream.0, ::hex::decode(bytes[i]).unwrap());
1483 let err_bytes = vec![
1486 "ff00000000ffffffff",
1496 let mut stream = crate::io::Cursor::new(::hex::decode(err_bytes[i]).unwrap());
1498 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1500 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));