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};
46 use crate::util::string::UntrustedString;
48 /// serialization buffer size
49 pub const MAX_BUF_SIZE: usize = 64 * 1024;
51 /// A simplified version of [`std::io::Write`] that exists largely for backwards compatibility.
52 /// An impl is provided for any type that also impls [`std::io::Write`].
54 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
56 /// Writes the given buf out. See std::io::Write::write_all for more
57 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
60 impl<W: Write> Writer for W {
62 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
63 <Self as io::Write>::write_all(self, buf)
67 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
68 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
70 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
74 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
75 self.0.write_all(buf)?;
79 fn flush(&mut self) -> Result<(), io::Error> {
84 pub(crate) struct VecWriter(pub Vec<u8>);
85 impl Writer for VecWriter {
87 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
88 self.0.extend_from_slice(buf);
93 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
94 /// of some data when serialized but don't yet need the full data.
96 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
97 pub struct LengthCalculatingWriter(pub usize);
98 impl Writer for LengthCalculatingWriter {
100 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
106 /// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
107 /// forward to ensure we always consume exactly the fixed length specified.
109 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
110 pub struct FixedLengthReader<R: Read> {
115 impl<R: Read> FixedLengthReader<R> {
116 /// Returns a new [`FixedLengthReader`].
117 pub fn new(read: R, total_bytes: u64) -> Self {
118 Self { read, bytes_read: 0, total_bytes }
121 /// Returns whether some bytes are remaining or not.
123 pub fn bytes_remain(&mut self) -> bool {
124 self.bytes_read != self.total_bytes
127 /// Consumes the remaining bytes.
129 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
130 copy(self, &mut sink()).unwrap();
131 if self.bytes_read != self.total_bytes {
132 Err(DecodeError::ShortRead)
138 impl<R: Read> Read for FixedLengthReader<R> {
140 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
141 if self.total_bytes == self.bytes_read {
144 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
145 match self.read.read(&mut dest[0..(read_len as usize)]) {
147 self.bytes_read += v as u64;
156 impl<R: Read> LengthRead for FixedLengthReader<R> {
158 fn total_bytes(&self) -> u64 {
163 /// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
164 /// between "EOF reached before we started" and "EOF reached mid-read".
166 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
167 pub struct ReadTrackingReader<R: Read> {
169 /// Returns whether we have read from this reader or not yet.
172 impl<R: Read> ReadTrackingReader<R> {
173 /// Returns a new [`ReadTrackingReader`].
174 pub fn new(read: R) -> Self {
175 Self { read, have_read: false }
178 impl<R: Read> Read for ReadTrackingReader<R> {
180 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
181 match self.read.read(dest) {
184 self.have_read = true;
192 /// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
194 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
195 pub trait Writeable {
196 /// Writes `self` out to the given [`Writer`].
197 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
199 /// Writes `self` out to a `Vec<u8>`.
200 fn encode(&self) -> Vec<u8> {
201 let mut msg = VecWriter(Vec::new());
202 self.write(&mut msg).unwrap();
206 /// Writes `self` out to a `Vec<u8>`.
208 fn encode_with_len(&self) -> Vec<u8> {
209 let mut msg = VecWriter(Vec::new());
210 0u16.write(&mut msg).unwrap();
211 self.write(&mut msg).unwrap();
212 let len = msg.0.len();
213 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
217 /// Gets the length of this object after it has been serialized. This can be overridden to
218 /// optimize cases where we prepend an object with its length.
219 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
221 fn serialized_length(&self) -> usize {
222 let mut len_calc = LengthCalculatingWriter(0);
223 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
228 impl<'a, T: Writeable> Writeable for &'a T {
229 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
232 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
234 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
238 /// Reads a `Self` in from the given [`Read`].
239 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
242 /// A trait that various LDK types implement allowing them to be read in from a
243 /// [`Read`]` + `[`Seek`].
244 pub(crate) trait SeekReadable where Self: Sized {
245 /// Reads a `Self` in from the given [`Read`].
246 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
249 /// A trait that various higher-level LDK types implement allowing them to be read in
250 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
252 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
253 pub trait ReadableArgs<P>
256 /// Reads a `Self` in from the given [`Read`].
257 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
260 /// A [`std::io::Read`] that also provides the total bytes available to be read.
261 pub(crate) trait LengthRead: Read {
262 /// The total number of bytes available to be read.
263 fn total_bytes(&self) -> u64;
266 /// A trait that various higher-level LDK types implement allowing them to be read in
267 /// from a Read given some additional set of arguments which is required to deserialize, requiring
268 /// the implementer to provide the total length of the read.
269 pub(crate) trait LengthReadableArgs<P> where Self: Sized
271 /// Reads a `Self` in from the given [`LengthRead`].
272 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
275 /// A trait that various higher-level LDK types implement allowing them to be read in
276 /// from a [`Read`], requiring the implementer to provide the total length of the read.
277 pub(crate) trait LengthReadable where Self: Sized
279 /// Reads a `Self` in from the given [`LengthRead`].
280 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
283 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
285 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
286 pub trait MaybeReadable
289 /// Reads a `Self` in from the given [`Read`].
290 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
293 impl<T: Readable> MaybeReadable for T {
295 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
296 Ok(Some(Readable::read(reader)?))
300 /// Wrapper to read a required (non-optional) TLV record.
302 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
303 pub struct RequiredWrapper<T>(pub Option<T>);
304 impl<T: Readable> Readable for RequiredWrapper<T> {
306 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
307 Ok(Self(Some(Readable::read(reader)?)))
310 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
312 fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
313 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
316 /// When handling `default_values`, we want to map the default-value T directly
317 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
318 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
319 impl<T> From<T> for RequiredWrapper<T> {
320 fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
323 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
324 /// backwards compat.
326 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
327 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
328 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
330 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
331 let tlv = MaybeReadable::read(reader)?;
332 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
337 pub(crate) struct U48(pub u64);
338 impl Writeable for U48 {
340 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
341 writer.write_all(&be48_to_array(self.0))
344 impl Readable for U48 {
346 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
347 let mut buf = [0; 6];
348 reader.read_exact(&mut buf)?;
349 Ok(U48(slice_to_be48(&buf)))
353 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
354 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
356 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
357 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
358 /// you're looking for an example of a variable-length integer to use for your own project, move
359 /// along, this is a rather poor design.
360 pub struct BigSize(pub u64);
361 impl Writeable for BigSize {
363 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
366 (self.0 as u8).write(writer)
369 0xFDu8.write(writer)?;
370 (self.0 as u16).write(writer)
372 0x10000...0xFFFFFFFF => {
373 0xFEu8.write(writer)?;
374 (self.0 as u32).write(writer)
377 0xFFu8.write(writer)?;
378 (self.0 as u64).write(writer)
383 impl Readable for BigSize {
385 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
386 let n: u8 = Readable::read(reader)?;
389 let x: u64 = Readable::read(reader)?;
391 Err(DecodeError::InvalidValue)
397 let x: u32 = Readable::read(reader)?;
399 Err(DecodeError::InvalidValue)
401 Ok(BigSize(x as u64))
405 let x: u16 = Readable::read(reader)?;
407 Err(DecodeError::InvalidValue)
409 Ok(BigSize(x as u64))
412 n => Ok(BigSize(n as u64))
417 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
418 /// primarily targets that, we must as well. However, because we may serialize objects that have
419 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
420 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
421 /// "read eight more bytes".
423 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
424 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
425 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
426 struct CollectionLength(pub u64);
427 impl Writeable for CollectionLength {
429 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
431 (self.0 as u16).write(writer)
433 0xffffu16.write(writer)?;
434 (self.0 - 0xffff).write(writer)
439 impl Readable for CollectionLength {
441 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
442 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
444 val = <u64 as Readable>::read(r)?
445 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
447 Ok(CollectionLength(val))
451 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
452 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
453 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
454 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
455 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
457 macro_rules! impl_writeable_primitive {
458 ($val_type:ty, $len: expr) => {
459 impl Writeable for $val_type {
461 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
462 writer.write_all(&self.to_be_bytes())
465 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
467 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
468 // Skip any full leading 0 bytes when writing (in BE):
469 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
472 impl Readable for $val_type {
474 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
475 let mut buf = [0; $len];
476 reader.read_exact(&mut buf)?;
477 Ok(<$val_type>::from_be_bytes(buf))
480 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
482 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
483 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
484 // the high bytes being dropped. To do so, we start reading into the middle of buf
485 // and then convert the appropriate number of bytes with extra high bytes out of
487 let mut buf = [0; $len*2];
488 let mut read_len = reader.read(&mut buf[$len..])?;
489 let mut total_read_len = read_len;
490 while read_len != 0 && total_read_len != $len {
491 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
492 total_read_len += read_len;
494 if total_read_len == 0 || buf[$len] != 0 {
495 let first_byte = $len - ($len - total_read_len);
496 let mut bytes = [0; $len];
497 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
498 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
500 // If the encoding had extra zero bytes, return a failure even though we know
501 // what they meant (as the TLV test vectors require this)
502 Err(DecodeError::InvalidValue)
506 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
507 fn from(val: $val_type) -> Self { Self(val) }
512 impl_writeable_primitive!(u128, 16);
513 impl_writeable_primitive!(u64, 8);
514 impl_writeable_primitive!(u32, 4);
515 impl_writeable_primitive!(u16, 2);
516 impl_writeable_primitive!(i64, 8);
517 impl_writeable_primitive!(i32, 4);
518 impl_writeable_primitive!(i16, 2);
519 impl_writeable_primitive!(i8, 1);
521 impl Writeable for u8 {
523 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
524 writer.write_all(&[*self])
527 impl Readable for u8 {
529 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
530 let mut buf = [0; 1];
531 reader.read_exact(&mut buf)?;
536 impl Writeable for bool {
538 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
539 writer.write_all(&[if *self {1} else {0}])
542 impl Readable for bool {
544 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
545 let mut buf = [0; 1];
546 reader.read_exact(&mut buf)?;
547 if buf[0] != 0 && buf[0] != 1 {
548 return Err(DecodeError::InvalidValue);
555 macro_rules! impl_array {
557 impl Writeable for [u8; $size]
560 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
565 impl Readable for [u8; $size]
568 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
569 let mut buf = [0u8; $size];
570 r.read_exact(&mut buf)?;
577 impl_array!(3); // for rgb, ISO 4712 code
578 impl_array!(4); // for IPv4
579 impl_array!(12); // for OnionV2
580 impl_array!(16); // for IPv6
581 impl_array!(32); // for channel id & hmac
582 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
583 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
584 impl_array!(66); // for MuSig2 nonces
585 impl_array!(1300); // for OnionPacket.hop_data
587 impl Writeable for [u16; 8] {
589 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
590 for v in self.iter() {
591 w.write_all(&v.to_be_bytes())?
597 impl Readable for [u16; 8] {
599 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
600 let mut buf = [0u8; 16];
601 r.read_exact(&mut buf)?;
602 let mut res = [0u16; 8];
603 for (idx, v) in res.iter_mut().enumerate() {
604 *v = (buf[idx*2] as u16) << 8 | (buf[idx*2 + 1] as u16)
610 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
611 /// Used to prevent encoding the length twice.
613 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
614 pub struct WithoutLength<T>(pub T);
616 impl Writeable for WithoutLength<&String> {
618 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
619 w.write_all(self.0.as_bytes())
622 impl Readable for WithoutLength<String> {
624 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
625 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
626 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
629 impl<'a> From<&'a String> for WithoutLength<&'a String> {
630 fn from(s: &'a String) -> Self { Self(s) }
634 impl Writeable for WithoutLength<&UntrustedString> {
636 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
637 WithoutLength(&self.0.0).write(w)
640 impl Readable for WithoutLength<UntrustedString> {
642 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
643 let s: WithoutLength<String> = Readable::read(r)?;
644 Ok(Self(UntrustedString(s.0)))
648 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
650 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
651 for ref v in self.0.iter() {
658 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
660 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
661 let mut values = Vec::new();
663 let mut track_read = ReadTrackingReader::new(&mut reader);
664 match MaybeReadable::read(&mut track_read) {
665 Ok(Some(v)) => { values.push(v); },
667 // If we failed to read any bytes at all, we reached the end of our TLV
668 // stream and have simply exhausted all entries.
669 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
670 Err(e) => return Err(e),
676 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
677 fn from(v: &'a Vec<T>) -> Self { Self(v) }
680 impl Writeable for WithoutLength<&Script> {
682 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
683 writer.write_all(self.0.as_bytes())
687 impl Readable for WithoutLength<Script> {
689 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
690 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
691 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
696 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
698 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
700 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
701 for ref v in self.0.clone() {
709 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
710 fn eq(&self, other: &Self) -> bool {
711 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
715 macro_rules! impl_for_map {
716 ($ty: ident, $keybound: ident, $constr: expr) => {
717 impl<K, V> Writeable for $ty<K, V>
718 where K: Writeable + Eq + $keybound, V: Writeable
721 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
722 CollectionLength(self.len() as u64).write(w)?;
723 for (key, value) in self.iter() {
731 impl<K, V> Readable for $ty<K, V>
732 where K: Readable + Eq + $keybound, V: MaybeReadable
735 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
736 let len: CollectionLength = Readable::read(r)?;
737 let mut ret = $constr(len.0 as usize);
740 let v_opt = V::read(r)?;
741 if let Some(v) = v_opt {
742 if ret.insert(k, v).is_some() {
743 return Err(DecodeError::InvalidValue);
753 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
754 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
757 impl<T> Writeable for HashSet<T>
758 where T: Writeable + Eq + Hash
761 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
762 CollectionLength(self.len() as u64).write(w)?;
763 for item in self.iter() {
770 impl<T> Readable for HashSet<T>
771 where T: Readable + Eq + Hash
774 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
775 let len: CollectionLength = Readable::read(r)?;
776 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
778 if !ret.insert(T::read(r)?) {
779 return Err(DecodeError::InvalidValue)
787 macro_rules! impl_writeable_for_vec {
788 ($ty: ty $(, $name: ident)*) => {
789 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
791 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
792 CollectionLength(self.len() as u64).write(w)?;
793 for elem in self.iter() {
801 macro_rules! impl_readable_for_vec {
802 ($ty: ty $(, $name: ident)*) => {
803 impl<$($name : Readable),*> Readable for Vec<$ty> {
805 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
806 let len: CollectionLength = Readable::read(r)?;
807 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
809 if let Some(val) = MaybeReadable::read(r)? {
818 macro_rules! impl_for_vec {
819 ($ty: ty $(, $name: ident)*) => {
820 impl_writeable_for_vec!($ty $(, $name)*);
821 impl_readable_for_vec!($ty $(, $name)*);
825 impl Writeable for Vec<u8> {
827 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
828 CollectionLength(self.len() as u64).write(w)?;
833 impl Readable for Vec<u8> {
835 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
836 let mut len: CollectionLength = Readable::read(r)?;
837 let mut ret = Vec::new();
839 let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
840 let readstart = ret.len();
841 ret.resize(readstart + readamt, 0);
842 r.read_exact(&mut ret[readstart..])?;
843 len.0 -= readamt as u64;
849 impl_for_vec!(ecdsa::Signature);
850 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
851 impl_for_vec!((A, B), A, B);
852 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
853 impl_readable_for_vec!(crate::routing::router::BlindedTail);
855 impl Writeable for Vec<Witness> {
857 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
858 (self.len() as u16).write(w)?;
859 for witness in self {
860 (witness.serialized_len() as u16).write(w)?;
867 impl Readable for Vec<Witness> {
869 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
870 let num_witnesses = <u16 as Readable>::read(r)? as usize;
871 let mut witnesses = Vec::with_capacity(num_witnesses);
872 for _ in 0..num_witnesses {
873 // Even though the length of each witness can be inferred in its consensus-encoded form,
874 // the spec includes a length prefix so that implementations don't have to deserialize
875 // each initially. We do that here anyway as in general we'll need to be able to make
876 // assertions on some properties of the witnesses when receiving a message providing a list
877 // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
878 let witness_len = <u16 as Readable>::read(r)? as usize;
879 let witness = <Witness as Readable>::read(r)?;
880 if witness.serialized_len() != witness_len {
881 return Err(DecodeError::BadLengthDescriptor);
883 witnesses.push(witness);
889 impl Writeable for Script {
890 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
891 (self.len() as u16).write(w)?;
892 w.write_all(self.as_bytes())
896 impl Readable for Script {
897 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
898 let len = <u16 as Readable>::read(r)? as usize;
899 let mut buf = vec![0; len];
900 r.read_exact(&mut buf)?;
901 Ok(Script::from(buf))
905 impl Writeable for PublicKey {
906 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
907 self.serialize().write(w)
910 fn serialized_length(&self) -> usize {
915 impl Readable for PublicKey {
916 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
917 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
918 match PublicKey::from_slice(&buf) {
920 Err(_) => return Err(DecodeError::InvalidValue),
925 impl Writeable for SecretKey {
926 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
927 let mut ser = [0; SECRET_KEY_SIZE];
928 ser.copy_from_slice(&self[..]);
932 fn serialized_length(&self) -> usize {
937 impl Readable for SecretKey {
938 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
939 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
940 match SecretKey::from_slice(&buf) {
942 Err(_) => return Err(DecodeError::InvalidValue),
948 impl Writeable for musig2::types::PublicNonce {
949 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
950 self.serialize().write(w)
955 impl Readable for musig2::types::PublicNonce {
956 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
957 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
958 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
963 impl Writeable for PartialSignatureWithNonce {
964 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
965 self.0.serialize().write(w)?;
971 impl Readable for PartialSignatureWithNonce {
972 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
973 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
974 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
975 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
976 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
980 impl Writeable for Sha256dHash {
981 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
982 w.write_all(&self[..])
986 impl Readable for Sha256dHash {
987 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
988 use bitcoin::hashes::Hash;
990 let buf: [u8; 32] = Readable::read(r)?;
991 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
995 impl Writeable for ecdsa::Signature {
996 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
997 self.serialize_compact().write(w)
1001 impl Readable for ecdsa::Signature {
1002 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1003 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1004 match ecdsa::Signature::from_compact(&buf) {
1006 Err(_) => return Err(DecodeError::InvalidValue),
1011 impl Writeable for schnorr::Signature {
1012 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1013 self.as_ref().write(w)
1017 impl Readable for schnorr::Signature {
1018 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1019 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1020 match schnorr::Signature::from_slice(&buf) {
1022 Err(_) => return Err(DecodeError::InvalidValue),
1027 impl Writeable for PaymentPreimage {
1028 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1033 impl Readable for PaymentPreimage {
1034 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1035 let buf: [u8; 32] = Readable::read(r)?;
1036 Ok(PaymentPreimage(buf))
1040 impl Writeable for PaymentHash {
1041 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1046 impl Readable for PaymentHash {
1047 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1048 let buf: [u8; 32] = Readable::read(r)?;
1049 Ok(PaymentHash(buf))
1053 impl Writeable for PaymentSecret {
1054 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1059 impl Readable for PaymentSecret {
1060 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1061 let buf: [u8; 32] = Readable::read(r)?;
1062 Ok(PaymentSecret(buf))
1066 impl<T: Writeable> Writeable for Box<T> {
1067 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1068 T::write(&**self, w)
1072 impl<T: Readable> Readable for Box<T> {
1073 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1074 Ok(Box::new(Readable::read(r)?))
1078 impl<T: Writeable> Writeable for Option<T> {
1079 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1081 None => 0u8.write(w)?,
1083 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1091 impl<T: Readable> Readable for Option<T>
1093 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1094 let len: BigSize = Readable::read(r)?;
1098 let mut reader = FixedLengthReader::new(r, len - 1);
1099 Ok(Some(Readable::read(&mut reader)?))
1105 impl Writeable for Txid {
1106 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1107 w.write_all(&self[..])
1111 impl Readable for Txid {
1112 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1113 use bitcoin::hashes::Hash;
1115 let buf: [u8; 32] = Readable::read(r)?;
1116 Ok(Txid::from_slice(&buf[..]).unwrap())
1120 impl Writeable for BlockHash {
1121 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1122 w.write_all(&self[..])
1126 impl Readable for BlockHash {
1127 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1128 use bitcoin::hashes::Hash;
1130 let buf: [u8; 32] = Readable::read(r)?;
1131 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1135 impl Writeable for ChainHash {
1136 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1137 w.write_all(self.as_bytes())
1141 impl Readable for ChainHash {
1142 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1143 let buf: [u8; 32] = Readable::read(r)?;
1144 Ok(ChainHash::from(&buf[..]))
1148 impl Writeable for OutPoint {
1149 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1150 self.txid.write(w)?;
1151 self.vout.write(w)?;
1156 impl Readable for OutPoint {
1157 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1158 let txid = Readable::read(r)?;
1159 let vout = Readable::read(r)?;
1167 macro_rules! impl_consensus_ser {
1168 ($bitcoin_type: ty) => {
1169 impl Writeable for $bitcoin_type {
1170 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1171 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1178 impl Readable for $bitcoin_type {
1179 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1180 match consensus::encode::Decodable::consensus_decode(r) {
1182 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1183 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1184 Err(_) => Err(DecodeError::InvalidValue),
1190 impl_consensus_ser!(Transaction);
1191 impl_consensus_ser!(TxOut);
1192 impl_consensus_ser!(Witness);
1194 impl<T: Readable> Readable for Mutex<T> {
1195 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1196 let t: T = Readable::read(r)?;
1200 impl<T: Writeable> Writeable for Mutex<T> {
1201 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1202 self.lock().unwrap().write(w)
1206 impl<A: Readable, B: Readable> Readable for (A, B) {
1207 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1208 let a: A = Readable::read(r)?;
1209 let b: B = Readable::read(r)?;
1213 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1214 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1220 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
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)?;
1228 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1229 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1236 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1237 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1238 let a: A = Readable::read(r)?;
1239 let b: B = Readable::read(r)?;
1240 let c: C = Readable::read(r)?;
1241 let d: D = Readable::read(r)?;
1245 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1246 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1254 impl Writeable for () {
1255 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1259 impl Readable for () {
1260 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1265 impl Writeable for String {
1267 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1268 CollectionLength(self.len() as u64).write(w)?;
1269 w.write_all(self.as_bytes())
1272 impl Readable for String {
1274 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1275 let v: Vec<u8> = Readable::read(r)?;
1276 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1281 /// Represents a hostname for serialization purposes.
1282 /// Only the character set and length will be validated.
1283 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1284 /// Its length is guaranteed to be representable by a single byte.
1285 /// This serialization is used by [`BOLT 7`] hostnames.
1287 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1288 #[derive(Clone, Debug, PartialEq, Eq)]
1289 pub struct Hostname(String);
1291 /// Returns the length of the hostname.
1292 pub fn len(&self) -> u8 {
1293 (&self.0).len() as u8
1296 impl Deref for Hostname {
1297 type Target = String;
1299 fn deref(&self) -> &Self::Target {
1303 impl From<Hostname> for String {
1304 fn from(hostname: Hostname) -> Self {
1308 impl TryFrom<Vec<u8>> for Hostname {
1311 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1312 if let Ok(s) = String::from_utf8(bytes) {
1313 Hostname::try_from(s)
1319 impl TryFrom<String> for Hostname {
1322 fn try_from(s: String) -> Result<Self, Self::Error> {
1323 if s.len() <= 255 && s.chars().all(|c|
1324 c.is_ascii_alphanumeric() ||
1334 impl Writeable for Hostname {
1336 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1337 self.len().write(w)?;
1338 w.write_all(self.as_bytes())
1341 impl Readable for Hostname {
1343 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1344 let len: u8 = Readable::read(r)?;
1345 let mut vec = Vec::with_capacity(len.into());
1346 vec.resize(len.into(), 0);
1347 r.read_exact(&mut vec)?;
1348 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1352 impl Writeable for Duration {
1354 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1355 self.as_secs().write(w)?;
1356 self.subsec_nanos().write(w)
1359 impl Readable for Duration {
1361 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1362 let secs = Readable::read(r)?;
1363 let nanos = Readable::read(r)?;
1364 Ok(Duration::new(secs, nanos))
1368 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1369 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1371 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1372 #[derive(Clone, Debug, PartialEq, Eq)]
1373 pub struct TransactionU16LenLimited(Transaction);
1375 impl TransactionU16LenLimited {
1376 /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1377 /// serialized length is <= u16::MAX.
1378 pub fn new(transaction: Transaction) -> Result<Self, ()> {
1379 if transaction.serialized_length() > (u16::MAX as usize) {
1382 Ok(Self(transaction))
1386 /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1387 pub fn into_transaction(self) -> Transaction {
1392 impl Writeable for TransactionU16LenLimited {
1393 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1394 (self.0.serialized_length() as u16).write(w)?;
1399 impl Readable for TransactionU16LenLimited {
1400 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1401 let len = <u16 as Readable>::read(r)?;
1402 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1403 let tx: Transaction = Readable::read(&mut tx_reader)?;
1404 if tx_reader.bytes_remain() {
1405 Err(DecodeError::BadLengthDescriptor)
1414 use core::convert::TryFrom;
1415 use bitcoin::secp256k1::ecdsa;
1416 use crate::util::ser::{Readable, Hostname, Writeable};
1419 fn hostname_conversion() {
1420 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1422 assert!(Hostname::try_from(String::from("\"")).is_err());
1423 assert!(Hostname::try_from(String::from("$")).is_err());
1424 assert!(Hostname::try_from(String::from("⚡")).is_err());
1425 let mut large_vec = Vec::with_capacity(256);
1426 large_vec.resize(256, b'A');
1427 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1431 fn hostname_serialization() {
1432 let hostname = Hostname::try_from(String::from("test")).unwrap();
1433 let mut buf: Vec<u8> = Vec::new();
1434 hostname.write(&mut buf).unwrap();
1435 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1439 /// Taproot will likely fill legacy signature fields with all 0s.
1440 /// This test ensures that doing so won't break serialization.
1441 fn null_signature_codec() {
1442 let buffer = vec![0u8; 64];
1443 let mut cursor = crate::io::Cursor::new(buffer.clone());
1444 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1445 let serialization = signature.serialize_compact();
1446 assert_eq!(buffer, serialization.to_vec())
1450 fn bigsize_encoding_decoding() {
1451 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1459 "ff0000000100000000",
1460 "ffffffffffffffffff"
1463 let mut stream = crate::io::Cursor::new(::hex::decode(bytes[i]).unwrap());
1464 assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1465 let mut stream = super::VecWriter(Vec::new());
1466 super::BigSize(values[i]).write(&mut stream).unwrap();
1467 assert_eq!(stream.0, ::hex::decode(bytes[i]).unwrap());
1469 let err_bytes = vec![
1472 "ff00000000ffffffff",
1482 let mut stream = crate::io::Cursor::new(::hex::decode(err_bytes[i]).unwrap());
1484 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1486 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));