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