Chore/more error macros (#2686)

* cleaned up MixProcessingError

* Added Error impl to (hopefully) all error enums in the codebase

* Replaced all occurences of error("{0}") with error(transparent)

* Changelog entry
This commit is contained in:
Jędrzej Stuczyński
2022-12-13 17:42:11 +00:00
committed by GitHub
parent a020f2ad1c
commit 97b01db23e
94 changed files with 583 additions and 714 deletions
+15 -25
View File
@@ -164,17 +164,13 @@ mod test {
let err = extract_encryption_key(&req, tx_entry.clone())
.await
.unwrap_err();
assert_eq!(
err.to_string(),
assert!(matches!(
err,
CoconutError::Ed25519ParseError(
// this is really just a useless, dummy error value needed to generate the error type
// and get its string representation
crypto::asymmetric::identity::Ed25519RecoveryError::MalformedBytes(
crypto::asymmetric::identity::SignatureError::new(),
),
crypto::asymmetric::identity::Ed25519RecoveryError::MalformedSignatureString { .. }
)
.to_string()
);
));
let correct_request = BlindSignRequestBody::new(
&blind_sign_req,
@@ -279,17 +275,13 @@ mod test {
let err = extract_encryption_key(&correct_request, tx_entry.clone())
.await
.unwrap_err();
assert_eq!(
err.to_string(),
assert!(matches!(
err,
CoconutError::Ed25519ParseError(
// this is really just a useless, dummy error value needed to generate the error type
// and get its string representation
crypto::asymmetric::identity::Ed25519RecoveryError::MalformedBytes(
crypto::asymmetric::identity::SignatureError::new(),
),
crypto::asymmetric::identity::Ed25519RecoveryError::MalformedPublicKeyString { .. }
)
.to_string(),
);
));
tx_entry.tx_result.events.get_mut(0).unwrap().attributes = vec![
Tag {
@@ -338,15 +330,13 @@ mod test {
let err = extract_encryption_key(&correct_request, tx_entry.clone())
.await
.unwrap_err();
assert_eq!(
err.to_string(),
assert!(matches!(
err,
CoconutError::X25519ParseError(
// this is really just a useless, dummy error value needed to generate the error type
// and get its string representation
crypto::asymmetric::encryption::KeyRecoveryError::InvalidPublicKeyBytes,
crypto::asymmetric::encryption::KeyRecoveryError::MalformedPublicKeyString { .. }
)
.to_string(),
);
));
let expected_encryption_key = "HxnTpWTkgigSTAysVKLE8pEiUULHdTT1BxFfzfJvQRi6";
tx_entry.tx_result.events.get_mut(0).unwrap().attributes = vec![
+4 -4
View File
@@ -20,16 +20,16 @@ pub type Result<T> = std::result::Result<T, CoconutError>;
#[derive(Debug, Error)]
pub enum CoconutError {
#[error("{0}")]
#[error(transparent)]
IOError(#[from] std::io::Error),
#[error("{0}")]
#[error(transparent)]
SerdeJsonError(#[from] serde_json::Error),
#[error("Could not parse Ed25519 data")]
#[error("Could not parse Ed25519 data - {0}")]
Ed25519ParseError(#[from] Ed25519RecoveryError),
#[error("Could not parse X25519 data")]
#[error("Could not parse X25519 data - {0}")]
X25519ParseError(#[from] KeyRecoveryError),
#[error("Could not parse tx hash in request body")]
+2 -2
View File
@@ -192,7 +192,7 @@ impl<C> ValidatorCacheRefresher<C> {
.await;
if let Err(err) = self.update_notifier.send(CacheNotification::Updated) {
warn!("Failed to notify validator cache refresh: {}", err);
warn!("Failed to notify validator cache refresh: {err}");
}
Ok(())
@@ -213,7 +213,7 @@ impl<C> ValidatorCacheRefresher<C> {
}
ret = self.refresh_cache() => {
if let Err(err) = ret {
error!("Failed to refresh validator cache - {}", err);
error!("Failed to refresh validator cache - {err}");
} else {
// relaxed memory ordering is fine here. worst case scenario network monitor
// will just have to wait for an additional backoff to see the change.
+6 -6
View File
@@ -208,7 +208,7 @@ impl RewardedSetUpdater {
let rewarded_set: Vec<MixId> = match self.nymd_client.get_rewarded_set_mixnodes().await {
Ok(nodes) => nodes.into_iter().map(|(id, _)| id).collect::<Vec<_>>(),
Err(err) => {
warn!("failed to obtain the current rewarded set - {}. falling back to the cached version", err);
warn!("failed to obtain the current rewarded set - {err}. falling back to the cached version");
self.validator_cache
.rewarded_set()
.await
@@ -285,7 +285,7 @@ impl RewardedSetUpdater {
// Reward all the nodes in the still current, soon to be previous rewarded set
log::info!("Rewarding the current rewarded set...");
if let Err(err) = self.reward_current_rewarded_set(interval).await {
log::error!("FAILED to reward rewarded set - {}", err);
log::error!("FAILED to reward rewarded set - {err}");
// since we haven't advanced the epoch yet, we will attempt to reward those nodes again
// next time we enter this function (i.e. within 2min or so)
//
@@ -303,7 +303,7 @@ impl RewardedSetUpdater {
log::info!("Reconciling all pending epoch events...");
if let Err(err) = self.nymd_client.reconcile_epoch_events().await {
log::error!("FAILED to reconcile epoch events... - {}", err);
log::error!("FAILED to reconcile epoch events... - {err}");
return Err(err.into());
} else {
log::info!("Reconciled all pending epoch events... SUCCESS");
@@ -314,7 +314,7 @@ impl RewardedSetUpdater {
.update_rewarded_set_and_advance_epoch(&all_mixnodes)
.await
{
log::error!("FAILED to advance the current epoch... - {}", err);
log::error!("FAILED to advance the current epoch... - {err}");
return Err(err);
} else {
log::info!("Advanced the epoch and updated the rewarded set... SUCCESS");
@@ -434,11 +434,11 @@ impl RewardedSetUpdater {
Some(interval) => interval,
};
if let Err(err) = self.update_blacklist(&interval_details).await {
error!("failed to update the node blacklist - {}", err);
error!("failed to update the node blacklist - {err}");
continue;
}
if let Err(err) = self.perform_epoch_operations(interval_details).await {
error!("failed to perform epoch operations - {}", err);
error!("failed to perform epoch operations - {err}");
sleep(Duration::from_secs(30)).await;
}
}
+2 -2
View File
@@ -278,7 +278,7 @@ fn override_config(mut config: Config, matches: &ArgMatches) -> Config {
if let Some(raw_validator) = matches.value_of(NYMD_VALIDATOR_ARG) {
let parsed = match raw_validator.parse() {
Err(err) => {
error!("Passed validator argument is invalid - {}", err);
error!("Passed validator argument is invalid - {err}");
process::exit(1)
}
Ok(url) => url,
@@ -336,7 +336,7 @@ fn override_config(mut config: Config, matches: &ArgMatches) -> Config {
if matches.is_present(WRITE_CONFIG_ARG) {
info!("Saving the configuration to a file");
if let Err(err) = config.save_to_file(None) {
error!("Failed to write config to a file - {}", err);
error!("Failed to write config to a file - {err}");
process::exit(1)
}
}
@@ -2,45 +2,39 @@
// SPDX-License-Identifier: Apache-2.0
use crate::network_monitor::gateways_reader::GatewayMessages;
use crate::network_monitor::test_packet::TestPacket;
use crate::network_monitor::test_packet::{TestPacket, TestPacketError};
use crate::network_monitor::ROUTE_TESTING_TEST_NONCE;
use crypto::asymmetric::encryption;
use futures::channel::mpsc;
use futures::lock::{Mutex, MutexGuard};
use futures::{SinkExt, StreamExt};
use log::warn;
use nymsphinx::receiver::MessageReceiver;
use std::fmt::{self, Display, Formatter};
use nymsphinx::receiver::{MessageReceiver, MessageRecoveryError};
use std::mem;
use std::sync::Arc;
use thiserror::Error;
pub(crate) type ReceivedProcessorSender = mpsc::UnboundedSender<GatewayMessages>;
pub(crate) type ReceivedProcessorReceiver = mpsc::UnboundedReceiver<GatewayMessages>;
#[derive(Debug)]
#[derive(Error, Debug)]
enum ProcessingError {
MalformedPacketReceived,
NonTestPacketReceived,
NonMatchingNonce(u64),
ReceivedOutsideTestRun,
}
#[error(
"could not recover underlying data from the received packet since it was malformed - {0}"
)]
MalformedPacketReceived(#[from] MessageRecoveryError),
impl Display for ProcessingError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
ProcessingError::MalformedPacketReceived => write!(f, "received malformed packet"),
ProcessingError::NonTestPacketReceived => write!(f, "received a non-test packet"),
ProcessingError::NonMatchingNonce(nonce) => write!(
f,
"received packet with nonce {} which is different than the expected",
nonce
),
ProcessingError::ReceivedOutsideTestRun => write!(
f,
"received packet while the test is currently not in progress"
),
}
}
#[error("received a mix packet that was NOT a proper network monitor test packet")]
NonTestPacketReceived,
#[error("the received test packet was malformed - {0}")]
MalformedTestPacket(#[from] TestPacketError),
#[error("received packet with an unexpected nonce. Got: {received}, expected: {expected}")]
NonMatchingNonce { received: u64, expected: u64 },
#[error("received a mix packet while no test run is currently in progress")]
ReceivedOutsideTestRun,
}
// we can't use Notify due to possible edge case where both notification are consumed at once
@@ -80,23 +74,20 @@ impl ReceivedProcessorInner {
.recover_plaintext_from_regular_packet(
self.client_encryption_keypair.private_key(),
&mut message,
)
.map_err(|_| ProcessingError::MalformedPacketReceived)?;
let fragment = self
.message_receiver
.recover_fragment(plaintext)
.map_err(|_| ProcessingError::MalformedPacketReceived)?;
)?;
let fragment = self.message_receiver.recover_fragment(plaintext)?;
let (recovered, _) = self
.message_receiver
.insert_new_fragment(fragment)
.map_err(|_| ProcessingError::MalformedPacketReceived)?
.insert_new_fragment(fragment)?
.ok_or(ProcessingError::NonTestPacketReceived)?; // if it's a test packet it MUST BE reconstructed with single fragment
let test_packet = TestPacket::try_from_bytes(&recovered.into_inner_data())
.map_err(|_| ProcessingError::MalformedPacketReceived)?;
let test_packet = TestPacket::try_from_bytes(&recovered.into_inner_data())?;
// we know nonce is NOT none
if test_packet.test_nonce() != self.test_nonce.unwrap() {
return Err(ProcessingError::NonMatchingNonce(test_packet.test_nonce()));
return Err(ProcessingError::NonMatchingNonce {
received: test_packet.test_nonce(),
expected: self.test_nonce.unwrap(),
});
}
self.received_packets.push(test_packet);
@@ -162,7 +153,7 @@ impl ReceivedProcessor {
Some(messages) => {
for message in messages {
if let Err(err) = inner.on_message(message) {
warn!(target: "Monitor", "failed to process received gateway message - {}", err)
warn!(target: "Monitor", "failed to process received gateway message - {err}")
}
}
}
@@ -3,12 +3,14 @@
use crate::network_monitor::monitor::preparer::TestedNode;
use crypto::asymmetric::identity;
use crypto::asymmetric::identity::Ed25519RecoveryError;
use mixnet_contract_common::MixId;
use std::convert::TryInto;
use std::fmt::{self, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::mem;
use std::str::Utf8Error;
use thiserror::Error;
use topology::{gateway, mix};
const MIXNODE_TYPE: u8 = 0;
@@ -67,24 +69,25 @@ impl NodeType {
}
}
#[derive(Debug)]
#[derive(Debug, Error)]
pub(crate) enum TestPacketError {
IncompletePacket,
#[error(
"the received packet was incomplete. Got {received} bytes but expected at least {min_expected}"
)]
IncompletePacket {
received: usize,
min_expected: usize,
},
// TODO: ideally this should contain more information but that'd require more refactoring than I'm willing to commit to now
#[error("the received packet did not contain a valid node type")]
InvalidNodeType,
InvalidNodeKey,
InvalidOwner(Utf8Error),
}
impl From<identity::Ed25519RecoveryError> for TestPacketError {
fn from(_: identity::Ed25519RecoveryError) -> Self {
TestPacketError::InvalidNodeKey
}
}
#[error("the received node identity key was malformed - {0}")]
InvalidNodeKey(#[from] Ed25519RecoveryError),
impl From<Utf8Error> for TestPacketError {
fn from(err: Utf8Error) -> Self {
TestPacketError::InvalidOwner(err)
}
#[error("the received packet contained malformed owner data - {0}")]
InvalidOwner(#[from] Utf8Error),
}
#[derive(Eq, Clone, Debug)]
@@ -184,7 +187,10 @@ impl TestPacket {
let n = mem::size_of::<u64>();
if b.len() < 2 * n + 1 + identity::PUBLIC_KEY_LENGTH {
return Err(TestPacketError::IncompletePacket);
return Err(TestPacketError::IncompletePacket {
received: b.len(),
min_expected: 2 * n + 1 + identity::PUBLIC_KEY_LENGTH,
});
}
// those unwraps can't fail as we've already checked for the size
+37 -48
View File
@@ -17,18 +17,19 @@ use schemars::gen::SchemaGenerator;
use schemars::schema::{InstanceType, Schema};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sqlx::Error;
use std::convert::TryFrom;
use std::fmt::{self, Display, Formatter};
use thiserror::Error;
use time::OffsetDateTime;
use validator_api_requests::models::{
GatewayStatusReportResponse, GatewayUptimeHistoryResponse, HistoricalUptimeResponse,
MixnodeStatusReportResponse, MixnodeUptimeHistoryResponse, RequestError,
};
// todo: put into some error enum
#[derive(Debug)]
pub struct InvalidUptime;
#[derive(Error, Debug)]
#[error("Received uptime value was within 0-100 range (got {received})")]
pub struct InvalidUptime {
received: isize,
}
// value in range 0-100
#[derive(Clone, Copy, Serialize, Deserialize, Debug, Default, JsonSchema)]
@@ -56,7 +57,9 @@ impl Uptime {
let uptime = ((numerator as f32 / denominator as f32) * 100.0).round() as u8;
if uptime > 100 {
Err(InvalidUptime)
Err(InvalidUptime {
received: uptime as isize,
})
} else {
Ok(Uptime(uptime))
}
@@ -70,7 +73,9 @@ impl Uptime {
let uptime = (running_sum / count as f32).round() as u8;
if uptime > 100 {
Err(InvalidUptime)
Err(InvalidUptime {
received: uptime as isize,
})
} else {
Ok(Uptime(uptime))
}
@@ -92,7 +97,9 @@ impl TryFrom<u8> for Uptime {
fn try_from(value: u8) -> Result<Self, Self::Error> {
if value > 100 {
Err(InvalidUptime)
Err(InvalidUptime {
received: value as isize,
})
} else {
Ok(Uptime(value))
}
@@ -104,7 +111,9 @@ impl TryFrom<i64> for Uptime {
fn try_from(value: i64) -> Result<Self, Self::Error> {
if !(0..=100).contains(&value) {
Err(InvalidUptime)
Err(InvalidUptime {
received: value as isize,
})
} else {
Ok(Uptime(value as u8))
}
@@ -365,47 +374,27 @@ impl OpenApiResponderInner for ErrorResponse {
#[derive(Debug, thiserror::Error)]
pub enum ValidatorApiStorageError {
MixnodeReportNotFound(MixId),
GatewayReportNotFound(String),
MixnodeUptimeHistoryNotFound(MixId),
GatewayUptimeHistoryNotFound(String),
#[error("could not find status report associated with mixnode {mix_id}")]
MixnodeReportNotFound { mix_id: MixId },
#[error("Could not find status report associated with gateway {identity}")]
GatewayReportNotFound { identity: IdentityKey },
#[error("could not find uptime history associated with mixnode {mix_id}")]
MixnodeUptimeHistoryNotFound { mix_id: MixId },
#[error("could not find uptime history associated with gateway {identity}")]
GatewayUptimeHistoryNotFound { identity: IdentityKey },
// I don't think we want to expose errors to the user about what really happened
InternalDatabaseError(String),
}
#[error("experienced internal database error")]
InternalDatabaseError(#[from] sqlx::Error),
impl From<sqlx::Error> for ValidatorApiStorageError {
fn from(err: Error) -> Self {
ValidatorApiStorageError::InternalDatabaseError(err.to_string())
}
}
// the same is true here (also note that the message is subtly different so we would be able to distinguish them)
#[error("experienced internal storage error")]
DatabaseInconsistency { reason: String },
impl Display for ValidatorApiStorageError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
ValidatorApiStorageError::MixnodeReportNotFound(mix_id) => write!(
f,
"Could not find status report associated with mixnode {}",
mix_id
),
ValidatorApiStorageError::GatewayReportNotFound(identity) => write!(
f,
"Could not find status report associated with gateway {}",
identity
),
ValidatorApiStorageError::MixnodeUptimeHistoryNotFound(mix_id) => write!(
f,
"Could not find uptime history associated with mixnode {}",
mix_id
),
ValidatorApiStorageError::GatewayUptimeHistoryNotFound(identity) => write!(
f,
"Could not find uptime history associated with gateway {}",
identity
),
ValidatorApiStorageError::InternalDatabaseError(err) => {
write!(f, "The internal database has experienced an issue: {err}")
}
}
}
// this one would never be returned to users since it's only possible on startup
#[error("failed to perform startup SQL migration - {0}")]
StartupMigrationFailure(#[from] sqlx::migrate::MigrateError),
}
+54 -84
View File
@@ -41,19 +41,15 @@ impl ValidatorApiStorage {
let connection_pool = match sqlx::SqlitePool::connect_with(opts).await {
Ok(db) => db,
Err(e) => {
error!("Failed to connect to SQLx database: {}", e);
return Err(ValidatorApiStorageError::InternalDatabaseError(
e.to_string(),
));
Err(err) => {
error!("Failed to connect to SQLx database: {err}");
return Err(err.into());
}
};
if let Err(e) = sqlx::migrate!("./migrations").run(&connection_pool).await {
error!("Failed to initialize SQLx database: {}", e);
return Err(ValidatorApiStorageError::InternalDatabaseError(
e.to_string(),
));
if let Err(err) = sqlx::migrate!("./migrations").run(&connection_pool).await {
error!("Failed to initialize SQLx database: {err}");
return Err(err.into());
}
info!("Database migration finished!");
@@ -175,7 +171,7 @@ impl ValidatorApiStorage {
// if we have no statuses, the node doesn't exist (or monitor is down), but either way, we can't make a report
if statuses.is_empty() {
return Err(ValidatorApiStorageError::MixnodeReportNotFound(mix_id));
return Err(ValidatorApiStorageError::MixnodeReportNotFound { mix_id });
}
// determine the number of runs the mixnode should have been online for
@@ -219,9 +215,9 @@ impl ValidatorApiStorage {
// if we have no statuses, the node doesn't exist (or monitor is down), but either way, we can't make a report
if statuses.is_empty() {
return Err(ValidatorApiStorageError::GatewayReportNotFound(
identity.to_owned(),
));
return Err(ValidatorApiStorageError::GatewayReportNotFound {
identity: identity.to_owned(),
});
}
// determine the number of runs the gateway should have been online for
@@ -253,9 +249,7 @@ impl ValidatorApiStorage {
let history = self.manager.get_mixnode_historical_uptimes(mix_id).await?;
if history.is_empty() {
return Err(ValidatorApiStorageError::MixnodeUptimeHistoryNotFound(
mix_id,
));
return Err(ValidatorApiStorageError::MixnodeUptimeHistoryNotFound { mix_id });
}
let mixnode_owner =
@@ -286,9 +280,9 @@ impl ValidatorApiStorage {
.await?;
if history.is_empty() {
return Err(ValidatorApiStorageError::GatewayUptimeHistoryNotFound(
identity.to_owned(),
));
return Err(ValidatorApiStorageError::GatewayUptimeHistoryNotFound {
identity: identity.to_owned(),
});
}
let gateway_owner =
@@ -447,30 +441,36 @@ impl ValidatorApiStorage {
let layer1_mix_db_id = self
.manager
.get_mixnode_database_id(test_route.layer_one_mix().mix_id)
.await
.map_err(|_| ValidatorApiStorageError::InternalDatabaseError("".to_string()))?
.ok_or_else(|| ValidatorApiStorageError::InternalDatabaseError("".to_string()))?;
.await?
.ok_or_else(|| ValidatorApiStorageError::DatabaseInconsistency {
reason: format!("could not get db id for layer1 mixnode from network monitor run {monitor_run_db_id}"),
})?;
let layer2_mix_db_id = self
.manager
.get_mixnode_database_id(test_route.layer_two_mix().mix_id)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?
.ok_or_else(|| ValidatorApiStorageError::InternalDatabaseError("".to_string()))?;
.await?
.ok_or_else(|| ValidatorApiStorageError::DatabaseInconsistency {
reason: format!("could not get db id for layer2 mixnode from network monitor run {monitor_run_db_id}"),
})?;
let layer3_mix_db_id = self
.manager
.get_mixnode_database_id(test_route.layer_three_mix().mix_id)
.await
.map_err(|_| ValidatorApiStorageError::InternalDatabaseError("".to_string()))?
.ok_or_else(|| ValidatorApiStorageError::InternalDatabaseError("".to_string()))?;
.await?
.ok_or_else(|| ValidatorApiStorageError::DatabaseInconsistency {
reason: format!("could not get db id for layer3 mixnode from network monitor run {monitor_run_db_id}"),
})?;
let gateway_db_id = self
.manager
.get_gateway_id(&test_route.gateway().identity_key.to_base58_string())
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?
.ok_or_else(|| ValidatorApiStorageError::InternalDatabaseError("".to_string()))?;
.await?
.ok_or_else(|| ValidatorApiStorageError::DatabaseInconsistency {
reason: format!(
"could not get db id for gateway from network monitor run {monitor_run_db_id}"
),
})?;
self.manager
.submit_testing_route_used(TestingRoute {
@@ -480,8 +480,7 @@ impl ValidatorApiStorage {
layer3_mix_db_id,
monitor_run_db_id,
})
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?;
.await?;
Ok(())
}
@@ -498,11 +497,7 @@ impl ValidatorApiStorage {
mix_id: MixId,
since: Option<i64>,
) -> Result<i32, ValidatorApiStorageError> {
let db_id = self
.manager
.get_mixnode_database_id(mix_id)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?;
let db_id = self.manager.get_mixnode_database_id(mix_id).await?;
if let Some(node_id) = db_id {
let since = since
@@ -511,7 +506,7 @@ impl ValidatorApiStorage {
self.manager
.get_mixnode_testing_route_presence_count_since(node_id, since)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))
.map_err(|err| err.into())
} else {
Ok(0)
}
@@ -530,11 +525,7 @@ impl ValidatorApiStorage {
identity: &str,
since: Option<i64>,
) -> Result<i32, ValidatorApiStorageError> {
let node_id = self
.manager
.get_gateway_id(identity)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?;
let node_id = self.manager.get_gateway_id(identity).await?;
if let Some(node_id) = node_id {
let since = since
@@ -543,7 +534,7 @@ impl ValidatorApiStorage {
self.manager
.get_gateway_testing_route_presence_count_since(node_id, since)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))
.map_err(|err| err.into())
} else {
Ok(0)
}
@@ -567,21 +558,15 @@ impl ValidatorApiStorage {
let now = OffsetDateTime::now_utc().unix_timestamp();
let monitor_run_id = self
.manager
.insert_monitor_run(now)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?;
let monitor_run_id = self.manager.insert_monitor_run(now).await?;
self.manager
.submit_mixnode_statuses(now, mixnode_results)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?;
.await?;
self.manager
.submit_gateway_statuses(now, gateway_results)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?;
.await?;
for test_route in test_routes {
self.insert_test_route(monitor_run_id, test_route).await?;
@@ -605,9 +590,9 @@ impl ValidatorApiStorage {
if run_count < 0 {
// I don't think it's ever possible for SQL to return a negative value from COUNT?
return Err(ValidatorApiStorageError::InternalDatabaseError(
"Negative run count".to_string(),
));
return Err(ValidatorApiStorageError::DatabaseInconsistency {
reason: "Negative run count".to_string(),
});
}
Ok(run_count as usize)
}
@@ -629,12 +614,7 @@ impl ValidatorApiStorage {
for report in mixnode_reports {
// if this ever fails, we have a super weird error because we just constructed report for that node
// and we never delete node data!
let node_id = match self
.manager
.get_mixnode_database_id(report.mix_id)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?
{
let node_id = match self.manager.get_mixnode_database_id(report.mix_id).await? {
Some(node_id) => node_id,
None => {
error!(
@@ -647,19 +627,13 @@ impl ValidatorApiStorage {
self.manager
.insert_mixnode_historical_uptime(node_id, today_iso_8601, report.last_day.u8())
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?;
.await?;
}
for report in gateway_reports {
// if this ever fails, we have a super weird error because we just constructed report for that node
// and we never delete node data!
let node_id = match self
.manager
.get_gateway_id(&report.identity)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?
{
let node_id = match self.manager.get_gateway_id(&report.identity).await? {
Some(node_id) => node_id,
None => {
error!(
@@ -672,8 +646,7 @@ impl ValidatorApiStorage {
self.manager
.insert_gateway_historical_uptime(node_id, today_iso_8601, report.last_day.u8())
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?;
.await?;
}
Ok(())
@@ -686,7 +659,7 @@ impl ValidatorApiStorage {
self.manager
.check_for_historical_uptime_existence(date_iso_8601)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))
.map_err(|err| err.into())
}
/// Removes all ipv4 and ipv6 statuses for all mixnodes and gateways that are older than the
@@ -699,14 +672,11 @@ impl ValidatorApiStorage {
&self,
until: i64,
) -> Result<(), ValidatorApiStorageError> {
self.manager
.purge_old_mixnode_statuses(until)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))?;
self.manager.purge_old_mixnode_statuses(until).await?;
self.manager
.purge_old_gateway_statuses(until)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))
.map_err(|err| err.into())
}
pub(crate) async fn insert_rewarding_report(
@@ -716,7 +686,7 @@ impl ValidatorApiStorage {
self.manager
.insert_rewarding_report(report)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))
.map_err(|err| err.into())
}
pub(crate) async fn get_rewarding_report(
@@ -726,7 +696,7 @@ impl ValidatorApiStorage {
self.manager
.get_rewarding_report(absolute_epoch_id)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))
.map_err(|err| err.into())
}
#[cfg(feature = "coconut")]
@@ -737,7 +707,7 @@ impl ValidatorApiStorage {
self.manager
.get_blinded_signature_response(tx_hash)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))
.map_err(|err| err.into())
}
#[cfg(feature = "coconut")]
@@ -749,6 +719,6 @@ impl ValidatorApiStorage {
self.manager
.insert_blinded_signature_response(tx_hash, blinded_signature_response)
.await
.map_err(|e| ValidatorApiStorageError::InternalDatabaseError(e.to_string()))
.map_err(|err| err.into())
}
}