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