Merge pull request #1273 from jkczyz/2022-01-invoice-expiry
[rust-lightning] / lightning / src / util / ser.rs
index c06293269ec0ffc28727a3d2624e92a9f95d1319..6a52e5e1c898230c0d31a4cb9ce20c6acc236076 100644 (file)
@@ -27,6 +27,7 @@ use bitcoin::consensus::Encodable;
 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
 use bitcoin::hash_types::{Txid, BlockHash};
 use core::marker::Sized;
+use core::time::Duration;
 use ln::msgs::DecodeError;
 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
 
@@ -474,10 +475,9 @@ macro_rules! impl_array {
        );
 }
 
-//TODO: performance issue with [u8; size] with impl_array!()
 impl_array!(3); // for rgb
 impl_array!(4); // for IPv4
-impl_array!(10); // for OnionV2
+impl_array!(12); // for OnionV2
 impl_array!(16); // for IPv6
 impl_array!(32); // for channel id & hmac
 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
@@ -502,14 +502,20 @@ impl<K, V> Writeable for HashMap<K, V>
 
 impl<K, V> Readable for HashMap<K, V>
        where K: Readable + Eq + Hash,
-             V: Readable
+             V: MaybeReadable
 {
        #[inline]
        fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
                let len: u16 = Readable::read(r)?;
                let mut ret = HashMap::with_capacity(len as usize);
                for _ in 0..len {
-                       ret.insert(K::read(r)?, V::read(r)?);
+                       let k = K::read(r)?;
+                       let v_opt = V::read(r)?;
+                       if let Some(v) = v_opt {
+                               if ret.insert(k, v).is_some() {
+                                       return Err(DecodeError::InvalidValue);
+                               }
+                       }
                }
                Ok(ret)
        }
@@ -879,6 +885,11 @@ impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
        }
 }
 
+impl Writeable for () {
+       fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
+               Ok(())
+       }
+}
 impl Readable for () {
        fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
                Ok(())
@@ -892,7 +903,6 @@ impl Writeable for String {
                w.write_all(self.as_bytes())
        }
 }
-
 impl Readable for String {
        #[inline]
        fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
@@ -901,3 +911,19 @@ impl Readable for String {
                Ok(ret)
        }
 }
+
+impl Writeable for Duration {
+       #[inline]
+       fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
+               self.as_secs().write(w)?;
+               self.subsec_nanos().write(w)
+       }
+}
+impl Readable for Duration {
+       #[inline]
+       fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
+               let secs = Readable::read(r)?;
+               let nanos = Readable::read(r)?;
+               Ok(Duration::new(secs, nanos))
+       }
+}