Move in-flight `ChannelMonitorUpdate`s to `ChannelManager`
[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::{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;
42 #[cfg(taproot)]
43 use crate::ln::msgs::PartialSignatureWithNonce;
44 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
45
46 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
47 use crate::util::string::UntrustedString;
48
49 /// serialization buffer size
50 pub const MAX_BUF_SIZE: usize = 64 * 1024;
51
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`].
54 ///
55 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
56 pub trait Writer {
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>;
59 }
60
61 impl<W: Write> Writer for W {
62         #[inline]
63         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
64                 <Self as io::Write>::write_all(self, buf)
65         }
66 }
67
68 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
69 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
70         #[inline]
71         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
72                 self.0.write_all(buf)
73         }
74         #[inline]
75         fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
76                 self.0.write_all(buf)?;
77                 Ok(buf.len())
78         }
79         #[inline]
80         fn flush(&mut self) -> Result<(), io::Error> {
81                 Ok(())
82         }
83 }
84
85 pub(crate) struct VecWriter(pub Vec<u8>);
86 impl Writer for VecWriter {
87         #[inline]
88         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
89                 self.0.extend_from_slice(buf);
90                 Ok(())
91         }
92 }
93
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.
96 ///
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 {
100         #[inline]
101         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
102                 self.0 += buf.len();
103                 Ok(())
104         }
105 }
106
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.
109 ///
110 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
111 pub struct FixedLengthReader<R: Read> {
112         read: R,
113         bytes_read: u64,
114         total_bytes: u64,
115 }
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 }
120         }
121
122         /// Returns whether some bytes are remaining or not.
123         #[inline]
124         pub fn bytes_remain(&mut self) -> bool {
125                 self.bytes_read != self.total_bytes
126         }
127
128         /// Consumes the remaining bytes.
129         #[inline]
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)
134                 } else {
135                         Ok(())
136                 }
137         }
138 }
139 impl<R: Read> Read for FixedLengthReader<R> {
140         #[inline]
141         fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
142                 if self.total_bytes == self.bytes_read {
143                         Ok(0)
144                 } else {
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)]) {
147                                 Ok(v) => {
148                                         self.bytes_read += v as u64;
149                                         Ok(v)
150                                 },
151                                 Err(e) => Err(e),
152                         }
153                 }
154         }
155 }
156
157 impl<R: Read> LengthRead for FixedLengthReader<R> {
158         #[inline]
159         fn total_bytes(&self) -> u64 {
160                 self.total_bytes
161         }
162 }
163
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".
166 ///
167 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
168 pub struct ReadTrackingReader<R: Read> {
169         read: R,
170         /// Returns whether we have read from this reader or not yet.
171         pub have_read: bool,
172 }
173 impl<R: Read> ReadTrackingReader<R> {
174         /// Returns a new [`ReadTrackingReader`].
175         pub fn new(read: R) -> Self {
176                 Self { read, have_read: false }
177         }
178 }
179 impl<R: Read> Read for ReadTrackingReader<R> {
180         #[inline]
181         fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
182                 match self.read.read(dest) {
183                         Ok(0) => Ok(0),
184                         Ok(len) => {
185                                 self.have_read = true;
186                                 Ok(len)
187                         },
188                         Err(e) => Err(e),
189                 }
190         }
191 }
192
193 /// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
194 ///
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>;
199
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();
204                 msg.0
205         }
206
207         /// Writes `self` out to a `Vec<u8>`.
208         #[cfg(test)]
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());
215                 msg.0
216         }
217
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!
221         #[inline]
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");
225                 len_calc.0
226         }
227 }
228
229 impl<'a, T: Writeable> Writeable for &'a T {
230         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
231 }
232
233 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
234 ///
235 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
236 pub trait Readable
237         where Self: Sized
238 {
239         /// Reads a `Self` in from the given [`Read`].
240         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
241 }
242
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>;
248 }
249
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.
252 ///
253 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
254 pub trait ReadableArgs<P>
255         where Self: Sized
256 {
257         /// Reads a `Self` in from the given [`Read`].
258         fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
259 }
260
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;
265 }
266
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
271 {
272         /// Reads a `Self` in from the given [`LengthRead`].
273         fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
274 }
275
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
279 {
280         /// Reads a `Self` in from the given [`LengthRead`].
281         fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
282 }
283
284 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
285 ///
286 /// This is not exported to bindings users as we only export serialization to/from byte arrays instead
287 pub trait MaybeReadable
288         where Self: Sized
289 {
290         /// Reads a `Self` in from the given [`Read`].
291         fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
292 }
293
294 impl<T: Readable> MaybeReadable for T {
295         #[inline]
296         fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
297                 Ok(Some(Readable::read(reader)?))
298         }
299 }
300
301 /// Wrapper to read a required (non-optional) TLV record.
302 ///
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> {
306         #[inline]
307         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
308                 Ok(Self(Some(Readable::read(reader)?)))
309         }
310 }
311 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
312         #[inline]
313         fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
314                 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
315         }
316 }
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)) }
322 }
323
324 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
325 /// backwards compat.
326 ///
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> {
330         #[inline]
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)))) }
334                 Ok(None)
335         }
336 }
337
338 pub(crate) struct U48(pub u64);
339 impl Writeable for U48 {
340         #[inline]
341         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
342                 writer.write_all(&be48_to_array(self.0))
343         }
344 }
345 impl Readable for U48 {
346         #[inline]
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)))
351         }
352 }
353
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.
356 ///
357 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
358 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
359 /// you're looking for an example of a variable-length integer to use for your own project, move
360 /// along, this is a rather poor design.
361 pub struct BigSize(pub u64);
362 impl Writeable for BigSize {
363         #[inline]
364         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
365                 match self.0 {
366                         0...0xFC => {
367                                 (self.0 as u8).write(writer)
368                         },
369                         0xFD...0xFFFF => {
370                                 0xFDu8.write(writer)?;
371                                 (self.0 as u16).write(writer)
372                         },
373                         0x10000...0xFFFFFFFF => {
374                                 0xFEu8.write(writer)?;
375                                 (self.0 as u32).write(writer)
376                         },
377                         _ => {
378                                 0xFFu8.write(writer)?;
379                                 (self.0 as u64).write(writer)
380                         },
381                 }
382         }
383 }
384 impl Readable for BigSize {
385         #[inline]
386         fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
387                 let n: u8 = Readable::read(reader)?;
388                 match n {
389                         0xFF => {
390                                 let x: u64 = Readable::read(reader)?;
391                                 if x < 0x100000000 {
392                                         Err(DecodeError::InvalidValue)
393                                 } else {
394                                         Ok(BigSize(x))
395                                 }
396                         }
397                         0xFE => {
398                                 let x: u32 = Readable::read(reader)?;
399                                 if x < 0x10000 {
400                                         Err(DecodeError::InvalidValue)
401                                 } else {
402                                         Ok(BigSize(x as u64))
403                                 }
404                         }
405                         0xFD => {
406                                 let x: u16 = Readable::read(reader)?;
407                                 if x < 0xFD {
408                                         Err(DecodeError::InvalidValue)
409                                 } else {
410                                         Ok(BigSize(x as u64))
411                                 }
412                         }
413                         n => Ok(BigSize(n as u64))
414                 }
415         }
416 }
417
418 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
419 /// primarily targets that, we must as well. However, because we may serialize objects that have
420 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
421 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
422 /// "read eight more bytes".
423 ///
424 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
425 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
426 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
427 struct CollectionLength(pub u64);
428 impl Writeable for CollectionLength {
429         #[inline]
430         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
431                 if self.0 < 0xffff {
432                         (self.0 as u16).write(writer)
433                 } else {
434                         0xffffu16.write(writer)?;
435                         (self.0 - 0xffff).write(writer)
436                 }
437         }
438 }
439
440 impl Readable for CollectionLength {
441         #[inline]
442         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
443                 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
444                 if val == 0xffff {
445                         val = <u64 as Readable>::read(r)?
446                                 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
447                 }
448                 Ok(CollectionLength(val))
449         }
450 }
451
452 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
453 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
454 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
455 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
456 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
457
458 macro_rules! impl_writeable_primitive {
459         ($val_type:ty, $len: expr) => {
460                 impl Writeable for $val_type {
461                         #[inline]
462                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
463                                 writer.write_all(&self.to_be_bytes())
464                         }
465                 }
466                 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
467                         #[inline]
468                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
469                                 // Skip any full leading 0 bytes when writing (in BE):
470                                 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
471                         }
472                 }
473                 impl Readable for $val_type {
474                         #[inline]
475                         fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
476                                 let mut buf = [0; $len];
477                                 reader.read_exact(&mut buf)?;
478                                 Ok(<$val_type>::from_be_bytes(buf))
479                         }
480                 }
481                 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
482                         #[inline]
483                         fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
484                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
485                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
486                                 // and then convert the appropriate number of bytes with extra high bytes out of
487                                 // buf.
488                                 let mut buf = [0; $len*2];
489                                 let mut read_len = reader.read(&mut buf[$len..])?;
490                                 let mut total_read_len = read_len;
491                                 while read_len != 0 && total_read_len != $len {
492                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
493                                         total_read_len += read_len;
494                                 }
495                                 if total_read_len == 0 || buf[$len] != 0 {
496                                         let first_byte = $len - ($len - total_read_len);
497                                         let mut bytes = [0; $len];
498                                         bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
499                                         Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
500                                 } else {
501                                         // If the encoding had extra zero bytes, return a failure even though we know
502                                         // what they meant (as the TLV test vectors require this)
503                                         Err(DecodeError::InvalidValue)
504                                 }
505                         }
506                 }
507                 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
508                         fn from(val: $val_type) -> Self { Self(val) }
509                 }
510         }
511 }
512
513 impl_writeable_primitive!(u128, 16);
514 impl_writeable_primitive!(u64, 8);
515 impl_writeable_primitive!(u32, 4);
516 impl_writeable_primitive!(u16, 2);
517 impl_writeable_primitive!(i64, 8);
518 impl_writeable_primitive!(i32, 4);
519 impl_writeable_primitive!(i16, 2);
520 impl_writeable_primitive!(i8, 1);
521
522 impl Writeable for u8 {
523         #[inline]
524         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
525                 writer.write_all(&[*self])
526         }
527 }
528 impl Readable for u8 {
529         #[inline]
530         fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
531                 let mut buf = [0; 1];
532                 reader.read_exact(&mut buf)?;
533                 Ok(buf[0])
534         }
535 }
536
537 impl Writeable for bool {
538         #[inline]
539         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
540                 writer.write_all(&[if *self {1} else {0}])
541         }
542 }
543 impl Readable for bool {
544         #[inline]
545         fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
546                 let mut buf = [0; 1];
547                 reader.read_exact(&mut buf)?;
548                 if buf[0] != 0 && buf[0] != 1 {
549                         return Err(DecodeError::InvalidValue);
550                 }
551                 Ok(buf[0] == 1)
552         }
553 }
554
555 // u8 arrays
556 macro_rules! impl_array {
557         ( $size:expr ) => (
558                 impl Writeable for [u8; $size]
559                 {
560                         #[inline]
561                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
562                                 w.write_all(self)
563                         }
564                 }
565
566                 impl Readable for [u8; $size]
567                 {
568                         #[inline]
569                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
570                                 let mut buf = [0u8; $size];
571                                 r.read_exact(&mut buf)?;
572                                 Ok(buf)
573                         }
574                 }
575         );
576 }
577
578 impl_array!(3); // for rgb, ISO 4712 code
579 impl_array!(4); // for IPv4
580 impl_array!(12); // for OnionV2
581 impl_array!(16); // for IPv6
582 impl_array!(32); // for channel id & hmac
583 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
584 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
585 impl_array!(66); // for MuSig2 nonces
586 impl_array!(1300); // for OnionPacket.hop_data
587
588 impl Writeable for [u16; 8] {
589         #[inline]
590         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
591                 for v in self.iter() {
592                         w.write_all(&v.to_be_bytes())?
593                 }
594                 Ok(())
595         }
596 }
597
598 impl Readable for [u16; 8] {
599         #[inline]
600         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
601                 let mut buf = [0u8; 16];
602                 r.read_exact(&mut buf)?;
603                 let mut res = [0u16; 8];
604                 for (idx, v) in res.iter_mut().enumerate() {
605                         *v = (buf[idx*2] as u16) << 8 | (buf[idx*2 + 1] as u16)
606                 }
607                 Ok(res)
608         }
609 }
610
611 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
612 /// Used to prevent encoding the length twice.
613 ///
614 /// This is not exported to bindings users as manual TLV building is not currently supported in bindings
615 pub struct WithoutLength<T>(pub T);
616
617 impl Writeable for WithoutLength<&String> {
618         #[inline]
619         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
620                 w.write_all(self.0.as_bytes())
621         }
622 }
623 impl Readable for WithoutLength<String> {
624         #[inline]
625         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
626                 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
627                 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
628         }
629 }
630 impl<'a> From<&'a String> for WithoutLength<&'a String> {
631         fn from(s: &'a String) -> Self { Self(s) }
632 }
633
634
635 impl Writeable for WithoutLength<&UntrustedString> {
636         #[inline]
637         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
638                 WithoutLength(&self.0.0).write(w)
639         }
640 }
641 impl Readable for WithoutLength<UntrustedString> {
642         #[inline]
643         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
644                 let s: WithoutLength<String> = Readable::read(r)?;
645                 Ok(Self(UntrustedString(s.0)))
646         }
647 }
648
649 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
650         #[inline]
651         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
652                 for ref v in self.0.iter() {
653                         v.write(writer)?;
654                 }
655                 Ok(())
656         }
657 }
658
659 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
660         #[inline]
661         fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
662                 let mut values = Vec::new();
663                 loop {
664                         let mut track_read = ReadTrackingReader::new(&mut reader);
665                         match MaybeReadable::read(&mut track_read) {
666                                 Ok(Some(v)) => { values.push(v); },
667                                 Ok(None) => { },
668                                 // If we failed to read any bytes at all, we reached the end of our TLV
669                                 // stream and have simply exhausted all entries.
670                                 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
671                                 Err(e) => return Err(e),
672                         }
673                 }
674                 Ok(Self(values))
675         }
676 }
677 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
678         fn from(v: &'a Vec<T>) -> Self { Self(v) }
679 }
680
681 impl Writeable for WithoutLength<&Script> {
682         #[inline]
683         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
684                 writer.write_all(self.0.as_bytes())
685         }
686 }
687
688 impl Readable for WithoutLength<Script> {
689         #[inline]
690         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
691                 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
692                 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
693         }
694 }
695
696 #[derive(Debug)]
697 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
698
699 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
700         #[inline]
701         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
702                 for ref v in self.0.clone() {
703                         v.write(writer)?;
704                 }
705                 Ok(())
706         }
707 }
708
709 #[cfg(test)]
710 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
711         fn eq(&self, other: &Self) -> bool {
712                 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
713         }
714 }
715
716 macro_rules! impl_for_map {
717         ($ty: ident, $keybound: ident, $constr: expr) => {
718                 impl<K, V> Writeable for $ty<K, V>
719                         where K: Writeable + Eq + $keybound, V: Writeable
720                 {
721                         #[inline]
722                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
723                                 CollectionLength(self.len() as u64).write(w)?;
724                                 for (key, value) in self.iter() {
725                                         key.write(w)?;
726                                         value.write(w)?;
727                                 }
728                                 Ok(())
729                         }
730                 }
731
732                 impl<K, V> Readable for $ty<K, V>
733                         where K: Readable + Eq + $keybound, V: MaybeReadable
734                 {
735                         #[inline]
736                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
737                                 let len: CollectionLength = Readable::read(r)?;
738                                 let mut ret = $constr(len.0 as usize);
739                                 for _ in 0..len.0 {
740                                         let k = K::read(r)?;
741                                         let v_opt = V::read(r)?;
742                                         if let Some(v) = v_opt {
743                                                 if ret.insert(k, v).is_some() {
744                                                         return Err(DecodeError::InvalidValue);
745                                                 }
746                                         }
747                                 }
748                                 Ok(ret)
749                         }
750                 }
751         }
752 }
753
754 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
755 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
756
757 // HashSet
758 impl<T> Writeable for HashSet<T>
759 where T: Writeable + Eq + Hash
760 {
761         #[inline]
762         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
763                 CollectionLength(self.len() as u64).write(w)?;
764                 for item in self.iter() {
765                         item.write(w)?;
766                 }
767                 Ok(())
768         }
769 }
770
771 impl<T> Readable for HashSet<T>
772 where T: Readable + Eq + Hash
773 {
774         #[inline]
775         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
776                 let len: CollectionLength = Readable::read(r)?;
777                 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
778                 for _ in 0..len.0 {
779                         if !ret.insert(T::read(r)?) {
780                                 return Err(DecodeError::InvalidValue)
781                         }
782                 }
783                 Ok(ret)
784         }
785 }
786
787 // Vectors
788 macro_rules! impl_writeable_for_vec {
789         ($ty: ty $(, $name: ident)*) => {
790                 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
791                         #[inline]
792                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
793                                 CollectionLength(self.len() as u64).write(w)?;
794                                 for elem in self.iter() {
795                                         elem.write(w)?;
796                                 }
797                                 Ok(())
798                         }
799                 }
800         }
801 }
802 macro_rules! impl_readable_for_vec {
803         ($ty: ty $(, $name: ident)*) => {
804                 impl<$($name : Readable),*> Readable for Vec<$ty> {
805                         #[inline]
806                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
807                                 let len: CollectionLength = Readable::read(r)?;
808                                 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
809                                 for _ in 0..len.0 {
810                                         if let Some(val) = MaybeReadable::read(r)? {
811                                                 ret.push(val);
812                                         }
813                                 }
814                                 Ok(ret)
815                         }
816                 }
817         }
818 }
819 macro_rules! impl_for_vec {
820         ($ty: ty $(, $name: ident)*) => {
821                 impl_writeable_for_vec!($ty $(, $name)*);
822                 impl_readable_for_vec!($ty $(, $name)*);
823         }
824 }
825
826 impl Writeable for Vec<u8> {
827         #[inline]
828         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
829                 CollectionLength(self.len() as u64).write(w)?;
830                 w.write_all(&self)
831         }
832 }
833
834 impl Readable for Vec<u8> {
835         #[inline]
836         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
837                 let mut len: CollectionLength = Readable::read(r)?;
838                 let mut ret = Vec::new();
839                 while len.0 > 0 {
840                         let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
841                         let readstart = ret.len();
842                         ret.resize(readstart + readamt, 0);
843                         r.read_exact(&mut ret[readstart..])?;
844                         len.0 -= readamt as u64;
845                 }
846                 Ok(ret)
847         }
848 }
849
850 impl_for_vec!(ecdsa::Signature);
851 impl_for_vec!(crate::chain::channelmonitor::ChannelMonitorUpdate);
852 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
853 impl_for_vec!((A, B), A, B);
854 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
855 impl_readable_for_vec!(crate::routing::router::BlindedTail);
856
857 impl Writeable for Vec<Witness> {
858         #[inline]
859         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
860                 (self.len() as u16).write(w)?;
861                 for witness in self {
862                         (witness.serialized_len() as u16).write(w)?;
863                         witness.write(w)?;
864                 }
865                 Ok(())
866         }
867 }
868
869 impl Readable for Vec<Witness> {
870         #[inline]
871         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
872                 let num_witnesses = <u16 as Readable>::read(r)? as usize;
873                 let mut witnesses = Vec::with_capacity(num_witnesses);
874                 for _ in 0..num_witnesses {
875                         // Even though the length of each witness can be inferred in its consensus-encoded form,
876                         // the spec includes a length prefix so that implementations don't have to deserialize
877                         //  each initially. We do that here anyway as in general we'll need to be able to make
878                         // assertions on some properties of the witnesses when receiving a message providing a list
879                         // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
880                         let witness_len = <u16 as Readable>::read(r)? as usize;
881                         let witness = <Witness as Readable>::read(r)?;
882                         if witness.serialized_len() != witness_len {
883                                 return Err(DecodeError::BadLengthDescriptor);
884                         }
885                         witnesses.push(witness);
886                 }
887                 Ok(witnesses)
888         }
889 }
890
891 impl Writeable for Script {
892         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
893                 (self.len() as u16).write(w)?;
894                 w.write_all(self.as_bytes())
895         }
896 }
897
898 impl Readable for Script {
899         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
900                 let len = <u16 as Readable>::read(r)? as usize;
901                 let mut buf = vec![0; len];
902                 r.read_exact(&mut buf)?;
903                 Ok(Script::from(buf))
904         }
905 }
906
907 impl Writeable for PublicKey {
908         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
909                 self.serialize().write(w)
910         }
911         #[inline]
912         fn serialized_length(&self) -> usize {
913                 PUBLIC_KEY_SIZE
914         }
915 }
916
917 impl Readable for PublicKey {
918         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
919                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
920                 match PublicKey::from_slice(&buf) {
921                         Ok(key) => Ok(key),
922                         Err(_) => return Err(DecodeError::InvalidValue),
923                 }
924         }
925 }
926
927 impl Writeable for SecretKey {
928         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
929                 let mut ser = [0; SECRET_KEY_SIZE];
930                 ser.copy_from_slice(&self[..]);
931                 ser.write(w)
932         }
933         #[inline]
934         fn serialized_length(&self) -> usize {
935                 SECRET_KEY_SIZE
936         }
937 }
938
939 impl Readable for SecretKey {
940         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
941                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
942                 match SecretKey::from_slice(&buf) {
943                         Ok(key) => Ok(key),
944                         Err(_) => return Err(DecodeError::InvalidValue),
945                 }
946         }
947 }
948
949 #[cfg(taproot)]
950 impl Writeable for musig2::types::PublicNonce {
951         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
952                 self.serialize().write(w)
953         }
954 }
955
956 #[cfg(taproot)]
957 impl Readable for musig2::types::PublicNonce {
958         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
959                 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
960                 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
961         }
962 }
963
964 #[cfg(taproot)]
965 impl Writeable for PartialSignatureWithNonce {
966         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
967                 self.0.serialize().write(w)?;
968                 self.1.write(w)
969         }
970 }
971
972 #[cfg(taproot)]
973 impl Readable for PartialSignatureWithNonce {
974         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
975                 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
976                 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
977                 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
978                 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
979         }
980 }
981
982 impl Writeable for Sha256dHash {
983         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
984                 w.write_all(&self[..])
985         }
986 }
987
988 impl Readable for Sha256dHash {
989         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
990                 use bitcoin::hashes::Hash;
991
992                 let buf: [u8; 32] = Readable::read(r)?;
993                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
994         }
995 }
996
997 impl Writeable for ecdsa::Signature {
998         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
999                 self.serialize_compact().write(w)
1000         }
1001 }
1002
1003 impl Readable for ecdsa::Signature {
1004         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1005                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1006                 match ecdsa::Signature::from_compact(&buf) {
1007                         Ok(sig) => Ok(sig),
1008                         Err(_) => return Err(DecodeError::InvalidValue),
1009                 }
1010         }
1011 }
1012
1013 impl Writeable for schnorr::Signature {
1014         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1015                 self.as_ref().write(w)
1016         }
1017 }
1018
1019 impl Readable for schnorr::Signature {
1020         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1021                 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1022                 match schnorr::Signature::from_slice(&buf) {
1023                         Ok(sig) => Ok(sig),
1024                         Err(_) => return Err(DecodeError::InvalidValue),
1025                 }
1026         }
1027 }
1028
1029 impl Writeable for PaymentPreimage {
1030         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1031                 self.0.write(w)
1032         }
1033 }
1034
1035 impl Readable for PaymentPreimage {
1036         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1037                 let buf: [u8; 32] = Readable::read(r)?;
1038                 Ok(PaymentPreimage(buf))
1039         }
1040 }
1041
1042 impl Writeable for PaymentHash {
1043         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1044                 self.0.write(w)
1045         }
1046 }
1047
1048 impl Readable for PaymentHash {
1049         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1050                 let buf: [u8; 32] = Readable::read(r)?;
1051                 Ok(PaymentHash(buf))
1052         }
1053 }
1054
1055 impl Writeable for PaymentSecret {
1056         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1057                 self.0.write(w)
1058         }
1059 }
1060
1061 impl Readable for PaymentSecret {
1062         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1063                 let buf: [u8; 32] = Readable::read(r)?;
1064                 Ok(PaymentSecret(buf))
1065         }
1066 }
1067
1068 impl<T: Writeable> Writeable for Box<T> {
1069         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1070                 T::write(&**self, w)
1071         }
1072 }
1073
1074 impl<T: Readable> Readable for Box<T> {
1075         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1076                 Ok(Box::new(Readable::read(r)?))
1077         }
1078 }
1079
1080 impl<T: Writeable> Writeable for Option<T> {
1081         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1082                 match *self {
1083                         None => 0u8.write(w)?,
1084                         Some(ref data) => {
1085                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1086                                 data.write(w)?;
1087                         }
1088                 }
1089                 Ok(())
1090         }
1091 }
1092
1093 impl<T: Readable> Readable for Option<T>
1094 {
1095         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1096                 let len: BigSize = Readable::read(r)?;
1097                 match len.0 {
1098                         0 => Ok(None),
1099                         len => {
1100                                 let mut reader = FixedLengthReader::new(r, len - 1);
1101                                 Ok(Some(Readable::read(&mut reader)?))
1102                         }
1103                 }
1104         }
1105 }
1106
1107 impl Writeable for Txid {
1108         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1109                 w.write_all(&self[..])
1110         }
1111 }
1112
1113 impl Readable for Txid {
1114         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1115                 use bitcoin::hashes::Hash;
1116
1117                 let buf: [u8; 32] = Readable::read(r)?;
1118                 Ok(Txid::from_slice(&buf[..]).unwrap())
1119         }
1120 }
1121
1122 impl Writeable for BlockHash {
1123         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1124                 w.write_all(&self[..])
1125         }
1126 }
1127
1128 impl Readable for BlockHash {
1129         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1130                 use bitcoin::hashes::Hash;
1131
1132                 let buf: [u8; 32] = Readable::read(r)?;
1133                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1134         }
1135 }
1136
1137 impl Writeable for ChainHash {
1138         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1139                 w.write_all(self.as_bytes())
1140         }
1141 }
1142
1143 impl Readable for ChainHash {
1144         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1145                 let buf: [u8; 32] = Readable::read(r)?;
1146                 Ok(ChainHash::from(&buf[..]))
1147         }
1148 }
1149
1150 impl Writeable for OutPoint {
1151         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1152                 self.txid.write(w)?;
1153                 self.vout.write(w)?;
1154                 Ok(())
1155         }
1156 }
1157
1158 impl Readable for OutPoint {
1159         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1160                 let txid = Readable::read(r)?;
1161                 let vout = Readable::read(r)?;
1162                 Ok(OutPoint {
1163                         txid,
1164                         vout,
1165                 })
1166         }
1167 }
1168
1169 macro_rules! impl_consensus_ser {
1170         ($bitcoin_type: ty) => {
1171                 impl Writeable for $bitcoin_type {
1172                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1173                                 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1174                                         Ok(_) => Ok(()),
1175                                         Err(e) => Err(e),
1176                                 }
1177                         }
1178                 }
1179
1180                 impl Readable for $bitcoin_type {
1181                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1182                                 match consensus::encode::Decodable::consensus_decode(r) {
1183                                         Ok(t) => Ok(t),
1184                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1185                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1186                                         Err(_) => Err(DecodeError::InvalidValue),
1187                                 }
1188                         }
1189                 }
1190         }
1191 }
1192 impl_consensus_ser!(Transaction);
1193 impl_consensus_ser!(TxOut);
1194 impl_consensus_ser!(Witness);
1195
1196 impl<T: Readable> Readable for Mutex<T> {
1197         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1198                 let t: T = Readable::read(r)?;
1199                 Ok(Mutex::new(t))
1200         }
1201 }
1202 impl<T: Writeable> Writeable for Mutex<T> {
1203         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1204                 self.lock().unwrap().write(w)
1205         }
1206 }
1207
1208 impl<A: Readable, B: Readable> Readable for (A, B) {
1209         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1210                 let a: A = Readable::read(r)?;
1211                 let b: B = Readable::read(r)?;
1212                 Ok((a, b))
1213         }
1214 }
1215 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1216         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1217                 self.0.write(w)?;
1218                 self.1.write(w)
1219         }
1220 }
1221
1222 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1223         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1224                 let a: A = Readable::read(r)?;
1225                 let b: B = Readable::read(r)?;
1226                 let c: C = Readable::read(r)?;
1227                 Ok((a, b, c))
1228         }
1229 }
1230 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1231         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1232                 self.0.write(w)?;
1233                 self.1.write(w)?;
1234                 self.2.write(w)
1235         }
1236 }
1237
1238 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1239         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1240                 let a: A = Readable::read(r)?;
1241                 let b: B = Readable::read(r)?;
1242                 let c: C = Readable::read(r)?;
1243                 let d: D = Readable::read(r)?;
1244                 Ok((a, b, c, d))
1245         }
1246 }
1247 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1248         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1249                 self.0.write(w)?;
1250                 self.1.write(w)?;
1251                 self.2.write(w)?;
1252                 self.3.write(w)
1253         }
1254 }
1255
1256 impl Writeable for () {
1257         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1258                 Ok(())
1259         }
1260 }
1261 impl Readable for () {
1262         fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1263                 Ok(())
1264         }
1265 }
1266
1267 impl Writeable for String {
1268         #[inline]
1269         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1270                 CollectionLength(self.len() as u64).write(w)?;
1271                 w.write_all(self.as_bytes())
1272         }
1273 }
1274 impl Readable for String {
1275         #[inline]
1276         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1277                 let v: Vec<u8> = Readable::read(r)?;
1278                 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1279                 Ok(ret)
1280         }
1281 }
1282
1283 /// Represents a hostname for serialization purposes.
1284 /// Only the character set and length will be validated.
1285 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1286 /// Its length is guaranteed to be representable by a single byte.
1287 /// This serialization is used by [`BOLT 7`] hostnames.
1288 ///
1289 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1290 #[derive(Clone, Debug, PartialEq, Eq)]
1291 pub struct Hostname(String);
1292 impl Hostname {
1293         /// Returns the length of the hostname.
1294         pub fn len(&self) -> u8 {
1295                 (&self.0).len() as u8
1296         }
1297 }
1298 impl Deref for Hostname {
1299         type Target = String;
1300
1301         fn deref(&self) -> &Self::Target {
1302                 &self.0
1303         }
1304 }
1305 impl From<Hostname> for String {
1306         fn from(hostname: Hostname) -> Self {
1307                 hostname.0
1308         }
1309 }
1310 impl TryFrom<Vec<u8>> for Hostname {
1311         type Error = ();
1312
1313         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1314                 if let Ok(s) = String::from_utf8(bytes) {
1315                         Hostname::try_from(s)
1316                 } else {
1317                         Err(())
1318                 }
1319         }
1320 }
1321 impl TryFrom<String> for Hostname {
1322         type Error = ();
1323
1324         fn try_from(s: String) -> Result<Self, Self::Error> {
1325                 if s.len() <= 255 && s.chars().all(|c|
1326                         c.is_ascii_alphanumeric() ||
1327                         c == '.' ||
1328                         c == '-'
1329                 ) {
1330                         Ok(Hostname(s))
1331                 } else {
1332                         Err(())
1333                 }
1334         }
1335 }
1336 impl Writeable for Hostname {
1337         #[inline]
1338         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1339                 self.len().write(w)?;
1340                 w.write_all(self.as_bytes())
1341         }
1342 }
1343 impl Readable for Hostname {
1344         #[inline]
1345         fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1346                 let len: u8 = Readable::read(r)?;
1347                 let mut vec = Vec::with_capacity(len.into());
1348                 vec.resize(len.into(), 0);
1349                 r.read_exact(&mut vec)?;
1350                 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1351         }
1352 }
1353
1354 impl Writeable for Duration {
1355         #[inline]
1356         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1357                 self.as_secs().write(w)?;
1358                 self.subsec_nanos().write(w)
1359         }
1360 }
1361 impl Readable for Duration {
1362         #[inline]
1363         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1364                 let secs = Readable::read(r)?;
1365                 let nanos = Readable::read(r)?;
1366                 Ok(Duration::new(secs, nanos))
1367         }
1368 }
1369
1370 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1371 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1372 ///
1373 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1374 #[derive(Clone, Debug, PartialEq, Eq)]
1375 pub struct TransactionU16LenLimited(Transaction);
1376
1377 impl TransactionU16LenLimited {
1378         /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1379         /// serialized length is <= u16::MAX.
1380         pub fn new(transaction: Transaction) -> Result<Self, ()> {
1381                 if transaction.serialized_length() > (u16::MAX as usize) {
1382                         Err(())
1383                 } else {
1384                         Ok(Self(transaction))
1385                 }
1386         }
1387
1388         /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1389         pub fn into_transaction(self) -> Transaction {
1390                 self.0
1391         }
1392 }
1393
1394 impl Writeable for TransactionU16LenLimited {
1395         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1396                 (self.0.serialized_length() as u16).write(w)?;
1397                 self.0.write(w)
1398         }
1399 }
1400
1401 impl Readable for TransactionU16LenLimited {
1402         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1403                 let len = <u16 as Readable>::read(r)?;
1404                 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1405                 let tx: Transaction = Readable::read(&mut tx_reader)?;
1406                 if tx_reader.bytes_remain() {
1407                         Err(DecodeError::BadLengthDescriptor)
1408                 } else {
1409                         Ok(Self(tx))
1410                 }
1411         }
1412 }
1413
1414 impl Writeable for ClaimId {
1415         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1416                 self.0.write(writer)
1417         }
1418 }
1419
1420 impl Readable for ClaimId {
1421         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1422                 Ok(Self(Readable::read(reader)?))
1423         }
1424 }
1425
1426 #[cfg(test)]
1427 mod tests {
1428         use core::convert::TryFrom;
1429         use bitcoin::secp256k1::ecdsa;
1430         use crate::util::ser::{Readable, Hostname, Writeable};
1431
1432         #[test]
1433         fn hostname_conversion() {
1434                 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1435
1436                 assert!(Hostname::try_from(String::from("\"")).is_err());
1437                 assert!(Hostname::try_from(String::from("$")).is_err());
1438                 assert!(Hostname::try_from(String::from("⚡")).is_err());
1439                 let mut large_vec = Vec::with_capacity(256);
1440                 large_vec.resize(256, b'A');
1441                 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1442         }
1443
1444         #[test]
1445         fn hostname_serialization() {
1446                 let hostname = Hostname::try_from(String::from("test")).unwrap();
1447                 let mut buf: Vec<u8> = Vec::new();
1448                 hostname.write(&mut buf).unwrap();
1449                 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1450         }
1451
1452         #[test]
1453         /// Taproot will likely fill legacy signature fields with all 0s.
1454         /// This test ensures that doing so won't break serialization.
1455         fn null_signature_codec() {
1456                 let buffer = vec![0u8; 64];
1457                 let mut cursor = crate::io::Cursor::new(buffer.clone());
1458                 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1459                 let serialization = signature.serialize_compact();
1460                 assert_eq!(buffer, serialization.to_vec())
1461         }
1462
1463         #[test]
1464         fn bigsize_encoding_decoding() {
1465                 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1466                 let bytes = vec![
1467                         "00",
1468                         "fc",
1469                         "fd00fd",
1470                         "fdffff",
1471                         "fe00010000",
1472                         "feffffffff",
1473                         "ff0000000100000000",
1474                         "ffffffffffffffffff"
1475                 ];
1476                 for i in 0..=7 {
1477                         let mut stream = crate::io::Cursor::new(::hex::decode(bytes[i]).unwrap());
1478                         assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1479                         let mut stream = super::VecWriter(Vec::new());
1480                         super::BigSize(values[i]).write(&mut stream).unwrap();
1481                         assert_eq!(stream.0, ::hex::decode(bytes[i]).unwrap());
1482                 }
1483                 let err_bytes = vec![
1484                         "fd00fc",
1485                         "fe0000ffff",
1486                         "ff00000000ffffffff",
1487                         "fd00",
1488                         "feffff",
1489                         "ffffffffff",
1490                         "fd",
1491                         "fe",
1492                         "ff",
1493                         ""
1494                 ];
1495                 for i in 0..=9 {
1496                         let mut stream = crate::io::Cursor::new(::hex::decode(err_bytes[i]).unwrap());
1497                         if i < 3 {
1498                                 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1499                         } else {
1500                                 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));
1501                         }
1502                 }
1503         }
1504 }