Browse Source

Reordered the impl blocks to be in a sane order.

Matthew Carr 2 years ago
parent
commit
2a3ba283c6
2 changed files with 136 additions and 152 deletions
  1. 67 71
      crates/node/src/crypto.rs
  2. 69 81
      crates/node/src/main.rs

+ 67 - 71
crates/node/src/crypto.rs

@@ -7,36 +7,43 @@ use openssl::{
     pkey::{PKey, Public, Private},
     symm::{Cipher, encrypt as openssl_encrypt, decrypt as openssl_decrypt},
 };
-use serde_block_tree::{to_vec, from_vec};
+use serde_block_tree::{self, to_vec, from_vec};
 use serde::de::{DeserializeOwned};
 
 /// Data that may or may not be encrypted.
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 pub enum Cryptotext<T: Serialize> {
-    /// The inner value of `T` is in plaintext.
+    /// The inner value of `T` is plaintext.
     Plain(T),
-    /// The inner value of `T` is in ciphertext.
+    /// The inner value is ciphertext.
     Cipher(Vec<u8>),
 }
 
-pub trait Hydrate<const N: usize> {
-    fn hydrate(template: Self, data: [u8; N]) -> Self;
-}
-
 /// Errors that can occur during cryptographic operations.
 #[derive(Debug)]
 pub enum Error {
     NoReadCap,
     NoKeyAvailable,
     MissingPrivateKey,
-    Encryption(String),
-    Decryption(String),
+    Message(String),
+    Serde(serde_block_tree::Error),
+}
+
+impl From<ErrorStack> for Error {
+    fn from(error: ErrorStack) -> Error {
+        Error::Message(error.to_string())
+    }
+}
+
+impl From<serde_block_tree::Error> for Error {
+    fn from(error: serde_block_tree::Error) -> Error {
+        Error::Serde(error)
+    }
 }
 
 pub type Result<T> = std::result::Result<T, Error>;
 
 /// A cryptographic hash.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable)]
 pub enum Hash {
     Sha2_256([u8; 32]),
@@ -45,7 +52,6 @@ pub enum Hash {
 }
 
 /// A cryptographic signature.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 pub enum Signature {
     #[serde(with = "BigArray")]
@@ -53,7 +59,6 @@ pub enum Signature {
 }
 
 /// A cryptographic key.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 pub enum Key {
     // For keys that contain IVs, the key always comes first. The function `key_len` can be used
@@ -74,30 +79,6 @@ pub enum Key {
     },
 }
 
-enum EncryptionAlgo<'a> {
-    Symmetric {
-        cipher: Cipher,
-        key: &'a [u8],
-        iv: Option<&'a [u8]>
-    },
-    Asymmetric(PKey<Public>),
-}
-
-enum DecryptionAlgo<'a> {
-    Symmetric {
-        cipher: Cipher,
-        key: &'a [u8],
-        iv: Option<&'a [u8]>
-    },
-    Asymmetric(PKey<Private>),
-}
-
-impl From<ErrorStack> for Error {
-    fn from(error: ErrorStack) -> Error {
-        Error::Encryption(error.to_string())
-    }
-}
-
 impl Key {
     /// Returns the key part of this `Key`. Note that if this `Key` is for an asymmetric algorithm,
     /// then this returns the *private* key (if it is present).
@@ -121,27 +102,13 @@ impl Key {
     }
 }
 
-impl<'a> TryFrom<&'a Key> for EncryptionAlgo<'a> {
-    type Error = Error;
-    fn try_from(key: &'a Key) -> Result<EncryptionAlgo<'a>> {
-        match key {
-            Key::Aes256Cbc { key: key_slice, iv } => Ok(EncryptionAlgo::Symmetric {
-                cipher: Cipher::aes_256_cbc(),
-                key: key_slice,
-                iv: Some(iv),
-            }),
-            Key::Aes256Ctr(key_slice) => Ok(EncryptionAlgo::Symmetric {
-                cipher: Cipher::aes_256_ctr(),
-                key: key_slice,
-                iv: None
-            }),
-            Key::Ed25519 { public, .. } => {
-                let pkey = PKey::public_key_from_der(public.as_slice())
-                    .map_err(|err| Error::Encryption(err.to_string()));
-                Ok(EncryptionAlgo::Asymmetric(pkey?))
-            },
-        }
-    }
+enum EncryptionAlgo<'a> {
+    Symmetric {
+        cipher: Cipher,
+        key: &'a [u8],
+        iv: Option<&'a [u8]>
+    },
+    Asymmetric(PKey<Public>),
 }
 
 impl<'a> EncryptionAlgo<'a> {
@@ -163,30 +130,38 @@ impl<'a> EncryptionAlgo<'a> {
     }
 }
 
-impl<'a> TryFrom<&'a Key> for DecryptionAlgo<'a> {
+impl<'a> TryFrom<&'a Key> for EncryptionAlgo<'a> {
     type Error = Error;
-    fn try_from(key: &'a Key) -> Result<DecryptionAlgo<'a>> {
+    fn try_from(key: &'a Key) -> Result<EncryptionAlgo<'a>> {
         match key {
-            Key::Aes256Cbc { key: key_slice, iv } => Ok(DecryptionAlgo::Symmetric {
+            Key::Aes256Cbc { key: key_slice, iv } => Ok(EncryptionAlgo::Symmetric {
                 cipher: Cipher::aes_256_cbc(),
                 key: key_slice,
                 iv: Some(iv),
             }),
-            Key::Aes256Ctr(key_slice) => Ok(DecryptionAlgo::Symmetric {
+            Key::Aes256Ctr(key_slice) => Ok(EncryptionAlgo::Symmetric {
                 cipher: Cipher::aes_256_ctr(),
                 key: key_slice,
                 iv: None
             }),
-            Key::Ed25519 { private, .. } => {
-                let private = private.ok_or(Error::MissingPrivateKey)?;
-                let pkey = PKey::private_key_from_der(private.as_slice())
-                    .map_err(|err| Error::Decryption(err.to_string()));
-                Ok(DecryptionAlgo::Asymmetric(pkey?))
-            }
+            Key::Ed25519 { public, .. } => {
+                let pkey = PKey::public_key_from_der(public.as_slice())
+                    .map_err(|err| Error::Message(err.to_string()));
+                Ok(EncryptionAlgo::Asymmetric(pkey?))
+            },
         }
     }
 }
 
+enum DecryptionAlgo<'a> {
+    Symmetric {
+        cipher: Cipher,
+        key: &'a [u8],
+        iv: Option<&'a [u8]>
+    },
+    Asymmetric(PKey<Private>),
+}
+
 impl<'a> DecryptionAlgo<'a> {
     fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
         match self {
@@ -206,7 +181,29 @@ impl<'a> DecryptionAlgo<'a> {
     }
 }
 
-#[allow(dead_code)]
+impl<'a> TryFrom<&'a Key> for DecryptionAlgo<'a> {
+    type Error = Error;
+    fn try_from(key: &'a Key) -> Result<DecryptionAlgo<'a>> {
+        match key {
+            Key::Aes256Cbc { key: key_slice, iv } => Ok(DecryptionAlgo::Symmetric {
+                cipher: Cipher::aes_256_cbc(),
+                key: key_slice,
+                iv: Some(iv),
+            }),
+            Key::Aes256Ctr(key_slice) => Ok(DecryptionAlgo::Symmetric {
+                cipher: Cipher::aes_256_ctr(),
+                key: key_slice,
+                iv: None
+            }),
+            Key::Ed25519 { private, .. } => {
+                let private = private.ok_or(Error::MissingPrivateKey)?;
+                let pkey = PKey::private_key_from_der(private.as_slice()).map_err(Error::from);
+                Ok(DecryptionAlgo::Asymmetric(pkey?))
+            }
+        }
+    }
+}
+
 pub(crate) fn encrypt_block(
     versioned_block: VersionedBlock, principal: &Principal, key: &Key
 ) -> Result<VersionedBlock> {
@@ -224,7 +221,6 @@ pub(crate) fn encrypt_block(
     Ok(VersionedBlock::V0(block))
 }
 
-#[allow(dead_code)]
 pub(crate) fn decrypt_block(
     versioned_block: VersionedBlock, principal: &Principal, key: &Key
 ) -> Result<VersionedBlock> {
@@ -243,7 +239,7 @@ pub(crate) fn decrypt_block(
 }
 
 fn encrypt<T: Serialize>(value: &T, key: &Key) -> Result<Cryptotext<T>> {
-    let data = to_vec(value).map_err(|err| Error::Encryption(err.to_string()))?;
+    let data = to_vec(value).map_err(Error::from)?;
     let vec = encrypt_slice(&data, key);
     Ok(Cryptotext::Cipher(vec?))
 }
@@ -254,7 +250,7 @@ fn decrypt<T: Serialize + DeserializeOwned>(cryptotext: Cryptotext<T>, key: &Key
         Cryptotext::Cipher(data) => data
     };
     let vec = decrypt_slice(&data, key);
-    from_vec(&vec?).map_err(|err| Error::Decryption(err.to_string()))
+    from_vec(&vec?).map_err(Error::from)
 }
 
 fn encrypt_slice(plaintext: &[u8], key: &Key) -> Result<Vec<u8>> {

+ 69 - 81
crates/node/src/main.rs

@@ -18,7 +18,6 @@ mod crypto;
 use crypto::{Hash, Signature, Key, Cryptotext};
 
 /// A Block tagged with its version number.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 enum VersionedBlock {
     V0(Block)
@@ -26,7 +25,6 @@ enum VersionedBlock {
 
 /// A container which binds together ciphertext along with the metadata needed to identify,
 /// verify and decrypt it.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 struct Block {
     /// Identifies this block and defines its location in the tree.
@@ -45,7 +43,6 @@ struct Block {
 }
 
 /// An envelopment of a key, which is tagged with the principal who the key is meant for.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 struct ReadCap {
     /// The principal this `ReadCap` was issued to.
@@ -54,8 +51,13 @@ struct ReadCap {
     key: Cryptotext<Key>,
 }
 
+impl ReadCap {
+    fn new(issued_to: Hash, key: Cryptotext<Key>) -> ReadCap {
+        ReadCap { issued_to: Principal(issued_to), key }
+    }
+}
+
 /// Verifies that a principal is authorized to write blocks in a tree.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 struct WriteCap {
     /// The principal this `WriteCap` was issued to.
@@ -76,7 +78,6 @@ struct WriteCap {
 
 /// Fragments are created from blocks using Erasure Encoding and stored with other nodes in the
 /// network to provide availability and redundancy of data.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 struct Fragment {
     /// The path to the block this fragment is from.
@@ -87,8 +88,20 @@ struct Fragment {
     body: Vec<u8>,
 }
 
+impl Fragment {
+    /// Create a new fragment with the given fields. If `path_str` cannot be parsed then a failed
+    /// `Result` is returned containing a `PathError`.
+    fn new(path_str: &str, serial_num: u32, body: Vec<u8>) -> Result<Fragment, PathError> {
+        let result = Path::try_from(path_str);
+        Ok(Fragment {
+            path: result?,
+            serial: FragmentSerial(serial_num),
+            body
+        })
+    }
+}
+
 /// The body of every non-leaf node in a tree contains this data structure.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 struct Directory {
     /// The nodes that are attached to the tree at this block.
@@ -98,7 +111,6 @@ struct Directory {
 }
 
 /// Keeps track of which principal is storing a fragment.
-#[allow(dead_code)]
 #[derive(Debug, PartialEq, Serialize, Deserialize)]
 struct FragmentRecord {
     /// The fragment serial number this record is for.
@@ -107,62 +119,9 @@ struct FragmentRecord {
     stored_by: Principal,
 }
 
-/// An identifier for a security principal, which is any entity that can be authenticated.
-#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable)]
-struct Principal(Hash);
-
-/// An identifier for a block in a tree.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
-struct Path(Vec<String>);
-
-/// Errors which can occur when converting a string to a `Path`.
-#[derive(Debug, PartialEq)]
-enum PathError {
-    /// Occurs when the number of bytes in a string is greater than `Path::BYTE_LIMIT`.
-    PathTooLong(usize),
-    /// Indicates that a path string was empty.
-    Empty,
-    /// Occurs when a component in a path string was empty.
-    EmptyComponent,
-}
-
-/// An instant in time represented by the number of seconds since January 1st 1970, 00:00:00 UTC.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
-struct Epoch(i64);
-
-/// The serial number of a block fragment.
-#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable)]
-struct FragmentSerial(u32);
-
-fn main() {
-    println!("Hello, world!");
-}
-
-impl ReadCap {
-    #[allow(dead_code)]
-    fn new(issued_to: Hash, key: Cryptotext<Key>) -> ReadCap {
-        ReadCap { issued_to: Principal(issued_to), key }
-    }
-}
-
-impl Fragment {
-    /// Create a new fragment with the given fields. If `path_str` cannot be parsed then a failed
-    /// `Result` is returned containing a `PathError`.
-    #[allow(dead_code)]
-    fn new(path_str: &str, serial_num: u32, body: Vec<u8>) -> Result<Fragment, PathError> {
-        let result = Path::try_from(path_str);
-        Ok(Fragment {
-            path: result?,
-            serial: FragmentSerial(serial_num),
-            body
-        })
-    }
-}
-
 impl FragmentRecord {
     /// Creates a new `FragmentRecord` whose `serial` and `stored_by` fields are set to
     /// the given values.
-    #[allow(dead_code)]
     fn new(serial: u32, stored_by: Hash) -> FragmentRecord {
         FragmentRecord {
             serial: FragmentSerial(serial),
@@ -171,28 +130,20 @@ impl FragmentRecord {
     }
 }
 
+/// An identifier for a security principal, which is any entity that can be authenticated.
+#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable)]
+struct Principal(Hash);
+
+/// An identifier for a block in a tree.
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+struct Path(Vec<String>);
+
 impl Path {
     /// The character that is used to separate path components.
     const SEP: char = '/';
     /// The limit, in bytes, of a `Path`'s length.
     const BYTE_LIMIT: usize = 4096;
-}
 
-impl Display for PathError {
-    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
-       match self {
-           PathError::PathTooLong(length) => formatter.write_fmt(format_args!(
-                "path contained {} bytes, which is over the {} byte limit",
-                length,
-                Path::BYTE_LIMIT)
-           ),
-           PathError::Empty => formatter.write_str("path was empty"),
-           PathError::EmptyComponent => formatter.write_str("component of path was empty"),
-       }
-    }
-}
-
-impl Path {
     /// Returns a result which, when successful, returns the index after the last character in the
     /// current path component.
     fn component_end<I: Iterator<Item = (usize, char)>>(
@@ -241,11 +192,11 @@ impl Path {
 
     /// Asserts that the number of bytes in the given string is no more than `Path::BYTE_LIMIT`.
     fn assert_not_too_long(string: &str) -> Result<(), PathError> {
-            let len = string.len();
-            if len > Path::BYTE_LIMIT {
-                return Err(PathError::PathTooLong(len))
-            }
-            Ok(())
+        let len = string.len();
+        if len > Path::BYTE_LIMIT {
+            return Err(PathError::PathTooLong(len))
+        }
+        Ok(())
     }
 }
 
@@ -272,6 +223,43 @@ impl<'s> TryFrom<&'s str> for Path {
     }
 }
 
+/// Errors which can occur when converting a string to a `Path`.
+#[derive(Debug, PartialEq)]
+enum PathError {
+    /// Occurs when the number of bytes in a string is greater than `Path::BYTE_LIMIT`.
+    PathTooLong(usize),
+    /// Indicates that a path string was empty.
+    Empty,
+    /// Occurs when a component in a path string was empty.
+    EmptyComponent,
+}
+
+impl Display for PathError {
+    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
+       match self {
+           PathError::PathTooLong(length) => formatter.write_fmt(format_args!(
+                "path contained {} bytes, which is over the {} byte limit",
+                length,
+                Path::BYTE_LIMIT)
+           ),
+           PathError::Empty => formatter.write_str("path was empty"),
+           PathError::EmptyComponent => formatter.write_str("component of path was empty"),
+       }
+    }
+}
+
+/// An instant in time represented by the number of seconds since January 1st 1970, 00:00:00 UTC.
+#[derive(Debug, PartialEq, Serialize, Deserialize)]
+struct Epoch(i64);
+
+/// The serial number of a block fragment.
+#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable)]
+struct FragmentSerial(u32);
+
+fn main() {
+    println!("Hello, world!");
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;