diff --git a/src/certificate.rs b/src/certificate.rs index f8c84ac..f5d6537 100644 --- a/src/certificate.rs +++ b/src/certificate.rs @@ -15,10 +15,11 @@ */ use crate::certificate::CertificateError::{ - CertificateLengthError, DecodeError, ExpirationError, KeyInCertificateError, MalformedRoot, - NoTrustedRoot, VerificationError, + CertificateLengthError, DecodeError, DecodeTrustError, ExpirationError, IncorrectByteLength, + IncorrectCertificateFormat, KeyInCertificateError, MalformedRoot, NoTrustedRoot, + VerificationError, }; -use crate::trust::{Trust, TRUST_LEN}; +use crate::trust::{Trust, TrustError, TRUST_LEN}; use fluence_identity::key_pair::KeyPair; use fluence_identity::public_key::PublicKey; use std::str::FromStr; @@ -40,8 +41,12 @@ pub struct Certificate { #[derive(ThisError, Debug)] pub enum CertificateError { - #[error("Error while decoding a certificate: {0}")] - DecodeError(String), + #[error("Incorrect format of the certificate: {0}")] + IncorrectCertificateFormat(String), + #[error("Incorrect length of an array. Should be 2 bytes of a format, 4 bytes of a version and 104 bytes for each trust")] + IncorrectByteLength, + #[error("Error while decoding a trust in a certificate: {0}")] + DecodeError(TrustError), #[error("Certificate is expired. Issued at {issued_at} and expired at {expires_at}")] ExpirationError { expires_at: String, @@ -50,21 +55,17 @@ pub enum CertificateError { #[error("Certificate does not contain a trusted root.")] NoTrustedRoot, #[error("Root trust did not pass verification: {0}")] - MalformedRoot(String), + MalformedRoot(TrustError), #[error("There is no `issued_by` public key in a certificate")] KeyInCertificateError, #[error("The certificate must have at least 1 trust")] CertificateLengthError, + #[error("Cannot convert trust number {0} from string: {1}")] + DecodeTrustError(usize, TrustError), #[error("Trust {0} in chain did not pass verification: {1}")] - VerificationError(usize, String), - #[error("Unexpected error: {0}")] - Unexpected(String), -} - -impl From for String { - fn from(err: CertificateError) -> Self { - format!("{}", err) - } + VerificationError(usize, TrustError), + #[error("there cannot be paths without any nodes after adding verified certificates")] + Unexpected, } impl Certificate { @@ -156,8 +157,7 @@ impl Certificate { // check root trust and its existence in trusted roots list let root = &chain[0]; - Trust::verify(root, &root.issued_for, cur_time) - .map_err(|e| MalformedRoot(format!("{}", e)))?; + Trust::verify(root, &root.issued_for, cur_time).map_err(|e| MalformedRoot(e))?; if !trusted_roots.contains(&root.issued_for) { return Err(NoTrustedRoot); } @@ -169,7 +169,7 @@ impl Certificate { let trust_giver = &chain[trust_id - 1]; Trust::verify(trust, &trust_giver.issued_for, cur_time) - .map_err(|e| VerificationError(trust_id, format!("{}", e)))?; + .map_err(|e| VerificationError(trust_id, e))?; } Ok(()) @@ -195,7 +195,7 @@ impl Certificate { pub fn decode(arr: &[u8]) -> Result { let trusts_offset = arr.len() - 2 - 4; if trusts_offset % TRUST_LEN != 0 { - return Err(DecodeError("Incorrect length of an array. Should be 2 bytes of a format, 4 bytes of a version and 104 bytes for each trust. ".to_string())); + return Err(IncorrectByteLength); } let number_of_trusts = trusts_offset / TRUST_LEN; @@ -214,7 +214,7 @@ impl Certificate { let from = i * TRUST_LEN + 6; let to = (i + 1) * TRUST_LEN + 6; let slice = &arr[from..to]; - let t = Trust::decode(slice).map_err(|e| DecodeError(format!("{}", e)))?; + let t = Trust::decode(slice).map_err(|e| DecodeError(e))?; chain.push(t); } @@ -244,10 +244,7 @@ impl FromStr for Certificate { let _version = str_lines[1]; if (str_lines.len() - 2) % 4 != 0 { - return Err(DecodeError(format!( - "Incorrect format of the certificate: {}", - s - ))); + return Err(IncorrectCertificateFormat(s.to_string())); } let num_of_trusts = (str_lines.len() - 2) / 4; @@ -260,12 +257,7 @@ impl FromStr for Certificate { str_lines[i + 2], str_lines[i + 3], ) - .map_err(|e| { - DecodeError(format!( - "Cannot convert trust number {} from string: {}", - i, e - )) - })?; + .map_err(|e| DecodeTrustError(i, e))?; trusts.push(trust); } diff --git a/src/public_key_hashable.rs b/src/public_key_hashable.rs index 1bccaa7..0bc0dea 100644 --- a/src/public_key_hashable.rs +++ b/src/public_key_hashable.rs @@ -16,7 +16,9 @@ use fluence_identity::public_key::PublicKey; +use crate::public_key_hashable::PkError::{Base58DecodeError, BytesDecodeError}; use core::fmt; +use ed25519_dalek::SignatureError; use ref_cast::RefCast; use serde::ser::Serializer; use std::str::FromStr; @@ -24,6 +26,7 @@ use std::{ fmt::{Display, Formatter}, hash::{Hash, Hasher}, }; +use thiserror::Error as ThisError; /// Wrapper to use PublicKey in HashMap #[derive(PartialEq, Eq, Debug, Clone, RefCast)] @@ -81,16 +84,23 @@ impl Display for PublicKeyHashable { } } +#[derive(ThisError, Debug)] +pub enum PkError { + #[error("Invalid string '{0}': {1}")] + Base58DecodeError(String, bs58::decode::Error), + #[error("Invalid bytes {0:?}: {1}")] + BytesDecodeError(Vec, SignatureError), +} + impl FromStr for PublicKeyHashable { - type Err = String; + type Err = PkError; fn from_str(s: &str) -> Result { let bytes = bs58::decode(s) .into_vec() - .map_err(|err| format!("Invalid string '{}': {}", s, err))?; + .map_err(|err| Base58DecodeError(s.to_string(), err))?; - let pk = PublicKey::from_bytes(&bytes) - .map_err(|err| format!("Invalid bytes {:?}: {}", bytes, err))?; + let pk = PublicKey::from_bytes(&bytes).map_err(|err| BytesDecodeError(bytes, err))?; Ok(PublicKeyHashable::from(pk)) } } diff --git a/src/trust.rs b/src/trust.rs index 74a5721..8b1a35a 100644 --- a/src/trust.rs +++ b/src/trust.rs @@ -64,11 +64,11 @@ pub enum TrustError { Expired(Duration, Duration), /// Errors occured on signature verification - #[error("{0:?}")] + #[error("{0}")] SignatureError(String), /// Errors occured on trust decoding from differrent formats - #[error("{0:?}")] + #[error("{0}")] DecodeError(String), } diff --git a/src/trust_graph.rs b/src/trust_graph.rs index 7d2f55f..34f9792 100644 --- a/src/trust_graph.rs +++ b/src/trust_graph.rs @@ -21,10 +21,11 @@ use crate::revoke::Revoke; use crate::revoke::RevokeError; use crate::trust::Trust; use crate::trust_graph::TrustGraphError::{ - CertificateCheckError, InternalStorageError, NoRoot, RevokeCheckError, + CertificateCheckError, EmptyChain, InternalStorageError, NoRoot, RevokeCheckError, }; use crate::trust_graph_storage::Storage; use crate::trust_node::{Auth, TrustNode}; +use crate::StorageError; use fluence_identity::public_key::PublicKey; use std::borrow::Borrow; use std::collections::{HashSet, VecDeque}; @@ -50,15 +51,23 @@ where #[derive(ThisError, Debug)] pub enum TrustGraphError { #[error("Internal storage error: {0}")] - InternalStorageError(String), + InternalStorageError(Box), #[error("There is no root for this certificate.")] NoRoot, + #[error("Chain is empty")] + EmptyChain, #[error("Certificate check error: {0}")] CertificateCheckError(CertificateError), #[error("Error on revoking a trust: {0}")] RevokeCheckError(RevokeError), } +impl From for TrustGraphError { + fn from(err: T) -> Self { + InternalStorageError(Box::new(err)) + } +} + impl From for TrustGraphError { fn from(err: CertificateError) -> Self { CertificateCheckError(err) @@ -92,16 +101,12 @@ where pk: PublicKeyHashable, weight: Weight, ) -> Result<(), TrustGraphError> { - self.storage - .add_root_weight(pk, weight) - .map_err(|e| InternalStorageError(e.into())) + Ok(self.storage.add_root_weight(pk, weight)?) } /// Get trust by public key pub fn get(&self, pk: PublicKey) -> Result, TrustGraphError> { - self.storage - .get(&pk.into()) - .map_err(|e| InternalStorageError(e.into())) + Ok(self.storage.get(&pk.into())?) } // TODO: remove cur_time from api, leave it for tests only @@ -112,8 +117,7 @@ where { let roots: Vec = self .storage - .root_keys() - .map_err(|e| InternalStorageError(e.into()))? + .root_keys()? .iter() .cloned() .map(Into::into) @@ -122,28 +126,18 @@ where Certificate::verify(cert.borrow(), roots.as_slice(), cur_time)?; let mut chain = cert.borrow().chain.iter(); - let root_trust = chain - .next() - .ok_or("empty chain") - .map_err(|e| InternalStorageError(e.into()))?; + let root_trust = chain.next().ok_or(EmptyChain)?; let root_pk: PublicKeyHashable = root_trust.issued_for.clone().into(); // Insert new TrustNode for this root_pk if there wasn't one - if self - .storage - .get(&root_pk) - .map_err(|e| InternalStorageError(e.into()))? - .is_none() - { + if self.storage.get(&root_pk)?.is_none() { let mut trust_node = TrustNode::new(root_trust.issued_for.clone(), cur_time); let root_auth = Auth { trust: root_trust.clone(), issued_by: root_trust.issued_for.clone(), }; trust_node.update_auth(root_auth); - self.storage - .insert(root_pk, trust_node) - .map_err(|e| InternalStorageError(e.into()))?; + self.storage.insert(root_pk, trust_node)?; } // Insert remaining trusts to the graph @@ -157,8 +151,7 @@ where }; self.storage - .update_auth(&pk, auth, &root_trust.issued_for, cur_time) - .map_err(|e| InternalStorageError(e.into()))?; + .update_auth(&pk, auth, &root_trust.issued_for, cur_time)?; previous_trust = trust; } @@ -171,18 +164,13 @@ where where P: Borrow, { - if let Some(weight) = self - .storage - .get_root_weight(pk.borrow().as_ref()) - .map_err(|e| InternalStorageError(e.into()))? - { + if let Some(weight) = self.storage.get_root_weight(pk.borrow().as_ref())? { return Ok(Some(weight)); } let roots: Vec = self .storage - .root_keys() - .map_err(|e| InternalStorageError(e.into()))? + .root_keys()? .iter() .map(|pk| pk.clone().into()) .collect(); @@ -220,9 +208,7 @@ where let root_weight = self .storage - .get_root_weight(first.issued_for.as_ref()) - // This panic shouldn't happen // TODO: why? - .map_err(|e| InternalStorageError(e.into()))? + .get_root_weight(first.issued_for.as_ref())? .ok_or(NoRoot)?; // certificate weight = root weight + 1 * every other element in the chain @@ -264,12 +250,8 @@ where let auths: Vec = self .storage - .get(&last.issued_by.clone().into()) - .map_err(|e| InternalStorageError(e.into()))? - .ok_or(CertificateCheckError(Unexpected( - "there cannot be paths without any nodes after adding verified certificates" - .to_string(), - )))? + .get(&last.issued_by.clone().into())? + .ok_or(CertificateCheckError(Unexpected))? .authorizations() .cloned() .collect(); @@ -314,16 +296,10 @@ where P: Borrow, { // get all auths (edges) for issued public key - let issued_for_node = self - .storage - .get(issued_for.borrow().as_ref()) - .map_err(|e| InternalStorageError(e.into()))?; + let issued_for_node = self.storage.get(issued_for.borrow().as_ref())?; let roots = roots.iter().map(|pk| pk.as_ref()); - let keys = self - .storage - .root_keys() - .map_err(|e| InternalStorageError(e.into()))?; + let keys = self.storage.root_keys()?; let roots = keys.iter().chain(roots).collect(); match issued_for_node { @@ -356,9 +332,7 @@ where let pk: PublicKeyHashable = revoke.pk.clone().into(); - self.storage - .revoke(&pk, revoke) - .map_err(|e| InternalStorageError(e.into())) + Ok(self.storage.revoke(&pk, revoke)?) } /// Check information about new certificates and about revoked certificates. diff --git a/src/trust_graph_storage.rs b/src/trust_graph_storage.rs index ffa19c3..3a79302 100644 --- a/src/trust_graph_storage.rs +++ b/src/trust_graph_storage.rs @@ -1,29 +1,29 @@ -use crate::public_key_hashable::PublicKeyHashable; +use crate::public_key_hashable::PublicKeyHashable as PK; use crate::revoke::Revoke; use crate::trust_graph::Weight; use crate::trust_graph_storage::InMemoryStorageError::RevokeError; use crate::trust_node::{Auth, TrustNode}; use fluence_identity::public_key::PublicKey; use std::collections::HashMap; +use std::fmt::Display; use std::time::Duration; use thiserror::Error as ThisError; -pub trait StorageError: std::error::Error {} +pub trait StorageError: std::error::Error + Display {} pub trait Storage { - type Error: StorageError + Into; + type Error: StorageError + 'static; - fn get(&self, pk: &PublicKeyHashable) -> Result, Self::Error>; - fn insert(&mut self, pk: PublicKeyHashable, node: TrustNode) -> Result<(), Self::Error>; + fn get(&self, pk: &PK) -> Result, Self::Error>; + fn insert(&mut self, pk: PK, node: TrustNode) -> Result<(), Self::Error>; - fn get_root_weight(&self, pk: &PublicKeyHashable) -> Result, Self::Error>; - fn add_root_weight(&mut self, pk: PublicKeyHashable, weight: Weight) - -> Result<(), Self::Error>; - fn root_keys(&self) -> Result, Self::Error>; - fn revoke(&mut self, pk: &PublicKeyHashable, revoke: Revoke) -> Result<(), Self::Error>; + fn get_root_weight(&self, pk: &PK) -> Result, Self::Error>; + fn add_root_weight(&mut self, pk: PK, weight: Weight) -> Result<(), Self::Error>; + fn root_keys(&self) -> Result, Self::Error>; + fn revoke(&mut self, pk: &PK, revoke: Revoke) -> Result<(), Self::Error>; fn update_auth( &mut self, - pk: &PublicKeyHashable, + pk: &PK, auth: Auth, issued_for: &PublicKey, cur_time: Duration, @@ -32,8 +32,8 @@ pub trait Storage { #[derive(Debug, Default)] pub struct InMemoryStorage { - nodes: HashMap, - root_weights: HashMap, + nodes: HashMap, + root_weights: HashMap, } impl InMemoryStorage { @@ -64,44 +64,34 @@ pub enum InMemoryStorageError { RevokeError(String), } -impl From for String { - fn from(err: InMemoryStorageError) -> Self { - err.into() - } -} - impl StorageError for InMemoryStorageError {} impl Storage for InMemoryStorage { type Error = InMemoryStorageError; - fn get(&self, pk: &PublicKeyHashable) -> Result, Self::Error> { + fn get(&self, pk: &PK) -> Result, Self::Error> { Ok(self.nodes.get(pk).cloned()) } - fn insert(&mut self, pk: PublicKeyHashable, node: TrustNode) -> Result<(), Self::Error> { + fn insert(&mut self, pk: PK, node: TrustNode) -> Result<(), Self::Error> { &self.nodes.insert(pk, node); Ok(()) } - fn get_root_weight(&self, pk: &PublicKeyHashable) -> Result, Self::Error> { + fn get_root_weight(&self, pk: &PK) -> Result, Self::Error> { Ok(self.root_weights.get(pk).cloned()) } - fn add_root_weight( - &mut self, - pk: PublicKeyHashable, - weight: Weight, - ) -> Result<(), Self::Error> { + fn add_root_weight(&mut self, pk: PK, weight: Weight) -> Result<(), Self::Error> { &self.root_weights.insert(pk, weight); Ok({}) } - fn root_keys(&self) -> Result, Self::Error> { + fn root_keys(&self) -> Result, Self::Error> { Ok(self.root_weights.keys().cloned().map(Into::into).collect()) } - fn revoke(&mut self, pk: &PublicKeyHashable, revoke: Revoke) -> Result<(), Self::Error> { + fn revoke(&mut self, pk: &PK, revoke: Revoke) -> Result<(), Self::Error> { match self.nodes.get_mut(&pk) { Some(trust_node) => { trust_node.update_revoke(revoke); @@ -115,7 +105,7 @@ impl Storage for InMemoryStorage { fn update_auth( &mut self, - pk: &PublicKeyHashable, + pk: &PK, auth: Auth, issued_for: &PublicKey, cur_time: Duration, diff --git a/bin/Cargo.lock b/wasm/Cargo.lock similarity index 100% rename from bin/Cargo.lock rename to wasm/Cargo.lock diff --git a/bin/Cargo.toml b/wasm/Cargo.toml similarity index 100% rename from bin/Cargo.toml rename to wasm/Cargo.toml diff --git a/bin/Config.toml b/wasm/Config.toml similarity index 100% rename from bin/Config.toml rename to wasm/Config.toml diff --git a/bin/run-repl.sh b/wasm/run-repl.sh similarity index 100% rename from bin/run-repl.sh rename to wasm/run-repl.sh diff --git a/bin/src/proxy_structs.rs b/wasm/src/dto.rs similarity index 76% rename from bin/src/proxy_structs.rs rename to wasm/src/dto.rs index 9178854..60302a3 100644 --- a/bin/src/proxy_structs.rs +++ b/wasm/src/dto.rs @@ -1,14 +1,13 @@ use fluence::fce; -use trust_graph::{Certificate as TGCertificate, Trust as TGTrust}; #[fce] pub struct Certificate { pub chain: Vec, } -impl From for Certificate { - fn from(t: TGCertificate) -> Self { - let chain: Vec = t.chain.into_iter().map(|t| t.into()).collect(); +impl From for Certificate { + fn from(c: trust_graph::Certificate) -> Self { + let chain: Vec = c.chain.into_iter().map(|t| t.into()).collect(); return Certificate { chain }; } } @@ -26,8 +25,8 @@ pub struct Trust { pub issued_at: u64, } -impl From for Trust { - fn from(t: TGTrust) -> Self { +impl From for Trust { + fn from(t: trust_graph::Trust) -> Self { let issued_for = bs58::encode(t.issued_for.to_bytes()).into_string(); let signature = bs58::encode(t.signature.to_bytes()).into_string(); let expires_at = t.expires_at.as_secs(); diff --git a/bin/src/main.rs b/wasm/src/main.rs similarity index 95% rename from bin/src/main.rs rename to wasm/src/main.rs index 6152877..2b1848b 100644 --- a/bin/src/main.rs +++ b/wasm/src/main.rs @@ -1,6 +1,6 @@ use fluence::WasmLoggerBuilder; -mod proxy_structs; +mod dto; mod results; mod service_api; mod storage_impl; diff --git a/bin/src/results.rs b/wasm/src/results.rs similarity index 97% rename from bin/src/results.rs rename to wasm/src/results.rs index 714d6d5..fa8cdee 100644 --- a/bin/src/results.rs +++ b/wasm/src/results.rs @@ -1,4 +1,4 @@ -use crate::proxy_structs::Certificate; +use crate::dto::Certificate; use fluence::fce; #[fce] diff --git a/bin/src/service_api.rs b/wasm/src/service_api.rs similarity index 84% rename from bin/src/service_api.rs rename to wasm/src/service_api.rs index b0868a3..9ac8de7 100644 --- a/bin/src/service_api.rs +++ b/wasm/src/service_api.rs @@ -1,17 +1,16 @@ -use crate::proxy_structs::Certificate; +use crate::dto::Certificate; use crate::results::{AllCertsResult, InsertResult, WeightResult}; use crate::storage_impl::get_data; use fluence::fce; use fluence_identity::{KeyPair, PublicKey}; -use std::convert::{From, Into}; -use std::fmt::Display; +use std::convert::Into; use std::str::FromStr; use std::time::Duration; -use trust_graph::Certificate as TGCertificate; fn insert_cert_impl(certificate: String, duration: u64) -> Result<(), String> { let duration = Duration::from_millis(duration); - let certificate = TGCertificate::from_str(&certificate)?; + let certificate = + trust_graph::Certificate::from_str(&certificate).map_err(|e| format!("{}", e))?; let mut tg = get_data().lock(); tg.add(certificate, duration)?; @@ -25,7 +24,7 @@ fn insert_cert(certificate: String, duration: u64) -> InsertResult { } fn get_weight_impl(public_key: String) -> Result, String> { - let mut tg = get_data().lock(); + let tg = get_data().lock(); let public_key = string_to_public_key(public_key)?; @@ -49,12 +48,13 @@ fn string_to_public_key(public_key: String) -> Result { Ok(public_key) } +#[fce] fn get_all_certs(issued_for: String) -> AllCertsResult { get_all_certs_impl(issued_for).into() } fn get_all_certs_impl(issued_for: String) -> Result, String> { - let mut tg = get_data().lock(); + let tg = get_data().lock(); let public_key = string_to_public_key(issued_for)?; let certs = tg.get_all_certs(public_key, &[])?; @@ -72,7 +72,12 @@ fn test() -> String { let expires_at = Duration::new(15, 15); let issued_at = Duration::new(5, 5); - let cert = TGCertificate::issue_root(&root_kp, second_kp.public_key(), expires_at, issued_at); + let cert = trust_graph::Certificate::issue_root( + &root_kp, + second_kp.public_key(), + expires_at, + issued_at, + ); tg.add_root_weight(root_kp.public().into(), 0).unwrap(); tg.add_root_weight(root_kp2.public().into(), 1).unwrap(); tg.add(cert, Duration::new(10, 10)).unwrap(); diff --git a/bin/src/storage_impl.rs b/wasm/src/storage_impl.rs similarity index 71% rename from bin/src/storage_impl.rs rename to wasm/src/storage_impl.rs index 256ff36..5176e33 100644 --- a/bin/src/storage_impl.rs +++ b/wasm/src/storage_impl.rs @@ -2,8 +2,9 @@ // check if trust is already in list before adding // if there is an older trust - don't add received trust -use crate::storage_impl::SqliteStorageError::{ - ConvertionError, DecodeError, EncodeError, RevokeError, SqliteError, Unexpected, +use crate::storage_impl::SQLiteStorageError::{ + DecodeError, EncodeError, PublcKeyNotFound, PublicKeyConversion, PublicKeyFromStr, SQLiteError, + TrustNodeConversion, WeightConversionDB, }; use core::convert::TryFrom; use fce_sqlite_connector; @@ -23,9 +24,9 @@ use trust_graph::{ Auth, PublicKeyHashable, Revoke, Storage, StorageError, TrustGraph, TrustNode, Weight, }; -static INSTANCE: OnceCell>> = OnceCell::new(); +static INSTANCE: OnceCell>> = OnceCell::new(); -pub fn get_data() -> &'static Mutex> { +pub fn get_data() -> &'static Mutex> { INSTANCE.get_or_init(|| { let db_path = "/tmp/users123123.sqlite"; let connection = fce_sqlite_connector::open(db_path).unwrap(); @@ -41,64 +42,68 @@ pub fn get_data() -> &'static Mutex> { connection.execute(init_sql).expect("cannot connect to db"); - Mutex::new(TrustGraph::new(Box::new(SqliteStorage::new(connection)))) + Mutex::new(TrustGraph::new(Box::new(SQLiteStorage::new(connection)))) }) } -pub struct SqliteStorage { +pub struct SQLiteStorage { connection: Connection, } -impl SqliteStorage { - pub fn new(connection: Connection) -> SqliteStorage { - SqliteStorage { connection } +impl SQLiteStorage { + pub fn new(connection: Connection) -> SQLiteStorage { + SQLiteStorage { connection } } } #[derive(ThisError, Debug)] -pub enum SqliteStorageError { - #[error("Unexpected: {0}")] - Unexpected(String), +pub enum SQLiteStorageError { #[error("{0}")] - SqliteError(InternalSqliteError), + SQLiteError(InternalSqliteError), #[error("{0}")] - EncodeError(String), + PublicKeyFromStr(String), #[error("{0}")] - DecodeError(String), - #[error("There is no entry for {0}")] - ConvertionError(String), - #[error("Cannot revoke a trust: {0}")] - RevokeError(String), + EncodeError(RmpEncodeError), + #[error("{0}")] + DecodeError(RmpDecodeError), + #[error("Cannot convert weight as integer from DB")] + WeightConversionDB, + #[error("Cannot convert public key as binary from DB")] + PublicKeyConversion, + #[error("Cannot convert trust node as binary from DB")] + TrustNodeConversion, + #[error("Cannot revoke. There is no trust with such PublicKey")] + PublcKeyNotFound, } -impl From for SqliteStorageError { +impl From for SQLiteStorageError { fn from(err: InternalSqliteError) -> Self { - SqliteError(err) + SQLiteError(err) } } -impl From for SqliteStorageError { +impl From for SQLiteStorageError { fn from(err: RmpEncodeError) -> Self { - EncodeError(format!("{}", err)) + EncodeError(err) } } -impl From for SqliteStorageError { +impl From for SQLiteStorageError { fn from(err: RmpDecodeError) -> Self { - DecodeError(format!("{}", err)) + DecodeError(err) } } -impl From for String { - fn from(err: SqliteStorageError) -> Self { +impl From for String { + fn from(err: SQLiteStorageError) -> Self { err.into() } } -impl StorageError for SqliteStorageError {} +impl StorageError for SQLiteStorageError {} -impl Storage for SqliteStorage { - type Error = SqliteStorageError; +impl Storage for SQLiteStorage { + type Error = SQLiteStorageError; fn get(&self, pk: &PublicKeyHashable) -> Result, Self::Error> { let mut cursor = self @@ -111,9 +116,7 @@ impl Storage for SqliteStorage { match cursor.next().unwrap() { Some(r) => { log::info!("row: {:?}", r); - let tn_bin: &[u8] = r[0].as_binary().ok_or(ConvertionError( - "cannot get trustnode as binary".to_string(), - ))?; + let tn_bin: &[u8] = r[0].as_binary().ok_or(TrustNodeConversion)?; log::info!("binary: {:?}", tn_bin); @@ -155,12 +158,8 @@ impl Storage for SqliteStorage { if let Some(row) = cursor.next()? { log::info!("row: {:?}", row); - let w = u32::try_from( - row[1] - .as_integer() - .ok_or(ConvertionError("cannot get weight as integer".to_string()))?, - ) - .map_err(|e| Unexpected(format!("Unexpected. Cannot convert weight to u32: {}", e)))?; + let w = u32::try_from(row[1].as_integer().ok_or(WeightConversionDB)?) + .map_err(|_e| WeightConversionDB)?; Ok(Some(w)) } else { @@ -198,11 +197,9 @@ impl Storage for SqliteStorage { while let Some(row) = cursor.next()? { log::info!("row: {:?}", row); - let pk = row[0].as_string().ok_or(ConvertionError( - "cannot get public key as binary".to_string(), - ))?; + let pk = row[0].as_string().ok_or(PublicKeyConversion)?; let pk: PublicKeyHashable = - PublicKeyHashable::from_str(pk).map_err(|e| DecodeError(e.to_string()))?; + PublicKeyHashable::from_str(pk).map_err(|e| PublicKeyFromStr(e.to_string()))?; roots.push(pk) } @@ -217,9 +214,7 @@ impl Storage for SqliteStorage { self.insert(pk.clone(), trust_node)?; Ok(()) } - None => Err(RevokeError( - "There is no trust with such PublicKey".to_string(), - )), + None => Err(PublcKeyNotFound), } }