1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A very simple serialization framework which is used to serialize/deserialize messages as well
11 //! as [`ChannelManager`]s and [`ChannelMonitor`]s.
13 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
14 //! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
16 use crate::prelude::*;
17 use crate::io::{self, Read, Seek, Write};
18 use crate::io_extras::{copy, sink};
20 use crate::sync::{Mutex, RwLock};
22 use core::convert::TryFrom;
25 use alloc::collections::BTreeMap;
27 use bitcoin::secp256k1::{PublicKey, SecretKey};
28 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE, SCHNORR_SIGNATURE_SIZE};
29 use bitcoin::secp256k1::ecdsa;
30 use bitcoin::secp256k1::schnorr;
31 use bitcoin::blockdata::constants::ChainHash;
32 use bitcoin::blockdata::script::{self, 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 #[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
362 pub struct BigSize(pub u64);
363 impl Writeable for BigSize {
365 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
368 (self.0 as u8).write(writer)
371 0xFDu8.write(writer)?;
372 (self.0 as u16).write(writer)
374 0x10000...0xFFFFFFFF => {
375 0xFEu8.write(writer)?;
376 (self.0 as u32).write(writer)
379 0xFFu8.write(writer)?;
380 (self.0 as u64).write(writer)
385 impl Readable for BigSize {
387 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
388 let n: u8 = Readable::read(reader)?;
391 let x: u64 = Readable::read(reader)?;
393 Err(DecodeError::InvalidValue)
399 let x: u32 = Readable::read(reader)?;
401 Err(DecodeError::InvalidValue)
403 Ok(BigSize(x as u64))
407 let x: u16 = Readable::read(reader)?;
409 Err(DecodeError::InvalidValue)
411 Ok(BigSize(x as u64))
414 n => Ok(BigSize(n as u64))
419 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
420 /// primarily targets that, we must as well. However, because we may serialize objects that have
421 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
422 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
423 /// "read eight more bytes".
425 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
426 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
427 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
428 struct CollectionLength(pub u64);
429 impl Writeable for CollectionLength {
431 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
433 (self.0 as u16).write(writer)
435 0xffffu16.write(writer)?;
436 (self.0 - 0xffff).write(writer)
441 impl Readable for CollectionLength {
443 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
444 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
446 val = <u64 as Readable>::read(r)?
447 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
449 Ok(CollectionLength(val))
453 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
454 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
455 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
456 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
457 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
459 macro_rules! impl_writeable_primitive {
460 ($val_type:ty, $len: expr) => {
461 impl Writeable for $val_type {
463 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
464 writer.write_all(&self.to_be_bytes())
467 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
469 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
470 // Skip any full leading 0 bytes when writing (in BE):
471 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
474 impl Readable for $val_type {
476 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
477 let mut buf = [0; $len];
478 reader.read_exact(&mut buf)?;
479 Ok(<$val_type>::from_be_bytes(buf))
482 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
484 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
485 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
486 // the high bytes being dropped. To do so, we start reading into the middle of buf
487 // and then convert the appropriate number of bytes with extra high bytes out of
489 let mut buf = [0; $len*2];
490 let mut read_len = reader.read(&mut buf[$len..])?;
491 let mut total_read_len = read_len;
492 while read_len != 0 && total_read_len != $len {
493 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
494 total_read_len += read_len;
496 if total_read_len == 0 || buf[$len] != 0 {
497 let first_byte = $len - ($len - total_read_len);
498 let mut bytes = [0; $len];
499 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
500 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
502 // If the encoding had extra zero bytes, return a failure even though we know
503 // what they meant (as the TLV test vectors require this)
504 Err(DecodeError::InvalidValue)
508 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
509 fn from(val: $val_type) -> Self { Self(val) }
514 impl_writeable_primitive!(u128, 16);
515 impl_writeable_primitive!(u64, 8);
516 impl_writeable_primitive!(u32, 4);
517 impl_writeable_primitive!(u16, 2);
518 impl_writeable_primitive!(i64, 8);
519 impl_writeable_primitive!(i32, 4);
520 impl_writeable_primitive!(i16, 2);
521 impl_writeable_primitive!(i8, 1);
523 impl Writeable for u8 {
525 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
526 writer.write_all(&[*self])
529 impl Readable for u8 {
531 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
532 let mut buf = [0; 1];
533 reader.read_exact(&mut buf)?;
538 impl Writeable for bool {
540 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
541 writer.write_all(&[if *self {1} else {0}])
544 impl Readable for bool {
546 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
547 let mut buf = [0; 1];
548 reader.read_exact(&mut buf)?;
549 if buf[0] != 0 && buf[0] != 1 {
550 return Err(DecodeError::InvalidValue);
556 macro_rules! impl_array {
557 ($size:expr, $ty: ty) => (
558 impl Writeable for [$ty; $size] {
560 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
561 let mut out = [0; $size * core::mem::size_of::<$ty>()];
562 for (idx, v) in self.iter().enumerate() {
563 let startpos = idx * core::mem::size_of::<$ty>();
564 out[startpos..startpos + core::mem::size_of::<$ty>()].copy_from_slice(&v.to_be_bytes());
570 impl Readable for [$ty; $size] {
572 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
573 let mut buf = [0u8; $size * core::mem::size_of::<$ty>()];
574 r.read_exact(&mut buf)?;
575 let mut res = [0; $size];
576 for (idx, v) in res.iter_mut().enumerate() {
577 let startpos = idx * core::mem::size_of::<$ty>();
578 let mut arr = [0; core::mem::size_of::<$ty>()];
579 arr.copy_from_slice(&buf[startpos..startpos + core::mem::size_of::<$ty>()]);
580 *v = <$ty>::from_be_bytes(arr);
588 impl_array!(3, u8); // for rgb, ISO 4712 code
589 impl_array!(4, u8); // for IPv4
590 impl_array!(12, u8); // for OnionV2
591 impl_array!(16, u8); // for IPv6
592 impl_array!(32, u8); // for channel id & hmac
593 impl_array!(PUBLIC_KEY_SIZE, u8); // for PublicKey
594 impl_array!(64, u8); // for ecdsa::Signature and schnorr::Signature
595 impl_array!(66, u8); // for MuSig2 nonces
596 impl_array!(1300, u8); // for OnionPacket.hop_data
599 impl_array!(32, u16);
601 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
602 /// Used to prevent encoding the length twice.
604 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
605 pub struct WithoutLength<T>(pub T);
607 impl Writeable for WithoutLength<&String> {
609 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
610 w.write_all(self.0.as_bytes())
613 impl Readable for WithoutLength<String> {
615 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
616 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
617 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
620 impl<'a> From<&'a String> for WithoutLength<&'a String> {
621 fn from(s: &'a String) -> Self { Self(s) }
625 impl Writeable for WithoutLength<&UntrustedString> {
627 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
628 WithoutLength(&self.0.0).write(w)
631 impl Readable for WithoutLength<UntrustedString> {
633 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
634 let s: WithoutLength<String> = Readable::read(r)?;
635 Ok(Self(UntrustedString(s.0)))
639 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
641 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
642 for ref v in self.0.iter() {
649 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
651 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
652 let mut values = Vec::new();
654 let mut track_read = ReadTrackingReader::new(&mut reader);
655 match MaybeReadable::read(&mut track_read) {
656 Ok(Some(v)) => { values.push(v); },
658 // If we failed to read any bytes at all, we reached the end of our TLV
659 // stream and have simply exhausted all entries.
660 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
661 Err(e) => return Err(e),
667 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
668 fn from(v: &'a Vec<T>) -> Self { Self(v) }
671 impl Writeable for WithoutLength<&Script> {
673 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
674 writer.write_all(self.0.as_bytes())
678 impl Readable for WithoutLength<Script> {
680 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
681 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
682 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
687 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
689 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
691 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
692 for ref v in self.0.clone() {
700 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
701 fn eq(&self, other: &Self) -> bool {
702 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
706 macro_rules! impl_for_map {
707 ($ty: ident, $keybound: ident, $constr: expr) => {
708 impl<K, V> Writeable for $ty<K, V>
709 where K: Writeable + Eq + $keybound, V: Writeable
712 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
713 CollectionLength(self.len() as u64).write(w)?;
714 for (key, value) in self.iter() {
722 impl<K, V> Readable for $ty<K, V>
723 where K: Readable + Eq + $keybound, V: MaybeReadable
726 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
727 let len: CollectionLength = Readable::read(r)?;
728 let mut ret = $constr(len.0 as usize);
731 let v_opt = V::read(r)?;
732 if let Some(v) = v_opt {
733 if ret.insert(k, v).is_some() {
734 return Err(DecodeError::InvalidValue);
744 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
745 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
748 impl<T> Writeable for HashSet<T>
749 where T: Writeable + Eq + Hash
752 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
753 CollectionLength(self.len() as u64).write(w)?;
754 for item in self.iter() {
761 impl<T> Readable for HashSet<T>
762 where T: Readable + Eq + Hash
765 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
766 let len: CollectionLength = Readable::read(r)?;
767 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
769 if !ret.insert(T::read(r)?) {
770 return Err(DecodeError::InvalidValue)
778 macro_rules! impl_writeable_for_vec {
779 ($ty: ty $(, $name: ident)*) => {
780 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
782 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
783 CollectionLength(self.len() as u64).write(w)?;
784 for elem in self.iter() {
792 macro_rules! impl_readable_for_vec {
793 ($ty: ty $(, $name: ident)*) => {
794 impl<$($name : Readable),*> Readable for Vec<$ty> {
796 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
797 let len: CollectionLength = Readable::read(r)?;
798 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
800 if let Some(val) = MaybeReadable::read(r)? {
809 macro_rules! impl_for_vec {
810 ($ty: ty $(, $name: ident)*) => {
811 impl_writeable_for_vec!($ty $(, $name)*);
812 impl_readable_for_vec!($ty $(, $name)*);
816 impl Writeable for Vec<u8> {
818 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
819 CollectionLength(self.len() as u64).write(w)?;
824 impl Readable for Vec<u8> {
826 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
827 let mut len: CollectionLength = Readable::read(r)?;
828 let mut ret = Vec::new();
830 let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
831 let readstart = ret.len();
832 ret.resize(readstart + readamt, 0);
833 r.read_exact(&mut ret[readstart..])?;
834 len.0 -= readamt as u64;
840 impl_for_vec!(ecdsa::Signature);
841 impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
842 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
843 impl_for_vec!((A, B), A, B);
844 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
845 impl_readable_for_vec!(crate::routing::router::BlindedTail);
847 impl Writeable for Vec<Witness> {
849 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
850 (self.len() as u16).write(w)?;
851 for witness in self {
852 (witness.serialized_len() as u16).write(w)?;
859 impl Readable for Vec<Witness> {
861 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
862 let num_witnesses = <u16 as Readable>::read(r)? as usize;
863 let mut witnesses = Vec::with_capacity(num_witnesses);
864 for _ in 0..num_witnesses {
865 // Even though the length of each witness can be inferred in its consensus-encoded form,
866 // the spec includes a length prefix so that implementations don't have to deserialize
867 // each initially. We do that here anyway as in general we'll need to be able to make
868 // assertions on some properties of the witnesses when receiving a message providing a list
869 // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
870 let witness_len = <u16 as Readable>::read(r)? as usize;
871 let witness = <Witness as Readable>::read(r)?;
872 if witness.serialized_len() != witness_len {
873 return Err(DecodeError::BadLengthDescriptor);
875 witnesses.push(witness);
881 impl Writeable for Script {
882 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
883 (self.len() as u16).write(w)?;
884 w.write_all(self.as_bytes())
888 impl Readable for Script {
889 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
890 let len = <u16 as Readable>::read(r)? as usize;
891 let mut buf = vec![0; len];
892 r.read_exact(&mut buf)?;
893 Ok(Script::from(buf))
897 impl Writeable for PublicKey {
898 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
899 self.serialize().write(w)
902 fn serialized_length(&self) -> usize {
907 impl Readable for PublicKey {
908 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
909 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
910 match PublicKey::from_slice(&buf) {
912 Err(_) => return Err(DecodeError::InvalidValue),
917 impl Writeable for SecretKey {
918 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
919 let mut ser = [0; SECRET_KEY_SIZE];
920 ser.copy_from_slice(&self[..]);
924 fn serialized_length(&self) -> usize {
929 impl Readable for SecretKey {
930 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
931 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
932 match SecretKey::from_slice(&buf) {
934 Err(_) => return Err(DecodeError::InvalidValue),
940 impl Writeable for musig2::types::PublicNonce {
941 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
942 self.serialize().write(w)
947 impl Readable for musig2::types::PublicNonce {
948 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
949 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
950 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
955 impl Writeable for PartialSignatureWithNonce {
956 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
957 self.0.serialize().write(w)?;
963 impl Readable for PartialSignatureWithNonce {
964 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
965 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
966 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
967 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
968 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
972 impl Writeable for Sha256dHash {
973 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
974 w.write_all(&self[..])
978 impl Readable for Sha256dHash {
979 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
980 use bitcoin::hashes::Hash;
982 let buf: [u8; 32] = Readable::read(r)?;
983 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
987 impl Writeable for ecdsa::Signature {
988 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
989 self.serialize_compact().write(w)
993 impl Readable for ecdsa::Signature {
994 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
995 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
996 match ecdsa::Signature::from_compact(&buf) {
998 Err(_) => return Err(DecodeError::InvalidValue),
1003 impl Writeable for schnorr::Signature {
1004 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1005 self.as_ref().write(w)
1009 impl Readable for schnorr::Signature {
1010 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1011 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1012 match schnorr::Signature::from_slice(&buf) {
1014 Err(_) => return Err(DecodeError::InvalidValue),
1019 impl Writeable for PaymentPreimage {
1020 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1025 impl Readable for PaymentPreimage {
1026 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1027 let buf: [u8; 32] = Readable::read(r)?;
1028 Ok(PaymentPreimage(buf))
1032 impl Writeable for PaymentHash {
1033 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1038 impl Readable for PaymentHash {
1039 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1040 let buf: [u8; 32] = Readable::read(r)?;
1041 Ok(PaymentHash(buf))
1045 impl Writeable for PaymentSecret {
1046 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1051 impl Readable for PaymentSecret {
1052 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1053 let buf: [u8; 32] = Readable::read(r)?;
1054 Ok(PaymentSecret(buf))
1058 impl<T: Writeable> Writeable for Box<T> {
1059 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1060 T::write(&**self, w)
1064 impl<T: Readable> Readable for Box<T> {
1065 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1066 Ok(Box::new(Readable::read(r)?))
1070 impl<T: Writeable> Writeable for Option<T> {
1071 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1073 None => 0u8.write(w)?,
1075 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1083 impl<T: Readable> Readable for Option<T>
1085 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1086 let len: BigSize = Readable::read(r)?;
1090 let mut reader = FixedLengthReader::new(r, len - 1);
1091 Ok(Some(Readable::read(&mut reader)?))
1097 impl Writeable for Txid {
1098 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1099 w.write_all(&self[..])
1103 impl Readable for Txid {
1104 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1105 use bitcoin::hashes::Hash;
1107 let buf: [u8; 32] = Readable::read(r)?;
1108 Ok(Txid::from_slice(&buf[..]).unwrap())
1112 impl Writeable for BlockHash {
1113 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1114 w.write_all(&self[..])
1118 impl Readable for BlockHash {
1119 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1120 use bitcoin::hashes::Hash;
1122 let buf: [u8; 32] = Readable::read(r)?;
1123 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1127 impl Writeable for ChainHash {
1128 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1129 w.write_all(self.as_bytes())
1133 impl Readable for ChainHash {
1134 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1135 let buf: [u8; 32] = Readable::read(r)?;
1136 Ok(ChainHash::from(&buf[..]))
1140 impl Writeable for OutPoint {
1141 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1142 self.txid.write(w)?;
1143 self.vout.write(w)?;
1148 impl Readable for OutPoint {
1149 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1150 let txid = Readable::read(r)?;
1151 let vout = Readable::read(r)?;
1159 macro_rules! impl_consensus_ser {
1160 ($bitcoin_type: ty) => {
1161 impl Writeable for $bitcoin_type {
1162 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1163 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1170 impl Readable for $bitcoin_type {
1171 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1172 match consensus::encode::Decodable::consensus_decode(r) {
1174 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1175 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1176 Err(_) => Err(DecodeError::InvalidValue),
1182 impl_consensus_ser!(Transaction);
1183 impl_consensus_ser!(TxOut);
1184 impl_consensus_ser!(Witness);
1186 impl<T: Readable> Readable for Mutex<T> {
1187 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1188 let t: T = Readable::read(r)?;
1192 impl<T: Writeable> Writeable for Mutex<T> {
1193 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1194 self.lock().unwrap().write(w)
1198 impl<T: Readable> Readable for RwLock<T> {
1199 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1200 let t: T = Readable::read(r)?;
1204 impl<T: Writeable> Writeable for RwLock<T> {
1205 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1206 self.read().unwrap().write(w)
1210 impl<A: Readable, B: Readable> Readable for (A, B) {
1211 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1212 let a: A = Readable::read(r)?;
1213 let b: B = Readable::read(r)?;
1217 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1218 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1224 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1225 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1226 let a: A = Readable::read(r)?;
1227 let b: B = Readable::read(r)?;
1228 let c: C = Readable::read(r)?;
1232 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1233 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1240 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1241 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1242 let a: A = Readable::read(r)?;
1243 let b: B = Readable::read(r)?;
1244 let c: C = Readable::read(r)?;
1245 let d: D = Readable::read(r)?;
1249 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1250 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1258 impl Writeable for () {
1259 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1263 impl Readable for () {
1264 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1269 impl Writeable for String {
1271 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1272 CollectionLength(self.len() as u64).write(w)?;
1273 w.write_all(self.as_bytes())
1276 impl Readable for String {
1278 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1279 let v: Vec<u8> = Readable::read(r)?;
1280 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1285 /// Represents a hostname for serialization purposes.
1286 /// Only the character set and length will be validated.
1287 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1288 /// Its length is guaranteed to be representable by a single byte.
1289 /// This serialization is used by [`BOLT 7`] hostnames.
1291 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1292 #[derive(Clone, Debug, PartialEq, Eq)]
1293 pub struct Hostname(String);
1295 /// Returns the length of the hostname.
1296 pub fn len(&self) -> u8 {
1297 (&self.0).len() as u8
1301 impl core::fmt::Display for Hostname {
1302 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1303 write!(f, "{}", self.0)?;
1307 impl Deref for Hostname {
1308 type Target = String;
1310 fn deref(&self) -> &Self::Target {
1314 impl From<Hostname> for String {
1315 fn from(hostname: Hostname) -> Self {
1319 impl TryFrom<Vec<u8>> for Hostname {
1322 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1323 if let Ok(s) = String::from_utf8(bytes) {
1324 Hostname::try_from(s)
1330 impl TryFrom<String> for Hostname {
1333 fn try_from(s: String) -> Result<Self, Self::Error> {
1334 if s.len() <= 255 && s.chars().all(|c|
1335 c.is_ascii_alphanumeric() ||
1345 impl Writeable for Hostname {
1347 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1348 self.len().write(w)?;
1349 w.write_all(self.as_bytes())
1352 impl Readable for Hostname {
1354 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1355 let len: u8 = Readable::read(r)?;
1356 let mut vec = Vec::with_capacity(len.into());
1357 vec.resize(len.into(), 0);
1358 r.read_exact(&mut vec)?;
1359 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1363 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1364 impl Writeable for Duration {
1366 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1367 self.as_secs().write(w)?;
1368 self.subsec_nanos().write(w)
1371 /// This is not exported to bindings users as `Duration`s are simply mapped as ints.
1372 impl Readable for Duration {
1374 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1375 let secs = Readable::read(r)?;
1376 let nanos = Readable::read(r)?;
1377 Ok(Duration::new(secs, nanos))
1381 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1382 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1384 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1385 #[derive(Clone, Debug, PartialEq, Eq)]
1386 pub struct TransactionU16LenLimited(Transaction);
1388 impl TransactionU16LenLimited {
1389 /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1390 /// serialized length is <= u16::MAX.
1391 pub fn new(transaction: Transaction) -> Result<Self, ()> {
1392 if transaction.serialized_length() > (u16::MAX as usize) {
1395 Ok(Self(transaction))
1399 /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1400 pub fn into_transaction(self) -> Transaction {
1405 impl Writeable for TransactionU16LenLimited {
1406 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1407 (self.0.serialized_length() as u16).write(w)?;
1412 impl Readable for TransactionU16LenLimited {
1413 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1414 let len = <u16 as Readable>::read(r)?;
1415 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1416 let tx: Transaction = Readable::read(&mut tx_reader)?;
1417 if tx_reader.bytes_remain() {
1418 Err(DecodeError::BadLengthDescriptor)
1425 impl Writeable for ClaimId {
1426 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1427 self.0.write(writer)
1431 impl Readable for ClaimId {
1432 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1433 Ok(Self(Readable::read(reader)?))
1439 use core::convert::TryFrom;
1440 use bitcoin::secp256k1::ecdsa;
1441 use crate::util::ser::{Readable, Hostname, Writeable};
1444 fn hostname_conversion() {
1445 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1447 assert!(Hostname::try_from(String::from("\"")).is_err());
1448 assert!(Hostname::try_from(String::from("$")).is_err());
1449 assert!(Hostname::try_from(String::from("⚡")).is_err());
1450 let mut large_vec = Vec::with_capacity(256);
1451 large_vec.resize(256, b'A');
1452 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1456 fn hostname_serialization() {
1457 let hostname = Hostname::try_from(String::from("test")).unwrap();
1458 let mut buf: Vec<u8> = Vec::new();
1459 hostname.write(&mut buf).unwrap();
1460 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1464 /// Taproot will likely fill legacy signature fields with all 0s.
1465 /// This test ensures that doing so won't break serialization.
1466 fn null_signature_codec() {
1467 let buffer = vec![0u8; 64];
1468 let mut cursor = crate::io::Cursor::new(buffer.clone());
1469 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1470 let serialization = signature.serialize_compact();
1471 assert_eq!(buffer, serialization.to_vec())
1475 fn bigsize_encoding_decoding() {
1476 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1484 "ff0000000100000000",
1485 "ffffffffffffffffff"
1488 let mut stream = crate::io::Cursor::new(::hex::decode(bytes[i]).unwrap());
1489 assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1490 let mut stream = super::VecWriter(Vec::new());
1491 super::BigSize(values[i]).write(&mut stream).unwrap();
1492 assert_eq!(stream.0, ::hex::decode(bytes[i]).unwrap());
1494 let err_bytes = vec![
1497 "ff00000000ffffffff",
1507 let mut stream = crate::io::Cursor::new(::hex::decode(err_bytes[i]).unwrap());
1509 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1511 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));