Ver código fonte

more explicit names for network errors

ghassmo 4 anos atrás
pai
commit
fe147fe8ae

+ 1 - 1
bin/ircd/src/server.rs

@@ -184,7 +184,7 @@ impl IrcServerConnection {
             }
             "QUIT" => {
                 // Close the connection
-                return Err(Error::ServiceStopped)
+                return Err(Error::NetworkServiceStopped)
             }
             _ => {
                 warn!("Unimplemented `{}` command", command);

+ 2 - 2
bin/tau/tau-cli/src/main.rs

@@ -8,7 +8,7 @@ use url::Url;
 use darkfi::{
     rpc::client::RpcClient,
     util::cli::{get_log_config, get_log_level},
-    Error, Result,
+    Result,
 };
 
 mod filter;
@@ -123,7 +123,7 @@ async fn main() -> Result<()> {
                             states.len(),
                             states
                         );
-                        return Err(Error::OperationFailed)
+                        Ok(())
                     }
                 }
                 None => {

+ 11 - 0
bin/tau/taud/src/error.rs

@@ -14,6 +14,8 @@ pub enum TaudError {
     Darkfi(#[from] darkfi::error::Error),
     #[error("Json serialization error: `{0}`")]
     SerdeJsonError(String),
+    #[error("Encryption error: `{0}`")]
+    EncryptionError(String),
 }
 
 pub type TaudResult<T> = std::result::Result<T, TaudError>;
@@ -24,6 +26,12 @@ impl From<serde_json::Error> for TaudError {
     }
 }
 
+impl From<crypto_box::aead::Error> for TaudError {
+    fn from(err: crypto_box::aead::Error) -> TaudError {
+        TaudError::EncryptionError(err.to_string())
+    }
+}
+
 pub fn to_json_result(res: TaudResult<Value>, id: Value) -> JsonResult {
     match res {
         Ok(v) => JsonResponse::new(v, id).into(),
@@ -37,6 +45,9 @@ pub fn to_json_result(res: TaudResult<Value>, id: Value) -> JsonResult {
             TaudError::InvalidDueTime => {
                 JsonError::new(ErrorCode::InvalidParams, Some("invalid due time".into()), id).into()
             }
+            TaudError::EncryptionError(e) => {
+                JsonError::new(ErrorCode::InternalError, Some(e), id).into()
+            }
             TaudError::Darkfi(e) => {
                 JsonError::new(ErrorCode::InternalError, Some(e.to_string()), id).into()
             }

+ 9 - 15
bin/tau/taud/src/main.rs

@@ -46,37 +46,30 @@ fn encrypt_task(
     task: &TaskInfo,
     secret_key: &SecretKey,
     rng: &mut crypto_box::rand_core::OsRng,
-) -> Result<EncryptedTask> {
+) -> TaudResult<EncryptedTask> {
     debug!("start encrypting task");
     let public_key = secret_key.public_key();
     let msg_box = Box::new(&public_key, secret_key);
 
     let nonce = crypto_box::generate_nonce(rng);
     let payload = &serialize(task)[..];
-    let payload = match msg_box.encrypt(&nonce, payload) {
-        Ok(p) => p,
-        Err(e) => {
-            error!("Unable to encrypt task: {}", e);
-            return Err(Error::OperationFailed)
-        }
-    };
+    let payload = msg_box.encrypt(&nonce, payload)?;
 
     let nonce = nonce.to_vec();
     Ok(EncryptedTask { nonce, payload })
 }
 
-fn decrypt_task(encrypt_task: &EncryptedTask, secret_key: &SecretKey) -> Option<TaskInfo> {
+fn decrypt_task(encrypt_task: &EncryptedTask, secret_key: &SecretKey) -> TaudResult<TaskInfo> {
     debug!("start decrypting task");
     let public_key = secret_key.public_key();
     let msg_box = Box::new(&public_key, secret_key);
 
     let nonce = encrypt_task.nonce.as_slice();
-    let decrypted_task = match msg_box.decrypt(nonce.into(), &encrypt_task.payload[..]) {
-        Ok(m) => m,
-        Err(_) => return None,
-    };
+    let decrypted_task = msg_box.decrypt(nonce.into(), &encrypt_task.payload[..])?;
+
+    let task = deserialize(&decrypted_task)?;
 
-    deserialize(&decrypted_task).ok()
+    Ok(task)
 }
 
 async_daemonize!(realmain);
@@ -161,7 +154,8 @@ async fn realmain(settings: Args, executor: Arc<Executor<'_>>) -> Result<()> {
                     let recv = task.map_err(Error::from)?;
                     let task = decrypt_task(&recv, &secret_key);
 
-                    if task.is_none() {
+                    if let Err(e) = task {
+                        warn!("unable to decrypt the task: {}", e);
                         continue
                     }
 

+ 7 - 10
src/error.rs

@@ -118,8 +118,8 @@ pub enum Error {
     #[error("Channel timed out")]
     ChannelTimeout,
 
-    #[error("Service stopped")]
-    ServiceStopped,
+    #[error("Network service stopped")]
+    NetworkServiceStopped,
 
     #[error("Create listener bound to {0} failed")]
     BindFailed(String),
@@ -130,8 +130,8 @@ pub enum Error {
     #[error("Accept a new tls connection from the listener {0} failed")]
     AcceptTlsConnectionFailed(String),
 
-    #[error("Operation failed")]
-    OperationFailed,
+    #[error("Network operation failed")]
+    NetworkOperationFailed,
 
     #[error("Malformed packet")]
     MalformedPacket,
@@ -153,6 +153,9 @@ pub enum Error {
     #[error("async_native_tls error: {0}")]
     AsyncNativeTlsError(String),
 
+    #[error("Tor error: {0}")]
+    TorError(String),
+
     // =============
     // Crypto errors
     // =============
@@ -199,12 +202,6 @@ pub enum Error {
     #[error("JSON-RPC error: {0}")]
     JsonRpcError(String),
 
-    #[error("Cashier error: {0}")]
-    CashierError(String),
-
-    #[error("Tor error: {0}")]
-    TorError(String),
-
     // ===============
     // Database errors
     // ===============

+ 1 - 1
src/net/acceptor.rs

@@ -132,7 +132,7 @@ impl Acceptor {
         self.task.clone().start(
             self.clone().run_accept_loop(listener),
             |result| self2.handle_stop(result),
-            Error::ServiceStopped,
+            Error::NetworkServiceStopped,
             executor,
         );
     }

+ 1 - 1
src/net/channel.rs

@@ -103,7 +103,7 @@ impl Channel {
         self.receive_task.clone().start(
             self.clone().main_receive_loop(),
             |result| self2.handle_stop(result),
-            Error::ServiceStopped,
+            Error::NetworkServiceStopped,
             executor,
         );
         debug!(target: "net", "Channel::start() [END, address={}]", self.address());

+ 1 - 1
src/net/message_subscriber.rs

@@ -194,7 +194,7 @@ impl MessageSubsystem {
             None => {
                 // normall return failure here
                 // for now panic
-                return Err(Error::OperationFailed)
+                return Err(Error::NetworkOperationFailed)
             }
         };
 

+ 1 - 1
src/net/session/inbound_session.rs

@@ -66,7 +66,7 @@ impl InboundSession {
             self.clone().channel_sub_loop(executor.clone()),
             // Ignore stop handler
             |_| async {},
-            Error::ServiceStopped,
+            Error::NetworkServiceStopped,
             executor,
         );
 

+ 1 - 1
src/net/session/manual_session.rs

@@ -44,7 +44,7 @@ impl ManualSession {
             self.clone().channel_connect_loop(addr.clone(), executor.clone()),
             // Ignore stop handler
             |_| async {},
-            Error::ServiceStopped,
+            Error::NetworkServiceStopped,
             executor.clone(),
         );
 

+ 2 - 2
src/net/session/outbound_session.rs

@@ -105,7 +105,7 @@ impl OutboundSession {
                 self.clone().channel_connect_loop(i, executor.clone()),
                 // Ignore stop handler
                 |_| async {},
-                Error::ServiceStopped,
+                Error::NetworkServiceStopped,
                 executor.clone(),
             );
 
@@ -221,7 +221,7 @@ impl OutboundSession {
         }
 
         error!(target: "net", "Hosts address pool is empty. Closing connect slot #{}", slot_number);
-        Err(Error::ServiceStopped)
+        Err(Error::NetworkServiceStopped)
     }
 
     /// Checks whether an address is our own inbound address to avoid connecting

+ 2 - 2
src/net/session/seed_session.rs

@@ -70,13 +70,13 @@ impl SeedSession {
 
         if result.is_err() {
             error!("Querying seeds timed out");
-            return Err(Error::OperationFailed)
+            return Err(Error::NetworkOperationFailed)
         }
 
         // Seed process complete
         if self.p2p().hosts().is_empty().await {
             error!("Hosts pool still empty after seeding");
-            return Err(Error::OperationFailed)
+            return Err(Error::NetworkOperationFailed)
         }
 
         debug!(target: "net", "SeedSession::start() [END]");

+ 2 - 2
src/rpc/client.rs

@@ -47,7 +47,7 @@ impl RpcClient {
         // sending to a closed channel.
         if let Err(e) = self.send.send(json!(value)).await {
             error!("JSON-RPC client unable to send to {} (channels closed): {}", self.url, e);
-            return Err(Error::OperationFailed)
+            return Err(Error::NetworkOperationFailed)
         }
 
         // If the connection is closed, the receiver will get an error for
@@ -55,7 +55,7 @@ impl RpcClient {
         let reply = self.recv.recv().await;
         if reply.is_err() {
             error!("JSON-RPC client unable to recv from {} (channels closed)", self.url);
-            return Err(Error::OperationFailed)
+            return Err(Error::NetworkOperationFailed)
         }
 
         match reply? {