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 std::io::{Read, Write};
14 use std::collections::HashMap;
19 use bitcoin::secp256k1::Signature;
20 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
21 use bitcoin::blockdata::script::Script;
22 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
23 use bitcoin::consensus;
24 use bitcoin::consensus::Encodable;
25 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
26 use bitcoin::hash_types::{Txid, BlockHash};
27 use std::marker::Sized;
28 use ln::msgs::DecodeError;
29 use ln::channelmanager::{PaymentPreimage, PaymentHash, PaymentSecret};
32 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};
34 const MAX_BUF_SIZE: usize = 64 * 1024;
36 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
37 /// buffers being written into.
38 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
41 /// Writes the given buf out. See std::io::Write::write_all for more
42 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
43 /// Hints that data of the given size is about the be written. This may not always be called
44 /// prior to data being written and may be safely ignored.
45 fn size_hint(&mut self, size: usize);
48 impl<W: Write> Writer for W {
50 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
51 <Self as ::std::io::Write>::write_all(self, buf)
54 fn size_hint(&mut self, _size: usize) { }
57 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
58 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
59 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
62 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
63 self.0.write_all(buf)?;
66 fn flush(&mut self) -> Result<(), ::std::io::Error> {
71 pub(crate) struct VecWriter(pub Vec<u8>);
72 impl Writer for VecWriter {
73 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
74 self.0.extend_from_slice(buf);
77 fn size_hint(&mut self, size: usize) {
78 self.0.reserve_exact(size);
82 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
83 /// of some data when serialized but don't yet need the full data.
84 pub(crate) struct LengthCalculatingWriter(pub usize);
85 impl Writer for LengthCalculatingWriter {
87 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
92 fn size_hint(&mut self, _size: usize) {}
95 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
96 /// forward to ensure we always consume exactly the fixed length specified.
97 pub(crate) struct FixedLengthReader<R: Read> {
102 impl<R: Read> FixedLengthReader<R> {
103 pub fn new(read: R, total_bytes: u64) -> Self {
104 Self { read, bytes_read: 0, total_bytes }
107 pub fn bytes_remain(&mut self) -> bool {
108 self.bytes_read != self.total_bytes
111 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
112 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
113 if self.bytes_read != self.total_bytes {
114 Err(DecodeError::ShortRead)
120 impl<R: Read> Read for FixedLengthReader<R> {
121 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
122 if self.total_bytes == self.bytes_read {
125 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
126 match self.read.read(&mut dest[0..(read_len as usize)]) {
128 self.bytes_read += v as u64;
137 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
138 /// between "EOF reached before we started" and "EOF reached mid-read".
139 pub(crate) struct ReadTrackingReader<R: Read> {
143 impl<R: Read> ReadTrackingReader<R> {
144 pub fn new(read: R) -> Self {
145 Self { read, have_read: false }
148 impl<R: Read> Read for ReadTrackingReader<R> {
149 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
150 match self.read.read(dest) {
153 self.have_read = true;
161 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
162 pub trait Writeable {
163 /// Writes self out to the given Writer
164 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
166 /// Writes self out to a Vec<u8>
167 fn encode(&self) -> Vec<u8> {
168 let mut msg = VecWriter(Vec::new());
169 self.write(&mut msg).unwrap();
173 /// Writes self out to a Vec<u8>
174 fn encode_with_len(&self) -> Vec<u8> {
175 let mut msg = VecWriter(Vec::new());
176 0u16.write(&mut msg).unwrap();
177 self.write(&mut msg).unwrap();
178 let len = msg.0.len();
179 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
184 impl<'a, T: Writeable> Writeable for &'a T {
185 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> { (*self).write(writer) }
188 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
192 /// Reads a Self in from the given Read
193 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
196 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
197 /// from a Read given some additional set of arguments which is required to deserialize.
198 pub trait ReadableArgs<P>
201 /// Reads a Self in from the given Read
202 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
205 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
206 pub trait MaybeReadable
209 /// Reads a Self in from the given Read
210 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
213 pub(crate) struct U48(pub u64);
214 impl Writeable for U48 {
216 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
217 writer.write_all(&be48_to_array(self.0))
220 impl Readable for U48 {
222 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
223 let mut buf = [0; 6];
224 reader.read_exact(&mut buf)?;
225 Ok(U48(slice_to_be48(&buf)))
229 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
230 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
232 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
233 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
234 /// you're looking for an example of a variable-length integer to use for your own project, move
235 /// along, this is a rather poor design.
236 pub(crate) struct BigSize(pub u64);
237 impl Writeable for BigSize {
239 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
242 (self.0 as u8).write(writer)
245 0xFDu8.write(writer)?;
246 (self.0 as u16).write(writer)
248 0x10000...0xFFFFFFFF => {
249 0xFEu8.write(writer)?;
250 (self.0 as u32).write(writer)
253 0xFFu8.write(writer)?;
254 (self.0 as u64).write(writer)
259 impl Readable for BigSize {
261 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
262 let n: u8 = Readable::read(reader)?;
265 let x: u64 = Readable::read(reader)?;
267 Err(DecodeError::InvalidValue)
273 let x: u32 = Readable::read(reader)?;
275 Err(DecodeError::InvalidValue)
277 Ok(BigSize(x as u64))
281 let x: u16 = Readable::read(reader)?;
283 Err(DecodeError::InvalidValue)
285 Ok(BigSize(x as u64))
288 n => Ok(BigSize(n as u64))
293 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
294 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
295 /// encapsulates such integers implementing Readable/Writeable for them.
296 #[cfg_attr(test, derive(PartialEq, Debug))]
297 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
299 macro_rules! impl_writeable_primitive {
300 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
301 impl Writeable for $val_type {
303 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
304 writer.write_all(&$meth_write(*self))
307 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
309 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
310 // Skip any full leading 0 bytes when writing (in BE):
311 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
314 impl Readable for $val_type {
316 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
317 let mut buf = [0; $len];
318 reader.read_exact(&mut buf)?;
322 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
324 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
325 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
326 // the high bytes being dropped. To do so, we start reading into the middle of buf
327 // and then convert the appropriate number of bytes with extra high bytes out of
329 let mut buf = [0; $len*2];
330 let mut read_len = reader.read(&mut buf[$len..])?;
331 let mut total_read_len = read_len;
332 while read_len != 0 && total_read_len != $len {
333 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
334 total_read_len += read_len;
336 if total_read_len == 0 || buf[$len] != 0 {
337 let first_byte = $len - ($len - total_read_len);
338 Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
340 // If the encoding had extra zero bytes, return a failure even though we know
341 // what they meant (as the TLV test vectors require this)
342 Err(DecodeError::InvalidValue)
349 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
350 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
351 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
353 impl Writeable for u8 {
355 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
356 writer.write_all(&[*self])
359 impl Readable for u8 {
361 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
362 let mut buf = [0; 1];
363 reader.read_exact(&mut buf)?;
368 impl Writeable for bool {
370 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
371 writer.write_all(&[if *self {1} else {0}])
374 impl Readable for bool {
376 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
377 let mut buf = [0; 1];
378 reader.read_exact(&mut buf)?;
379 if buf[0] != 0 && buf[0] != 1 {
380 return Err(DecodeError::InvalidValue);
387 macro_rules! impl_array {
389 impl Writeable for [u8; $size]
392 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
397 impl Readable for [u8; $size]
400 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
401 let mut buf = [0u8; $size];
402 r.read_exact(&mut buf)?;
409 //TODO: performance issue with [u8; size] with impl_array!()
410 impl_array!(3); // for rgb
411 impl_array!(4); // for IPv4
412 impl_array!(10); // for OnionV2
413 impl_array!(16); // for IPv6
414 impl_array!(32); // for channel id & hmac
415 impl_array!(33); // for PublicKey
416 impl_array!(64); // for Signature
417 impl_array!(1300); // for OnionPacket.hop_data
420 impl<K, V> Writeable for HashMap<K, V>
421 where K: Writeable + Eq + Hash,
425 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
426 (self.len() as u16).write(w)?;
427 for (key, value) in self.iter() {
435 impl<K, V> Readable for HashMap<K, V>
436 where K: Readable + Eq + Hash,
440 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
441 let len: u16 = Readable::read(r)?;
442 let mut ret = HashMap::with_capacity(len as usize);
444 ret.insert(K::read(r)?, V::read(r)?);
451 impl Writeable for Vec<u8> {
453 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
454 (self.len() as u16).write(w)?;
459 impl Readable for Vec<u8> {
461 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
462 let len: u16 = Readable::read(r)?;
463 let mut ret = Vec::with_capacity(len as usize);
464 ret.resize(len as usize, 0);
465 r.read_exact(&mut ret)?;
469 impl Writeable for Vec<Signature> {
471 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
472 (self.len() as u16).write(w)?;
473 for e in self.iter() {
480 impl Readable for Vec<Signature> {
482 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
483 let len: u16 = Readable::read(r)?;
484 let byte_size = (len as usize)
486 .ok_or(DecodeError::BadLengthDescriptor)?;
487 if byte_size > MAX_BUF_SIZE {
488 return Err(DecodeError::BadLengthDescriptor);
490 let mut ret = Vec::with_capacity(len as usize);
491 for _ in 0..len { ret.push(Signature::read(r)?); }
496 impl Writeable for Script {
497 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
498 (self.len() as u16).write(w)?;
499 w.write_all(self.as_bytes())
503 impl Readable for Script {
504 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
505 let len = <u16 as Readable>::read(r)? as usize;
506 let mut buf = vec![0; len];
507 r.read_exact(&mut buf)?;
508 Ok(Script::from(buf))
512 impl Writeable for PublicKey {
513 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
514 self.serialize().write(w)
518 impl Readable for PublicKey {
519 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
520 let buf: [u8; 33] = Readable::read(r)?;
521 match PublicKey::from_slice(&buf) {
523 Err(_) => return Err(DecodeError::InvalidValue),
528 impl Writeable for SecretKey {
529 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
530 let mut ser = [0; 32];
531 ser.copy_from_slice(&self[..]);
536 impl Readable for SecretKey {
537 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
538 let buf: [u8; 32] = Readable::read(r)?;
539 match SecretKey::from_slice(&buf) {
541 Err(_) => return Err(DecodeError::InvalidValue),
546 impl Writeable for Sha256dHash {
547 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
548 w.write_all(&self[..])
552 impl Readable for Sha256dHash {
553 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
554 use bitcoin::hashes::Hash;
556 let buf: [u8; 32] = Readable::read(r)?;
557 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
561 impl Writeable for Signature {
562 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
563 self.serialize_compact().write(w)
567 impl Readable for Signature {
568 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
569 let buf: [u8; 64] = Readable::read(r)?;
570 match Signature::from_compact(&buf) {
572 Err(_) => return Err(DecodeError::InvalidValue),
577 impl Writeable for PaymentPreimage {
578 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
583 impl Readable for PaymentPreimage {
584 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
585 let buf: [u8; 32] = Readable::read(r)?;
586 Ok(PaymentPreimage(buf))
590 impl Writeable for PaymentHash {
591 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
596 impl Readable for PaymentHash {
597 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
598 let buf: [u8; 32] = Readable::read(r)?;
603 impl Writeable for PaymentSecret {
604 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
609 impl Readable for PaymentSecret {
610 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
611 let buf: [u8; 32] = Readable::read(r)?;
612 Ok(PaymentSecret(buf))
616 impl<T: Writeable> Writeable for Option<T> {
617 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
619 None => 0u8.write(w)?,
621 let mut len_calc = LengthCalculatingWriter(0);
622 data.write(&mut len_calc).expect("No in-memory data may fail to serialize");
623 BigSize(len_calc.0 as u64 + 1).write(w)?;
631 impl<T: Readable> Readable for Option<T>
633 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
634 match BigSize::read(r)?.0 {
637 let mut reader = FixedLengthReader::new(r, len - 1);
638 Ok(Some(Readable::read(&mut reader)?))
644 impl Writeable for Txid {
645 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
646 w.write_all(&self[..])
650 impl Readable for Txid {
651 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
652 use bitcoin::hashes::Hash;
654 let buf: [u8; 32] = Readable::read(r)?;
655 Ok(Txid::from_slice(&buf[..]).unwrap())
659 impl Writeable for BlockHash {
660 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
661 w.write_all(&self[..])
665 impl Readable for BlockHash {
666 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
667 use bitcoin::hashes::Hash;
669 let buf: [u8; 32] = Readable::read(r)?;
670 Ok(BlockHash::from_slice(&buf[..]).unwrap())
674 impl Writeable for OutPoint {
675 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
682 impl Readable for OutPoint {
683 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
684 let txid = Readable::read(r)?;
685 let vout = Readable::read(r)?;
693 macro_rules! impl_consensus_ser {
694 ($bitcoin_type: ty) => {
695 impl Writeable for $bitcoin_type {
696 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
697 match self.consensus_encode(WriterWriteAdaptor(writer)) {
699 Err(consensus::encode::Error::Io(e)) => Err(e),
700 Err(_) => panic!("We shouldn't get a consensus::encode::Error unless our Write generated an std::io::Error"),
705 impl Readable for $bitcoin_type {
706 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
707 match consensus::encode::Decodable::consensus_decode(r) {
709 Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
710 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e)),
711 Err(_) => Err(DecodeError::InvalidValue),
717 impl_consensus_ser!(Transaction);
718 impl_consensus_ser!(TxOut);
720 impl<T: Readable> Readable for Mutex<T> {
721 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
722 let t: T = Readable::read(r)?;
726 impl<T: Writeable> Writeable for Mutex<T> {
727 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
728 self.lock().unwrap().write(w)
732 impl<A: Readable, B: Readable> Readable for (A, B) {
733 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
734 let a: A = Readable::read(r)?;
735 let b: B = Readable::read(r)?;
739 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
740 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {