From a18ecfba0f76434b4a52db31cd961c434630d0eb Mon Sep 17 00:00:00 2001 From: Vaibhav Dixit Date: Fri, 9 Jun 2023 14:45:35 +0530 Subject: [PATCH] refactor: delete error.rs (#226) * refactor: delete error.rs * fix: BdkError semantics --------- Co-authored-by: bodymindarts --- src/account/keys/repo.rs | 4 +- src/admin/error.rs | 20 ++++---- src/api/server/convert.rs | 21 +++------ src/api/server/mod.rs | 12 ++--- src/app/error.rs | 4 ++ src/bdk/error.rs | 2 + src/bdk/pg/transactions.rs | 6 +-- src/bdk/pg/utxos.rs | 4 +- src/error.rs | 97 -------------------------------------- src/job/error.rs | 2 +- src/job/mod.rs | 8 ++-- src/ledger/mod.rs | 4 +- src/lib.rs | 1 - src/xpub/error.rs | 2 + src/xpub/reference.rs | 2 +- src/xpub/value.rs | 13 ++--- 16 files changed, 51 insertions(+), 151 deletions(-) delete mode 100644 src/error.rs diff --git a/src/account/keys/repo.rs b/src/account/keys/repo.rs index f292d995..9be6cfd0 100644 --- a/src/account/keys/repo.rs +++ b/src/account/keys/repo.rs @@ -19,7 +19,7 @@ impl AccountApiKeys { tx: &mut sqlx::Transaction<'_, Postgres>, name: String, account_id: AccountId, - ) -> Result { + ) -> Result { let code = Alphanumeric.sample_string(&mut rand::thread_rng(), 64); let key = format!("bria_{code}"); let record = sqlx::query!( @@ -39,7 +39,7 @@ impl AccountApiKeys { }) } - pub async fn find_by_key(&self, key: &str) -> Result { + pub async fn find_by_key(&self, key: &str) -> Result { let record = sqlx::query!( r#"SELECT id, account_id, name FROM bria_account_api_keys WHERE encrypted_key = crypt($1, encrypted_key)"#, key diff --git a/src/admin/error.rs b/src/admin/error.rs index 6d905c5a..1e646d20 100644 --- a/src/admin/error.rs +++ b/src/admin/error.rs @@ -1,7 +1,9 @@ -use sqlx_ledger::SqlxLedgerError; use thiserror::Error; -use crate::{account::error::AccountError, error::*, profile::error::ProfileError}; +use crate::{ + account::error::AccountError, app::error::ApplicationError, ledger::error::LedgerError, + profile::error::ProfileError, +}; #[allow(clippy::large_enum_variant)] #[derive(Error, Debug)] @@ -10,23 +12,23 @@ pub enum AdminApiError { TonicError(#[from] tonic::transport::Error), #[error("AdminApiError - SqlxError: {0}")] SqlxError(#[from] sqlx::Error), - #[error("AdminApiError - SqlxLedgerError: {0}")] - SqlxLedgerError(#[from] SqlxLedgerError), #[error("AdminApiError - BriaError: {0}")] - BriaError(BriaError), + BriaError(ApplicationError), #[error("AdminApiError - BadNetworkForDev")] BadNetworkForDev, #[error("{0}")] AccountError(#[from] AccountError), #[error("{0}")] ProfileError(#[from] ProfileError), + #[error("{0}")] + LedgerError(#[from] LedgerError), } -impl From for AdminApiError { - fn from(err: BriaError) -> Self { +impl From for AdminApiError { + fn from(err: ApplicationError) -> Self { match err { - BriaError::Sqlx(e) => AdminApiError::SqlxError(e), - BriaError::Tonic(e) => AdminApiError::TonicError(e), + ApplicationError::Sqlx(e) => AdminApiError::SqlxError(e), + ApplicationError::ServerError(e) => AdminApiError::TonicError(e), e => AdminApiError::BriaError(e), } } diff --git a/src/api/server/convert.rs b/src/api/server/convert.rs index 97cde102..a4b76f09 100644 --- a/src/api/server/convert.rs +++ b/src/api/server/convert.rs @@ -5,7 +5,6 @@ use crate::{ account::balance::AccountBalanceSummary, address::*, app::error::*, - error::BriaError, outbox::*, payout::*, payout_queue::*, @@ -19,20 +18,6 @@ use crate::{ xpub::*, }; -impl From for tonic::Status { - fn from(err: BriaError) -> Self { - match err { - BriaError::CouldNotParseIncomingMetadata(err) => { - tonic::Status::invalid_argument(err.to_string()) - } - BriaError::CouldNotParseIncomingUuid(err) => { - tonic::Status::invalid_argument(err.to_string()) - } - _ => tonic::Status::new(tonic::Code::Unknown, format!("{err}")), - } - } -} - impl From for proto::Profile { fn from(p: Profile) -> Self { Self { @@ -525,6 +510,12 @@ impl From for tonic::Status { ApplicationError::PayoutError(PayoutError::PayoutIdNotFound(_)) => { tonic::Status::not_found(err.to_string()) } + ApplicationError::CouldNotParseIncomingMetadata(err) => { + tonic::Status::invalid_argument(err.to_string()) + } + ApplicationError::CouldNotParseIncomingUuid(err) => { + tonic::Status::invalid_argument(err.to_string()) + } _ => tonic::Status::internal(err.to_string()), } } diff --git a/src/api/server/mod.rs b/src/api/server/mod.rs index 3d512aea..8b91f0b0 100644 --- a/src/api/server/mod.rs +++ b/src/api/server/mod.rs @@ -19,7 +19,6 @@ use proto::{bria_service_server::BriaService, *}; use super::config::*; use crate::{ app::{error::ApplicationError, *}, - error::*, payout_queue, primitives::*, }; @@ -280,7 +279,7 @@ impl BriaService for Bria { metadata .map(serde_json::to_value) .transpose() - .map_err(BriaError::CouldNotParseIncomingMetadata)?, + .map_err(ApplicationError::CouldNotParseIncomingMetadata)?, ) .await?; Ok(Response::new(NewAddressResponse { address })) @@ -313,7 +312,7 @@ impl BriaService for Bria { new_metadata .map(serde_json::to_value) .transpose() - .map_err(BriaError::CouldNotParseIncomingMetadata)?, + .map_err(ApplicationError::CouldNotParseIncomingMetadata)?, ) .await?; Ok(Response::new(UpdateAddressResponse {})) @@ -496,7 +495,7 @@ impl BriaService for Bria { metadata .map(serde_json::to_value) .transpose() - .map_err(BriaError::CouldNotParseIncomingMetadata)?, + .map_err(ApplicationError::CouldNotParseIncomingMetadata)?, ) .await?; Ok(Response::new(SubmitPayoutResponse { id: id.to_string() })) @@ -593,7 +592,8 @@ impl BriaService for Bria { self.app .update_payout_queue( profile, - id.parse().map_err(BriaError::CouldNotParseIncomingUuid)?, + id.parse() + .map_err(ApplicationError::CouldNotParseIncomingUuid)?, new_description, new_config.map(payout_queue::PayoutQueueConfig::from), ) @@ -620,7 +620,7 @@ impl BriaService for Bria { profile, batch_id .parse() - .map_err(BriaError::CouldNotParseIncomingUuid)?, + .map_err(ApplicationError::CouldNotParseIncomingUuid)?, ) .await?; diff --git a/src/app/error.rs b/src/app/error.rs index 8189ea14..3cbdbf5a 100644 --- a/src/app/error.rs +++ b/src/app/error.rs @@ -47,4 +47,8 @@ pub enum ApplicationError { ServerError(#[from] tonic::transport::Error), #[error("ApplicationError - UnsupportedPubKeyType")] UnsupportedPubKeyType, + #[error("ApplicationError - CouldNotParseIncomingMetadata: {0}")] + CouldNotParseIncomingMetadata(serde_json::Error), + #[error("ApplicationError - CouldNotParseIncomingUuid: {0}")] + CouldNotParseIncomingUuid(uuid::Error), } diff --git a/src/bdk/error.rs b/src/bdk/error.rs index 3dee51b2..b65f8538 100644 --- a/src/bdk/error.rs +++ b/src/bdk/error.rs @@ -10,4 +10,6 @@ pub enum BdkError { ElectrumClient(#[from] electrum_client::Error), #[error("BdkError - Sqlx: {0}")] Sqlx(#[from] sqlx::Error), + #[error("BdkError - Serde: {0}")] + Serde(#[from] serde_json::Error), } diff --git a/src/bdk/pg/transactions.rs b/src/bdk/pg/transactions.rs index 2542cf2f..3aab7393 100644 --- a/src/bdk/pg/transactions.rs +++ b/src/bdk/pg/transactions.rs @@ -3,7 +3,7 @@ use sqlx::{PgPool, Postgres, QueryBuilder, Transaction}; use tracing::instrument; use uuid::Uuid; -use crate::{bdk::error::BdkError, error::*, primitives::*}; +use crate::{bdk::error::BdkError, primitives::*}; #[derive(Debug)] pub struct UnsyncedTransaction { @@ -96,7 +96,7 @@ impl Transactions { pub async fn find_unsynced_tx( &self, excluded_tx_ids: &[String], - ) -> Result, BriaError> { + ) -> Result, BdkError> { let rows = sqlx::query!( r#"WITH tx_to_sync AS ( SELECT tx_id, details_json, height @@ -169,7 +169,7 @@ impl Transactions { &self, tx: &mut Transaction<'_, Postgres>, min_height: u32, - ) -> Result, BriaError> { + ) -> Result, BdkError> { let rows = sqlx::query!(r#" WITH tx_to_sync AS ( UPDATE bdk_transactions SET confirmation_synced_to_bria = true, modified_at = NOW() diff --git a/src/bdk/pg/utxos.rs b/src/bdk/pg/utxos.rs index 171096fd..5f733b08 100644 --- a/src/bdk/pg/utxos.rs +++ b/src/bdk/pg/utxos.rs @@ -3,7 +3,7 @@ use sqlx::{PgPool, Postgres, QueryBuilder, Transaction}; use tracing::instrument; use uuid::Uuid; -use crate::{bdk::error::BdkError, error::*, primitives::*}; +use crate::{bdk::error::BdkError, primitives::*}; pub struct ConfirmedIncomeUtxo { pub outpoint: bitcoin::OutPoint, @@ -106,7 +106,7 @@ impl Utxos { &self, tx: &mut Transaction<'_, Postgres>, min_height: u32, - ) -> Result, BriaError> { + ) -> Result, BdkError> { let row = sqlx::query!( r#"WITH updated_utxo AS ( UPDATE bdk_utxos SET confirmation_synced_to_bria = true, modified_at = NOW() diff --git a/src/error.rs b/src/error.rs deleted file mode 100644 index 943da3cd..00000000 --- a/src/error.rs +++ /dev/null @@ -1,97 +0,0 @@ -use thiserror::Error; - -use crate::{ - address::error::AddressError, - bdk::error::BdkError, - job::JobExecutionError, - payout::error::PayoutError, - payout_queue::error::PayoutQueueError, - primitives::bitcoin::{bip32, consensus, psbt, AddressError as BitcoinAddressError}, - wallet::error::WalletError, - xpub::SigningClientError, -}; - -#[derive(Error, Debug)] -pub enum BriaError { - #[error("BriaError - BdkError: {0}")] - BdkError(#[from] BdkError), - #[error("BriaError - WalletError: {0}")] - WalletError(#[from] WalletError), - #[error("BriaError - PayoutError: {0}")] - PayoutError(#[from] PayoutError), - #[error("BriaError - AddressError: {0}")] - AddressError(#[from] AddressError), - #[error("BriaError - PayoutQueueError: {0}")] - PayoutQueueError(#[from] PayoutQueueError), - - #[error("BriaError - FromHex: {0}")] - FromHex(#[from] hex::FromHexError), - #[error("BriaError - Tonic: {0}")] - Tonic(#[from] tonic::transport::Error), - #[error("BriaError - Sqlx: {0}")] - Sqlx(#[from] sqlx::Error), - #[error("BriaError - Migrate: {0}")] - Migrate(#[from] sqlx::migrate::MigrateError), - #[error("BriaError - ParseId: {0}")] - ParseId(#[from] uuid::Error), - #[error("BriaError - SqlxLedger: {0}")] - SqlxLedger(#[from] sqlx_ledger::SqlxLedgerError), - #[error("BriaError - SerdeJson: {0}")] - SerdeJson(#[from] serde_json::Error), - #[error("BriaError - psbt::Error: {0}")] - PsbtError(#[from] psbt::Error), - #[error("BriaError - EventStreamError: {0}")] - EventStreamError(#[from] tokio_stream::wrappers::errors::BroadcastStreamRecvError), - #[error("BriaError - SendEventError")] - SendEventError, - #[error("BriaError - MissingTxMetadata")] - MissingTxMetadata, - #[error("BriaError - SigningClientError: {0}")] - SigningClient(#[from] SigningClientError), - #[error("BriaError - EntityError: {0}")] - EntityError(#[from] crate::entity::EntityError), - #[error("BriaError - Bip32: {0}")] - Bip32(#[from] bip32::Error), - #[error("BriaError - WalletNotFound")] - WalletNotFound, - #[error("BriaError - PayoutNotFound")] - PayoutNotFound, - #[error("BriaError - ProfileNotFound")] - ProfileNotFound, - #[error("BriaError - BatchSigningSessionNotFound")] - BatchSigningSessionNotFound, - #[error("BriaError - CouldNotRetrieveWalletBalance")] - CouldNotRetrieveWalletBalance, - #[error("BriaError - PayoutQueueNotFound({0})")] - PayoutQueueNotFound(String), - #[error("BriaError - BatchNotFound")] - BatchNotFound, - #[error("BriaError - PsbtMissingInSigningSessions")] - PsbtMissingInSigningSessions, - #[error("BriaError - DescriptorAlreadyInUse")] - DescriptorAlreadyInUse, - #[error("BriaError - BitcoinConsensusEncodeError: {0}")] - BitcoinConsensusEncodeError(#[from] consensus::encode::Error), - #[error("BriaError - TryFromIntError")] - TryFromIntError(#[from] std::num::TryFromIntError), - #[error("BriaError - BitcoinAddressParseError")] - BitcoinAddressParseError(#[from] BitcoinAddressError), - #[error("BriaError - XPubDepthMismatch: expected depth {0}, got {1}")] - XPubDepthMismatch(u8, usize), - #[error("BriaError - XPubParseError: {0}")] - XPubParseError(bdk::bitcoin::util::base58::Error), - #[error("BriaError - UnsupportedPubKeyType")] - UnsupportedPubKeyType, - #[error("BriaError - BdkMiniscriptError: {0}")] - BdkMiniscriptError(#[from] bdk::miniscript::Error), - #[error("BriaError - FeeEstimation: {0}")] - FeeEstimation(reqwest::Error), - #[error("BriaError - CouldNotCombinePsbts: {0}")] - CouldNotCombinePsbts(psbt::Error), - #[error("BriaError - CouldNotParseIncomingMetadata: {0}")] - CouldNotParseIncomingMetadata(serde_json::Error), - #[error("BriaError - CouldNotParseIncomingUuid: {0}")] - CouldNotParseIncomingUuid(uuid::Error), -} - -impl JobExecutionError for BriaError {} diff --git a/src/job/error.rs b/src/job/error.rs index d75c46f9..d1a562a6 100644 --- a/src/job/error.rs +++ b/src/job/error.rs @@ -55,7 +55,7 @@ pub enum JobError { Sqlx(#[from] sqlx::Error), #[error("JobError - PsbtMissingInSigningSessions")] PsbtMissingInSigningSessions, - #[error("BriaError - psbt::Error: {0}")] + #[error("JobError - psbt::Error: {0}")] PsbtError(#[from] psbt::Error), } diff --git a/src/job/mod.rs b/src/job/mod.rs index c04078f0..79dd88db 100644 --- a/src/job/mod.rs +++ b/src/job/mod.rs @@ -16,9 +16,9 @@ use tracing::instrument; use uuid::{uuid, Uuid}; use crate::{ - account::*, address::Addresses, app::BlockchainConfig, batch::*, error::*, - fees::MempoolSpaceClient, ledger::Ledger, outbox::*, payout::*, payout_queue::*, primitives::*, - signing_session::*, utxo::Utxos, wallet::*, xpub::*, + account::*, address::Addresses, app::BlockchainConfig, batch::*, fees::MempoolSpaceClient, + ledger::Ledger, outbox::*, payout::*, payout_queue::*, primitives::*, signing_session::*, + utxo::Utxos, wallet::*, xpub::*, }; use batch_broadcasting::BatchBroadcastingData; use batch_signing::BatchSigningData; @@ -442,7 +442,7 @@ async fn spawn_schedule_process_payout_queue( pool: &sqlx::PgPool, data: impl Into, delay: std::time::Duration, -) -> Result<(), BriaError> { +) -> Result<(), JobError> { let data = data.into(); match JobBuilder::new_with_id( Uuid::from(data.payout_queue_id), diff --git a/src/ledger/mod.rs b/src/ledger/mod.rs index 26e405df..e33d630f 100644 --- a/src/ledger/mod.rs +++ b/src/ledger/mod.rs @@ -14,7 +14,7 @@ use tracing::instrument; use std::collections::HashMap; -use crate::{account::balance::*, error::*, primitives::*}; +use crate::{account::balance::*, primitives::*}; use constants::*; use error::LedgerError; pub use event::*; @@ -413,7 +413,7 @@ impl Ledger { tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, id: AccountId, account_name: String, - ) -> Result { + ) -> Result { let new_journal = NewJournal::builder() .id(id) .description(format!("Journal for account '{account_name}'")) diff --git a/src/lib.rs b/src/lib.rs index 3456c574..9f3d5b53 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,7 +12,6 @@ pub mod cli; pub mod descriptor; mod dev_constants; mod entity; -mod error; pub mod fees; mod job; pub mod ledger; diff --git a/src/xpub/error.rs b/src/xpub/error.rs index f47afb46..880dcece 100644 --- a/src/xpub/error.rs +++ b/src/xpub/error.rs @@ -16,4 +16,6 @@ pub enum XPubError { XPubParseError(bdk::bitcoin::util::base58::Error), #[error("XPubError - Bip32: {0}")] Bip32(#[from] crate::primitives::bitcoin::bip32::Error), + #[error("XPubError - UnsupportedPubKeyType")] + UnsupportedPubKeyType, } diff --git a/src/xpub/reference.rs b/src/xpub/reference.rs index 2b40acea..ffea6180 100644 --- a/src/xpub/reference.rs +++ b/src/xpub/reference.rs @@ -6,7 +6,7 @@ pub enum XPubRef { } impl std::str::FromStr for XPubRef { - type Err = crate::error::BriaError; + type Err = super::error::XPubError; fn from_str(s: &str) -> Result { if let Ok(id) = XPubId::from_str(s) { diff --git a/src/xpub/value.rs b/src/xpub/value.rs index 7735906f..28477acd 100644 --- a/src/xpub/value.rs +++ b/src/xpub/value.rs @@ -3,12 +3,9 @@ use serde::{Deserialize, Serialize}; use std::fmt; use super::error::XPubError; -use crate::{ - error::*, - primitives::{ - bitcoin::{DerivationPath, ExtendedPubKey}, - XPubId, - }, +use crate::primitives::{ + bitcoin::{DerivationPath, ExtendedPubKey}, + XPubId, }; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] @@ -42,12 +39,12 @@ impl fmt::Display for XPub { } impl TryFrom<&DescriptorPublicKey> for XPub { - type Error = BriaError; + type Error = XPubError; fn try_from(pk: &DescriptorPublicKey) -> Result { let derivation_path = pk.full_derivation_path(); match pk { - DescriptorPublicKey::Single(_) => Err(BriaError::UnsupportedPubKeyType), + DescriptorPublicKey::Single(_) => Err(XPubError::UnsupportedPubKeyType), DescriptorPublicKey::XPub(inner) => Ok(Self { derivation: Some(derivation_path), inner: inner.xkey,