mirror of
https://github.com/fluencelabs/trust-graph-test
synced 2025-04-24 19:52:27 +00:00
rename dir, restruct all errors
This commit is contained in:
parent
61fd3cb312
commit
b10726032e
@ -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<CertificateError> 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<Self, CertificateError> {
|
||||
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);
|
||||
}
|
||||
|
@ -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<u8>, SignatureError),
|
||||
}
|
||||
|
||||
impl FromStr for PublicKeyHashable {
|
||||
type Err = String;
|
||||
type Err = PkError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
@ -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),
|
||||
}
|
||||
|
||||
|
@ -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<dyn StorageError>),
|
||||
#[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<T: StorageError + 'static> From<T> for TrustGraphError {
|
||||
fn from(err: T) -> Self {
|
||||
InternalStorageError(Box::new(err))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CertificateError> 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<Option<TrustNode>, 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<PublicKey> = 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<PublicKey>,
|
||||
{
|
||||
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<PublicKey> = 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<Auth> = 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<PublicKey>,
|
||||
{
|
||||
// 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.
|
||||
|
@ -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<String>;
|
||||
type Error: StorageError + 'static;
|
||||
|
||||
fn get(&self, pk: &PublicKeyHashable) -> Result<Option<TrustNode>, Self::Error>;
|
||||
fn insert(&mut self, pk: PublicKeyHashable, node: TrustNode) -> Result<(), Self::Error>;
|
||||
fn get(&self, pk: &PK) -> Result<Option<TrustNode>, Self::Error>;
|
||||
fn insert(&mut self, pk: PK, node: TrustNode) -> Result<(), Self::Error>;
|
||||
|
||||
fn get_root_weight(&self, pk: &PublicKeyHashable) -> Result<Option<Weight>, Self::Error>;
|
||||
fn add_root_weight(&mut self, pk: PublicKeyHashable, weight: Weight)
|
||||
-> Result<(), Self::Error>;
|
||||
fn root_keys(&self) -> Result<Vec<PublicKeyHashable>, Self::Error>;
|
||||
fn revoke(&mut self, pk: &PublicKeyHashable, revoke: Revoke) -> Result<(), Self::Error>;
|
||||
fn get_root_weight(&self, pk: &PK) -> Result<Option<Weight>, Self::Error>;
|
||||
fn add_root_weight(&mut self, pk: PK, weight: Weight) -> Result<(), Self::Error>;
|
||||
fn root_keys(&self) -> Result<Vec<PK>, 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<PublicKeyHashable, TrustNode>,
|
||||
root_weights: HashMap<PublicKeyHashable, Weight>,
|
||||
nodes: HashMap<PK, TrustNode>,
|
||||
root_weights: HashMap<PK, Weight>,
|
||||
}
|
||||
|
||||
impl InMemoryStorage {
|
||||
@ -64,44 +64,34 @@ pub enum InMemoryStorageError {
|
||||
RevokeError(String),
|
||||
}
|
||||
|
||||
impl From<InMemoryStorageError> 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<Option<TrustNode>, Self::Error> {
|
||||
fn get(&self, pk: &PK) -> Result<Option<TrustNode>, 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<Option<Weight>, Self::Error> {
|
||||
fn get_root_weight(&self, pk: &PK) -> Result<Option<Weight>, 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<Vec<PublicKeyHashable>, Self::Error> {
|
||||
fn root_keys(&self) -> Result<Vec<PK>, 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,
|
||||
|
0
bin/Cargo.lock → wasm/Cargo.lock
generated
0
bin/Cargo.lock → wasm/Cargo.lock
generated
@ -1,14 +1,13 @@
|
||||
use fluence::fce;
|
||||
use trust_graph::{Certificate as TGCertificate, Trust as TGTrust};
|
||||
|
||||
#[fce]
|
||||
pub struct Certificate {
|
||||
pub chain: Vec<Trust>,
|
||||
}
|
||||
|
||||
impl From<TGCertificate> for Certificate {
|
||||
fn from(t: TGCertificate) -> Self {
|
||||
let chain: Vec<Trust> = t.chain.into_iter().map(|t| t.into()).collect();
|
||||
impl From<trust_graph::Certificate> for Certificate {
|
||||
fn from(c: trust_graph::Certificate) -> Self {
|
||||
let chain: Vec<Trust> = 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<TGTrust> for Trust {
|
||||
fn from(t: TGTrust) -> Self {
|
||||
impl From<trust_graph::Trust> 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();
|
@ -1,6 +1,6 @@
|
||||
use fluence::WasmLoggerBuilder;
|
||||
|
||||
mod proxy_structs;
|
||||
mod dto;
|
||||
mod results;
|
||||
mod service_api;
|
||||
mod storage_impl;
|
@ -1,4 +1,4 @@
|
||||
use crate::proxy_structs::Certificate;
|
||||
use crate::dto::Certificate;
|
||||
use fluence::fce;
|
||||
|
||||
#[fce]
|
@ -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<Option<u32>, 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<PublicKey, String> {
|
||||
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<Vec<Certificate>, 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();
|
@ -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<Mutex<TrustGraph<SqliteStorage>>> = OnceCell::new();
|
||||
static INSTANCE: OnceCell<Mutex<TrustGraph<SQLiteStorage>>> = OnceCell::new();
|
||||
|
||||
pub fn get_data() -> &'static Mutex<TrustGraph<SqliteStorage>> {
|
||||
pub fn get_data() -> &'static Mutex<TrustGraph<SQLiteStorage>> {
|
||||
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<TrustGraph<SqliteStorage>> {
|
||||
|
||||
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<InternalSqliteError> for SqliteStorageError {
|
||||
impl From<InternalSqliteError> for SQLiteStorageError {
|
||||
fn from(err: InternalSqliteError) -> Self {
|
||||
SqliteError(err)
|
||||
SQLiteError(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RmpEncodeError> for SqliteStorageError {
|
||||
impl From<RmpEncodeError> for SQLiteStorageError {
|
||||
fn from(err: RmpEncodeError) -> Self {
|
||||
EncodeError(format!("{}", err))
|
||||
EncodeError(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RmpDecodeError> for SqliteStorageError {
|
||||
impl From<RmpDecodeError> for SQLiteStorageError {
|
||||
fn from(err: RmpDecodeError) -> Self {
|
||||
DecodeError(format!("{}", err))
|
||||
DecodeError(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SqliteStorageError> for String {
|
||||
fn from(err: SqliteStorageError) -> Self {
|
||||
impl From<SQLiteStorageError> 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<Option<TrustNode>, 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),
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user