Track actions to execute after a `ChannelMonitor` is updated
[rust-lightning] / lightning / src / util / ser.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! A very simple serialization framework which is used to serialize/deserialize messages as well
11 //! as [`ChannelManager`]s and [`ChannelMonitor`]s.
12 //!
13 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
14 //! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
15
16 use crate::prelude::*;
17 use crate::io::{self, Read, Seek, Write};
18 use crate::io_extras::{copy, sink};
19 use core::hash::Hash;
20 use crate::sync::Mutex;
21 use core::cmp;
22 use core::convert::TryFrom;
23 use core::ops::Deref;
24
25 use alloc::collections::BTreeMap;
26
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};
42
43 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
44
45 /// serialization buffer size
46 pub const MAX_BUF_SIZE: usize = 64 * 1024;
47
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`].
50 ///
51 /// (C-not exported) as we only export serialization to/from byte arrays instead
52 pub trait Writer {
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>;
55 }
56
57 impl<W: Write> Writer for W {
58         #[inline]
59         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
60                 <Self as io::Write>::write_all(self, buf)
61         }
62 }
63
64 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
65 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
66         #[inline]
67         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
68                 self.0.write_all(buf)
69         }
70         #[inline]
71         fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
72                 self.0.write_all(buf)?;
73                 Ok(buf.len())
74         }
75         #[inline]
76         fn flush(&mut self) -> Result<(), io::Error> {
77                 Ok(())
78         }
79 }
80
81 pub(crate) struct VecWriter(pub Vec<u8>);
82 impl Writer for VecWriter {
83         #[inline]
84         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
85                 self.0.extend_from_slice(buf);
86                 Ok(())
87         }
88 }
89
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.
92 pub struct LengthCalculatingWriter(pub usize);
93 impl Writer for LengthCalculatingWriter {
94         #[inline]
95         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
96                 self.0 += buf.len();
97                 Ok(())
98         }
99 }
100
101 /// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
102 /// forward to ensure we always consume exactly the fixed length specified.
103 pub struct FixedLengthReader<R: Read> {
104         read: R,
105         bytes_read: u64,
106         total_bytes: u64,
107 }
108 impl<R: Read> FixedLengthReader<R> {
109         /// Returns a new [`FixedLengthReader`].
110         pub fn new(read: R, total_bytes: u64) -> Self {
111                 Self { read, bytes_read: 0, total_bytes }
112         }
113
114         /// Returns whether some bytes are remaining or not.
115         #[inline]
116         pub fn bytes_remain(&mut self) -> bool {
117                 self.bytes_read != self.total_bytes
118         }
119
120         /// Consumes the remaining bytes.
121         #[inline]
122         pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
123                 copy(self, &mut sink()).unwrap();
124                 if self.bytes_read != self.total_bytes {
125                         Err(DecodeError::ShortRead)
126                 } else {
127                         Ok(())
128                 }
129         }
130 }
131 impl<R: Read> Read for FixedLengthReader<R> {
132         #[inline]
133         fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
134                 if self.total_bytes == self.bytes_read {
135                         Ok(0)
136                 } else {
137                         let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
138                         match self.read.read(&mut dest[0..(read_len as usize)]) {
139                                 Ok(v) => {
140                                         self.bytes_read += v as u64;
141                                         Ok(v)
142                                 },
143                                 Err(e) => Err(e),
144                         }
145                 }
146         }
147 }
148
149 impl<R: Read> LengthRead for FixedLengthReader<R> {
150         #[inline]
151         fn total_bytes(&self) -> u64 {
152                 self.total_bytes
153         }
154 }
155
156 /// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
157 /// between "EOF reached before we started" and "EOF reached mid-read".
158 pub struct ReadTrackingReader<R: Read> {
159         read: R,
160         /// Returns whether we have read from this reader or not yet.
161         pub have_read: bool,
162 }
163 impl<R: Read> ReadTrackingReader<R> {
164         /// Returns a new [`ReadTrackingReader`].
165         pub fn new(read: R) -> Self {
166                 Self { read, have_read: false }
167         }
168 }
169 impl<R: Read> Read for ReadTrackingReader<R> {
170         #[inline]
171         fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
172                 match self.read.read(dest) {
173                         Ok(0) => Ok(0),
174                         Ok(len) => {
175                                 self.have_read = true;
176                                 Ok(len)
177                         },
178                         Err(e) => Err(e),
179                 }
180         }
181 }
182
183 /// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
184 ///
185 /// (C-not exported) as we only export serialization to/from byte arrays instead
186 pub trait Writeable {
187         /// Writes `self` out to the given [`Writer`].
188         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
189
190         /// Writes `self` out to a `Vec<u8>`.
191         fn encode(&self) -> Vec<u8> {
192                 let mut msg = VecWriter(Vec::new());
193                 self.write(&mut msg).unwrap();
194                 msg.0
195         }
196
197         /// Writes `self` out to a `Vec<u8>`.
198         #[cfg(test)]
199         fn encode_with_len(&self) -> Vec<u8> {
200                 let mut msg = VecWriter(Vec::new());
201                 0u16.write(&mut msg).unwrap();
202                 self.write(&mut msg).unwrap();
203                 let len = msg.0.len();
204                 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
205                 msg.0
206         }
207
208         /// Gets the length of this object after it has been serialized. This can be overridden to
209         /// optimize cases where we prepend an object with its length.
210         // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
211         #[inline]
212         fn serialized_length(&self) -> usize {
213                 let mut len_calc = LengthCalculatingWriter(0);
214                 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
215                 len_calc.0
216         }
217 }
218
219 impl<'a, T: Writeable> Writeable for &'a T {
220         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
221 }
222
223 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
224 ///
225 /// (C-not exported) as we only export serialization to/from byte arrays instead
226 pub trait Readable
227         where Self: Sized
228 {
229         /// Reads a `Self` in from the given [`Read`].
230         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
231 }
232
233 /// A trait that various LDK types implement allowing them to be read in from a
234 /// [`Read`]` + `[`Seek`].
235 pub(crate) trait SeekReadable where Self: Sized {
236         /// Reads a `Self` in from the given [`Read`].
237         fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
238 }
239
240 /// A trait that various higher-level LDK types implement allowing them to be read in
241 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
242 ///
243 /// (C-not exported) as we only export serialization to/from byte arrays instead
244 pub trait ReadableArgs<P>
245         where Self: Sized
246 {
247         /// Reads a `Self` in from the given [`Read`].
248         fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
249 }
250
251 /// A [`std::io::Read`] that also provides the total bytes available to be read.
252 pub(crate) trait LengthRead: Read {
253         /// The total number of bytes available to be read.
254         fn total_bytes(&self) -> u64;
255 }
256
257 /// A trait that various higher-level LDK types implement allowing them to be read in
258 /// from a Read given some additional set of arguments which is required to deserialize, requiring
259 /// the implementer to provide the total length of the read.
260 pub(crate) trait LengthReadableArgs<P> where Self: Sized
261 {
262         /// Reads a `Self` in from the given [`LengthRead`].
263         fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
264 }
265
266 /// A trait that various higher-level LDK types implement allowing them to be read in
267 /// from a [`Read`], requiring the implementer to provide the total length of the read.
268 pub(crate) trait LengthReadable where Self: Sized
269 {
270         /// Reads a `Self` in from the given [`LengthRead`].
271         fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
272 }
273
274 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
275 ///
276 /// (C-not exported) as we only export serialization to/from byte arrays instead
277 pub trait MaybeReadable
278         where Self: Sized
279 {
280         /// Reads a `Self` in from the given [`Read`].
281         fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
282 }
283
284 impl<T: Readable> MaybeReadable for T {
285         #[inline]
286         fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
287                 Ok(Some(Readable::read(reader)?))
288         }
289 }
290
291 /// Wrapper to read a required (non-optional) TLV record.
292 pub struct OptionDeserWrapper<T: Readable>(pub Option<T>);
293 impl<T: Readable> Readable for OptionDeserWrapper<T> {
294         #[inline]
295         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
296                 Ok(Self(Some(Readable::read(reader)?)))
297         }
298 }
299 /// When handling `default_values`, we want to map the default-value T directly
300 /// to a `OptionDeserWrapper<T>` in a way that works for `field: T = t;` as
301 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
302 impl<T: Readable> From<T> for OptionDeserWrapper<T> {
303         fn from(t: T) -> OptionDeserWrapper<T> { OptionDeserWrapper(Some(t)) }
304 }
305
306 pub(crate) struct U48(pub u64);
307 impl Writeable for U48 {
308         #[inline]
309         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
310                 writer.write_all(&be48_to_array(self.0))
311         }
312 }
313 impl Readable for U48 {
314         #[inline]
315         fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
316                 let mut buf = [0; 6];
317                 reader.read_exact(&mut buf)?;
318                 Ok(U48(slice_to_be48(&buf)))
319         }
320 }
321
322 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
323 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
324 ///
325 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
326 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
327 /// you're looking for an example of a variable-length integer to use for your own project, move
328 /// along, this is a rather poor design.
329 pub struct BigSize(pub u64);
330 impl Writeable for BigSize {
331         #[inline]
332         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
333                 match self.0 {
334                         0...0xFC => {
335                                 (self.0 as u8).write(writer)
336                         },
337                         0xFD...0xFFFF => {
338                                 0xFDu8.write(writer)?;
339                                 (self.0 as u16).write(writer)
340                         },
341                         0x10000...0xFFFFFFFF => {
342                                 0xFEu8.write(writer)?;
343                                 (self.0 as u32).write(writer)
344                         },
345                         _ => {
346                                 0xFFu8.write(writer)?;
347                                 (self.0 as u64).write(writer)
348                         },
349                 }
350         }
351 }
352 impl Readable for BigSize {
353         #[inline]
354         fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
355                 let n: u8 = Readable::read(reader)?;
356                 match n {
357                         0xFF => {
358                                 let x: u64 = Readable::read(reader)?;
359                                 if x < 0x100000000 {
360                                         Err(DecodeError::InvalidValue)
361                                 } else {
362                                         Ok(BigSize(x))
363                                 }
364                         }
365                         0xFE => {
366                                 let x: u32 = Readable::read(reader)?;
367                                 if x < 0x10000 {
368                                         Err(DecodeError::InvalidValue)
369                                 } else {
370                                         Ok(BigSize(x as u64))
371                                 }
372                         }
373                         0xFD => {
374                                 let x: u16 = Readable::read(reader)?;
375                                 if x < 0xFD {
376                                         Err(DecodeError::InvalidValue)
377                                 } else {
378                                         Ok(BigSize(x as u64))
379                                 }
380                         }
381                         n => Ok(BigSize(n as u64))
382                 }
383         }
384 }
385
386 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
387 /// primarily targets that, we must as well. However, because we may serialize objects that have
388 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
389 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
390 /// "read eight more bytes".
391 ///
392 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
393 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
394 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
395 struct CollectionLength(pub u64);
396 impl Writeable for CollectionLength {
397         #[inline]
398         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
399                 if self.0 < 0xffff {
400                         (self.0 as u16).write(writer)
401                 } else {
402                         0xffffu16.write(writer)?;
403                         (self.0 - 0xffff).write(writer)
404                 }
405         }
406 }
407
408 impl Readable for CollectionLength {
409         #[inline]
410         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
411                 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
412                 if val == 0xffff {
413                         val = <u64 as Readable>::read(r)?
414                                 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
415                 }
416                 Ok(CollectionLength(val))
417         }
418 }
419
420 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
421 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
422 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
423 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
424 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
425
426 macro_rules! impl_writeable_primitive {
427         ($val_type:ty, $len: expr) => {
428                 impl Writeable for $val_type {
429                         #[inline]
430                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
431                                 writer.write_all(&self.to_be_bytes())
432                         }
433                 }
434                 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
435                         #[inline]
436                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
437                                 // Skip any full leading 0 bytes when writing (in BE):
438                                 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
439                         }
440                 }
441                 impl Readable for $val_type {
442                         #[inline]
443                         fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
444                                 let mut buf = [0; $len];
445                                 reader.read_exact(&mut buf)?;
446                                 Ok(<$val_type>::from_be_bytes(buf))
447                         }
448                 }
449                 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
450                         #[inline]
451                         fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
452                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
453                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
454                                 // and then convert the appropriate number of bytes with extra high bytes out of
455                                 // buf.
456                                 let mut buf = [0; $len*2];
457                                 let mut read_len = reader.read(&mut buf[$len..])?;
458                                 let mut total_read_len = read_len;
459                                 while read_len != 0 && total_read_len != $len {
460                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
461                                         total_read_len += read_len;
462                                 }
463                                 if total_read_len == 0 || buf[$len] != 0 {
464                                         let first_byte = $len - ($len - total_read_len);
465                                         let mut bytes = [0; $len];
466                                         bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
467                                         Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
468                                 } else {
469                                         // If the encoding had extra zero bytes, return a failure even though we know
470                                         // what they meant (as the TLV test vectors require this)
471                                         Err(DecodeError::InvalidValue)
472                                 }
473                         }
474                 }
475                 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
476                         fn from(val: $val_type) -> Self { Self(val) }
477                 }
478         }
479 }
480
481 impl_writeable_primitive!(u128, 16);
482 impl_writeable_primitive!(u64, 8);
483 impl_writeable_primitive!(u32, 4);
484 impl_writeable_primitive!(u16, 2);
485
486 impl Writeable for u8 {
487         #[inline]
488         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
489                 writer.write_all(&[*self])
490         }
491 }
492 impl Readable for u8 {
493         #[inline]
494         fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
495                 let mut buf = [0; 1];
496                 reader.read_exact(&mut buf)?;
497                 Ok(buf[0])
498         }
499 }
500
501 impl Writeable for bool {
502         #[inline]
503         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
504                 writer.write_all(&[if *self {1} else {0}])
505         }
506 }
507 impl Readable for bool {
508         #[inline]
509         fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
510                 let mut buf = [0; 1];
511                 reader.read_exact(&mut buf)?;
512                 if buf[0] != 0 && buf[0] != 1 {
513                         return Err(DecodeError::InvalidValue);
514                 }
515                 Ok(buf[0] == 1)
516         }
517 }
518
519 // u8 arrays
520 macro_rules! impl_array {
521         ( $size:expr ) => (
522                 impl Writeable for [u8; $size]
523                 {
524                         #[inline]
525                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
526                                 w.write_all(self)
527                         }
528                 }
529
530                 impl Readable for [u8; $size]
531                 {
532                         #[inline]
533                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
534                                 let mut buf = [0u8; $size];
535                                 r.read_exact(&mut buf)?;
536                                 Ok(buf)
537                         }
538                 }
539         );
540 }
541
542 impl_array!(3); // for rgb, ISO 4712 code
543 impl_array!(4); // for IPv4
544 impl_array!(12); // for OnionV2
545 impl_array!(16); // for IPv6
546 impl_array!(32); // for channel id & hmac
547 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
548 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
549 impl_array!(1300); // for OnionPacket.hop_data
550
551 impl Writeable for [u16; 8] {
552         #[inline]
553         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
554                 for v in self.iter() {
555                         w.write_all(&v.to_be_bytes())?
556                 }
557                 Ok(())
558         }
559 }
560
561 impl Readable for [u16; 8] {
562         #[inline]
563         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
564                 let mut buf = [0u8; 16];
565                 r.read_exact(&mut buf)?;
566                 let mut res = [0u16; 8];
567                 for (idx, v) in res.iter_mut().enumerate() {
568                         *v = (buf[idx] as u16) << 8 | (buf[idx + 1] as u16)
569                 }
570                 Ok(res)
571         }
572 }
573
574 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
575 /// Used to prevent encoding the length twice.
576 pub struct WithoutLength<T>(pub T);
577
578 impl Writeable for WithoutLength<&String> {
579         #[inline]
580         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
581                 w.write_all(self.0.as_bytes())
582         }
583 }
584 impl Readable for WithoutLength<String> {
585         #[inline]
586         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
587                 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
588                 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
589         }
590 }
591 impl<'a> From<&'a String> for WithoutLength<&'a String> {
592         fn from(s: &'a String) -> Self { Self(s) }
593 }
594
595 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
596         #[inline]
597         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
598                 for ref v in self.0.iter() {
599                         v.write(writer)?;
600                 }
601                 Ok(())
602         }
603 }
604
605 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
606         #[inline]
607         fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
608                 let mut values = Vec::new();
609                 loop {
610                         let mut track_read = ReadTrackingReader::new(&mut reader);
611                         match MaybeReadable::read(&mut track_read) {
612                                 Ok(Some(v)) => { values.push(v); },
613                                 Ok(None) => { },
614                                 // If we failed to read any bytes at all, we reached the end of our TLV
615                                 // stream and have simply exhausted all entries.
616                                 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
617                                 Err(e) => return Err(e),
618                         }
619                 }
620                 Ok(Self(values))
621         }
622 }
623 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
624         fn from(v: &'a Vec<T>) -> Self { Self(v) }
625 }
626
627 #[derive(Debug)]
628 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
629
630 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
631         #[inline]
632         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
633                 for ref v in self.0.clone() {
634                         v.write(writer)?;
635                 }
636                 Ok(())
637         }
638 }
639
640 #[cfg(test)]
641 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
642         fn eq(&self, other: &Self) -> bool {
643                 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
644         }
645 }
646
647 macro_rules! impl_for_map {
648         ($ty: ident, $keybound: ident, $constr: expr) => {
649                 impl<K, V> Writeable for $ty<K, V>
650                         where K: Writeable + Eq + $keybound, V: Writeable
651                 {
652                         #[inline]
653                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
654                                 CollectionLength(self.len() as u64).write(w)?;
655                                 for (key, value) in self.iter() {
656                                         key.write(w)?;
657                                         value.write(w)?;
658                                 }
659                                 Ok(())
660                         }
661                 }
662
663                 impl<K, V> Readable for $ty<K, V>
664                         where K: Readable + Eq + $keybound, V: MaybeReadable
665                 {
666                         #[inline]
667                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
668                                 let len: CollectionLength = Readable::read(r)?;
669                                 let mut ret = $constr(len.0 as usize);
670                                 for _ in 0..len.0 {
671                                         let k = K::read(r)?;
672                                         let v_opt = V::read(r)?;
673                                         if let Some(v) = v_opt {
674                                                 if ret.insert(k, v).is_some() {
675                                                         return Err(DecodeError::InvalidValue);
676                                                 }
677                                         }
678                                 }
679                                 Ok(ret)
680                         }
681                 }
682         }
683 }
684
685 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
686 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
687
688 // HashSet
689 impl<T> Writeable for HashSet<T>
690 where T: Writeable + Eq + Hash
691 {
692         #[inline]
693         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
694                 CollectionLength(self.len() as u64).write(w)?;
695                 for item in self.iter() {
696                         item.write(w)?;
697                 }
698                 Ok(())
699         }
700 }
701
702 impl<T> Readable for HashSet<T>
703 where T: Readable + Eq + Hash
704 {
705         #[inline]
706         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
707                 let len: CollectionLength = Readable::read(r)?;
708                 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
709                 for _ in 0..len.0 {
710                         if !ret.insert(T::read(r)?) {
711                                 return Err(DecodeError::InvalidValue)
712                         }
713                 }
714                 Ok(ret)
715         }
716 }
717
718 // Vectors
719 macro_rules! impl_for_vec {
720         ($ty: ty $(, $name: ident)*) => {
721                 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
722                         #[inline]
723                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
724                                 CollectionLength(self.len() as u64).write(w)?;
725                                 for elem in self.iter() {
726                                         elem.write(w)?;
727                                 }
728                                 Ok(())
729                         }
730                 }
731
732                 impl<$($name : Readable),*> Readable for Vec<$ty> {
733                         #[inline]
734                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
735                                 let len: CollectionLength = Readable::read(r)?;
736                                 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
737                                 for _ in 0..len.0 {
738                                         if let Some(val) = MaybeReadable::read(r)? {
739                                                 ret.push(val);
740                                         }
741                                 }
742                                 Ok(ret)
743                         }
744                 }
745         }
746 }
747
748 impl Writeable for Vec<u8> {
749         #[inline]
750         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
751                 CollectionLength(self.len() as u64).write(w)?;
752                 w.write_all(&self)
753         }
754 }
755
756 impl Readable for Vec<u8> {
757         #[inline]
758         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
759                 let mut len: CollectionLength = Readable::read(r)?;
760                 let mut ret = Vec::new();
761                 while len.0 > 0 {
762                         let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
763                         let readstart = ret.len();
764                         ret.resize(readstart + readamt, 0);
765                         r.read_exact(&mut ret[readstart..])?;
766                         len.0 -= readamt as u64;
767                 }
768                 Ok(ret)
769         }
770 }
771
772 impl_for_vec!(ecdsa::Signature);
773 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
774 impl_for_vec!((A, B), A, B);
775
776 impl Writeable for Script {
777         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
778                 (self.len() as u16).write(w)?;
779                 w.write_all(self.as_bytes())
780         }
781 }
782
783 impl Readable for Script {
784         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
785                 let len = <u16 as Readable>::read(r)? as usize;
786                 let mut buf = vec![0; len];
787                 r.read_exact(&mut buf)?;
788                 Ok(Script::from(buf))
789         }
790 }
791
792 impl Writeable for PublicKey {
793         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
794                 self.serialize().write(w)
795         }
796         #[inline]
797         fn serialized_length(&self) -> usize {
798                 PUBLIC_KEY_SIZE
799         }
800 }
801
802 impl Readable for PublicKey {
803         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
804                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
805                 match PublicKey::from_slice(&buf) {
806                         Ok(key) => Ok(key),
807                         Err(_) => return Err(DecodeError::InvalidValue),
808                 }
809         }
810 }
811
812 impl Writeable for SecretKey {
813         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
814                 let mut ser = [0; SECRET_KEY_SIZE];
815                 ser.copy_from_slice(&self[..]);
816                 ser.write(w)
817         }
818         #[inline]
819         fn serialized_length(&self) -> usize {
820                 SECRET_KEY_SIZE
821         }
822 }
823
824 impl Readable for SecretKey {
825         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
826                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
827                 match SecretKey::from_slice(&buf) {
828                         Ok(key) => Ok(key),
829                         Err(_) => return Err(DecodeError::InvalidValue),
830                 }
831         }
832 }
833
834 impl Writeable for Sha256dHash {
835         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
836                 w.write_all(&self[..])
837         }
838 }
839
840 impl Readable for Sha256dHash {
841         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
842                 use bitcoin::hashes::Hash;
843
844                 let buf: [u8; 32] = Readable::read(r)?;
845                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
846         }
847 }
848
849 impl Writeable for ecdsa::Signature {
850         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
851                 self.serialize_compact().write(w)
852         }
853 }
854
855 impl Readable for ecdsa::Signature {
856         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
857                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
858                 match ecdsa::Signature::from_compact(&buf) {
859                         Ok(sig) => Ok(sig),
860                         Err(_) => return Err(DecodeError::InvalidValue),
861                 }
862         }
863 }
864
865 impl Writeable for schnorr::Signature {
866         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
867                 self.as_ref().write(w)
868         }
869 }
870
871 impl Readable for schnorr::Signature {
872         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
873                 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
874                 match schnorr::Signature::from_slice(&buf) {
875                         Ok(sig) => Ok(sig),
876                         Err(_) => return Err(DecodeError::InvalidValue),
877                 }
878         }
879 }
880
881 impl Writeable for PaymentPreimage {
882         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
883                 self.0.write(w)
884         }
885 }
886
887 impl Readable for PaymentPreimage {
888         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
889                 let buf: [u8; 32] = Readable::read(r)?;
890                 Ok(PaymentPreimage(buf))
891         }
892 }
893
894 impl Writeable for PaymentHash {
895         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
896                 self.0.write(w)
897         }
898 }
899
900 impl Readable for PaymentHash {
901         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
902                 let buf: [u8; 32] = Readable::read(r)?;
903                 Ok(PaymentHash(buf))
904         }
905 }
906
907 impl Writeable for PaymentSecret {
908         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
909                 self.0.write(w)
910         }
911 }
912
913 impl Readable for PaymentSecret {
914         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
915                 let buf: [u8; 32] = Readable::read(r)?;
916                 Ok(PaymentSecret(buf))
917         }
918 }
919
920 impl<T: Writeable> Writeable for Box<T> {
921         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
922                 T::write(&**self, w)
923         }
924 }
925
926 impl<T: Readable> Readable for Box<T> {
927         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
928                 Ok(Box::new(Readable::read(r)?))
929         }
930 }
931
932 impl<T: Writeable> Writeable for Option<T> {
933         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
934                 match *self {
935                         None => 0u8.write(w)?,
936                         Some(ref data) => {
937                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
938                                 data.write(w)?;
939                         }
940                 }
941                 Ok(())
942         }
943 }
944
945 impl<T: Readable> Readable for Option<T>
946 {
947         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
948                 let len: BigSize = Readable::read(r)?;
949                 match len.0 {
950                         0 => Ok(None),
951                         len => {
952                                 let mut reader = FixedLengthReader::new(r, len - 1);
953                                 Ok(Some(Readable::read(&mut reader)?))
954                         }
955                 }
956         }
957 }
958
959 impl Writeable for Txid {
960         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
961                 w.write_all(&self[..])
962         }
963 }
964
965 impl Readable for Txid {
966         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
967                 use bitcoin::hashes::Hash;
968
969                 let buf: [u8; 32] = Readable::read(r)?;
970                 Ok(Txid::from_slice(&buf[..]).unwrap())
971         }
972 }
973
974 impl Writeable for BlockHash {
975         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
976                 w.write_all(&self[..])
977         }
978 }
979
980 impl Readable for BlockHash {
981         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
982                 use bitcoin::hashes::Hash;
983
984                 let buf: [u8; 32] = Readable::read(r)?;
985                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
986         }
987 }
988
989 impl Writeable for ChainHash {
990         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
991                 w.write_all(self.as_bytes())
992         }
993 }
994
995 impl Readable for ChainHash {
996         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
997                 let buf: [u8; 32] = Readable::read(r)?;
998                 Ok(ChainHash::from(&buf[..]))
999         }
1000 }
1001
1002 impl Writeable for OutPoint {
1003         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1004                 self.txid.write(w)?;
1005                 self.vout.write(w)?;
1006                 Ok(())
1007         }
1008 }
1009
1010 impl Readable for OutPoint {
1011         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1012                 let txid = Readable::read(r)?;
1013                 let vout = Readable::read(r)?;
1014                 Ok(OutPoint {
1015                         txid,
1016                         vout,
1017                 })
1018         }
1019 }
1020
1021 macro_rules! impl_consensus_ser {
1022         ($bitcoin_type: ty) => {
1023                 impl Writeable for $bitcoin_type {
1024                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1025                                 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1026                                         Ok(_) => Ok(()),
1027                                         Err(e) => Err(e),
1028                                 }
1029                         }
1030                 }
1031
1032                 impl Readable for $bitcoin_type {
1033                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1034                                 match consensus::encode::Decodable::consensus_decode(r) {
1035                                         Ok(t) => Ok(t),
1036                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1037                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1038                                         Err(_) => Err(DecodeError::InvalidValue),
1039                                 }
1040                         }
1041                 }
1042         }
1043 }
1044 impl_consensus_ser!(Transaction);
1045 impl_consensus_ser!(TxOut);
1046
1047 impl<T: Readable> Readable for Mutex<T> {
1048         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1049                 let t: T = Readable::read(r)?;
1050                 Ok(Mutex::new(t))
1051         }
1052 }
1053 impl<T: Writeable> Writeable for Mutex<T> {
1054         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1055                 self.lock().unwrap().write(w)
1056         }
1057 }
1058
1059 impl<A: Readable, B: Readable> Readable for (A, B) {
1060         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1061                 let a: A = Readable::read(r)?;
1062                 let b: B = Readable::read(r)?;
1063                 Ok((a, b))
1064         }
1065 }
1066 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1067         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1068                 self.0.write(w)?;
1069                 self.1.write(w)
1070         }
1071 }
1072
1073 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1074         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1075                 let a: A = Readable::read(r)?;
1076                 let b: B = Readable::read(r)?;
1077                 let c: C = Readable::read(r)?;
1078                 Ok((a, b, c))
1079         }
1080 }
1081 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1082         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1083                 self.0.write(w)?;
1084                 self.1.write(w)?;
1085                 self.2.write(w)
1086         }
1087 }
1088
1089 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
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)?;
1093                 let c: C = Readable::read(r)?;
1094                 let d: D = Readable::read(r)?;
1095                 Ok((a, b, c, d))
1096         }
1097 }
1098 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1099         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1100                 self.0.write(w)?;
1101                 self.1.write(w)?;
1102                 self.2.write(w)?;
1103                 self.3.write(w)
1104         }
1105 }
1106
1107 impl Writeable for () {
1108         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1109                 Ok(())
1110         }
1111 }
1112 impl Readable for () {
1113         fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1114                 Ok(())
1115         }
1116 }
1117
1118 impl Writeable for String {
1119         #[inline]
1120         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1121                 CollectionLength(self.len() as u64).write(w)?;
1122                 w.write_all(self.as_bytes())
1123         }
1124 }
1125 impl Readable for String {
1126         #[inline]
1127         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1128                 let v: Vec<u8> = Readable::read(r)?;
1129                 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1130                 Ok(ret)
1131         }
1132 }
1133
1134 /// Represents a hostname for serialization purposes.
1135 /// Only the character set and length will be validated.
1136 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1137 /// Its length is guaranteed to be representable by a single byte.
1138 /// This serialization is used by [`BOLT 7`] hostnames.
1139 ///
1140 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1141 #[derive(Clone, Debug, PartialEq, Eq)]
1142 pub struct Hostname(String);
1143 impl Hostname {
1144         /// Returns the length of the hostname.
1145         pub fn len(&self) -> u8 {
1146                 (&self.0).len() as u8
1147         }
1148 }
1149 impl Deref for Hostname {
1150         type Target = String;
1151
1152         fn deref(&self) -> &Self::Target {
1153                 &self.0
1154         }
1155 }
1156 impl From<Hostname> for String {
1157         fn from(hostname: Hostname) -> Self {
1158                 hostname.0
1159         }
1160 }
1161 impl TryFrom<Vec<u8>> for Hostname {
1162         type Error = ();
1163
1164         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1165                 if let Ok(s) = String::from_utf8(bytes) {
1166                         Hostname::try_from(s)
1167                 } else {
1168                         Err(())
1169                 }
1170         }
1171 }
1172 impl TryFrom<String> for Hostname {
1173         type Error = ();
1174
1175         fn try_from(s: String) -> Result<Self, Self::Error> {
1176                 if s.len() <= 255 && s.chars().all(|c|
1177                         c.is_ascii_alphanumeric() ||
1178                         c == '.' ||
1179                         c == '-'
1180                 ) {
1181                         Ok(Hostname(s))
1182                 } else {
1183                         Err(())
1184                 }
1185         }
1186 }
1187 impl Writeable for Hostname {
1188         #[inline]
1189         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1190                 self.len().write(w)?;
1191                 w.write_all(self.as_bytes())
1192         }
1193 }
1194 impl Readable for Hostname {
1195         #[inline]
1196         fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1197                 let len: u8 = Readable::read(r)?;
1198                 let mut vec = Vec::with_capacity(len.into());
1199                 vec.resize(len.into(), 0);
1200                 r.read_exact(&mut vec)?;
1201                 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1202         }
1203 }
1204
1205 impl Writeable for Duration {
1206         #[inline]
1207         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1208                 self.as_secs().write(w)?;
1209                 self.subsec_nanos().write(w)
1210         }
1211 }
1212 impl Readable for Duration {
1213         #[inline]
1214         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1215                 let secs = Readable::read(r)?;
1216                 let nanos = Readable::read(r)?;
1217                 Ok(Duration::new(secs, nanos))
1218         }
1219 }
1220
1221 #[cfg(test)]
1222 mod tests {
1223         use core::convert::TryFrom;
1224         use crate::util::ser::{Readable, Hostname, Writeable};
1225
1226         #[test]
1227         fn hostname_conversion() {
1228                 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1229
1230                 assert!(Hostname::try_from(String::from("\"")).is_err());
1231                 assert!(Hostname::try_from(String::from("$")).is_err());
1232                 assert!(Hostname::try_from(String::from("⚡")).is_err());
1233                 let mut large_vec = Vec::with_capacity(256);
1234                 large_vec.resize(256, b'A');
1235                 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1236         }
1237
1238         #[test]
1239         fn hostname_serialization() {
1240                 let hostname = Hostname::try_from(String::from("test")).unwrap();
1241                 let mut buf: Vec<u8> = Vec::new();
1242                 hostname.write(&mut buf).unwrap();
1243                 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1244         }
1245 }