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