Add key_storage selection in ChannelMonitor insert_combine
[rust-lightning] / src / util / ser.rs
index 2dea21ef175a96a7a58008cc14c950bd85c58d33..84cfa8d1633f98e78a996792d53c146d981be61a 100644 (file)
@@ -1,16 +1,20 @@
+//! A very simple serialization framework which is used to serialize/deserialize messages as well
+//! as ChannelsManagers and ChannelMonitors.
+
 use std::result::Result;
-use std::io::Read;
+use std::io::{Read, Write};
 use std::collections::HashMap;
 use std::hash::Hash;
 
 use secp256k1::{Secp256k1, Signature};
-use secp256k1::key::PublicKey;
+use secp256k1::key::{PublicKey, SecretKey};
 use bitcoin::util::hash::Sha256dHash;
 use bitcoin::blockdata::script::Script;
 use std::marker::Sized;
 use ln::msgs::DecodeError;
+use util::byte_utils;
 
-use util::byte_utils::{be64_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be64};
+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};
 
 const MAX_BUF_SIZE: usize = 64 * 1024;
 
@@ -26,7 +30,7 @@ pub trait Writer {
        fn size_hint(&mut self, size: usize);
 }
 
-impl<W: ::std::io::Write> Writer for W {
+impl<W: Write> Writer for W {
        #[inline]
        fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
                <Self as ::std::io::Write>::write_all(self, buf)
@@ -35,10 +39,52 @@ impl<W: ::std::io::Write> Writer for W {
        fn size_hint(&mut self, _size: usize) { }
 }
 
+pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
+impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
+       fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
+               self.0.write_all(buf)
+       }
+       fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
+               self.0.write_all(buf)?;
+               Ok(buf.len())
+       }
+       fn flush(&mut self) -> Result<(), ::std::io::Error> {
+               Ok(())
+       }
+}
+
+struct VecWriter(Vec<u8>);
+impl Writer for VecWriter {
+       fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
+               self.0.extend_from_slice(buf);
+               Ok(())
+       }
+       fn size_hint(&mut self, size: usize) {
+               self.0.reserve_exact(size);
+       }
+}
+
 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
 pub trait Writeable {
        /// Writes self out to the given Writer
        fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
+
+       /// Writes self out to a Vec<u8>
+       fn encode(&self) -> Vec<u8> {
+               let mut msg = VecWriter(Vec::new());
+               self.write(&mut msg).unwrap();
+               msg.0
+       }
+
+       /// Writes self out to a Vec<u8>
+       fn encode_with_len(&self) -> Vec<u8> {
+               let mut msg = VecWriter(Vec::new());
+               0u16.write(&mut msg).unwrap();
+               self.write(&mut msg).unwrap();
+               let len = msg.0.len();
+               msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
+               msg.0
+       }
 }
 
 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
@@ -50,6 +96,32 @@ pub trait Readable<R>
        fn read(reader: &mut R) -> Result<Self, DecodeError>;
 }
 
+/// A trait that various higher-level rust-lightning types implement allowing them to be read in
+/// from a Read given some additional set of arguments which is required to deserialize.
+pub trait ReadableArgs<R, P>
+       where Self: Sized,
+             R: Read
+{
+       /// Reads a Self in from the given Read
+       fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
+}
+
+pub(crate) struct U48(pub u64);
+impl Writeable for U48 {
+       #[inline]
+       fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
+               writer.write_all(&be48_to_array(self.0))
+       }
+}
+impl<R: Read> Readable<R> for U48 {
+       #[inline]
+       fn read(reader: &mut R) -> Result<U48, DecodeError> {
+               let mut buf = [0; 6];
+               reader.read_exact(&mut buf)?;
+               Ok(U48(slice_to_be48(&buf)))
+       }
+}
+
 macro_rules! impl_writeable_primitive {
        ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
                impl Writeable for $val_type {
@@ -263,7 +335,25 @@ impl<R: Read> Readable<R> for PublicKey {
                let buf: [u8; 33] = Readable::read(r)?;
                match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
                        Ok(key) => Ok(key),
-                       Err(_) => return Err(DecodeError::BadPublicKey),
+                       Err(_) => return Err(DecodeError::InvalidValue),
+               }
+       }
+}
+
+impl Writeable for SecretKey {
+       fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
+               let mut ser = [0; 32];
+               ser.copy_from_slice(&self[..]);
+               ser.write(w)
+       }
+}
+
+impl<R: Read> Readable<R> for SecretKey {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
+               let buf: [u8; 32] = Readable::read(r)?;
+               match SecretKey::from_slice(&Secp256k1::without_caps(), &buf) {
+                       Ok(key) => Ok(key),
+                       Err(_) => return Err(DecodeError::InvalidValue),
                }
        }
 }
@@ -292,7 +382,7 @@ impl<R: Read> Readable<R> for Signature {
                let buf: [u8; 64] = Readable::read(r)?;
                match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
                        Ok(sig) => Ok(sig),
-                       Err(_) => return Err(DecodeError::BadSignature),
+                       Err(_) => return Err(DecodeError::InvalidValue),
                }
        }
 }