diff --git a/bin/Cargo.lock b/bin/Cargo.lock index 425b0ae..2eb3a9f 100644 --- a/bin/Cargo.lock +++ b/bin/Cargo.lock @@ -984,12 +984,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" -[[package]] -name = "pkg-config" -version = "0.3.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c" - [[package]] name = "ppv-lite86" version = "0.2.10" @@ -1421,36 +1415,6 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" -[[package]] -name = "sqlite" -version = "0.25.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35f759dc2e373e1edd0a27da87aa9136416360c5077a23643fcd6fcdc9cb9e31" -dependencies = [ - "libc", - "sqlite3-sys", -] - -[[package]] -name = "sqlite3-src" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8bb25e66d026488228a97e0ad21e3d15ec5998dcd9ad73c97cc277c56a6b314" -dependencies = [ - "cc", - "pkg-config", -] - -[[package]] -name = "sqlite3-sys" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71fec807a1534bd13eeaaec396175d67c79bdc68df55e18a452726ec62a8fb08" -dependencies = [ - "libc", - "sqlite3-src", -] - [[package]] name = "static_assertions" version = "1.1.0" @@ -1593,7 +1557,6 @@ dependencies = [ "rmp-serde", "serde_bencode", "serde_json", - "sqlite", "thiserror", "trust-graph", ] diff --git a/bin/Cargo.toml b/bin/Cargo.toml index 0c614ca..69c1ad0 100644 --- a/bin/Cargo.toml +++ b/bin/Cargo.toml @@ -25,5 +25,4 @@ bs58 = "0.3.1" rmp-serde = "0.15.0" bincode = "1.3.1" serde_bencode = "^0.2.3" -sqlite = "0.25.3" thiserror = "1.0.23" diff --git a/bin/src/service_api.rs b/bin/src/service_api.rs index 5ba6d5f..70d41aa 100644 --- a/bin/src/service_api.rs +++ b/bin/src/service_api.rs @@ -1,28 +1,44 @@ use crate::storage_impl::get_data; use fluence::fce; use fluence_identity::KeyPair; +use std::convert::{From, Into}; +use std::fmt::Display; +use std::str::FromStr; use std::time::Duration; use trust_graph::Certificate; -use std::str::FromStr; struct InsertResult { ret_code: u32, error: String, } -// TODO: some sort of auth? -fn insert_cert(certificate: String, duration: u64) -> InsertResult { +impl From> for InsertResult { + fn from(result: Result<(), String>) -> Self { + match result { + Ok(()) => InsertResult { + ret_code: 0, + error: "".to_string(), + }, + Err(e) => InsertResult { + ret_code: 1, + error: e, + }, + } + } +} +fn insert_cert_impl(certificate: String, duration: u64) -> Result<(), String> { let duration = Duration::from_millis(duration); - let certificate = Certificate::from_str(&certificate).unwrap(); + let certificate = Certificate::from_str(&certificate)?; let mut tg = get_data().lock(); - tg.add(certificate, duration).unwrap(); + tg.add(certificate, duration)?; + Ok(()) +} - return InsertResult { - ret_code: 0, - error: "".to_string() - } +// TODO: some sort of auth? +fn insert_cert(certificate: String, duration: u64) -> InsertResult { + insert_cert_impl(certificate, duration).into() } #[fce] diff --git a/bin/src/storage_impl.rs b/bin/src/storage_impl.rs index 3ce2ef8..256ff36 100644 --- a/bin/src/storage_impl.rs +++ b/bin/src/storage_impl.rs @@ -2,22 +2,26 @@ // 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 core::convert::TryFrom; +use fce_sqlite_connector; +use fce_sqlite_connector::Connection; +use fce_sqlite_connector::Error as InternalSqliteError; +use fce_sqlite_connector::Value; use fluence_identity::public_key::PublicKey; use once_cell::sync::OnceCell; use parking_lot::Mutex; -use fce_sqlite_connector; -use fce_sqlite_connector::Connection; -use fce_sqlite_connector::Value; -use fce_sqlite_connector::Error as InternalSqliteError; +use rmp_serde::decode::Error as RmpDecodeError; +use rmp_serde::encode::Error as RmpEncodeError; +use std::convert::From; use std::str::FromStr; use std::time::Duration; -use trust_graph::{Auth, PublicKeyHashable, Revoke, Storage, TrustGraph, TrustNode, Weight, StorageError}; use thiserror::Error as ThisError; -use crate::storage_impl::SqliteStorageError::{SqliteError, EncodeError, ConvertionError, DecodeError, Unexpected, RevokeError}; -use rmp_serde::encode::Error as RmpEncodeError; -use rmp_serde::decode::Error as RmpDecodeError; -use std::convert::From; +use trust_graph::{ + Auth, PublicKeyHashable, Revoke, Storage, StorageError, TrustGraph, TrustNode, Weight, +}; static INSTANCE: OnceCell>> = OnceCell::new(); @@ -64,7 +68,7 @@ pub enum SqliteStorageError { #[error("There is no entry for {0}")] ConvertionError(String), #[error("Cannot revoke a trust: {0}")] - RevokeError(String) + RevokeError(String), } impl From for SqliteStorageError { @@ -94,7 +98,6 @@ impl From for String { impl StorageError for SqliteStorageError {} impl Storage for SqliteStorage { - type Error = SqliteStorageError; fn get(&self, pk: &PublicKeyHashable) -> Result, Self::Error> { @@ -103,14 +106,14 @@ impl Storage for SqliteStorage { .prepare("SELECT trustnode FROM trustnodes WHERE public_key = ?")? .cursor(); - cursor - .bind(&[Value::String(format!("{}", pk))])?; + cursor.bind(&[Value::String(format!("{}", pk))])?; 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(ConvertionError( + "cannot get trustnode as binary".to_string(), + ))?; log::info!("binary: {:?}", tn_bin); @@ -135,8 +138,7 @@ impl Storage for SqliteStorage { log::info!("insert: {:?}", tn_vec); - cursor - .bind(&[Value::String(format!("{}", pk)), Value::Binary(tn_vec)])?; + cursor.bind(&[Value::String(format!("{}", pk)), Value::Binary(tn_vec)])?; cursor.next()?; Ok({}) @@ -153,8 +155,12 @@ 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(ConvertionError("cannot get weight as integer".to_string()))?, + ) + .map_err(|e| Unexpected(format!("Unexpected. Cannot convert weight to u32: {}", e)))?; Ok(Some(w)) } else { @@ -162,18 +168,21 @@ impl Storage for SqliteStorage { } } - fn add_root_weight(&mut self, pk: PublicKeyHashable, weight: Weight) -> Result<(), Self::Error> { + fn add_root_weight( + &mut self, + pk: PublicKeyHashable, + weight: Weight, + ) -> Result<(), Self::Error> { log::info!("add root: {} weight: {}", pk, weight); let mut cursor = self .connection .prepare("INSERT OR REPLACE INTO roots VALUES (?, ?)")? .cursor(); - cursor - .bind(&[ - Value::String(format!("{}", pk)), - Value::Integer(i64::from(weight)), - ])?; + cursor.bind(&[ + Value::String(format!("{}", pk)), + Value::Integer(i64::from(weight)), + ])?; cursor.next()?; Ok({}) @@ -189,8 +198,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(ConvertionError( + "cannot get public key as binary".to_string(), + ))?; let pk: PublicKeyHashable = PublicKeyHashable::from_str(pk).map_err(|e| DecodeError(e.to_string()))?; @@ -207,7 +217,9 @@ 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(RevokeError( + "There is no trust with such PublicKey".to_string(), + )), } } diff --git a/src/certificate.rs b/src/certificate.rs index ecd7d39..f8c84ac 100644 --- a/src/certificate.rs +++ b/src/certificate.rs @@ -14,7 +14,7 @@ * limitations under the License. */ -use crate::certificate::CerificateError::{ +use crate::certificate::CertificateError::{ CertificateLengthError, DecodeError, ExpirationError, KeyInCertificateError, MalformedRoot, NoTrustedRoot, VerificationError, }; @@ -39,7 +39,7 @@ pub struct Certificate { } #[derive(ThisError, Debug)] -pub enum CerificateError { +pub enum CertificateError { #[error("Error while decoding a certificate: {0}")] DecodeError(String), #[error("Certificate is expired. Issued at {issued_at} and expired at {expires_at}")] @@ -61,6 +61,12 @@ pub enum CerificateError { Unexpected(String), } +impl From for String { + fn from(err: CertificateError) -> Self { + format!("{}", err) + } +} + impl Certificate { pub fn new_unverified(chain: Vec) -> Self { Self { chain } @@ -93,7 +99,7 @@ impl Certificate { expires_at: Duration, issued_at: Duration, cur_time: Duration, - ) -> Result { + ) -> Result { if expires_at.lt(&issued_at) { return Err(ExpirationError { expires_at: format!("{:?}", expires_at), @@ -141,7 +147,7 @@ impl Certificate { cert: &Certificate, trusted_roots: &[PublicKey], cur_time: Duration, - ) -> Result<(), CerificateError> { + ) -> Result<(), CertificateError> { let chain = &cert.chain; if chain.is_empty() { @@ -186,7 +192,7 @@ impl Certificate { } #[allow(dead_code)] - pub fn decode(arr: &[u8]) -> Result { + 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())); @@ -228,7 +234,7 @@ impl std::fmt::Display for Certificate { } impl FromStr for Certificate { - type Err = CerificateError; + type Err = CertificateError; fn from_str(s: &str) -> Result { let str_lines: Vec<&str> = s.lines().collect(); diff --git a/src/revoke.rs b/src/revoke.rs index 35aa8f9..582e23a 100644 --- a/src/revoke.rs +++ b/src/revoke.rs @@ -22,9 +22,11 @@ use fluence_identity::public_key::PublicKey; use fluence_identity::signature::Signature; use serde::{Deserialize, Serialize}; use std::time::Duration; +use thiserror::Error as ThisError; -#[derive(Debug)] +#[derive(ThisError, Debug)] pub enum RevokeError { + #[error("Signature is incorrect: {0}")] IncorrectSignature(SignatureError), } diff --git a/src/trust_graph.rs b/src/trust_graph.rs index a099e26..7d2f55f 100644 --- a/src/trust_graph.rs +++ b/src/trust_graph.rs @@ -14,8 +14,8 @@ * limitations under the License. */ -use crate::certificate::CerificateError::{CertificateLengthError, Unexpected}; -use crate::certificate::{CerificateError, Certificate}; +use crate::certificate::CertificateError::{CertificateLengthError, Unexpected}; +use crate::certificate::{Certificate, CertificateError}; use crate::public_key_hashable::PublicKeyHashable; use crate::revoke::Revoke; use crate::revoke::RevokeError; @@ -31,6 +31,7 @@ use std::collections::{HashSet, VecDeque}; use std::convert::{From, Into}; use std::result::Result; use std::time::Duration; +use thiserror::Error as ThisError; /// for simplicity, we store `n` where Weight = 1/n^2 pub type Weight = u32; @@ -46,20 +47,30 @@ where storage: Box, } -#[derive(Debug)] +#[derive(ThisError, Debug)] pub enum TrustGraphError { + #[error("Internal storage error: {0}")] InternalStorageError(String), + #[error("There is no root for this certificate.")] NoRoot, - CertificateCheckError(CerificateError), + #[error("Certificate check error: {0}")] + CertificateCheckError(CertificateError), + #[error("Error on revoking a trust: {0}")] RevokeCheckError(RevokeError), } -impl From for TrustGraphError { - fn from(err: CerificateError) -> Self { +impl From for TrustGraphError { + fn from(err: CertificateError) -> Self { CertificateCheckError(err) } } +impl From for String { + fn from(err: TrustGraphError) -> Self { + format!("{}", err) + } +} + impl From for TrustGraphError { fn from(err: RevokeError) -> Self { RevokeCheckError(err) @@ -130,7 +141,9 @@ where 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) + .map_err(|e| InternalStorageError(e.into()))?; } // Insert remaining trusts to the graph @@ -144,7 +157,8 @@ 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) + .map_err(|e| InternalStorageError(e.into()))?; previous_trust = trust; }