Răsfoiți Sursa

Addressed the clippy warnings.

Matthew Carr 2 ani în urmă
părinte
comite
fe2ffc7077

+ 2 - 2
crates/btlib/src/block_path.rs

@@ -145,9 +145,9 @@ mod private {
             };
             let mut iter = self.components.iter();
             let first = iter.next().unwrap();
-            let mut output = write!(f, "{}", first);
+            let mut output = write!(f, "{first}");
             for component in iter {
-                output = write!(f, "{}{}", BlockPath::SEP, component)
+                output = write!(f, "{}{component}", BlockPath::SEP)
             }
             output
         }

+ 1 - 1
crates/btlib/src/blocktree.rs

@@ -127,7 +127,7 @@ mod private {
 
         fn open_block<P: AsRef<Path>>(btdir: P, inode: Inode, creds: C) -> Result<Box<dyn Block>> {
             let path = Self::block_path(&btdir, inode);
-            let dir = path.ancestors().skip(1).next().unwrap();
+            let dir = path.ancestors().nth(1).unwrap();
             if let Err(err) = std::fs::create_dir(dir) {
                 match err.kind() {
                     io::ErrorKind::AlreadyExists => (),

+ 41 - 42
crates/btlib/src/crypto/mod.rs

@@ -76,28 +76,13 @@ pub enum Error {
     BlockNotEncrypted,
     InvalidHashFormat,
     InvalidSignature,
-    IncorrectSize {
-        expected: usize,
-        actual: usize,
-    },
-    IndexOutOfBounds {
-        index: usize,
-        limit: usize,
-    },
-    IndivisibleSize {
-        divisor: usize,
-        actual: usize,
-    },
-    InvalidOffset {
-        actual: usize,
-        limit: usize,
-    },
+    IncorrectSize { expected: usize, actual: usize },
+    IndexOutOfBounds { index: usize, limit: usize },
+    IndivisibleSize { divisor: usize, actual: usize },
+    InvalidOffset { actual: usize, limit: usize },
     HashCmpFailure,
     RootHashNotVerified,
-    SignatureMismatch {
-        actual: Principal,
-        expected: Principal,
-    },
+    SignatureMismatch(Box<SignatureMismatch>),
     WritecapAuthzErr(WritecapAuthzErr),
     Serde(btserde::Error),
     Io(std::io::Error),
@@ -105,9 +90,13 @@ pub enum Error {
 }
 
 impl Error {
-    pub(crate) fn custom<E: std::fmt::Debug + Send + Sync + 'static>(err: E) -> Self {
+    pub(crate) fn custom<E: std::fmt::Debug + Send + Sync + 'static>(err: E) -> Error {
         Error::Custom(Box::new(err))
     }
+
+    fn signature_mismatch(expected: Principal, actual: Principal) -> Error {
+        Error::SignatureMismatch(Box::new(SignatureMismatch { expected, actual }))
+    }
 }
 
 impl Display for Error {
@@ -121,7 +110,7 @@ impl Display for Error {
             Error::InvalidHashFormat => write!(f, "invalid format"),
             Error::InvalidSignature => write!(f, "invalid signature"),
             Error::IncorrectSize { expected, actual } => {
-                write!(f, "expected size {} but got {}", expected, actual)
+                write!(f, "expected size {expected} but got {actual}")
             }
             Error::IndexOutOfBounds { index, limit } => write!(
                 f,
@@ -140,10 +129,14 @@ impl Display for Error {
             ),
             Error::HashCmpFailure => write!(f, "hash data are not equal"),
             Error::RootHashNotVerified => write!(f, "root hash is not verified"),
-            Error::SignatureMismatch { actual, expected } => write!(
-                f,
-                "expected a signature from {expected} but found one from {actual}"
-            ),
+            Error::SignatureMismatch(mismatch) => {
+                let actual = &mismatch.actual;
+                let expected = &mismatch.expected;
+                write!(
+                    f,
+                    "expected a signature from {expected} but found one from {actual}"
+                )
+            }
             Error::WritecapAuthzErr(err) => err.fmt(f),
             Error::Serde(err) => err.fmt(f),
             Error::Io(err) => err.fmt(f),
@@ -198,6 +191,12 @@ impl From<crate::Error> for Error {
 
 pub(crate) type Result<T> = std::result::Result<T, Error>;
 
+#[derive(Debug)]
+pub struct SignatureMismatch {
+    pub actual: Principal,
+    pub expected: Principal,
+}
+
 /// Returns an array of the given length filled with cryptographically strong random data.
 pub fn rand_array<const LEN: usize>() -> Result<[u8; LEN]> {
     let mut array = [0; LEN];
@@ -670,7 +669,7 @@ impl Display for VarHash {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         let hash_kind: HashKind = self.into();
         let hash_data = base64_url::encode(self.as_ref());
-        write!(f, "{}{}{}", hash_kind as u32, VarHash::HASH_SEP, hash_data)
+        write!(f, "{}{}{hash_data}", hash_kind as u32, VarHash::HASH_SEP)
     }
 }
 
@@ -1175,7 +1174,7 @@ impl Scheme for RsaEsOaep {
     }
 
     fn hash_kind(&self) -> HashKind {
-        self.hash_kind.into()
+        self.hash_kind
     }
 
     fn padding(&self) -> Option<OpensslPadding> {
@@ -1219,7 +1218,7 @@ impl Scheme for RsaSsaPss {
     }
 
     fn hash_kind(&self) -> HashKind {
-        self.hash_kind.into()
+        self.hash_kind
     }
 
     fn padding(&self) -> Option<OpensslPadding> {
@@ -1422,7 +1421,7 @@ impl Decrypter for AsymKey<Private, Encrypt> {
 impl Signer for AsymKey<Private, Sign> {
     type Op<'s> = OsslSignOp<'s>;
 
-    fn init_sign<'s>(&'s self) -> Result<Self::Op<'s>> {
+    fn init_sign(&self) -> Result<Self::Op<'_>> {
         OsslSignOp::init((self.scheme, self.pkey.as_ref()))
     }
 
@@ -1443,7 +1442,7 @@ impl Signer for AsymKey<Private, Sign> {
 impl Verifier for AsymKey<Public, Sign> {
     type Op<'v> = OsslVerifyOp<'v>;
 
-    fn init_verify<'v>(&'v self) -> Result<Self::Op<'v>> {
+    fn init_verify(&self) -> Result<Self::Op<'_>> {
         OsslVerifyOp::init((self.scheme, self.pkey.as_ref()))
     }
 
@@ -1498,7 +1497,7 @@ impl Decrypter for AsymKeyPair<Encrypt> {
 
 impl Signer for AsymKeyPair<Sign> {
     type Op<'s> = <AsymKey<Private, Sign> as Signer>::Op<'s>;
-    fn init_sign<'s>(&'s self) -> Result<Self::Op<'s>> {
+    fn init_sign(&self) -> Result<Self::Op<'_>> {
         self.private.init_sign()
     }
     fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
@@ -1509,7 +1508,7 @@ impl Signer for AsymKeyPair<Sign> {
 impl Verifier for AsymKeyPair<Sign> {
     type Op<'v> = OsslVerifyOp<'v>;
 
-    fn init_verify<'v>(&'v self) -> Result<Self::Op<'v>> {
+    fn init_verify(&self) -> Result<Self::Op<'_>> {
         self.public.init_verify()
     }
 
@@ -1539,7 +1538,7 @@ impl Encrypter for PublicCreds {
 impl Verifier for PublicCreds {
     type Op<'v> = OsslVerifyOp<'v>;
 
-    fn init_verify<'v>(&'v self) -> Result<Self::Op<'v>> {
+    fn init_verify(&self) -> Result<Self::Op<'_>> {
         self.sign.init_verify()
     }
 
@@ -1591,7 +1590,7 @@ impl ConcreteCreds {
 impl Verifier for ConcreteCreds {
     type Op<'v> = OsslVerifyOp<'v>;
 
-    fn init_verify<'v>(&'v self) -> Result<Self::Op<'v>> {
+    fn init_verify(&self) -> Result<Self::Op<'_>> {
         self.sign.init_verify()
     }
 
@@ -1621,7 +1620,7 @@ impl CredsPub for ConcreteCreds {
 impl Signer for ConcreteCreds {
     type Op<'s> = <AsymKeyPair<Sign> as Signer>::Op<'s>;
 
-    fn init_sign<'s>(&'s self) -> Result<Self::Op<'s>> {
+    fn init_sign(&self) -> Result<Self::Op<'_>> {
         self.sign.init_sign()
     }
 
@@ -1760,7 +1759,7 @@ pub trait Signer {
         Self: 's;
 
     /// Starts a new signing operation and returns the struct representing it.
-    fn init_sign<'s>(&'s self) -> Result<Self::Op<'s>>;
+    fn init_sign(&self) -> Result<Self::Op<'_>>;
     fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature>;
 
     fn ser_sign<T: Serialize>(&self, value: &T) -> Result<Signed<T>> {
@@ -1878,7 +1877,7 @@ pub trait Verifier {
     where
         Self: 'v;
 
-    fn init_verify<'v>(&'v self) -> Result<Self::Op<'v>>;
+    fn init_verify(&self) -> Result<Self::Op<'_>>;
 
     fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()>;
 
@@ -1969,10 +1968,10 @@ impl BlockMeta {
         writecap.assert_valid_for(&body.path)?;
         let signed_by = body.signing_key.principal();
         if writecap.body.issued_to != signed_by {
-            return Err(Error::SignatureMismatch {
-                actual: signed_by,
-                expected: writecap.body.issued_to.clone(),
-            });
+            return Err(Error::signature_mismatch(
+                writecap.body.issued_to.clone(),
+                signed_by,
+            ));
         }
         body.signing_key.ser_verify(&body, self.sig.as_slice())
     }

+ 8 - 5
crates/btlib/src/crypto/tpm.rs

@@ -54,7 +54,7 @@ impl From<tss_esapi::Error> for Error {
             tss_esapi::Error::Tss2Error(err) => {
                 let rc = err.tss2_rc();
                 let text = tss2_rc_decode(err);
-                let string = format!("response code: {}, response text: {}", rc, text);
+                let string = format!("response code: {rc}, response text: {text}");
                 Error::custom(string)
             }
         }
@@ -620,7 +620,7 @@ impl TryFrom<KeyLen> for RsaKeyBits {
             KeyLen::Bits2048 => Ok(RsaKeyBits::Rsa2048),
             KeyLen::Bits3072 => Ok(RsaKeyBits::Rsa3072),
             KeyLen::Bits4096 => Ok(RsaKeyBits::Rsa4096),
-            _ => Err(Error::custom(format!("unsupported key len: {}", len))),
+            _ => Err(Error::custom(format!("unsupported key len: {len}"))),
         }
     }
 }
@@ -1342,7 +1342,7 @@ impl Principaled for TpmCreds {
 impl Verifier for TpmCreds {
     type Op<'v> = OsslVerifyOp<'v>;
 
-    fn init_verify<'v>(&'v self) -> Result<Self::Op<'v>> {
+    fn init_verify(&self) -> Result<Self::Op<'_>> {
         self.sign.public.init_verify()
     }
 
@@ -1406,7 +1406,10 @@ impl<'a> Op for TpmSignOp<'a> {
         };
 
         if buf.len() < slice.len() {
-            return Err(Error::IncorrectSize { expected: slice.len(), actual: buf.len() });
+            return Err(Error::IncorrectSize {
+                expected: slice.len(),
+                actual: buf.len(),
+            });
         }
         buf.copy_from_slice(slice);
         Ok(slice.len())
@@ -1422,7 +1425,7 @@ impl<'a> SignOp for TpmSignOp<'a> {
 impl Signer for TpmCreds {
     type Op<'s> = TpmSignOp<'s>;
 
-    fn init_sign<'s>(&'s self) -> Result<Self::Op<'s>> {
+    fn init_sign(&self) -> Result<Self::Op<'_>> {
         TpmSignOp::init(self)
     }
 

+ 10 - 3
crates/btlib/src/lib.rs

@@ -21,7 +21,6 @@ extern crate static_assertions;
 extern crate lazy_static;
 
 use brotli::{CompressorWriter, Decompressor};
-use btserde::{self, write_to};
 use crypto::{
     AsymKeyPub, Ciphertext, Creds, Decrypter, DecrypterExt, Encrypter, EncrypterExt, HashKind,
     MerkleStream, PublicCreds, SecretStream, Sign, Signature, Signer, SymKey, SymKeyKind, VarHash,
@@ -69,7 +68,7 @@ impl Display for Error {
             Error::Serde(err) => err.fmt(f),
             Error::Crypto(err) => err.fmt(f),
             Error::IncorrectSize { expected, actual } => {
-                write!(f, "incorrect size {}, expected {}", actual, expected)
+                write!(f, "incorrect size {actual}, expected {expected}")
             }
             Error::Custom(err) => err.fmt(f),
         }
@@ -327,7 +326,9 @@ impl<T: Write + Seek, C: Signer> WriteInteg for BlockStream<T, C> {
         let integ = meta_body.integrity.get_or_insert_with(VarHash::default);
         integ.as_mut().copy_from_slice(integrity);
         self.meta_body_buf.clear();
-        self.meta.sig = self.creds.ser_sign_into(&meta_body, &mut self.meta_body_buf)?;
+        self.meta.sig = self
+            .creds
+            .ser_sign_into(&meta_body, &mut self.meta_body_buf)?;
         self.trailered.flush(&self.meta)?;
         Ok(())
     }
@@ -664,6 +665,12 @@ impl Directory {
     }
 }
 
+impl Default for Directory {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
 /// Keeps track of which principal is storing a fragment.
 #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
 pub struct FragmentRecord {

+ 1 - 1
crates/btserde/src/error.rs

@@ -40,7 +40,7 @@ impl Display for Error {
             )),
             Error::TypeConversion => formatter.write_str("type conversion failed"),
             Error::NotSupported(message) => {
-                formatter.write_fmt(format_args!("Operation is not supported: {}", message))
+                formatter.write_fmt(format_args!("Operation is not supported: {message}"))
             }
             Error::InvalidUtf8Char => formatter.write_str("Invalid UTF-8 character encountered."),
             Error::Format(fmt_error) => fmt_error.fmt(formatter),

+ 1 - 0
crates/btserde/src/ser.rs

@@ -60,6 +60,7 @@ impl<'a, 'w, T: Write> ser::Serializer for &'a mut Serializer<'w, T> {
     type SerializeStructVariant = Self;
 
     /// A bool is serialized by writing the byte 1 if true and 0 if false.
+    #[allow(clippy::bool_to_int_with_if)]
     fn serialize_bool(self, v: bool) -> Result<Self::Ok> {
         self.output
             .write_all(&[if v { 1 } else { 0 }])

+ 1 - 1
crates/harness/src/lib.rs

@@ -67,7 +67,7 @@ impl Node {
         match self.message_rx.recv_timeout(timeout) {
             Ok(msg) => Some(msg),
             Err(err) => {
-                eprintln!("Failed to receive message from thread. Error: {:?}", err);
+                eprintln!("Failed to receive message from thread. Error: {err:?}");
                 None
             }
         }