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.
14 use std::io::{Read, Write};
15 use std::collections::HashMap;
20 use bitcoin::secp256k1::Signature;
21 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
22 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, COMPACT_SIGNATURE_SIZE};
23 use bitcoin::blockdata::script::Script;
24 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
25 use bitcoin::consensus;
26 use bitcoin::consensus::Encodable;
27 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
28 use bitcoin::hash_types::{Txid, BlockHash};
29 use core::marker::Sized;
30 use ln::msgs::DecodeError;
31 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
34 use util::byte_utils::{be64_to_array, be48_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be48, slice_to_be64};
36 /// serialization buffer size
37 pub const MAX_BUF_SIZE: usize = 64 * 1024;
39 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
40 /// buffers being written into.
41 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
44 /// (C-not exported) as we only export serialization to/from byte arrays instead
46 /// Writes the given buf out. See std::io::Write::write_all for more
47 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
48 /// Hints that data of the given size is about the be written. This may not always be called
49 /// prior to data being written and may be safely ignored.
50 fn size_hint(&mut self, size: usize);
53 impl<W: Write> Writer for W {
55 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
56 <Self as ::std::io::Write>::write_all(self, buf)
59 fn size_hint(&mut self, _size: usize) { }
62 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
63 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
64 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
67 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
68 self.0.write_all(buf)?;
71 fn flush(&mut self) -> Result<(), ::std::io::Error> {
76 pub(crate) struct VecWriter(pub Vec<u8>);
77 impl Writer for VecWriter {
78 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
79 self.0.extend_from_slice(buf);
82 fn size_hint(&mut self, size: usize) {
83 self.0.reserve_exact(size);
87 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
88 /// of some data when serialized but don't yet need the full data.
89 pub(crate) struct LengthCalculatingWriter(pub usize);
90 impl Writer for LengthCalculatingWriter {
92 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
97 fn size_hint(&mut self, _size: usize) {}
100 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
101 /// forward to ensure we always consume exactly the fixed length specified.
102 pub(crate) struct FixedLengthReader<R: Read> {
107 impl<R: Read> FixedLengthReader<R> {
108 pub fn new(read: R, total_bytes: u64) -> Self {
109 Self { read, bytes_read: 0, total_bytes }
112 pub fn bytes_remain(&mut self) -> bool {
113 self.bytes_read != self.total_bytes
116 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
117 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
118 if self.bytes_read != self.total_bytes {
119 Err(DecodeError::ShortRead)
125 impl<R: Read> Read for FixedLengthReader<R> {
126 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
127 if self.total_bytes == self.bytes_read {
130 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
131 match self.read.read(&mut dest[0..(read_len as usize)]) {
133 self.bytes_read += v as u64;
142 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
143 /// between "EOF reached before we started" and "EOF reached mid-read".
144 pub(crate) struct ReadTrackingReader<R: Read> {
148 impl<R: Read> ReadTrackingReader<R> {
149 pub fn new(read: R) -> Self {
150 Self { read, have_read: false }
153 impl<R: Read> Read for ReadTrackingReader<R> {
154 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
155 match self.read.read(dest) {
158 self.have_read = true;
166 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
168 /// (C-not exported) as we only export serialization to/from byte arrays instead
169 pub trait Writeable {
170 /// Writes self out to the given Writer
171 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
173 /// Writes self out to a Vec<u8>
174 fn encode(&self) -> Vec<u8> {
175 let mut msg = VecWriter(Vec::new());
176 self.write(&mut msg).unwrap();
180 /// Writes self out to a Vec<u8>
181 fn encode_with_len(&self) -> Vec<u8> {
182 let mut msg = VecWriter(Vec::new());
183 0u16.write(&mut msg).unwrap();
184 self.write(&mut msg).unwrap();
185 let len = msg.0.len();
186 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
191 impl<'a, T: Writeable> Writeable for &'a T {
192 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> { (*self).write(writer) }
195 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
197 /// (C-not exported) as we only export serialization to/from byte arrays instead
201 /// Reads a Self in from the given Read
202 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
205 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
206 /// from a Read given some additional set of arguments which is required to deserialize.
208 /// (C-not exported) as we only export serialization to/from byte arrays instead
209 pub trait ReadableArgs<P>
212 /// Reads a Self in from the given Read
213 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
216 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
218 /// (C-not exported) as we only export serialization to/from byte arrays instead
219 pub trait MaybeReadable
222 /// Reads a Self in from the given Read
223 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
226 pub(crate) struct U48(pub u64);
227 impl Writeable for U48 {
229 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
230 writer.write_all(&be48_to_array(self.0))
233 impl Readable for U48 {
235 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
236 let mut buf = [0; 6];
237 reader.read_exact(&mut buf)?;
238 Ok(U48(slice_to_be48(&buf)))
242 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
243 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
245 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
246 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
247 /// you're looking for an example of a variable-length integer to use for your own project, move
248 /// along, this is a rather poor design.
249 pub(crate) struct BigSize(pub u64);
250 impl Writeable for BigSize {
252 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
255 (self.0 as u8).write(writer)
258 0xFDu8.write(writer)?;
259 (self.0 as u16).write(writer)
261 0x10000...0xFFFFFFFF => {
262 0xFEu8.write(writer)?;
263 (self.0 as u32).write(writer)
266 0xFFu8.write(writer)?;
267 (self.0 as u64).write(writer)
272 impl Readable for BigSize {
274 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
275 let n: u8 = Readable::read(reader)?;
278 let x: u64 = Readable::read(reader)?;
280 Err(DecodeError::InvalidValue)
286 let x: u32 = Readable::read(reader)?;
288 Err(DecodeError::InvalidValue)
290 Ok(BigSize(x as u64))
294 let x: u16 = Readable::read(reader)?;
296 Err(DecodeError::InvalidValue)
298 Ok(BigSize(x as u64))
301 n => Ok(BigSize(n as u64))
306 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
307 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
308 /// encapsulates such integers implementing Readable/Writeable for them.
309 #[cfg_attr(test, derive(PartialEq, Debug))]
310 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
312 macro_rules! impl_writeable_primitive {
313 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
314 impl Writeable for $val_type {
316 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
317 writer.write_all(&$meth_write(*self))
320 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
322 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
323 // Skip any full leading 0 bytes when writing (in BE):
324 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
327 impl Readable for $val_type {
329 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
330 let mut buf = [0; $len];
331 reader.read_exact(&mut buf)?;
335 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
337 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
338 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
339 // the high bytes being dropped. To do so, we start reading into the middle of buf
340 // and then convert the appropriate number of bytes with extra high bytes out of
342 let mut buf = [0; $len*2];
343 let mut read_len = reader.read(&mut buf[$len..])?;
344 let mut total_read_len = read_len;
345 while read_len != 0 && total_read_len != $len {
346 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
347 total_read_len += read_len;
349 if total_read_len == 0 || buf[$len] != 0 {
350 let first_byte = $len - ($len - total_read_len);
351 Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
353 // If the encoding had extra zero bytes, return a failure even though we know
354 // what they meant (as the TLV test vectors require this)
355 Err(DecodeError::InvalidValue)
362 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
363 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
364 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
366 impl Writeable for u8 {
368 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
369 writer.write_all(&[*self])
372 impl Readable for u8 {
374 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
375 let mut buf = [0; 1];
376 reader.read_exact(&mut buf)?;
381 impl Writeable for bool {
383 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
384 writer.write_all(&[if *self {1} else {0}])
387 impl Readable for bool {
389 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
390 let mut buf = [0; 1];
391 reader.read_exact(&mut buf)?;
392 if buf[0] != 0 && buf[0] != 1 {
393 return Err(DecodeError::InvalidValue);
400 macro_rules! impl_array {
402 impl Writeable for [u8; $size]
405 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
410 impl Readable for [u8; $size]
413 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
414 let mut buf = [0u8; $size];
415 r.read_exact(&mut buf)?;
422 //TODO: performance issue with [u8; size] with impl_array!()
423 impl_array!(3); // for rgb
424 impl_array!(4); // for IPv4
425 impl_array!(10); // for OnionV2
426 impl_array!(16); // for IPv6
427 impl_array!(32); // for channel id & hmac
428 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
429 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
430 impl_array!(1300); // for OnionPacket.hop_data
433 impl<K, V> Writeable for HashMap<K, V>
434 where K: Writeable + Eq + Hash,
438 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
439 (self.len() as u16).write(w)?;
440 for (key, value) in self.iter() {
448 impl<K, V> Readable for HashMap<K, V>
449 where K: Readable + Eq + Hash,
453 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
454 let len: u16 = Readable::read(r)?;
455 let mut ret = HashMap::with_capacity(len as usize);
457 ret.insert(K::read(r)?, V::read(r)?);
464 impl Writeable for Vec<u8> {
466 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
467 (self.len() as u16).write(w)?;
472 impl Readable for Vec<u8> {
474 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
475 let len: u16 = Readable::read(r)?;
476 let mut ret = Vec::with_capacity(len as usize);
477 ret.resize(len as usize, 0);
478 r.read_exact(&mut ret)?;
482 impl Writeable for Vec<Signature> {
484 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
485 (self.len() as u16).write(w)?;
486 for e in self.iter() {
493 impl Readable for Vec<Signature> {
495 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
496 let len: u16 = Readable::read(r)?;
497 let byte_size = (len as usize)
498 .checked_mul(COMPACT_SIGNATURE_SIZE)
499 .ok_or(DecodeError::BadLengthDescriptor)?;
500 if byte_size > MAX_BUF_SIZE {
501 return Err(DecodeError::BadLengthDescriptor);
503 let mut ret = Vec::with_capacity(len as usize);
504 for _ in 0..len { ret.push(Signature::read(r)?); }
509 impl Writeable for Script {
510 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
511 (self.len() as u16).write(w)?;
512 w.write_all(self.as_bytes())
516 impl Readable for Script {
517 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
518 let len = <u16 as Readable>::read(r)? as usize;
519 let mut buf = vec![0; len];
520 r.read_exact(&mut buf)?;
521 Ok(Script::from(buf))
525 impl Writeable for PublicKey {
526 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
527 self.serialize().write(w)
531 impl Readable for PublicKey {
532 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
533 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
534 match PublicKey::from_slice(&buf) {
536 Err(_) => return Err(DecodeError::InvalidValue),
541 impl Writeable for SecretKey {
542 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
543 let mut ser = [0; 32];
544 ser.copy_from_slice(&self[..]);
549 impl Readable for SecretKey {
550 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
551 let buf: [u8; 32] = Readable::read(r)?;
552 match SecretKey::from_slice(&buf) {
554 Err(_) => return Err(DecodeError::InvalidValue),
559 impl Writeable for Sha256dHash {
560 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
561 w.write_all(&self[..])
565 impl Readable for Sha256dHash {
566 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
567 use bitcoin::hashes::Hash;
569 let buf: [u8; 32] = Readable::read(r)?;
570 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
574 impl Writeable for Signature {
575 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
576 self.serialize_compact().write(w)
580 impl Readable for Signature {
581 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
582 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
583 match Signature::from_compact(&buf) {
585 Err(_) => return Err(DecodeError::InvalidValue),
590 impl Writeable for PaymentPreimage {
591 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
596 impl Readable for PaymentPreimage {
597 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
598 let buf: [u8; 32] = Readable::read(r)?;
599 Ok(PaymentPreimage(buf))
603 impl Writeable for PaymentHash {
604 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
609 impl Readable for PaymentHash {
610 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
611 let buf: [u8; 32] = Readable::read(r)?;
616 impl Writeable for PaymentSecret {
617 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
622 impl Readable for PaymentSecret {
623 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
624 let buf: [u8; 32] = Readable::read(r)?;
625 Ok(PaymentSecret(buf))
629 impl<T: Writeable> Writeable for Option<T> {
630 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
632 None => 0u8.write(w)?,
634 let mut len_calc = LengthCalculatingWriter(0);
635 data.write(&mut len_calc).expect("No in-memory data may fail to serialize");
636 BigSize(len_calc.0 as u64 + 1).write(w)?;
644 impl<T: Readable> Readable for Option<T>
646 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
647 match BigSize::read(r)?.0 {
650 let mut reader = FixedLengthReader::new(r, len - 1);
651 Ok(Some(Readable::read(&mut reader)?))
657 impl Writeable for Txid {
658 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
659 w.write_all(&self[..])
663 impl Readable for Txid {
664 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
665 use bitcoin::hashes::Hash;
667 let buf: [u8; 32] = Readable::read(r)?;
668 Ok(Txid::from_slice(&buf[..]).unwrap())
672 impl Writeable for BlockHash {
673 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
674 w.write_all(&self[..])
678 impl Readable for BlockHash {
679 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
680 use bitcoin::hashes::Hash;
682 let buf: [u8; 32] = Readable::read(r)?;
683 Ok(BlockHash::from_slice(&buf[..]).unwrap())
687 impl Writeable for OutPoint {
688 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
695 impl Readable for OutPoint {
696 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
697 let txid = Readable::read(r)?;
698 let vout = Readable::read(r)?;
706 macro_rules! impl_consensus_ser {
707 ($bitcoin_type: ty) => {
708 impl Writeable for $bitcoin_type {
709 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
710 match self.consensus_encode(WriterWriteAdaptor(writer)) {
717 impl Readable for $bitcoin_type {
718 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
719 match consensus::encode::Decodable::consensus_decode(r) {
721 Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
722 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
723 Err(_) => Err(DecodeError::InvalidValue),
729 impl_consensus_ser!(Transaction);
730 impl_consensus_ser!(TxOut);
732 impl<T: Readable> Readable for Mutex<T> {
733 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
734 let t: T = Readable::read(r)?;
738 impl<T: Writeable> Writeable for Mutex<T> {
739 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
740 self.lock().unwrap().write(w)
744 impl<A: Readable, B: Readable> Readable for (A, B) {
745 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
746 let a: A = Readable::read(r)?;
747 let b: B = Readable::read(r)?;
751 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
752 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {