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