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