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