1 // This file is Copyright its original authors, visible in version control
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
10 //! A very simple serialization framework which is used to serialize/deserialize messages as well
11 //! as ChannelsManagers and ChannelMonitors.
13 use crate::prelude::*;
14 use crate::io::{self, Read, Seek, Write};
15 use crate::io_extras::{copy, sink};
17 use crate::sync::Mutex;
19 use core::convert::TryFrom;
22 use bitcoin::secp256k1::{PublicKey, SecretKey};
23 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE, SCHNORR_SIGNATURE_SIZE};
24 use bitcoin::secp256k1::ecdsa;
25 use bitcoin::secp256k1::schnorr;
26 use bitcoin::blockdata::constants::ChainHash;
27 use bitcoin::blockdata::script::Script;
28 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
29 use bitcoin::consensus;
30 use bitcoin::consensus::Encodable;
31 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
32 use bitcoin::hash_types::{Txid, BlockHash};
33 use core::marker::Sized;
34 use core::time::Duration;
35 use crate::ln::msgs::DecodeError;
36 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
38 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
40 /// serialization buffer size
41 pub const MAX_BUF_SIZE: usize = 64 * 1024;
43 /// A simplified version of std::io::Write that exists largely for backwards compatibility.
44 /// An impl is provided for any type that also impls std::io::Write.
46 /// (C-not exported) as we only export serialization to/from byte arrays instead
48 /// Writes the given buf out. See std::io::Write::write_all for more
49 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
52 impl<W: Write> Writer for W {
54 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
55 <Self as io::Write>::write_all(self, buf)
59 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
60 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
62 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
66 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
67 self.0.write_all(buf)?;
71 fn flush(&mut self) -> Result<(), io::Error> {
76 pub(crate) struct VecWriter(pub Vec<u8>);
77 impl Writer for VecWriter {
79 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
80 self.0.extend_from_slice(buf);
85 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
86 /// of some data when serialized but don't yet need the full data.
87 pub(crate) struct LengthCalculatingWriter(pub usize);
88 impl Writer for LengthCalculatingWriter {
90 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
96 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
97 /// forward to ensure we always consume exactly the fixed length specified.
98 pub(crate) struct FixedLengthReader<R: Read> {
103 impl<R: Read> FixedLengthReader<R> {
104 pub fn new(read: R, total_bytes: u64) -> Self {
105 Self { read, bytes_read: 0, total_bytes }
109 pub fn bytes_remain(&mut self) -> bool {
110 self.bytes_read != self.total_bytes
114 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
115 copy(self, &mut sink()).unwrap();
116 if self.bytes_read != self.total_bytes {
117 Err(DecodeError::ShortRead)
123 impl<R: Read> Read for FixedLengthReader<R> {
125 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
126 if self.total_bytes == self.bytes_read {
129 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
130 match self.read.read(&mut dest[0..(read_len as usize)]) {
132 self.bytes_read += v as u64;
141 impl<R: Read> LengthRead for FixedLengthReader<R> {
143 fn total_bytes(&self) -> u64 {
148 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
149 /// between "EOF reached before we started" and "EOF reached mid-read".
150 pub(crate) struct ReadTrackingReader<R: Read> {
154 impl<R: Read> ReadTrackingReader<R> {
155 pub fn new(read: R) -> Self {
156 Self { read, have_read: false }
159 impl<R: Read> Read for ReadTrackingReader<R> {
161 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
162 match self.read.read(dest) {
165 self.have_read = true;
173 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
175 /// (C-not exported) as we only export serialization to/from byte arrays instead
176 pub trait Writeable {
177 /// Writes self out to the given Writer
178 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
180 /// Writes self out to a Vec<u8>
181 fn encode(&self) -> Vec<u8> {
182 let mut msg = VecWriter(Vec::new());
183 self.write(&mut msg).unwrap();
187 /// Writes self out to a Vec<u8>
189 fn encode_with_len(&self) -> Vec<u8> {
190 let mut msg = VecWriter(Vec::new());
191 0u16.write(&mut msg).unwrap();
192 self.write(&mut msg).unwrap();
193 let len = msg.0.len();
194 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
198 /// Gets the length of this object after it has been serialized. This can be overridden to
199 /// optimize cases where we prepend an object with its length.
200 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
202 fn serialized_length(&self) -> usize {
203 let mut len_calc = LengthCalculatingWriter(0);
204 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
209 impl<'a, T: Writeable> Writeable for &'a T {
210 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
213 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
215 /// (C-not exported) as we only export serialization to/from byte arrays instead
219 /// Reads a Self in from the given Read
220 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
223 /// A trait that various rust-lightning types implement allowing them to be read in from a
225 pub(crate) trait SeekReadable where Self: Sized {
226 /// Reads a Self in from the given Read
227 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
230 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
231 /// from a Read given some additional set of arguments which is required to deserialize.
233 /// (C-not exported) as we only export serialization to/from byte arrays instead
234 pub trait ReadableArgs<P>
237 /// Reads a Self in from the given Read
238 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
241 /// A std::io::Read that also provides the total bytes available to read.
242 pub(crate) trait LengthRead: Read {
243 /// The total number of bytes available to read.
244 fn total_bytes(&self) -> u64;
247 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
248 /// from a Read given some additional set of arguments which is required to deserialize, requiring
249 /// the implementer to provide the total length of the read.
250 pub(crate) trait LengthReadableArgs<P> where Self: Sized
252 /// Reads a Self in from the given LengthRead
253 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
256 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
257 /// from a Read, requiring the implementer to provide the total length of the read.
258 pub(crate) trait LengthReadable where Self: Sized
260 /// Reads a Self in from the given LengthRead
261 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
264 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
266 /// (C-not exported) as we only export serialization to/from byte arrays instead
267 pub trait MaybeReadable
270 /// Reads a Self in from the given Read
271 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
274 impl<T: Readable> MaybeReadable for T {
276 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
277 Ok(Some(Readable::read(reader)?))
281 pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
282 impl<T: Readable> Readable for OptionDeserWrapper<T> {
284 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
285 Ok(Self(Some(Readable::read(reader)?)))
288 /// When handling default_values, we want to map the default-value T directly
289 /// to a OptionDeserWrapper<T> in a way that works for `field: T = t;` as
290 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
291 impl<T: Readable> From<T> for OptionDeserWrapper<T> {
292 fn from(t: T) -> OptionDeserWrapper<T> { OptionDeserWrapper(Some(t)) }
295 pub(crate) struct U48(pub u64);
296 impl Writeable for U48 {
298 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
299 writer.write_all(&be48_to_array(self.0))
302 impl Readable for U48 {
304 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
305 let mut buf = [0; 6];
306 reader.read_exact(&mut buf)?;
307 Ok(U48(slice_to_be48(&buf)))
311 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
312 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
314 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
315 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
316 /// you're looking for an example of a variable-length integer to use for your own project, move
317 /// along, this is a rather poor design.
318 pub struct BigSize(pub u64);
319 impl Writeable for BigSize {
321 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
324 (self.0 as u8).write(writer)
327 0xFDu8.write(writer)?;
328 (self.0 as u16).write(writer)
330 0x10000...0xFFFFFFFF => {
331 0xFEu8.write(writer)?;
332 (self.0 as u32).write(writer)
335 0xFFu8.write(writer)?;
336 (self.0 as u64).write(writer)
341 impl Readable for BigSize {
343 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
344 let n: u8 = Readable::read(reader)?;
347 let x: u64 = Readable::read(reader)?;
349 Err(DecodeError::InvalidValue)
355 let x: u32 = Readable::read(reader)?;
357 Err(DecodeError::InvalidValue)
359 Ok(BigSize(x as u64))
363 let x: u16 = Readable::read(reader)?;
365 Err(DecodeError::InvalidValue)
367 Ok(BigSize(x as u64))
370 n => Ok(BigSize(n as u64))
375 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
376 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
377 /// encapsulates such integers implementing Readable/Writeable for them.
378 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
379 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
381 macro_rules! impl_writeable_primitive {
382 ($val_type:ty, $len: expr) => {
383 impl Writeable for $val_type {
385 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
386 writer.write_all(&self.to_be_bytes())
389 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
391 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
392 // Skip any full leading 0 bytes when writing (in BE):
393 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
396 impl Readable for $val_type {
398 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
399 let mut buf = [0; $len];
400 reader.read_exact(&mut buf)?;
401 Ok(<$val_type>::from_be_bytes(buf))
404 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
406 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
407 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
408 // the high bytes being dropped. To do so, we start reading into the middle of buf
409 // and then convert the appropriate number of bytes with extra high bytes out of
411 let mut buf = [0; $len*2];
412 let mut read_len = reader.read(&mut buf[$len..])?;
413 let mut total_read_len = read_len;
414 while read_len != 0 && total_read_len != $len {
415 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
416 total_read_len += read_len;
418 if total_read_len == 0 || buf[$len] != 0 {
419 let first_byte = $len - ($len - total_read_len);
420 let mut bytes = [0; $len];
421 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
422 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
424 // If the encoding had extra zero bytes, return a failure even though we know
425 // what they meant (as the TLV test vectors require this)
426 Err(DecodeError::InvalidValue)
430 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
431 fn from(val: $val_type) -> Self { Self(val) }
436 impl_writeable_primitive!(u128, 16);
437 impl_writeable_primitive!(u64, 8);
438 impl_writeable_primitive!(u32, 4);
439 impl_writeable_primitive!(u16, 2);
441 impl Writeable for u8 {
443 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
444 writer.write_all(&[*self])
447 impl Readable for u8 {
449 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
450 let mut buf = [0; 1];
451 reader.read_exact(&mut buf)?;
456 impl Writeable for bool {
458 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
459 writer.write_all(&[if *self {1} else {0}])
462 impl Readable for bool {
464 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
465 let mut buf = [0; 1];
466 reader.read_exact(&mut buf)?;
467 if buf[0] != 0 && buf[0] != 1 {
468 return Err(DecodeError::InvalidValue);
475 macro_rules! impl_array {
477 impl Writeable for [u8; $size]
480 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
485 impl Readable for [u8; $size]
488 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
489 let mut buf = [0u8; $size];
490 r.read_exact(&mut buf)?;
497 impl_array!(3); // for rgb, ISO 4712 code
498 impl_array!(4); // for IPv4
499 impl_array!(12); // for OnionV2
500 impl_array!(16); // for IPv6
501 impl_array!(32); // for channel id & hmac
502 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
503 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
504 impl_array!(1300); // for OnionPacket.hop_data
506 impl Writeable for [u16; 8] {
508 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
509 for v in self.iter() {
510 w.write_all(&v.to_be_bytes())?
516 impl Readable for [u16; 8] {
518 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
519 let mut buf = [0u8; 16];
520 r.read_exact(&mut buf)?;
521 let mut res = [0u16; 8];
522 for (idx, v) in res.iter_mut().enumerate() {
523 *v = (buf[idx] as u16) << 8 | (buf[idx + 1] as u16)
529 /// For variable-length values within TLV record where the length is encoded as part of the record.
530 /// Used to prevent encoding the length twice.
531 pub(crate) struct WithoutLength<T>(pub T);
533 impl Writeable for WithoutLength<&String> {
535 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
536 w.write_all(self.0.as_bytes())
539 impl Readable for WithoutLength<String> {
541 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
542 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
543 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
546 impl<'a> From<&'a String> for WithoutLength<&'a String> {
547 fn from(s: &'a String) -> Self { Self(s) }
550 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
552 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
553 for ref v in self.0.iter() {
560 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
562 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
563 let mut values = Vec::new();
565 let mut track_read = ReadTrackingReader::new(&mut reader);
566 match MaybeReadable::read(&mut track_read) {
567 Ok(Some(v)) => { values.push(v); },
569 // If we failed to read any bytes at all, we reached the end of our TLV
570 // stream and have simply exhausted all entries.
571 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
572 Err(e) => return Err(e),
578 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
579 fn from(v: &'a Vec<T>) -> Self { Self(v) }
583 impl<K, V> Writeable for HashMap<K, V>
584 where K: Writeable + Eq + Hash,
588 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
589 (self.len() as u16).write(w)?;
590 for (key, value) in self.iter() {
598 impl<K, V> Readable for HashMap<K, V>
599 where K: Readable + Eq + Hash,
603 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
604 let len: u16 = Readable::read(r)?;
605 let mut ret = HashMap::with_capacity(len as usize);
608 let v_opt = V::read(r)?;
609 if let Some(v) = v_opt {
610 if ret.insert(k, v).is_some() {
611 return Err(DecodeError::InvalidValue);
620 impl<T> Writeable for HashSet<T>
621 where T: Writeable + Eq + Hash
624 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
625 (self.len() as u16).write(w)?;
626 for item in self.iter() {
633 impl<T> Readable for HashSet<T>
634 where T: Readable + Eq + Hash
637 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
638 let len: u16 = Readable::read(r)?;
639 let mut ret = HashSet::with_capacity(len as usize);
641 if !ret.insert(T::read(r)?) {
642 return Err(DecodeError::InvalidValue)
650 impl Writeable for Vec<u8> {
652 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
653 (self.len() as u16).write(w)?;
658 impl Readable for Vec<u8> {
660 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
661 let len: u16 = Readable::read(r)?;
662 let mut ret = Vec::with_capacity(len as usize);
663 ret.resize(len as usize, 0);
664 r.read_exact(&mut ret)?;
668 impl Writeable for Vec<ecdsa::Signature> {
670 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
671 (self.len() as u16).write(w)?;
672 for e in self.iter() {
679 impl Readable for Vec<ecdsa::Signature> {
681 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
682 let len: u16 = Readable::read(r)?;
683 let byte_size = (len as usize)
684 .checked_mul(COMPACT_SIGNATURE_SIZE)
685 .ok_or(DecodeError::BadLengthDescriptor)?;
686 if byte_size > MAX_BUF_SIZE {
687 return Err(DecodeError::BadLengthDescriptor);
689 let mut ret = Vec::with_capacity(len as usize);
690 for _ in 0..len { ret.push(Readable::read(r)?); }
695 impl Writeable for Script {
696 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
697 (self.len() as u16).write(w)?;
698 w.write_all(self.as_bytes())
702 impl Readable for Script {
703 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
704 let len = <u16 as Readable>::read(r)? as usize;
705 let mut buf = vec![0; len];
706 r.read_exact(&mut buf)?;
707 Ok(Script::from(buf))
711 impl Writeable for PublicKey {
712 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
713 self.serialize().write(w)
716 fn serialized_length(&self) -> usize {
721 impl Readable for PublicKey {
722 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
723 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
724 match PublicKey::from_slice(&buf) {
726 Err(_) => return Err(DecodeError::InvalidValue),
731 impl Writeable for SecretKey {
732 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
733 let mut ser = [0; SECRET_KEY_SIZE];
734 ser.copy_from_slice(&self[..]);
738 fn serialized_length(&self) -> usize {
743 impl Readable for SecretKey {
744 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
745 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
746 match SecretKey::from_slice(&buf) {
748 Err(_) => return Err(DecodeError::InvalidValue),
753 impl Writeable for Sha256dHash {
754 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
755 w.write_all(&self[..])
759 impl Readable for Sha256dHash {
760 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
761 use bitcoin::hashes::Hash;
763 let buf: [u8; 32] = Readable::read(r)?;
764 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
768 impl Writeable for ecdsa::Signature {
769 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
770 self.serialize_compact().write(w)
774 impl Readable for ecdsa::Signature {
775 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
776 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
777 match ecdsa::Signature::from_compact(&buf) {
779 Err(_) => return Err(DecodeError::InvalidValue),
784 impl Writeable for schnorr::Signature {
785 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
786 self.as_ref().write(w)
790 impl Readable for schnorr::Signature {
791 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
792 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
793 match schnorr::Signature::from_slice(&buf) {
795 Err(_) => return Err(DecodeError::InvalidValue),
800 impl Writeable for PaymentPreimage {
801 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
806 impl Readable for PaymentPreimage {
807 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
808 let buf: [u8; 32] = Readable::read(r)?;
809 Ok(PaymentPreimage(buf))
813 impl Writeable for PaymentHash {
814 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
819 impl Readable for PaymentHash {
820 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
821 let buf: [u8; 32] = Readable::read(r)?;
826 impl Writeable for PaymentSecret {
827 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
832 impl Readable for PaymentSecret {
833 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
834 let buf: [u8; 32] = Readable::read(r)?;
835 Ok(PaymentSecret(buf))
839 impl<T: Writeable> Writeable for Box<T> {
840 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
845 impl<T: Readable> Readable for Box<T> {
846 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
847 Ok(Box::new(Readable::read(r)?))
851 impl<T: Writeable> Writeable for Option<T> {
852 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
854 None => 0u8.write(w)?,
856 BigSize(data.serialized_length() as u64 + 1).write(w)?;
864 impl<T: Readable> Readable for Option<T>
866 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
867 let len: BigSize = Readable::read(r)?;
871 let mut reader = FixedLengthReader::new(r, len - 1);
872 Ok(Some(Readable::read(&mut reader)?))
878 impl Writeable for Txid {
879 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
880 w.write_all(&self[..])
884 impl Readable for Txid {
885 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
886 use bitcoin::hashes::Hash;
888 let buf: [u8; 32] = Readable::read(r)?;
889 Ok(Txid::from_slice(&buf[..]).unwrap())
893 impl Writeable for BlockHash {
894 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
895 w.write_all(&self[..])
899 impl Readable for BlockHash {
900 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
901 use bitcoin::hashes::Hash;
903 let buf: [u8; 32] = Readable::read(r)?;
904 Ok(BlockHash::from_slice(&buf[..]).unwrap())
908 impl Writeable for ChainHash {
909 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
910 w.write_all(self.as_bytes())
914 impl Readable for ChainHash {
915 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
916 let buf: [u8; 32] = Readable::read(r)?;
917 Ok(ChainHash::from(&buf[..]))
921 impl Writeable for OutPoint {
922 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
929 impl Readable for OutPoint {
930 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
931 let txid = Readable::read(r)?;
932 let vout = Readable::read(r)?;
940 macro_rules! impl_consensus_ser {
941 ($bitcoin_type: ty) => {
942 impl Writeable for $bitcoin_type {
943 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
944 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
951 impl Readable for $bitcoin_type {
952 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
953 match consensus::encode::Decodable::consensus_decode(r) {
955 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
956 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
957 Err(_) => Err(DecodeError::InvalidValue),
963 impl_consensus_ser!(Transaction);
964 impl_consensus_ser!(TxOut);
966 impl<T: Readable> Readable for Mutex<T> {
967 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
968 let t: T = Readable::read(r)?;
972 impl<T: Writeable> Writeable for Mutex<T> {
973 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
974 self.lock().unwrap().write(w)
978 impl<A: Readable, B: Readable> Readable for (A, B) {
979 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
980 let a: A = Readable::read(r)?;
981 let b: B = Readable::read(r)?;
985 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
986 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
992 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
993 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
994 let a: A = Readable::read(r)?;
995 let b: B = Readable::read(r)?;
996 let c: C = Readable::read(r)?;
1000 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1001 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1008 impl Writeable for () {
1009 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1013 impl Readable for () {
1014 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1019 impl Writeable for String {
1021 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1022 (self.len() as u16).write(w)?;
1023 w.write_all(self.as_bytes())
1026 impl Readable for String {
1028 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1029 let v: Vec<u8> = Readable::read(r)?;
1030 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1035 /// Represents a hostname for serialization purposes.
1036 /// Only the character set and length will be validated.
1037 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1038 /// Its length is guaranteed to be representable by a single byte.
1039 /// This serialization is used by BOLT 7 hostnames.
1040 #[derive(Clone, Debug, PartialEq, Eq)]
1041 pub struct Hostname(String);
1043 /// Returns the length of the hostname.
1044 pub fn len(&self) -> u8 {
1045 (&self.0).len() as u8
1048 impl Deref for Hostname {
1049 type Target = String;
1051 fn deref(&self) -> &Self::Target {
1055 impl From<Hostname> for String {
1056 fn from(hostname: Hostname) -> Self {
1060 impl TryFrom<Vec<u8>> for Hostname {
1063 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1064 if let Ok(s) = String::from_utf8(bytes) {
1065 Hostname::try_from(s)
1071 impl TryFrom<String> for Hostname {
1074 fn try_from(s: String) -> Result<Self, Self::Error> {
1075 if s.len() <= 255 && s.chars().all(|c|
1076 c.is_ascii_alphanumeric() ||
1086 impl Writeable for Hostname {
1088 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1089 self.len().write(w)?;
1090 w.write_all(self.as_bytes())
1093 impl Readable for Hostname {
1095 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1096 let len: u8 = Readable::read(r)?;
1097 let mut vec = Vec::with_capacity(len.into());
1098 vec.resize(len.into(), 0);
1099 r.read_exact(&mut vec)?;
1100 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1104 impl Writeable for Duration {
1106 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1107 self.as_secs().write(w)?;
1108 self.subsec_nanos().write(w)
1111 impl Readable for Duration {
1113 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1114 let secs = Readable::read(r)?;
1115 let nanos = Readable::read(r)?;
1116 Ok(Duration::new(secs, nanos))
1122 use core::convert::TryFrom;
1123 use crate::util::ser::{Readable, Hostname, Writeable};
1126 fn hostname_conversion() {
1127 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1129 assert!(Hostname::try_from(String::from("\"")).is_err());
1130 assert!(Hostname::try_from(String::from("$")).is_err());
1131 assert!(Hostname::try_from(String::from("⚡")).is_err());
1132 let mut large_vec = Vec::with_capacity(256);
1133 large_vec.resize(256, b'A');
1134 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1138 fn hostname_serialization() {
1139 let hostname = Hostname::try_from(String::from("test")).unwrap();
1140 let mut buf: Vec<u8> = Vec::new();
1141 hostname.write(&mut buf).unwrap();
1142 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");