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