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::Script;
33 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
34 use bitcoin::consensus;
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;
41 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
43 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
45 /// serialization buffer size
46 pub const MAX_BUF_SIZE: usize = 64 * 1024;
48 /// A simplified version of [`std::io::Write`] that exists largely for backwards compatibility.
49 /// An impl is provided for any type that also impls [`std::io::Write`].
51 /// (C-not exported) as we only export serialization to/from byte arrays instead
53 /// Writes the given buf out. See std::io::Write::write_all for more
54 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
57 impl<W: Write> Writer for W {
59 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
60 <Self as io::Write>::write_all(self, buf)
64 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
65 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
67 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
71 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
72 self.0.write_all(buf)?;
76 fn flush(&mut self) -> Result<(), io::Error> {
81 pub(crate) struct VecWriter(pub Vec<u8>);
82 impl Writer for VecWriter {
84 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
85 self.0.extend_from_slice(buf);
90 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
91 /// of some data when serialized but don't yet need the full data.
93 /// (C-not exported) as manual TLV building is not currently supported in bindings
94 pub struct LengthCalculatingWriter(pub usize);
95 impl Writer for LengthCalculatingWriter {
97 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
103 /// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
104 /// forward to ensure we always consume exactly the fixed length specified.
106 /// (C-not exported) as manual TLV building is not currently supported in bindings
107 pub struct FixedLengthReader<R: Read> {
112 impl<R: Read> FixedLengthReader<R> {
113 /// Returns a new [`FixedLengthReader`].
114 pub fn new(read: R, total_bytes: u64) -> Self {
115 Self { read, bytes_read: 0, total_bytes }
118 /// Returns whether some bytes are remaining or not.
120 pub fn bytes_remain(&mut self) -> bool {
121 self.bytes_read != self.total_bytes
124 /// Consumes the remaining bytes.
126 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
127 copy(self, &mut sink()).unwrap();
128 if self.bytes_read != self.total_bytes {
129 Err(DecodeError::ShortRead)
135 impl<R: Read> Read for FixedLengthReader<R> {
137 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
138 if self.total_bytes == self.bytes_read {
141 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
142 match self.read.read(&mut dest[0..(read_len as usize)]) {
144 self.bytes_read += v as u64;
153 impl<R: Read> LengthRead for FixedLengthReader<R> {
155 fn total_bytes(&self) -> u64 {
160 /// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
161 /// between "EOF reached before we started" and "EOF reached mid-read".
163 /// (C-not exported) as manual TLV building is not currently supported in bindings
164 pub struct ReadTrackingReader<R: Read> {
166 /// Returns whether we have read from this reader or not yet.
169 impl<R: Read> ReadTrackingReader<R> {
170 /// Returns a new [`ReadTrackingReader`].
171 pub fn new(read: R) -> Self {
172 Self { read, have_read: false }
175 impl<R: Read> Read for ReadTrackingReader<R> {
177 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
178 match self.read.read(dest) {
181 self.have_read = true;
189 /// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
191 /// (C-not exported) as we only export serialization to/from byte arrays instead
192 pub trait Writeable {
193 /// Writes `self` out to the given [`Writer`].
194 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
196 /// Writes `self` out to a `Vec<u8>`.
197 fn encode(&self) -> Vec<u8> {
198 let mut msg = VecWriter(Vec::new());
199 self.write(&mut msg).unwrap();
203 /// Writes `self` out to a `Vec<u8>`.
205 fn encode_with_len(&self) -> Vec<u8> {
206 let mut msg = VecWriter(Vec::new());
207 0u16.write(&mut msg).unwrap();
208 self.write(&mut msg).unwrap();
209 let len = msg.0.len();
210 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
214 /// Gets the length of this object after it has been serialized. This can be overridden to
215 /// optimize cases where we prepend an object with its length.
216 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
218 fn serialized_length(&self) -> usize {
219 let mut len_calc = LengthCalculatingWriter(0);
220 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
225 impl<'a, T: Writeable> Writeable for &'a T {
226 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
229 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
231 /// (C-not exported) as we only export serialization to/from byte arrays instead
235 /// Reads a `Self` in from the given [`Read`].
236 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
239 /// A trait that various LDK types implement allowing them to be read in from a
240 /// [`Read`]` + `[`Seek`].
241 pub(crate) trait SeekReadable where Self: Sized {
242 /// Reads a `Self` in from the given [`Read`].
243 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
246 /// A trait that various higher-level LDK types implement allowing them to be read in
247 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
249 /// (C-not exported) as we only export serialization to/from byte arrays instead
250 pub trait ReadableArgs<P>
253 /// Reads a `Self` in from the given [`Read`].
254 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
257 /// A [`std::io::Read`] that also provides the total bytes available to be read.
258 pub(crate) trait LengthRead: Read {
259 /// The total number of bytes available to be read.
260 fn total_bytes(&self) -> u64;
263 /// A trait that various higher-level LDK types implement allowing them to be read in
264 /// from a Read given some additional set of arguments which is required to deserialize, requiring
265 /// the implementer to provide the total length of the read.
266 pub(crate) trait LengthReadableArgs<P> where Self: Sized
268 /// Reads a `Self` in from the given [`LengthRead`].
269 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
272 /// A trait that various higher-level LDK types implement allowing them to be read in
273 /// from a [`Read`], requiring the implementer to provide the total length of the read.
274 pub(crate) trait LengthReadable where Self: Sized
276 /// Reads a `Self` in from the given [`LengthRead`].
277 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
280 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
282 /// (C-not exported) as we only export serialization to/from byte arrays instead
283 pub trait MaybeReadable
286 /// Reads a `Self` in from the given [`Read`].
287 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
290 impl<T: Readable> MaybeReadable for T {
292 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
293 Ok(Some(Readable::read(reader)?))
297 /// Wrapper to read a required (non-optional) TLV record.
299 /// (C-not exported) as manual TLV building is not currently supported in bindings
300 pub struct RequiredWrapper<T>(pub Option<T>);
301 impl<T: Readable> Readable for RequiredWrapper<T> {
303 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
304 Ok(Self(Some(Readable::read(reader)?)))
307 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
309 fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
310 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
313 /// When handling `default_values`, we want to map the default-value T directly
314 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
315 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
316 impl<T> From<T> for RequiredWrapper<T> {
317 fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
320 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
321 /// backwards compat.
323 /// (C-not exported) as manual TLV building is not currently supported in bindings
324 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
325 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
327 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
328 let tlv = MaybeReadable::read(reader)?;
329 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
334 pub(crate) struct U48(pub u64);
335 impl Writeable for U48 {
337 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
338 writer.write_all(&be48_to_array(self.0))
341 impl Readable for U48 {
343 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
344 let mut buf = [0; 6];
345 reader.read_exact(&mut buf)?;
346 Ok(U48(slice_to_be48(&buf)))
350 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
351 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
353 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
354 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
355 /// you're looking for an example of a variable-length integer to use for your own project, move
356 /// along, this is a rather poor design.
357 pub struct BigSize(pub u64);
358 impl Writeable for BigSize {
360 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
363 (self.0 as u8).write(writer)
366 0xFDu8.write(writer)?;
367 (self.0 as u16).write(writer)
369 0x10000...0xFFFFFFFF => {
370 0xFEu8.write(writer)?;
371 (self.0 as u32).write(writer)
374 0xFFu8.write(writer)?;
375 (self.0 as u64).write(writer)
380 impl Readable for BigSize {
382 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
383 let n: u8 = Readable::read(reader)?;
386 let x: u64 = Readable::read(reader)?;
388 Err(DecodeError::InvalidValue)
394 let x: u32 = Readable::read(reader)?;
396 Err(DecodeError::InvalidValue)
398 Ok(BigSize(x as u64))
402 let x: u16 = Readable::read(reader)?;
404 Err(DecodeError::InvalidValue)
406 Ok(BigSize(x as u64))
409 n => Ok(BigSize(n as u64))
414 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
415 /// primarily targets that, we must as well. However, because we may serialize objects that have
416 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
417 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
418 /// "read eight more bytes".
420 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
421 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
422 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
423 struct CollectionLength(pub u64);
424 impl Writeable for CollectionLength {
426 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
428 (self.0 as u16).write(writer)
430 0xffffu16.write(writer)?;
431 (self.0 - 0xffff).write(writer)
436 impl Readable for CollectionLength {
438 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
439 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
441 val = <u64 as Readable>::read(r)?
442 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
444 Ok(CollectionLength(val))
448 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
449 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
450 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
451 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
452 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
454 macro_rules! impl_writeable_primitive {
455 ($val_type:ty, $len: expr) => {
456 impl Writeable for $val_type {
458 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
459 writer.write_all(&self.to_be_bytes())
462 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
464 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
465 // Skip any full leading 0 bytes when writing (in BE):
466 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
469 impl Readable for $val_type {
471 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
472 let mut buf = [0; $len];
473 reader.read_exact(&mut buf)?;
474 Ok(<$val_type>::from_be_bytes(buf))
477 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
479 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
480 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
481 // the high bytes being dropped. To do so, we start reading into the middle of buf
482 // and then convert the appropriate number of bytes with extra high bytes out of
484 let mut buf = [0; $len*2];
485 let mut read_len = reader.read(&mut buf[$len..])?;
486 let mut total_read_len = read_len;
487 while read_len != 0 && total_read_len != $len {
488 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
489 total_read_len += read_len;
491 if total_read_len == 0 || buf[$len] != 0 {
492 let first_byte = $len - ($len - total_read_len);
493 let mut bytes = [0; $len];
494 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
495 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
497 // If the encoding had extra zero bytes, return a failure even though we know
498 // what they meant (as the TLV test vectors require this)
499 Err(DecodeError::InvalidValue)
503 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
504 fn from(val: $val_type) -> Self { Self(val) }
509 impl_writeable_primitive!(u128, 16);
510 impl_writeable_primitive!(u64, 8);
511 impl_writeable_primitive!(u32, 4);
512 impl_writeable_primitive!(u16, 2);
514 impl Writeable for u8 {
516 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
517 writer.write_all(&[*self])
520 impl Readable for u8 {
522 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
523 let mut buf = [0; 1];
524 reader.read_exact(&mut buf)?;
529 impl Writeable for bool {
531 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
532 writer.write_all(&[if *self {1} else {0}])
535 impl Readable for bool {
537 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
538 let mut buf = [0; 1];
539 reader.read_exact(&mut buf)?;
540 if buf[0] != 0 && buf[0] != 1 {
541 return Err(DecodeError::InvalidValue);
548 macro_rules! impl_array {
550 impl Writeable for [u8; $size]
553 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
558 impl Readable for [u8; $size]
561 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
562 let mut buf = [0u8; $size];
563 r.read_exact(&mut buf)?;
570 impl_array!(3); // for rgb, ISO 4712 code
571 impl_array!(4); // for IPv4
572 impl_array!(12); // for OnionV2
573 impl_array!(16); // for IPv6
574 impl_array!(32); // for channel id & hmac
575 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
576 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
577 impl_array!(1300); // for OnionPacket.hop_data
579 impl Writeable for [u16; 8] {
581 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
582 for v in self.iter() {
583 w.write_all(&v.to_be_bytes())?
589 impl Readable for [u16; 8] {
591 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
592 let mut buf = [0u8; 16];
593 r.read_exact(&mut buf)?;
594 let mut res = [0u16; 8];
595 for (idx, v) in res.iter_mut().enumerate() {
596 *v = (buf[idx] as u16) << 8 | (buf[idx + 1] as u16)
602 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
603 /// Used to prevent encoding the length twice.
605 /// (C-not exported) as manual TLV building is not currently supported in bindings
606 pub struct WithoutLength<T>(pub T);
608 impl Writeable for WithoutLength<&String> {
610 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
611 w.write_all(self.0.as_bytes())
614 impl Readable for WithoutLength<String> {
616 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
617 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
618 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
621 impl<'a> From<&'a String> for WithoutLength<&'a String> {
622 fn from(s: &'a String) -> Self { Self(s) }
625 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
627 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
628 for ref v in self.0.iter() {
635 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
637 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
638 let mut values = Vec::new();
640 let mut track_read = ReadTrackingReader::new(&mut reader);
641 match MaybeReadable::read(&mut track_read) {
642 Ok(Some(v)) => { values.push(v); },
644 // If we failed to read any bytes at all, we reached the end of our TLV
645 // stream and have simply exhausted all entries.
646 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
647 Err(e) => return Err(e),
653 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
654 fn from(v: &'a Vec<T>) -> Self { Self(v) }
658 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
660 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
662 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
663 for ref v in self.0.clone() {
671 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
672 fn eq(&self, other: &Self) -> bool {
673 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
677 macro_rules! impl_for_map {
678 ($ty: ident, $keybound: ident, $constr: expr) => {
679 impl<K, V> Writeable for $ty<K, V>
680 where K: Writeable + Eq + $keybound, V: Writeable
683 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
684 CollectionLength(self.len() as u64).write(w)?;
685 for (key, value) in self.iter() {
693 impl<K, V> Readable for $ty<K, V>
694 where K: Readable + Eq + $keybound, V: MaybeReadable
697 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
698 let len: CollectionLength = Readable::read(r)?;
699 let mut ret = $constr(len.0 as usize);
702 let v_opt = V::read(r)?;
703 if let Some(v) = v_opt {
704 if ret.insert(k, v).is_some() {
705 return Err(DecodeError::InvalidValue);
715 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
716 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
719 impl<T> Writeable for HashSet<T>
720 where T: Writeable + Eq + Hash
723 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
724 CollectionLength(self.len() as u64).write(w)?;
725 for item in self.iter() {
732 impl<T> Readable for HashSet<T>
733 where T: Readable + Eq + Hash
736 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
737 let len: CollectionLength = Readable::read(r)?;
738 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
740 if !ret.insert(T::read(r)?) {
741 return Err(DecodeError::InvalidValue)
749 macro_rules! impl_for_vec {
750 ($ty: ty $(, $name: ident)*) => {
751 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
753 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
754 CollectionLength(self.len() as u64).write(w)?;
755 for elem in self.iter() {
762 impl<$($name : Readable),*> Readable for Vec<$ty> {
764 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
765 let len: CollectionLength = Readable::read(r)?;
766 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
768 if let Some(val) = MaybeReadable::read(r)? {
778 impl Writeable for Vec<u8> {
780 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
781 CollectionLength(self.len() as u64).write(w)?;
786 impl Readable for Vec<u8> {
788 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
789 let mut len: CollectionLength = Readable::read(r)?;
790 let mut ret = Vec::new();
792 let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
793 let readstart = ret.len();
794 ret.resize(readstart + readamt, 0);
795 r.read_exact(&mut ret[readstart..])?;
796 len.0 -= readamt as u64;
802 impl_for_vec!(ecdsa::Signature);
803 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
804 impl_for_vec!((A, B), A, B);
806 impl Writeable for Script {
807 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
808 (self.len() as u16).write(w)?;
809 w.write_all(self.as_bytes())
813 impl Readable for Script {
814 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
815 let len = <u16 as Readable>::read(r)? as usize;
816 let mut buf = vec![0; len];
817 r.read_exact(&mut buf)?;
818 Ok(Script::from(buf))
822 impl Writeable for PublicKey {
823 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
824 self.serialize().write(w)
827 fn serialized_length(&self) -> usize {
832 impl Readable for PublicKey {
833 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
834 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
835 match PublicKey::from_slice(&buf) {
837 Err(_) => return Err(DecodeError::InvalidValue),
842 impl Writeable for SecretKey {
843 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
844 let mut ser = [0; SECRET_KEY_SIZE];
845 ser.copy_from_slice(&self[..]);
849 fn serialized_length(&self) -> usize {
854 impl Readable for SecretKey {
855 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
856 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
857 match SecretKey::from_slice(&buf) {
859 Err(_) => return Err(DecodeError::InvalidValue),
864 impl Writeable for Sha256dHash {
865 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
866 w.write_all(&self[..])
870 impl Readable for Sha256dHash {
871 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
872 use bitcoin::hashes::Hash;
874 let buf: [u8; 32] = Readable::read(r)?;
875 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
879 impl Writeable for ecdsa::Signature {
880 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
881 self.serialize_compact().write(w)
885 impl Readable for ecdsa::Signature {
886 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
887 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
888 match ecdsa::Signature::from_compact(&buf) {
890 Err(_) => return Err(DecodeError::InvalidValue),
895 impl Writeable for schnorr::Signature {
896 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
897 self.as_ref().write(w)
901 impl Readable for schnorr::Signature {
902 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
903 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
904 match schnorr::Signature::from_slice(&buf) {
906 Err(_) => return Err(DecodeError::InvalidValue),
911 impl Writeable for PaymentPreimage {
912 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
917 impl Readable for PaymentPreimage {
918 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
919 let buf: [u8; 32] = Readable::read(r)?;
920 Ok(PaymentPreimage(buf))
924 impl Writeable for PaymentHash {
925 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
930 impl Readable for PaymentHash {
931 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
932 let buf: [u8; 32] = Readable::read(r)?;
937 impl Writeable for PaymentSecret {
938 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
943 impl Readable for PaymentSecret {
944 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
945 let buf: [u8; 32] = Readable::read(r)?;
946 Ok(PaymentSecret(buf))
950 impl<T: Writeable> Writeable for Box<T> {
951 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
956 impl<T: Readable> Readable for Box<T> {
957 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
958 Ok(Box::new(Readable::read(r)?))
962 impl<T: Writeable> Writeable for Option<T> {
963 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
965 None => 0u8.write(w)?,
967 BigSize(data.serialized_length() as u64 + 1).write(w)?;
975 impl<T: Readable> Readable for Option<T>
977 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
978 let len: BigSize = Readable::read(r)?;
982 let mut reader = FixedLengthReader::new(r, len - 1);
983 Ok(Some(Readable::read(&mut reader)?))
989 impl Writeable for Txid {
990 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
991 w.write_all(&self[..])
995 impl Readable for Txid {
996 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
997 use bitcoin::hashes::Hash;
999 let buf: [u8; 32] = Readable::read(r)?;
1000 Ok(Txid::from_slice(&buf[..]).unwrap())
1004 impl Writeable for BlockHash {
1005 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1006 w.write_all(&self[..])
1010 impl Readable for BlockHash {
1011 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1012 use bitcoin::hashes::Hash;
1014 let buf: [u8; 32] = Readable::read(r)?;
1015 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1019 impl Writeable for ChainHash {
1020 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1021 w.write_all(self.as_bytes())
1025 impl Readable for ChainHash {
1026 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1027 let buf: [u8; 32] = Readable::read(r)?;
1028 Ok(ChainHash::from(&buf[..]))
1032 impl Writeable for OutPoint {
1033 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1034 self.txid.write(w)?;
1035 self.vout.write(w)?;
1040 impl Readable for OutPoint {
1041 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1042 let txid = Readable::read(r)?;
1043 let vout = Readable::read(r)?;
1051 macro_rules! impl_consensus_ser {
1052 ($bitcoin_type: ty) => {
1053 impl Writeable for $bitcoin_type {
1054 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1055 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1062 impl Readable for $bitcoin_type {
1063 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1064 match consensus::encode::Decodable::consensus_decode(r) {
1066 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1067 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1068 Err(_) => Err(DecodeError::InvalidValue),
1074 impl_consensus_ser!(Transaction);
1075 impl_consensus_ser!(TxOut);
1077 impl<T: Readable> Readable for Mutex<T> {
1078 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1079 let t: T = Readable::read(r)?;
1083 impl<T: Writeable> Writeable for Mutex<T> {
1084 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1085 self.lock().unwrap().write(w)
1089 impl<A: Readable, B: Readable> Readable for (A, B) {
1090 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1091 let a: A = Readable::read(r)?;
1092 let b: B = Readable::read(r)?;
1096 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1097 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1103 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1104 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1105 let a: A = Readable::read(r)?;
1106 let b: B = Readable::read(r)?;
1107 let c: C = Readable::read(r)?;
1111 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1112 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1119 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1120 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1121 let a: A = Readable::read(r)?;
1122 let b: B = Readable::read(r)?;
1123 let c: C = Readable::read(r)?;
1124 let d: D = Readable::read(r)?;
1128 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1129 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1137 impl Writeable for () {
1138 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1142 impl Readable for () {
1143 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1148 impl Writeable for String {
1150 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1151 CollectionLength(self.len() as u64).write(w)?;
1152 w.write_all(self.as_bytes())
1155 impl Readable for String {
1157 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1158 let v: Vec<u8> = Readable::read(r)?;
1159 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1164 /// Represents a hostname for serialization purposes.
1165 /// Only the character set and length will be validated.
1166 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1167 /// Its length is guaranteed to be representable by a single byte.
1168 /// This serialization is used by [`BOLT 7`] hostnames.
1170 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1171 #[derive(Clone, Debug, PartialEq, Eq)]
1172 pub struct Hostname(String);
1174 /// Returns the length of the hostname.
1175 pub fn len(&self) -> u8 {
1176 (&self.0).len() as u8
1179 impl Deref for Hostname {
1180 type Target = String;
1182 fn deref(&self) -> &Self::Target {
1186 impl From<Hostname> for String {
1187 fn from(hostname: Hostname) -> Self {
1191 impl TryFrom<Vec<u8>> for Hostname {
1194 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1195 if let Ok(s) = String::from_utf8(bytes) {
1196 Hostname::try_from(s)
1202 impl TryFrom<String> for Hostname {
1205 fn try_from(s: String) -> Result<Self, Self::Error> {
1206 if s.len() <= 255 && s.chars().all(|c|
1207 c.is_ascii_alphanumeric() ||
1217 impl Writeable for Hostname {
1219 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1220 self.len().write(w)?;
1221 w.write_all(self.as_bytes())
1224 impl Readable for Hostname {
1226 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1227 let len: u8 = Readable::read(r)?;
1228 let mut vec = Vec::with_capacity(len.into());
1229 vec.resize(len.into(), 0);
1230 r.read_exact(&mut vec)?;
1231 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1235 impl Writeable for Duration {
1237 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1238 self.as_secs().write(w)?;
1239 self.subsec_nanos().write(w)
1242 impl Readable for Duration {
1244 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1245 let secs = Readable::read(r)?;
1246 let nanos = Readable::read(r)?;
1247 Ok(Duration::new(secs, nanos))
1253 use core::convert::TryFrom;
1254 use crate::util::ser::{Readable, Hostname, Writeable};
1257 fn hostname_conversion() {
1258 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1260 assert!(Hostname::try_from(String::from("\"")).is_err());
1261 assert!(Hostname::try_from(String::from("$")).is_err());
1262 assert!(Hostname::try_from(String::from("⚡")).is_err());
1263 let mut large_vec = Vec::with_capacity(256);
1264 large_vec.resize(256, b'A');
1265 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1269 fn hostname_serialization() {
1270 let hostname = Hostname::try_from(String::from("test")).unwrap();
1271 let mut buf: Vec<u8> = Vec::new();
1272 hostname.write(&mut buf).unwrap();
1273 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1277 fn bigsize_encoding_decoding() {
1278 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1286 "ff0000000100000000",
1287 "ffffffffffffffffff"
1290 let mut stream = crate::io::Cursor::new(::hex::decode(bytes[i]).unwrap());
1291 assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1292 let mut stream = super::VecWriter(Vec::new());
1293 super::BigSize(values[i]).write(&mut stream).unwrap();
1294 assert_eq!(stream.0, ::hex::decode(bytes[i]).unwrap());
1296 let err_bytes = vec![
1299 "ff00000000ffffffff",
1309 let mut stream = crate::io::Cursor::new(::hex::decode(err_bytes[i]).unwrap());
1311 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1313 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));