Support WithoutLength for UntrustedString
[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::ln::msgs::DecodeError;
41 #[cfg(taproot)]
42 use crate::ln::msgs::PartialSignatureWithNonce;
43 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
44
45 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
46 use crate::util::string::UntrustedString;
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
634 impl Writeable for WithoutLength<&UntrustedString> {
635         #[inline]
636         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
637                 WithoutLength(&self.0.0).write(w)
638         }
639 }
640 impl Readable for WithoutLength<UntrustedString> {
641         #[inline]
642         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
643                 let s: WithoutLength<String> = Readable::read(r)?;
644                 Ok(Self(UntrustedString(s.0)))
645         }
646 }
647
648 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
649         #[inline]
650         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
651                 for ref v in self.0.iter() {
652                         v.write(writer)?;
653                 }
654                 Ok(())
655         }
656 }
657
658 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
659         #[inline]
660         fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
661                 let mut values = Vec::new();
662                 loop {
663                         let mut track_read = ReadTrackingReader::new(&mut reader);
664                         match MaybeReadable::read(&mut track_read) {
665                                 Ok(Some(v)) => { values.push(v); },
666                                 Ok(None) => { },
667                                 // If we failed to read any bytes at all, we reached the end of our TLV
668                                 // stream and have simply exhausted all entries.
669                                 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
670                                 Err(e) => return Err(e),
671                         }
672                 }
673                 Ok(Self(values))
674         }
675 }
676 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
677         fn from(v: &'a Vec<T>) -> Self { Self(v) }
678 }
679
680 impl Writeable for WithoutLength<&Script> {
681         #[inline]
682         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
683                 writer.write_all(self.0.as_bytes())
684         }
685 }
686
687 impl Readable for WithoutLength<Script> {
688         #[inline]
689         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
690                 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
691                 Ok(WithoutLength(script::Builder::from(v.0).into_script()))
692         }
693 }
694
695 #[derive(Debug)]
696 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
697
698 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
699         #[inline]
700         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
701                 for ref v in self.0.clone() {
702                         v.write(writer)?;
703                 }
704                 Ok(())
705         }
706 }
707
708 #[cfg(test)]
709 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
710         fn eq(&self, other: &Self) -> bool {
711                 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
712         }
713 }
714
715 macro_rules! impl_for_map {
716         ($ty: ident, $keybound: ident, $constr: expr) => {
717                 impl<K, V> Writeable for $ty<K, V>
718                         where K: Writeable + Eq + $keybound, V: Writeable
719                 {
720                         #[inline]
721                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
722                                 CollectionLength(self.len() as u64).write(w)?;
723                                 for (key, value) in self.iter() {
724                                         key.write(w)?;
725                                         value.write(w)?;
726                                 }
727                                 Ok(())
728                         }
729                 }
730
731                 impl<K, V> Readable for $ty<K, V>
732                         where K: Readable + Eq + $keybound, V: MaybeReadable
733                 {
734                         #[inline]
735                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
736                                 let len: CollectionLength = Readable::read(r)?;
737                                 let mut ret = $constr(len.0 as usize);
738                                 for _ in 0..len.0 {
739                                         let k = K::read(r)?;
740                                         let v_opt = V::read(r)?;
741                                         if let Some(v) = v_opt {
742                                                 if ret.insert(k, v).is_some() {
743                                                         return Err(DecodeError::InvalidValue);
744                                                 }
745                                         }
746                                 }
747                                 Ok(ret)
748                         }
749                 }
750         }
751 }
752
753 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
754 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
755
756 // HashSet
757 impl<T> Writeable for HashSet<T>
758 where T: Writeable + Eq + Hash
759 {
760         #[inline]
761         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
762                 CollectionLength(self.len() as u64).write(w)?;
763                 for item in self.iter() {
764                         item.write(w)?;
765                 }
766                 Ok(())
767         }
768 }
769
770 impl<T> Readable for HashSet<T>
771 where T: Readable + Eq + Hash
772 {
773         #[inline]
774         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
775                 let len: CollectionLength = Readable::read(r)?;
776                 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
777                 for _ in 0..len.0 {
778                         if !ret.insert(T::read(r)?) {
779                                 return Err(DecodeError::InvalidValue)
780                         }
781                 }
782                 Ok(ret)
783         }
784 }
785
786 // Vectors
787 macro_rules! impl_writeable_for_vec {
788         ($ty: ty $(, $name: ident)*) => {
789                 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
790                         #[inline]
791                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
792                                 CollectionLength(self.len() as u64).write(w)?;
793                                 for elem in self.iter() {
794                                         elem.write(w)?;
795                                 }
796                                 Ok(())
797                         }
798                 }
799         }
800 }
801 macro_rules! impl_readable_for_vec {
802         ($ty: ty $(, $name: ident)*) => {
803                 impl<$($name : Readable),*> Readable for Vec<$ty> {
804                         #[inline]
805                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
806                                 let len: CollectionLength = Readable::read(r)?;
807                                 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
808                                 for _ in 0..len.0 {
809                                         if let Some(val) = MaybeReadable::read(r)? {
810                                                 ret.push(val);
811                                         }
812                                 }
813                                 Ok(ret)
814                         }
815                 }
816         }
817 }
818 macro_rules! impl_for_vec {
819         ($ty: ty $(, $name: ident)*) => {
820                 impl_writeable_for_vec!($ty $(, $name)*);
821                 impl_readable_for_vec!($ty $(, $name)*);
822         }
823 }
824
825 impl Writeable for Vec<u8> {
826         #[inline]
827         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
828                 CollectionLength(self.len() as u64).write(w)?;
829                 w.write_all(&self)
830         }
831 }
832
833 impl Readable for Vec<u8> {
834         #[inline]
835         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
836                 let mut len: CollectionLength = Readable::read(r)?;
837                 let mut ret = Vec::new();
838                 while len.0 > 0 {
839                         let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
840                         let readstart = ret.len();
841                         ret.resize(readstart + readamt, 0);
842                         r.read_exact(&mut ret[readstart..])?;
843                         len.0 -= readamt as u64;
844                 }
845                 Ok(ret)
846         }
847 }
848
849 impl_for_vec!(ecdsa::Signature);
850 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
851 impl_for_vec!((A, B), A, B);
852 impl_writeable_for_vec!(&crate::routing::router::BlindedTail);
853 impl_readable_for_vec!(crate::routing::router::BlindedTail);
854
855 impl Writeable for Vec<Witness> {
856         #[inline]
857         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
858                 (self.len() as u16).write(w)?;
859                 for witness in self {
860                         (witness.serialized_len() as u16).write(w)?;
861                         witness.write(w)?;
862                 }
863                 Ok(())
864         }
865 }
866
867 impl Readable for Vec<Witness> {
868         #[inline]
869         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
870                 let num_witnesses = <u16 as Readable>::read(r)? as usize;
871                 let mut witnesses = Vec::with_capacity(num_witnesses);
872                 for _ in 0..num_witnesses {
873                         // Even though the length of each witness can be inferred in its consensus-encoded form,
874                         // the spec includes a length prefix so that implementations don't have to deserialize
875                         //  each initially. We do that here anyway as in general we'll need to be able to make
876                         // assertions on some properties of the witnesses when receiving a message providing a list
877                         // of witnesses. We'll just do a sanity check for the lengths and error if there is a mismatch.
878                         let witness_len = <u16 as Readable>::read(r)? as usize;
879                         let witness = <Witness as Readable>::read(r)?;
880                         if witness.serialized_len() != witness_len {
881                                 return Err(DecodeError::BadLengthDescriptor);
882                         }
883                         witnesses.push(witness);
884                 }
885                 Ok(witnesses)
886         }
887 }
888
889 impl Writeable for Script {
890         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
891                 (self.len() as u16).write(w)?;
892                 w.write_all(self.as_bytes())
893         }
894 }
895
896 impl Readable for Script {
897         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
898                 let len = <u16 as Readable>::read(r)? as usize;
899                 let mut buf = vec![0; len];
900                 r.read_exact(&mut buf)?;
901                 Ok(Script::from(buf))
902         }
903 }
904
905 impl Writeable for PublicKey {
906         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
907                 self.serialize().write(w)
908         }
909         #[inline]
910         fn serialized_length(&self) -> usize {
911                 PUBLIC_KEY_SIZE
912         }
913 }
914
915 impl Readable for PublicKey {
916         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
917                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
918                 match PublicKey::from_slice(&buf) {
919                         Ok(key) => Ok(key),
920                         Err(_) => return Err(DecodeError::InvalidValue),
921                 }
922         }
923 }
924
925 impl Writeable for SecretKey {
926         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
927                 let mut ser = [0; SECRET_KEY_SIZE];
928                 ser.copy_from_slice(&self[..]);
929                 ser.write(w)
930         }
931         #[inline]
932         fn serialized_length(&self) -> usize {
933                 SECRET_KEY_SIZE
934         }
935 }
936
937 impl Readable for SecretKey {
938         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
939                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
940                 match SecretKey::from_slice(&buf) {
941                         Ok(key) => Ok(key),
942                         Err(_) => return Err(DecodeError::InvalidValue),
943                 }
944         }
945 }
946
947 #[cfg(taproot)]
948 impl Writeable for musig2::types::PublicNonce {
949         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
950                 self.serialize().write(w)
951         }
952 }
953
954 #[cfg(taproot)]
955 impl Readable for musig2::types::PublicNonce {
956         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
957                 let buf: [u8; PUBLIC_KEY_SIZE * 2] = Readable::read(r)?;
958                 musig2::types::PublicNonce::from_slice(&buf).map_err(|_| DecodeError::InvalidValue)
959         }
960 }
961
962 #[cfg(taproot)]
963 impl Writeable for PartialSignatureWithNonce {
964         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
965                 self.0.serialize().write(w)?;
966                 self.1.write(w)
967         }
968 }
969
970 #[cfg(taproot)]
971 impl Readable for PartialSignatureWithNonce {
972         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
973                 let partial_signature_buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
974                 let partial_signature = musig2::types::PartialSignature::from_slice(&partial_signature_buf).map_err(|_| DecodeError::InvalidValue)?;
975                 let public_nonce: musig2::types::PublicNonce = Readable::read(r)?;
976                 Ok(PartialSignatureWithNonce(partial_signature, public_nonce))
977         }
978 }
979
980 impl Writeable for Sha256dHash {
981         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
982                 w.write_all(&self[..])
983         }
984 }
985
986 impl Readable for Sha256dHash {
987         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
988                 use bitcoin::hashes::Hash;
989
990                 let buf: [u8; 32] = Readable::read(r)?;
991                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
992         }
993 }
994
995 impl Writeable for ecdsa::Signature {
996         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
997                 self.serialize_compact().write(w)
998         }
999 }
1000
1001 impl Readable for ecdsa::Signature {
1002         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1003                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
1004                 match ecdsa::Signature::from_compact(&buf) {
1005                         Ok(sig) => Ok(sig),
1006                         Err(_) => return Err(DecodeError::InvalidValue),
1007                 }
1008         }
1009 }
1010
1011 impl Writeable for schnorr::Signature {
1012         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1013                 self.as_ref().write(w)
1014         }
1015 }
1016
1017 impl Readable for schnorr::Signature {
1018         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1019                 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
1020                 match schnorr::Signature::from_slice(&buf) {
1021                         Ok(sig) => Ok(sig),
1022                         Err(_) => return Err(DecodeError::InvalidValue),
1023                 }
1024         }
1025 }
1026
1027 impl Writeable for PaymentPreimage {
1028         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1029                 self.0.write(w)
1030         }
1031 }
1032
1033 impl Readable for PaymentPreimage {
1034         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1035                 let buf: [u8; 32] = Readable::read(r)?;
1036                 Ok(PaymentPreimage(buf))
1037         }
1038 }
1039
1040 impl Writeable for PaymentHash {
1041         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1042                 self.0.write(w)
1043         }
1044 }
1045
1046 impl Readable for PaymentHash {
1047         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1048                 let buf: [u8; 32] = Readable::read(r)?;
1049                 Ok(PaymentHash(buf))
1050         }
1051 }
1052
1053 impl Writeable for PaymentSecret {
1054         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1055                 self.0.write(w)
1056         }
1057 }
1058
1059 impl Readable for PaymentSecret {
1060         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1061                 let buf: [u8; 32] = Readable::read(r)?;
1062                 Ok(PaymentSecret(buf))
1063         }
1064 }
1065
1066 impl<T: Writeable> Writeable for Box<T> {
1067         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1068                 T::write(&**self, w)
1069         }
1070 }
1071
1072 impl<T: Readable> Readable for Box<T> {
1073         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1074                 Ok(Box::new(Readable::read(r)?))
1075         }
1076 }
1077
1078 impl<T: Writeable> Writeable for Option<T> {
1079         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1080                 match *self {
1081                         None => 0u8.write(w)?,
1082                         Some(ref data) => {
1083                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
1084                                 data.write(w)?;
1085                         }
1086                 }
1087                 Ok(())
1088         }
1089 }
1090
1091 impl<T: Readable> Readable for Option<T>
1092 {
1093         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1094                 let len: BigSize = Readable::read(r)?;
1095                 match len.0 {
1096                         0 => Ok(None),
1097                         len => {
1098                                 let mut reader = FixedLengthReader::new(r, len - 1);
1099                                 Ok(Some(Readable::read(&mut reader)?))
1100                         }
1101                 }
1102         }
1103 }
1104
1105 impl Writeable for Txid {
1106         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1107                 w.write_all(&self[..])
1108         }
1109 }
1110
1111 impl Readable for Txid {
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(Txid::from_slice(&buf[..]).unwrap())
1117         }
1118 }
1119
1120 impl Writeable for BlockHash {
1121         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1122                 w.write_all(&self[..])
1123         }
1124 }
1125
1126 impl Readable for BlockHash {
1127         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1128                 use bitcoin::hashes::Hash;
1129
1130                 let buf: [u8; 32] = Readable::read(r)?;
1131                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1132         }
1133 }
1134
1135 impl Writeable for ChainHash {
1136         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1137                 w.write_all(self.as_bytes())
1138         }
1139 }
1140
1141 impl Readable for ChainHash {
1142         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1143                 let buf: [u8; 32] = Readable::read(r)?;
1144                 Ok(ChainHash::from(&buf[..]))
1145         }
1146 }
1147
1148 impl Writeable for OutPoint {
1149         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1150                 self.txid.write(w)?;
1151                 self.vout.write(w)?;
1152                 Ok(())
1153         }
1154 }
1155
1156 impl Readable for OutPoint {
1157         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1158                 let txid = Readable::read(r)?;
1159                 let vout = Readable::read(r)?;
1160                 Ok(OutPoint {
1161                         txid,
1162                         vout,
1163                 })
1164         }
1165 }
1166
1167 macro_rules! impl_consensus_ser {
1168         ($bitcoin_type: ty) => {
1169                 impl Writeable for $bitcoin_type {
1170                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1171                                 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1172                                         Ok(_) => Ok(()),
1173                                         Err(e) => Err(e),
1174                                 }
1175                         }
1176                 }
1177
1178                 impl Readable for $bitcoin_type {
1179                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1180                                 match consensus::encode::Decodable::consensus_decode(r) {
1181                                         Ok(t) => Ok(t),
1182                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1183                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1184                                         Err(_) => Err(DecodeError::InvalidValue),
1185                                 }
1186                         }
1187                 }
1188         }
1189 }
1190 impl_consensus_ser!(Transaction);
1191 impl_consensus_ser!(TxOut);
1192 impl_consensus_ser!(Witness);
1193
1194 impl<T: Readable> Readable for Mutex<T> {
1195         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1196                 let t: T = Readable::read(r)?;
1197                 Ok(Mutex::new(t))
1198         }
1199 }
1200 impl<T: Writeable> Writeable for Mutex<T> {
1201         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1202                 self.lock().unwrap().write(w)
1203         }
1204 }
1205
1206 impl<A: Readable, B: Readable> Readable for (A, B) {
1207         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1208                 let a: A = Readable::read(r)?;
1209                 let b: B = Readable::read(r)?;
1210                 Ok((a, b))
1211         }
1212 }
1213 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1214         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1215                 self.0.write(w)?;
1216                 self.1.write(w)
1217         }
1218 }
1219
1220 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1221         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1222                 let a: A = Readable::read(r)?;
1223                 let b: B = Readable::read(r)?;
1224                 let c: C = Readable::read(r)?;
1225                 Ok((a, b, c))
1226         }
1227 }
1228 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1229         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1230                 self.0.write(w)?;
1231                 self.1.write(w)?;
1232                 self.2.write(w)
1233         }
1234 }
1235
1236 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1237         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1238                 let a: A = Readable::read(r)?;
1239                 let b: B = Readable::read(r)?;
1240                 let c: C = Readable::read(r)?;
1241                 let d: D = Readable::read(r)?;
1242                 Ok((a, b, c, d))
1243         }
1244 }
1245 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1246         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1247                 self.0.write(w)?;
1248                 self.1.write(w)?;
1249                 self.2.write(w)?;
1250                 self.3.write(w)
1251         }
1252 }
1253
1254 impl Writeable for () {
1255         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1256                 Ok(())
1257         }
1258 }
1259 impl Readable for () {
1260         fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1261                 Ok(())
1262         }
1263 }
1264
1265 impl Writeable for String {
1266         #[inline]
1267         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1268                 CollectionLength(self.len() as u64).write(w)?;
1269                 w.write_all(self.as_bytes())
1270         }
1271 }
1272 impl Readable for String {
1273         #[inline]
1274         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1275                 let v: Vec<u8> = Readable::read(r)?;
1276                 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1277                 Ok(ret)
1278         }
1279 }
1280
1281 /// Represents a hostname for serialization purposes.
1282 /// Only the character set and length will be validated.
1283 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1284 /// Its length is guaranteed to be representable by a single byte.
1285 /// This serialization is used by [`BOLT 7`] hostnames.
1286 ///
1287 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1288 #[derive(Clone, Debug, PartialEq, Eq)]
1289 pub struct Hostname(String);
1290 impl Hostname {
1291         /// Returns the length of the hostname.
1292         pub fn len(&self) -> u8 {
1293                 (&self.0).len() as u8
1294         }
1295 }
1296 impl Deref for Hostname {
1297         type Target = String;
1298
1299         fn deref(&self) -> &Self::Target {
1300                 &self.0
1301         }
1302 }
1303 impl From<Hostname> for String {
1304         fn from(hostname: Hostname) -> Self {
1305                 hostname.0
1306         }
1307 }
1308 impl TryFrom<Vec<u8>> for Hostname {
1309         type Error = ();
1310
1311         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1312                 if let Ok(s) = String::from_utf8(bytes) {
1313                         Hostname::try_from(s)
1314                 } else {
1315                         Err(())
1316                 }
1317         }
1318 }
1319 impl TryFrom<String> for Hostname {
1320         type Error = ();
1321
1322         fn try_from(s: String) -> Result<Self, Self::Error> {
1323                 if s.len() <= 255 && s.chars().all(|c|
1324                         c.is_ascii_alphanumeric() ||
1325                         c == '.' ||
1326                         c == '-'
1327                 ) {
1328                         Ok(Hostname(s))
1329                 } else {
1330                         Err(())
1331                 }
1332         }
1333 }
1334 impl Writeable for Hostname {
1335         #[inline]
1336         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1337                 self.len().write(w)?;
1338                 w.write_all(self.as_bytes())
1339         }
1340 }
1341 impl Readable for Hostname {
1342         #[inline]
1343         fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1344                 let len: u8 = Readable::read(r)?;
1345                 let mut vec = Vec::with_capacity(len.into());
1346                 vec.resize(len.into(), 0);
1347                 r.read_exact(&mut vec)?;
1348                 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1349         }
1350 }
1351
1352 impl Writeable for Duration {
1353         #[inline]
1354         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1355                 self.as_secs().write(w)?;
1356                 self.subsec_nanos().write(w)
1357         }
1358 }
1359 impl Readable for Duration {
1360         #[inline]
1361         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1362                 let secs = Readable::read(r)?;
1363                 let nanos = Readable::read(r)?;
1364                 Ok(Duration::new(secs, nanos))
1365         }
1366 }
1367
1368 /// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
1369 /// if the `Transaction`'s consensus-serialized length is <= u16::MAX.
1370 ///
1371 /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`.
1372 #[derive(Clone, Debug, PartialEq, Eq)]
1373 pub struct TransactionU16LenLimited(Transaction);
1374
1375 impl TransactionU16LenLimited {
1376         /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
1377         /// serialized length is <= u16::MAX.
1378         pub fn new(transaction: Transaction) -> Result<Self, ()> {
1379                 if transaction.serialized_length() > (u16::MAX as usize) {
1380                         Err(())
1381                 } else {
1382                         Ok(Self(transaction))
1383                 }
1384         }
1385
1386         /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
1387         pub fn into_transaction(self) -> Transaction {
1388                 self.0
1389         }
1390 }
1391
1392 impl Writeable for TransactionU16LenLimited {
1393         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1394                 (self.0.serialized_length() as u16).write(w)?;
1395                 self.0.write(w)
1396         }
1397 }
1398
1399 impl Readable for TransactionU16LenLimited {
1400         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1401                 let len = <u16 as Readable>::read(r)?;
1402                 let mut tx_reader = FixedLengthReader::new(r, len as u64);
1403                 let tx: Transaction = Readable::read(&mut tx_reader)?;
1404                 if tx_reader.bytes_remain() {
1405                         Err(DecodeError::BadLengthDescriptor)
1406                 } else {
1407                         Ok(Self(tx))
1408                 }
1409         }
1410 }
1411
1412 #[cfg(test)]
1413 mod tests {
1414         use core::convert::TryFrom;
1415         use bitcoin::secp256k1::ecdsa;
1416         use crate::util::ser::{Readable, Hostname, Writeable};
1417
1418         #[test]
1419         fn hostname_conversion() {
1420                 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1421
1422                 assert!(Hostname::try_from(String::from("\"")).is_err());
1423                 assert!(Hostname::try_from(String::from("$")).is_err());
1424                 assert!(Hostname::try_from(String::from("⚡")).is_err());
1425                 let mut large_vec = Vec::with_capacity(256);
1426                 large_vec.resize(256, b'A');
1427                 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1428         }
1429
1430         #[test]
1431         fn hostname_serialization() {
1432                 let hostname = Hostname::try_from(String::from("test")).unwrap();
1433                 let mut buf: Vec<u8> = Vec::new();
1434                 hostname.write(&mut buf).unwrap();
1435                 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1436         }
1437
1438         #[test]
1439         /// Taproot will likely fill legacy signature fields with all 0s.
1440         /// This test ensures that doing so won't break serialization.
1441         fn null_signature_codec() {
1442                 let buffer = vec![0u8; 64];
1443                 let mut cursor = crate::io::Cursor::new(buffer.clone());
1444                 let signature = ecdsa::Signature::read(&mut cursor).unwrap();
1445                 let serialization = signature.serialize_compact();
1446                 assert_eq!(buffer, serialization.to_vec())
1447         }
1448
1449         #[test]
1450         fn bigsize_encoding_decoding() {
1451                 let values = vec![0, 252, 253, 65535, 65536, 4294967295, 4294967296, 18446744073709551615];
1452                 let bytes = vec![
1453                         "00",
1454                         "fc",
1455                         "fd00fd",
1456                         "fdffff",
1457                         "fe00010000",
1458                         "feffffffff",
1459                         "ff0000000100000000",
1460                         "ffffffffffffffffff"
1461                 ];
1462                 for i in 0..=7 {
1463                         let mut stream = crate::io::Cursor::new(::hex::decode(bytes[i]).unwrap());
1464                         assert_eq!(super::BigSize::read(&mut stream).unwrap().0, values[i]);
1465                         let mut stream = super::VecWriter(Vec::new());
1466                         super::BigSize(values[i]).write(&mut stream).unwrap();
1467                         assert_eq!(stream.0, ::hex::decode(bytes[i]).unwrap());
1468                 }
1469                 let err_bytes = vec![
1470                         "fd00fc",
1471                         "fe0000ffff",
1472                         "ff00000000ffffffff",
1473                         "fd00",
1474                         "feffff",
1475                         "ffffffffff",
1476                         "fd",
1477                         "fe",
1478                         "ff",
1479                         ""
1480                 ];
1481                 for i in 0..=9 {
1482                         let mut stream = crate::io::Cursor::new(::hex::decode(err_bytes[i]).unwrap());
1483                         if i < 3 {
1484                                 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::InvalidValue));
1485                         } else {
1486                                 assert_eq!(super::BigSize::read(&mut stream).err(), Some(crate::ln::msgs::DecodeError::ShortRead));
1487                         }
1488                 }
1489         }
1490 }