1 //! A very simple serialization framework which is used to serialize/deserialize messages as well
2 //! as ChannelsManagers and ChannelMonitors.
4 use std::result::Result;
5 use std::io::{Read, Write};
6 use std::collections::HashMap;
11 use bitcoin::secp256k1::Signature;
12 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
13 use bitcoin::blockdata::script::Script;
14 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
15 use bitcoin::consensus;
16 use bitcoin::consensus::Encodable;
17 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
18 use bitcoin::hash_types::{Txid, BlockHash};
19 use std::marker::Sized;
20 use ln::msgs::DecodeError;
21 use ln::channelmanager::{PaymentPreimage, PaymentHash, PaymentSecret};
24 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};
26 const MAX_BUF_SIZE: usize = 64 * 1024;
28 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
29 /// buffers being written into.
30 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
33 /// Writes the given buf out. See std::io::Write::write_all for more
34 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
35 /// Hints that data of the given size is about the be written. This may not always be called
36 /// prior to data being written and may be safely ignored.
37 fn size_hint(&mut self, size: usize);
40 impl<W: Write> Writer for W {
42 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
43 <Self as ::std::io::Write>::write_all(self, buf)
46 fn size_hint(&mut self, _size: usize) { }
49 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
50 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
51 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
54 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
55 self.0.write_all(buf)?;
58 fn flush(&mut self) -> Result<(), ::std::io::Error> {
63 pub(crate) struct VecWriter(pub Vec<u8>);
64 impl Writer for VecWriter {
65 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
66 self.0.extend_from_slice(buf);
69 fn size_hint(&mut self, size: usize) {
70 self.0.reserve_exact(size);
74 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
75 /// of some data when serialized but don't yet need the full data.
76 pub(crate) struct LengthCalculatingWriter(pub usize);
77 impl Writer for LengthCalculatingWriter {
79 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
84 fn size_hint(&mut self, _size: usize) {}
87 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
88 /// forward to ensure we always consume exactly the fixed length specified.
89 pub(crate) struct FixedLengthReader<R: Read> {
94 impl<R: Read> FixedLengthReader<R> {
95 pub fn new(read: R, total_bytes: u64) -> Self {
96 Self { read, bytes_read: 0, total_bytes }
99 pub fn bytes_remain(&mut self) -> bool {
100 self.bytes_read != self.total_bytes
103 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
104 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
105 if self.bytes_read != self.total_bytes {
106 Err(DecodeError::ShortRead)
112 impl<R: Read> Read for FixedLengthReader<R> {
113 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
114 if self.total_bytes == self.bytes_read {
117 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
118 match self.read.read(&mut dest[0..(read_len as usize)]) {
120 self.bytes_read += v as u64;
129 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
130 /// between "EOF reached before we started" and "EOF reached mid-read".
131 pub(crate) struct ReadTrackingReader<R: Read> {
135 impl<R: Read> ReadTrackingReader<R> {
136 pub fn new(read: R) -> Self {
137 Self { read, have_read: false }
140 impl<R: Read> Read for ReadTrackingReader<R> {
141 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
142 match self.read.read(dest) {
145 self.have_read = true;
153 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
154 pub trait Writeable {
155 /// Writes self out to the given Writer
156 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
158 /// Writes self out to a Vec<u8>
159 fn encode(&self) -> Vec<u8> {
160 let mut msg = VecWriter(Vec::new());
161 self.write(&mut msg).unwrap();
165 /// Writes self out to a Vec<u8>
166 fn encode_with_len(&self) -> Vec<u8> {
167 let mut msg = VecWriter(Vec::new());
168 0u16.write(&mut msg).unwrap();
169 self.write(&mut msg).unwrap();
170 let len = msg.0.len();
171 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
176 impl<'a, T: Writeable> Writeable for &'a T {
177 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> { (*self).write(writer) }
180 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
184 /// Reads a Self in from the given Read
185 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
188 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
189 /// from a Read given some additional set of arguments which is required to deserialize.
190 pub trait ReadableArgs<P>
193 /// Reads a Self in from the given Read
194 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
197 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
198 pub trait MaybeReadable
201 /// Reads a Self in from the given Read
202 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
205 pub(crate) struct U48(pub u64);
206 impl Writeable for U48 {
208 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
209 writer.write_all(&be48_to_array(self.0))
212 impl Readable for U48 {
214 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
215 let mut buf = [0; 6];
216 reader.read_exact(&mut buf)?;
217 Ok(U48(slice_to_be48(&buf)))
221 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
222 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
224 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
225 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
226 /// you're looking for an example of a variable-length integer to use for your own project, move
227 /// along, this is a rather poor design.
228 pub(crate) struct BigSize(pub u64);
229 impl Writeable for BigSize {
231 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
234 (self.0 as u8).write(writer)
237 0xFDu8.write(writer)?;
238 (self.0 as u16).write(writer)
240 0x10000...0xFFFFFFFF => {
241 0xFEu8.write(writer)?;
242 (self.0 as u32).write(writer)
245 0xFFu8.write(writer)?;
246 (self.0 as u64).write(writer)
251 impl Readable for BigSize {
253 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
254 let n: u8 = Readable::read(reader)?;
257 let x: u64 = Readable::read(reader)?;
259 Err(DecodeError::InvalidValue)
265 let x: u32 = Readable::read(reader)?;
267 Err(DecodeError::InvalidValue)
269 Ok(BigSize(x as u64))
273 let x: u16 = Readable::read(reader)?;
275 Err(DecodeError::InvalidValue)
277 Ok(BigSize(x as u64))
280 n => Ok(BigSize(n as u64))
285 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
286 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
287 /// encapsulates such integers implementing Readable/Writeable for them.
288 #[cfg_attr(test, derive(PartialEq, Debug))]
289 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
291 macro_rules! impl_writeable_primitive {
292 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
293 impl Writeable for $val_type {
295 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
296 writer.write_all(&$meth_write(*self))
299 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
301 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
302 // Skip any full leading 0 bytes when writing (in BE):
303 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
306 impl Readable for $val_type {
308 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
309 let mut buf = [0; $len];
310 reader.read_exact(&mut buf)?;
314 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
316 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
317 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
318 // the high bytes being dropped. To do so, we start reading into the middle of buf
319 // and then convert the appropriate number of bytes with extra high bytes out of
321 let mut buf = [0; $len*2];
322 let mut read_len = reader.read(&mut buf[$len..])?;
323 let mut total_read_len = read_len;
324 while read_len != 0 && total_read_len != $len {
325 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
326 total_read_len += read_len;
328 if total_read_len == 0 || buf[$len] != 0 {
329 let first_byte = $len - ($len - total_read_len);
330 Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
332 // If the encoding had extra zero bytes, return a failure even though we know
333 // what they meant (as the TLV test vectors require this)
334 Err(DecodeError::InvalidValue)
341 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
342 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
343 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
345 impl Writeable for u8 {
347 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
348 writer.write_all(&[*self])
351 impl Readable for u8 {
353 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
354 let mut buf = [0; 1];
355 reader.read_exact(&mut buf)?;
360 impl Writeable for bool {
362 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
363 writer.write_all(&[if *self {1} else {0}])
366 impl Readable for bool {
368 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
369 let mut buf = [0; 1];
370 reader.read_exact(&mut buf)?;
371 if buf[0] != 0 && buf[0] != 1 {
372 return Err(DecodeError::InvalidValue);
379 macro_rules! impl_array {
381 impl Writeable for [u8; $size]
384 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
389 impl Readable for [u8; $size]
392 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
393 let mut buf = [0u8; $size];
394 r.read_exact(&mut buf)?;
401 //TODO: performance issue with [u8; size] with impl_array!()
402 impl_array!(3); // for rgb
403 impl_array!(4); // for IPv4
404 impl_array!(10); // for OnionV2
405 impl_array!(16); // for IPv6
406 impl_array!(32); // for channel id & hmac
407 impl_array!(33); // for PublicKey
408 impl_array!(64); // for Signature
409 impl_array!(1300); // for OnionPacket.hop_data
412 impl<K, V> Writeable for HashMap<K, V>
413 where K: Writeable + Eq + Hash,
417 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
418 (self.len() as u16).write(w)?;
419 for (key, value) in self.iter() {
427 impl<K, V> Readable for HashMap<K, V>
428 where K: Readable + Eq + Hash,
432 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
433 let len: u16 = Readable::read(r)?;
434 let mut ret = HashMap::with_capacity(len as usize);
436 ret.insert(K::read(r)?, V::read(r)?);
443 impl Writeable for Vec<u8> {
445 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
446 (self.len() as u16).write(w)?;
451 impl Readable for Vec<u8> {
453 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
454 let len: u16 = Readable::read(r)?;
455 let mut ret = Vec::with_capacity(len as usize);
456 ret.resize(len as usize, 0);
457 r.read_exact(&mut ret)?;
461 impl Writeable for Vec<Signature> {
463 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
464 (self.len() as u16).write(w)?;
465 for e in self.iter() {
472 impl Readable for Vec<Signature> {
474 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
475 let len: u16 = Readable::read(r)?;
476 let byte_size = (len as usize)
478 .ok_or(DecodeError::BadLengthDescriptor)?;
479 if byte_size > MAX_BUF_SIZE {
480 return Err(DecodeError::BadLengthDescriptor);
482 let mut ret = Vec::with_capacity(len as usize);
483 for _ in 0..len { ret.push(Signature::read(r)?); }
488 impl Writeable for Script {
489 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
490 (self.len() as u16).write(w)?;
491 w.write_all(self.as_bytes())
495 impl Readable for Script {
496 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
497 let len = <u16 as Readable>::read(r)? as usize;
498 let mut buf = vec![0; len];
499 r.read_exact(&mut buf)?;
500 Ok(Script::from(buf))
504 impl Writeable for PublicKey {
505 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
506 self.serialize().write(w)
510 impl Readable for PublicKey {
511 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
512 let buf: [u8; 33] = Readable::read(r)?;
513 match PublicKey::from_slice(&buf) {
515 Err(_) => return Err(DecodeError::InvalidValue),
520 impl Writeable for SecretKey {
521 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
522 let mut ser = [0; 32];
523 ser.copy_from_slice(&self[..]);
528 impl Readable for SecretKey {
529 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
530 let buf: [u8; 32] = Readable::read(r)?;
531 match SecretKey::from_slice(&buf) {
533 Err(_) => return Err(DecodeError::InvalidValue),
538 impl Writeable for Sha256dHash {
539 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
540 w.write_all(&self[..])
544 impl Readable for Sha256dHash {
545 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
546 use bitcoin::hashes::Hash;
548 let buf: [u8; 32] = Readable::read(r)?;
549 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
553 impl Writeable for Signature {
554 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
555 self.serialize_compact().write(w)
559 impl Readable for Signature {
560 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
561 let buf: [u8; 64] = Readable::read(r)?;
562 match Signature::from_compact(&buf) {
564 Err(_) => return Err(DecodeError::InvalidValue),
569 impl Writeable for PaymentPreimage {
570 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
575 impl Readable for PaymentPreimage {
576 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
577 let buf: [u8; 32] = Readable::read(r)?;
578 Ok(PaymentPreimage(buf))
582 impl Writeable for PaymentHash {
583 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
588 impl Readable for PaymentHash {
589 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
590 let buf: [u8; 32] = Readable::read(r)?;
595 impl Writeable for PaymentSecret {
596 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
601 impl Readable for PaymentSecret {
602 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
603 let buf: [u8; 32] = Readable::read(r)?;
604 Ok(PaymentSecret(buf))
608 impl<T: Writeable> Writeable for Option<T> {
609 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
611 None => 0u8.write(w)?,
613 let mut len_calc = LengthCalculatingWriter(0);
614 data.write(&mut len_calc).expect("No in-memory data may fail to serialize");
615 BigSize(len_calc.0 as u64 + 1).write(w)?;
623 impl<T: Readable> Readable for Option<T>
625 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
626 match BigSize::read(r)?.0 {
629 let mut reader = FixedLengthReader::new(r, len - 1);
630 Ok(Some(Readable::read(&mut reader)?))
636 impl Writeable for Txid {
637 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
638 w.write_all(&self[..])
642 impl Readable for Txid {
643 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
644 use bitcoin::hashes::Hash;
646 let buf: [u8; 32] = Readable::read(r)?;
647 Ok(Txid::from_slice(&buf[..]).unwrap())
651 impl Writeable for BlockHash {
652 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
653 w.write_all(&self[..])
657 impl Readable for BlockHash {
658 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
659 use bitcoin::hashes::Hash;
661 let buf: [u8; 32] = Readable::read(r)?;
662 Ok(BlockHash::from_slice(&buf[..]).unwrap())
666 impl Writeable for OutPoint {
667 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
674 impl Readable for OutPoint {
675 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
676 let txid = Readable::read(r)?;
677 let vout = Readable::read(r)?;
685 macro_rules! impl_consensus_ser {
686 ($bitcoin_type: ty) => {
687 impl Writeable for $bitcoin_type {
688 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
689 match self.consensus_encode(WriterWriteAdaptor(writer)) {
691 Err(consensus::encode::Error::Io(e)) => Err(e),
692 Err(_) => panic!("We shouldn't get a consensus::encode::Error unless our Write generated an std::io::Error"),
697 impl Readable for $bitcoin_type {
698 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
699 match consensus::encode::Decodable::consensus_decode(r) {
701 Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
702 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e)),
703 Err(_) => Err(DecodeError::InvalidValue),
709 impl_consensus_ser!(Transaction);
710 impl_consensus_ser!(TxOut);
712 impl<T: Readable> Readable for Mutex<T> {
713 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
714 let t: T = Readable::read(r)?;
718 impl<T: Writeable> Writeable for Mutex<T> {
719 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
720 self.lock().unwrap().write(w)
724 impl<A: Readable, B: Readable> Readable for (A, B) {
725 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
726 let a: A = Readable::read(r)?;
727 let b: B = Readable::read(r)?;
731 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
732 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {