1 Commits

Author SHA1 Message Date
ef1a7b9dfa folex 2021-09-21 18:48:10 +03:00
27 changed files with 208 additions and 1685 deletions

View File

@ -29,7 +29,7 @@ jobs:
paths: paths:
- ~/.cargo - ~/.cargo
- ~/.rustup - ~/.rustup
key: trust-graph00-{{ checksum "./Cargo.lock" }-{{ checksum "./service/Cargo.lock" }}}-{{ checksum "./keypair/Cargo.lock" }} key: trust-graph00-{{ checksum "./service/Cargo.lock" }}-{{ checksum "./Cargo.lock" }}-{{ checksum "./keypair/Cargo.lock" }}
workflows: workflows:

6
Cargo.lock generated
View File

@ -755,7 +755,7 @@ dependencies = [
[[package]] [[package]]
name = "fluence-keypair" name = "fluence-keypair"
version = "0.4.1" version = "0.3.0"
dependencies = [ dependencies = [
"asn1_der", "asn1_der",
"bs58 0.3.1", "bs58 0.3.1",
@ -2478,7 +2478,7 @@ dependencies = [
[[package]] [[package]]
name = "trust-graph" name = "trust-graph"
version = "0.2.9" version = "0.2.7"
dependencies = [ dependencies = [
"bs58 0.3.1", "bs58 0.3.1",
"derivative", "derivative",
@ -2498,7 +2498,7 @@ dependencies = [
[[package]] [[package]]
name = "trust-graph-wasm" name = "trust-graph-wasm"
version = "0.2.1" version = "0.2.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bincode", "bincode",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "trust-graph" name = "trust-graph"
version = "0.2.9" version = "0.2.7"
authors = ["Fluence Labs"] authors = ["Fluence Labs"]
edition = "2018" edition = "2018"
description = "trust graph" description = "trust graph"
@ -11,7 +11,7 @@ repository = "https://github.com/fluencelabs/trust-graph"
libp2p-core = { package = "fluence-fork-libp2p-core", version = "0.27.2", features = ["secp256k1"] } libp2p-core = { package = "fluence-fork-libp2p-core", version = "0.27.2", features = ["secp256k1"] }
serde = { version = "=1.0.118", features = ["derive"] } serde = { version = "=1.0.118", features = ["derive"] }
fluence-keypair = { path = "./keypair", version = "0.4.1" } fluence-keypair = { path = "./keypair", version = "0.3.0" }
serde_json = "1.0.58" serde_json = "1.0.58"
bs58 = "0.3.1" bs58 = "0.3.1"
failure = "0.1.6" failure = "0.1.6"

View File

@ -1,14 +1,14 @@
import "trust-graph.aqua" import "trust-graph.aqua"
import "@fluencelabs/aqua-lib/builtin.aqua" import "@fluencelabs/aqua-lib/builtin.aqua"
func get_trust_bytes(node: string, issued_for_peer_id: string, expires_at_sec: u64, issued_at_sec: u64) -> GetTrustBytesResult: func get_trust_metadata(node: string, issued_for_peer_id: string, expires_at_sec: u64, issued_at_sec: u64) -> GetTrustMetadataResult:
on node: on node:
result <- TrustGraph.get_trust_bytes(issued_for_peer_id, expires_at_sec, issued_at_sec) result <- TrustGraph.get_trust_metadata(issued_for_peer_id, expires_at_sec, issued_at_sec)
<- result <- result
func issue_trust(node: string, issued_for_peer_id: string, expires_at_sec: u64, issued_at_sec: u64, trust_bytes: []u8) -> IssueTrustResult: func issue_trust(node: string, issued_for_peer_id: string, expires_at_sec: u64, issued_at_sec: u64, signed_metadata: []u8) -> IssueTrustResult:
on node: on node:
result <- TrustGraph.issue_trust(issued_for_peer_id, expires_at_sec, issued_at_sec, trust_bytes) result <- TrustGraph.issue_trust(issued_for_peer_id, expires_at_sec, issued_at_sec, signed_metadata)
<- result <- result
func verify_trust(node: string, trust: Trust, issuer_peer_id: string) -> VerifyTrustResult: func verify_trust(node: string, trust: Trust, issuer_peer_id: string) -> VerifyTrustResult:
@ -16,48 +16,3 @@ func verify_trust(node: string, trust: Trust, issuer_peer_id: string) -> VerifyT
timestamp_sec <- Peer.timestamp_sec() timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.verify_trust(trust, issuer_peer_id, timestamp_sec) result <- TrustGraph.verify_trust(trust, issuer_peer_id, timestamp_sec)
<- result <- result
func add_trust(node: string, trust: Trust, issuer_peer_id: string) -> AddTrustResult:
on node:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.add_trust(trust, issuer_peer_id, timestamp_sec)
<- result
func add_root(node: string, peer_id: string, weight_factor: u32) -> AddRootResult:
on node:
result <- TrustGraph.add_root(peer_id, weight_factor)
<- result
func get_weight(node: string, peer_id: string) -> WeightResult:
on node:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.get_weight(peer_id, timestamp_sec)
<- result
func get_all_certs(node: string, issued_for: string) -> AllCertsResult:
on node:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.get_all_certs(issued_for, timestamp_sec)
<- result
func insert_cert(node: string, certificate: Certificate) -> InsertResult:
on node:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.insert_cert(certificate, timestamp_sec)
<- result
func get_revoke_bytes(node: string, revoked_peer_id: string, revoked_at: u64) -> GetRevokeBytesResult:
on node:
result <- TrustGraph.get_revoke_bytes(revoked_peer_id, revoked_at)
<- result
func issue_revocation(node: string, revoked_peer_id: string, revoked_by_peer_id: string, revoked_at_sec: u64, signature_bytes: []u8) -> IssueRevocationResult:
on node:
result <- TrustGraph.issue_revocation(revoked_peer_id, revoked_by_peer_id, revoked_at_sec, signature_bytes)
<- result
func revoke(node: string, revoke: Revoke) -> RevokeResult:
on node:
timestamp_sec <- Peer.timestamp_sec()
result <- TrustGraph.revoke(revoke, timestamp_sec)
<- result

View File

@ -24,12 +24,7 @@ data AllCertsResult:
certificates: []Certificate certificates: []Certificate
error: string error: string
data GetRevokeBytesResult: data GetTrustMetadataResult:
success: bool
error: string
result: []u8
data GetTrustBytesResult:
success: bool success: bool
error: string error: string
result: []u8 result: []u8
@ -38,27 +33,11 @@ data InsertResult:
success: bool success: bool
error: string error: string
data Revoke:
revoked_peer_id: string
revoked_at: u64
signature: string
sig_type: string
revoked_by: string
data IssueRevocationResult:
success: bool
error: string
revoke: Revoke
data IssueTrustResult: data IssueTrustResult:
success: bool success: bool
error: string error: string
trust: Trust trust: Trust
data RevokeResult:
success: bool
error: string
data VerifyTrustResult: data VerifyTrustResult:
success: bool success: bool
error: string error: string
@ -70,15 +49,12 @@ data WeightResult:
error: string error: string
service TrustGraph("trust-graph"): service TrustGraph("trust-graph"):
add_root(peer_id: string, weight_factor: u32) -> AddRootResult add_root(peer_id: string, weight: u32) -> AddRootResult
add_trust(trust: Trust, issuer_peer_id: string, timestamp_sec: u64) -> AddTrustResult add_trust(trust: Trust, issuer_peer_id: string, timestamp_sec: u64) -> AddTrustResult
get_all_certs(issued_for: string, timestamp_sec: u64) -> AllCertsResult get_all_certs(issued_for: string, timestamp_sec: u64) -> AllCertsResult
get_revoke_bytes(revoked_peer_id: string, revoked_at: u64) -> GetRevokeBytesResult get_trust_metadata(issued_for_peer_id: string, expires_at_sec: u64, issued_at_sec: u64) -> GetTrustMetadataResult
get_trust_bytes(issued_for_peer_id: string, expires_at_sec: u64, issued_at_sec: u64) -> GetTrustBytesResult
get_weight(peer_id: string, timestamp_sec: u64) -> WeightResult get_weight(peer_id: string, timestamp_sec: u64) -> WeightResult
insert_cert(certificate: Certificate, timestamp_sec: u64) -> InsertResult insert_cert(certificate: Certificate, timestamp_sec: u64) -> InsertResult
insert_cert_raw(certificate: string, timestamp_sec: u64) -> InsertResult insert_cert_raw(certificate: string, timestamp_sec: u64) -> InsertResult
issue_revocation(revoked_peer_id: string, revoked_by_peer_id: string, revoked_at_sec: u64, signature_bytes: []u8) -> IssueRevocationResult issue_trust(issued_for_peer_id: string, expires_at_sec: u64, issued_at_sec: u64, signed_metadata: []u8) -> IssueTrustResult
issue_trust(issued_for_peer_id: string, expires_at_sec: u64, issued_at_sec: u64, trust_bytes: []u8) -> IssueTrustResult
revoke(revoke: Revoke, timestamp_sec: u64) -> RevokeResult
verify_trust(trust: Trust, issuer_peer_id: string, timestamp_sec: u64) -> VerifyTrustResult verify_trust(trust: Trust, issuer_peer_id: string, timestamp_sec: u64) -> VerifyTrustResult

View File

@ -3,3 +3,4 @@
2. Run `docker compose up -d` to start Fluence node 2. Run `docker compose up -d` to start Fluence node
3. Go back to `../example` 3. Go back to `../example`
4. Run `npm run start` 4. Run `npm run start`
2

View File

@ -1,3 +1,3 @@
import get_trust_bytes, issue_trust, verify_trust, add_trust, add_root, get_weight, get_all_certs, insert_cert, get_revoke_bytes, issue_revocation, revoke from "../../aqua/trust-graph-api.aqua" import get_trust_metadata, issue_trust, verify_trust from "../../aqua/trust-graph-api.aqua"
export get_trust_bytes, issue_trust, verify_trust, add_trust, add_root, get_weight, get_all_certs, insert_cert, get_revoke_bytes, issue_revocation, revoke export get_trust_metadata, issue_trust, verify_trust

File diff suppressed because it is too large Load Diff

View File

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { get_trust_bytes, issue_trust, verify_trust, add_trust, add_root, get_weight, } from "./generated/export"; import { get_trust_metadata, issue_trust, verify_trust } from "./generated/export";
import { Fluence, KeyPair } from "@fluencelabs/fluence"; import { Fluence, KeyPair } from "@fluencelabs/fluence";
import { Node } from "@fluencelabs/fluence-network-environment"; import { Node } from "@fluencelabs/fluence-network-environment";
const bs58 = require('bs58'); const bs58 = require('bs58');
@ -33,36 +33,23 @@ let local: Node[] = [
]; ];
async function main(environment: Node[]) { async function main(environment: Node[]) {
let builtins_keypair = await KeyPair.fromBytes(bs58.decode("5CGiJio6m76GxJ2wLj46PzSu6V7SRa5agv6meR3SJBKtvTgethRCmgBJKXWDSpSEBpgNUPd7Re5cZjF8mWW4kBfs").slice(32)); let mgmt_keypair = await KeyPair.fromBytes(bs58.decode("/tmp/fluence/builtins_secret_key.ed25519:/.fluence/v1/builtins_secret_key.ed25519"));
await Fluence.start({ connectTo: environment[0], KeyPair: builtins_keypair}); await Fluence.start({ connectTo: environment[0] , KeyPair: mgmt_keypair});
console.log( console.log(
"📗 created a fluence peer %s with relay %s", "📗 created a fluence peer %s with relay %s",
Fluence.getStatus().peerId, Fluence.getStatus().peerId,
Fluence.getStatus().relayPeerId Fluence.getStatus().relayPeerId
); );
let trust_metadata = await get_trust_metadata(local[0].peerId, local[1].peerId, 99999999999, 0);
const issuer_kp = await KeyPair.fromBytes(bs58.decode("29Apzfedhw2Jxh94Jj4rNSmavQ1TkNe8ALYRA7bMegobwp423aLrURxLk32WtXgXHDqoSz7GAT9fQfoMhVd1e5Ww")); const issuer_kp = await KeyPair.fromBytes(bs58.decode("29Apzfedhw2Jxh94Jj4rNSmavQ1TkNe8ALYRA7bMegobwp423aLrURxLk32WtXgXHDqoSz7GAT9fQfoMhVd1e5Ww"));
console.log("Issuer peer id: %", issuer_kp.Libp2pPeerId.toB58String()); console.log("Issuer peer id: %", issuer_kp.Libp2pPeerId.toB58String());
let add_root_result = await add_root(local[0].peerId, local[0].peerId, 2);
console.log("Add root weight result: %s", add_root_result);
let trust_metadata = await get_trust_bytes(local[0].peerId, local[0].peerId, 99999999999, 0);
const signed_metadata = await issuer_kp.Libp2pPeerId.privKey.sign(Uint8Array.from(trust_metadata.result)); const signed_metadata = await issuer_kp.Libp2pPeerId.privKey.sign(Uint8Array.from(trust_metadata.result));
let trust = await issue_trust(local[0].peerId, local[1].peerId, 99999999999, 0, Array.from(signed_metadata));
let root_trust = await issue_trust(local[0].peerId, local[0].peerId, 99999999999, 0, Array.from(signed_metadata)); console.log("Trust %s", trust.trust);
console.log("Root trust %s", root_trust.trust); let result = await verify_trust(local[0].peerId, trust.trust, local[0].peerId);
console.log("Verify trust result: %s", result);
let result = await verify_trust(local[0].peerId, root_trust.trust, local[0].peerId);
console.log("Verify root trust result: %s", result);
let result_add = await add_trust(local[0].peerId, root_trust.trust, local[0].peerId);
console.log("Add root trust result: %s", result_add);
let root_weight_result = await get_weight(local[0].peerId, local[0].peerId);
console.log("Root weight: %s", root_weight_result);
// TODO: insert trust to local[1].peerId, get this certs, add local[1].peerId as root in local[1].peerId and insert_certificate
return; return;
} }

View File

@ -1,6 +1,6 @@
[package] [package]
name = "fluence-keypair" name = "fluence-keypair"
version = "0.4.1" version = "0.3.0"
authors = ["Fluence Labs"] authors = ["Fluence Labs"]
edition = "2018" edition = "2018"
description = "identity" description = "identity"

View File

@ -35,7 +35,7 @@ pub enum DecodingError {
Ed25519( Ed25519(
#[from] #[from]
#[source] #[source]
ed25519_dalek::ed25519::Error, ed25519_dalek::ed25519::Error
), ),
#[error("Failed to decode with RSA")] #[error("Failed to decode with RSA")]
Rsa, Rsa,
@ -49,8 +49,6 @@ pub enum DecodingError {
Base58DecodeError(#[source] bs58::decode::Error), Base58DecodeError(#[source] bs58::decode::Error),
#[error("Raw signature decoding failed: type {0} not supported")] #[error("Raw signature decoding failed: type {0} not supported")]
RawSignatureUnsupportedType(String), RawSignatureUnsupportedType(String),
#[error("public key is not inlined in peer id: {0}")]
PublicKeyNotInlined(String),
} }
/// An error during signing of a message. /// An error during signing of a message.
@ -60,7 +58,7 @@ pub enum SigningError {
Ed25519( Ed25519(
#[from] #[from]
#[source] #[source]
ed25519_dalek::ed25519::Error, ed25519_dalek::ed25519::Error
), ),
#[error("Failed to sign with RSA")] #[error("Failed to sign with RSA")]
Rsa, Rsa,
@ -68,6 +66,6 @@ pub enum SigningError {
Secp256k1( Secp256k1(
#[from] #[from]
#[source] #[source]
secp256k1::Error, secp256k1::Error
), ),
} }

View File

@ -20,15 +20,15 @@
//! A node's network identity keys. //! A node's network identity keys.
use crate::ed25519; use crate::ed25519;
use crate::error::{DecodingError, Error, SigningError};
use crate::public_key::PublicKey;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use crate::rsa; use crate::rsa;
use crate::secp256k1; use crate::secp256k1;
use crate::public_key::PublicKey;
use crate::signature::Signature; use crate::signature::Signature;
use libp2p_core::PeerId; use crate::error::{Error, DecodingError, SigningError};
use std::convert::TryFrom;
use std::str::FromStr; use std::str::FromStr;
use std::convert::TryFrom;
use libp2p_core::PeerId;
/// Identity keypair of a node. /// Identity keypair of a node.
/// ///
@ -48,6 +48,7 @@ use std::str::FromStr;
/// ``` /// ```
/// ///
pub enum KeyFormat { pub enum KeyFormat {
Ed25519, Ed25519,
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
@ -65,7 +66,7 @@ impl FromStr for KeyFormat {
"secp256k1" => Ok(KeyFormat::Secp256k1), "secp256k1" => Ok(KeyFormat::Secp256k1),
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
"rsa" => Ok(KeyFormat::Rsa), "rsa" => Ok(KeyFormat::Rsa),
_ => Err(Error::InvalidKeyFormat(s.to_string())), _ => Err(Error::InvalidKeyFormat(s.to_string()))
} }
} }
} }
@ -79,7 +80,7 @@ impl TryFrom<u8> for KeyFormat {
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
1 => Ok(KeyFormat::Rsa), 1 => Ok(KeyFormat::Rsa),
2 => Ok(KeyFormat::Secp256k1), 2 => Ok(KeyFormat::Secp256k1),
_ => Err(DecodingError::InvalidTypeByte), _ => Err(DecodingError::InvalidTypeByte)
} }
} }
} }
@ -95,16 +96,6 @@ impl From<KeyFormat> for u8 {
} }
} }
impl From<KeyFormat> for String {
fn from(kf: KeyFormat) -> Self {
match kf {
KeyFormat::Ed25519 => "ed25519".to_string(),
#[cfg(not(target_arch = "wasm32"))]
KeyFormat::Rsa => "rsa".to_string(),
KeyFormat::Secp256k1 => "secp256k1".to_string(),
}
}
}
#[derive(Clone)] #[derive(Clone)]
pub enum KeyPair { pub enum KeyPair {
/// An Ed25519 keypair. /// An Ed25519 keypair.
@ -162,9 +153,7 @@ impl KeyPair {
Ed25519(ref pair) => Ok(Signature::Ed25519(ed25519::Signature(pair.sign(msg)?))), Ed25519(ref pair) => Ok(Signature::Ed25519(ed25519::Signature(pair.sign(msg)?))),
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
Rsa(ref pair) => Ok(Signature::Rsa(rsa::Signature(pair.sign(msg)?))), Rsa(ref pair) => Ok(Signature::Rsa(rsa::Signature(pair.sign(msg)?))),
Secp256k1(ref pair) => Ok(Signature::Secp256k1(secp256k1::Signature( Secp256k1(ref pair) => Ok(Signature::Secp256k1(secp256k1::Signature(pair.secret().sign(msg)?)))
pair.secret().sign(msg)?,
))),
} }
} }
@ -211,7 +200,7 @@ impl KeyPair {
KeyFormat::Ed25519 => Ok(Ed25519(ed25519::Keypair::decode(&mut bytes)?)), KeyFormat::Ed25519 => Ok(Ed25519(ed25519::Keypair::decode(&mut bytes)?)),
KeyFormat::Secp256k1 => Ok(Secp256k1(secp256k1::SecretKey::from_bytes(bytes)?.into())), KeyFormat::Secp256k1 => Ok(Secp256k1(secp256k1::SecretKey::from_bytes(bytes)?.into())),
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
KeyFormat::Rsa => Err(DecodingError::KeypairDecodingIsNotSupported), KeyFormat::Rsa => Err(DecodingError::KeypairDecodingIsNotSupported)
} }
} }
@ -228,33 +217,23 @@ impl From<libp2p_core::identity::Keypair> for KeyPair {
Ed25519(kp) => KeyPair::Ed25519(ed25519::Keypair::decode(&mut kp.encode()).unwrap()), Ed25519(kp) => KeyPair::Ed25519(ed25519::Keypair::decode(&mut kp.encode()).unwrap()),
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
// safety: these Keypair structures are identical // safety: these Keypair structures are identical
Rsa(kp) => KeyPair::Rsa(unsafe { Rsa(kp) => KeyPair::Rsa(unsafe { std::mem::transmute::<libp2p_core::identity::rsa::Keypair, rsa::Keypair>(kp) }),
std::mem::transmute::<libp2p_core::identity::rsa::Keypair, rsa::Keypair>(kp) Secp256k1(kp) => KeyPair::Secp256k1(secp256k1::Keypair::from(secp256k1::SecretKey::from_bytes(kp.secret().to_bytes()).unwrap())),
}),
Secp256k1(kp) => KeyPair::Secp256k1(secp256k1::Keypair::from(
secp256k1::SecretKey::from_bytes(kp.secret().to_bytes()).unwrap(),
)),
} }
} }
} }
impl From<KeyPair> for libp2p_core::identity::Keypair { impl From<KeyPair> for libp2p_core::identity::Keypair {
fn from(key: KeyPair) -> Self { fn from(key: KeyPair) -> Self {
use libp2p_core::identity;
use libp2p_core::identity::Keypair;
use KeyPair::*; use KeyPair::*;
use libp2p_core::identity::Keypair;
use libp2p_core::identity;
match key { match key {
Ed25519(kp) => Keypair::Ed25519( Ed25519(kp) => Keypair::Ed25519(identity::ed25519::Keypair::decode(kp.encode().to_vec().as_mut_slice()).unwrap()),
identity::ed25519::Keypair::decode(kp.encode().to_vec().as_mut_slice()).unwrap(),
),
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
Rsa(kp) => Keypair::Rsa(unsafe { Rsa(kp) => Keypair::Rsa(unsafe { std::mem::transmute::<rsa::Keypair, libp2p_core::identity::rsa::Keypair>(kp) }),
std::mem::transmute::<rsa::Keypair, libp2p_core::identity::rsa::Keypair>(kp) Secp256k1(kp) => Keypair::Secp256k1(identity::secp256k1::Keypair::from(identity::secp256k1::SecretKey::from_bytes(kp.secret().to_bytes()).unwrap())),
}),
Secp256k1(kp) => Keypair::Secp256k1(identity::secp256k1::Keypair::from(
identity::secp256k1::SecretKey::from_bytes(kp.secret().to_bytes()).unwrap(),
)),
} }
} }
} }

View File

@ -111,17 +111,6 @@ impl PublicKey {
pub fn to_peer_id(&self) -> PeerId { pub fn to_peer_id(&self) -> PeerId {
PeerId::from_public_key(self.clone().into()) PeerId::from_public_key(self.clone().into())
} }
pub fn get_key_format(&self) -> KeyFormat {
use PublicKey::*;
match self {
Ed25519(_) => KeyFormat::Ed25519,
#[cfg(not(target_arch = "wasm32"))]
Rsa(_) => KeyFormat::Rsa,
Secp256k1(_) => KeyFormat::Secp256k1,
}
}
} }
impl From<libp2p_core::identity::PublicKey> for PublicKey { impl From<libp2p_core::identity::PublicKey> for PublicKey {
@ -160,16 +149,15 @@ impl From<PublicKey> for libp2p_core::identity::PublicKey {
} }
} }
impl TryFrom<libp2p_core::PeerId> for PublicKey { pub fn peer_id_to_fluence_pk(peer_id: libp2p_core::PeerId) -> eyre::Result<PublicKey> {
type Error = DecodingError;
fn try_from(peer_id: libp2p_core::PeerId) -> Result<Self, Self::Error> {
Ok(peer_id Ok(peer_id
.as_public_key() .as_public_key()
.ok_or(DecodingError::PublicKeyNotInlined(peer_id.to_base58()))? .ok_or(eyre::eyre!(
"public key is not inlined in peer id: {}",
peer_id
))?
.into()) .into())
} }
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
@ -191,15 +179,4 @@ mod tests {
let encoded_pk = pk.encode(); let encoded_pk = pk.encode();
assert_eq!(pk, PublicKey::decode(&encoded_pk).unwrap()); assert_eq!(pk, PublicKey::decode(&encoded_pk).unwrap());
} }
#[test]
fn public_key_peer_id_conversions() {
let kp = KeyPair::generate_secp256k1();
let fluence_pk = kp.public();
let libp2p_pk: libp2p_core::PublicKey = fluence_pk.clone().into();
let peer_id = PeerId::from_public_key(libp2p_pk);
let fluence_pk_converted = PublicKey::try_from(peer_id).unwrap();
assert_eq!(fluence_pk, fluence_pk_converted);
}
} }

View File

@ -13,13 +13,13 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
use crate::ed25519; use crate::{ed25519, PublicKey};
use crate::error::DecodingError; use crate::secp256k1;
use crate::key_pair::KeyFormat;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
use crate::rsa; use crate::rsa;
use crate::secp256k1; use crate::error::DecodingError;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::key_pair::KeyFormat;
use std::convert::TryFrom; use std::convert::TryFrom;
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
@ -32,7 +32,7 @@ pub enum Signature {
pub struct RawSignature { pub struct RawSignature {
pub bytes: Vec<u8>, pub bytes: Vec<u8>,
pub sig_type: KeyFormat, pub sig_type: String,
} }
impl Signature { impl Signature {
@ -42,7 +42,7 @@ impl Signature {
Ed25519(_) => KeyFormat::Ed25519.into(), Ed25519(_) => KeyFormat::Ed25519.into(),
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
Rsa(_) => KeyFormat::Rsa.into(), Rsa(_) => KeyFormat::Rsa.into(),
Secp256k1(_) => KeyFormat::Secp256k1.into(), Secp256k1(_) => KeyFormat::Secp256k1.into()
} }
} }
@ -68,9 +68,7 @@ impl Signature {
KeyFormat::Ed25519 => Ok(Signature::Ed25519(ed25519::Signature(bytes[1..].to_vec()))), KeyFormat::Ed25519 => Ok(Signature::Ed25519(ed25519::Signature(bytes[1..].to_vec()))),
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
KeyFormat::Rsa => Ok(Signature::Rsa(rsa::Signature(bytes[1..].to_vec()))), KeyFormat::Rsa => Ok(Signature::Rsa(rsa::Signature(bytes[1..].to_vec()))),
KeyFormat::Secp256k1 => Ok(Signature::Secp256k1(secp256k1::Signature( KeyFormat::Secp256k1 => Ok(Signature::Secp256k1(secp256k1::Signature(bytes[1..].to_vec()))),
bytes[1..].to_vec(),
))),
} }
} }
@ -85,30 +83,38 @@ impl Signature {
} }
} }
pub fn get_signature_type(&self) -> KeyFormat { pub fn get_signature_type(&self) -> String {
use Signature::*; use Signature::*;
match self { match self {
Ed25519(_) => KeyFormat::Ed25519, Ed25519(_) => "Ed25519".to_string(),
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
Rsa(_) => KeyFormat::Rsa, Rsa(_) => "RSA".to_string(),
Secp256k1(_) => KeyFormat::Secp256k1, Secp256k1(_) => "Secp256k1".to_string(),
} }
} }
pub fn get_raw_signature(&self) -> RawSignature { pub fn get_raw_signature(&self) -> RawSignature {
RawSignature { RawSignature { bytes: self.to_vec().clone().to_vec(), sig_type: self.get_signature_type() }
bytes: self.to_vec().clone().to_vec(), }
sig_type: self.get_signature_type(),
pub fn from_raw_signature(raw_signature: RawSignature) -> Result<Self, DecodingError> {
match raw_signature.sig_type.as_str() {
"Ed25519" => Ok(Signature::Ed25519(crate::ed25519::Signature(raw_signature.bytes))),
#[cfg(not(target_arch = "wasm32"))]
"RSA" => Ok(Signature::Rsa(crate::rsa::Signature(raw_signature.bytes))),
"Secp256k1" => Ok(Signature::Secp256k1(crate::secp256k1::Signature(raw_signature.bytes))),
_ => Err(DecodingError::RawSignatureUnsupportedType(raw_signature.sig_type)),
} }
} }
pub fn from_bytes(key_format: KeyFormat, bytes: Vec<u8>) -> Self { pub fn from_bytes_with_public_key(pk: &PublicKey, bytes: Vec<u8>) -> Self {
match key_format { use PublicKey::*;
KeyFormat::Ed25519 => Signature::Ed25519(ed25519::Signature(bytes)), match pk {
Ed25519(_) => Signature::Ed25519(ed25519::Signature(bytes)),
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
KeyFormat::Rsa => Signature::Rsa(rsa::Signature(bytes)), Rsa(_) => Signature::Rsa(rsa::Signature(bytes)),
KeyFormat::Secp256k1 => Signature::Secp256k1(secp256k1::Signature(bytes)), Secp256k1(_) => Signature::Secp256k1(secp256k1::Signature(bytes))
} }
} }
} }
@ -125,14 +131,8 @@ mod tests {
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
let rsa_sig = Signature::Rsa(crate::rsa::Signature(bytes.clone())); let rsa_sig = Signature::Rsa(crate::rsa::Signature(bytes.clone()));
assert_eq!( assert_eq!(Signature::decode(ed25519_sig.encode()).unwrap(), ed25519_sig);
Signature::decode(ed25519_sig.encode()).unwrap(), assert_eq!(Signature::decode(secp256k1_sig.encode()).unwrap(), secp256k1_sig);
ed25519_sig
);
assert_eq!(
Signature::decode(secp256k1_sig.encode()).unwrap(),
secp256k1_sig
);
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
assert_eq!(Signature::decode(rsa_sig.encode()).unwrap(), rsa_sig); assert_eq!(Signature::decode(rsa_sig.encode()).unwrap(), rsa_sig);
} }

View File

@ -1,4 +1,4 @@
# management secret key is NAB5rGwT4qOEB+6nLQawkTfCOV2eiFSjgQK8bfEdZXY= # management base58 or base64 secret key is NAB5rGwT4qOEB+6nLQawkTfCOV2eiFSjgQK8bfEdZXY=
services: services:
fluence-0: # /ip4/127.0.0.1/tcp/9990/ws/p2p/12D3KooWHBG9oaVx4i3vi6c1rSBUm7MLBmyGmmbHoZ23pmjDCnvK fluence-0: # /ip4/127.0.0.1/tcp/9990/ws/p2p/12D3KooWHBG9oaVx4i3vi6c1rSBUm7MLBmyGmmbHoZ23pmjDCnvK
command: -f ed25519 -k 29Apzfedhw2Jxh94Jj4rNSmavQ1TkNe8ALYRA7bMegobwp423aLrURxLk32WtXgXHDqoSz7GAT9fQfoMhVd1e5Ww -m 12D3KooWFRgVmb1uWcmCbmJqLr8tBQghL6ysSpK2VyE2VZbaQ6wy -t 7770 -w 9990 # --bootstraps /dns4/fluence-1/tcp/7771 /dns4/fluence-2/tcp/7772 command: -f ed25519 -k 29Apzfedhw2Jxh94Jj4rNSmavQ1TkNe8ALYRA7bMegobwp423aLrURxLk32WtXgXHDqoSz7GAT9fQfoMhVd1e5Ww -m 12D3KooWFRgVmb1uWcmCbmJqLr8tBQghL6ysSpK2VyE2VZbaQ6wy -t 7770 -w 9990 # --bootstraps /dns4/fluence-1/tcp/7771 /dns4/fluence-2/tcp/7772
@ -74,4 +74,4 @@ volumes:
# data-2: # data-2:
networks: networks:
fluence: fluence: null

31
local-network/fluence.yml Normal file
View File

@ -0,0 +1,31 @@
version: "3.8"
services:
fluence-0: # /ip4/127.0.0.1/tcp/9990/ws/p2p/12D3KooWHBG9oaVx4i3vi6c1rSBUm7MLBmyGmmbHoZ23pmjDCnvK
command: -m 12D3KooWFRgVmb1uWcmCbmJqLr8tBQghL6ysSpK2VyE2VZbaQ6wy -t 7770 -w 9990 # --bootstraps /dns4/fluence-1/tcp/7771 /dns4/fluence-2/tcp/7772
container_name: fluence-0
environment:
RUST_BACKTRACE: full
RUST_LOG: info,network=trace,aquamarine=info,aquamarine::actor=info,tokio_threadpool=info,tokio_reactor=info,mio=info,tokio_io=info,soketto=info,yamux=info,multistream_select=info,libp2p_secio=info,libp2p_websocket::framed=info,libp2p_ping=info,libp2p_core::upgrade::apply=info,libp2p_kad::kbucket=info,cranelift_codegen=info,wasmer_wasi=info,async_io=info,polling=info,wasmer_interface_types_fl=info,cranelift_codegen=info,wasmer_wasi=info,async_io=info,polling=info,wasmer_interface_types_fl=info,particle_server::behaviour::identify=info,libp2p_mplex=info,libp2p_identify=info,walrus=info,particle_protocol::libp2p_protocol::upgrade=info,kademlia::behaviour=info
WASM_LOG: info
image: fluencelabs/node:tg_test
ports:
- 7770:7770 # tcp
- 9990:9990 # ws
- 5000:5001 # ipfs rpc
- 4000:4001 # ipfs swarm
- 18080:18080 # /metrics
restart: always
volumes:
- fluence-0:/.fluence
- data-0:/config
- ./secret_key.ed25519:/.fluence/v1/secret_key.ed25519
- ./builtins_secret_key.ed25519:/.fluence/v1/builtins_secret_key.ed25519
networks:
- fluence
volumes:
fluence-0:
data-0:
networks:
fluence: null

View File

@ -0,0 +1 @@
3eRPuC6vrSzYER2j2SvuYNAifdioxswJtUgdchmMPn4cYBQKmqqWTPg3Dkici8vRPRzpEJ4FPUQShzd4tBJunzoF

View File

@ -1,6 +1,6 @@
[package] [package]
name = "trust-graph-wasm" name = "trust-graph-wasm"
version = "0.2.1" version = "0.2.0"
authors = ["Fluence Labs"] authors = ["Fluence Labs"]
edition = "2018" edition = "2018"
description = "trust graph wasm" description = "trust graph wasm"
@ -12,7 +12,7 @@ path = "src/main.rs"
[dependencies] [dependencies]
trust-graph = { version = "0.2.6", path = "../." } trust-graph = { version = "0.2.6", path = "../." }
fluence-keypair = { version = "0.4.1", path = "../keypair" } fluence-keypair = { version = "0.3.0", path = "../keypair" }
marine-rs-sdk = { version = "0.6.11", features = ["logger"] } marine-rs-sdk = { version = "0.6.11", features = ["logger"] }
marine-sqlite-connector = "0.5.1" marine-sqlite-connector = "0.5.1"

View File

@ -1,13 +1,14 @@
use crate::dto::DtoConversionError::PeerIdDecodeError;
use fluence_keypair::error::DecodingError;
use fluence_keypair::signature::RawSignature;
use fluence_keypair::{KeyFormat, PublicKey, Signature};
use libp2p_core::PeerId;
use marine_rs_sdk::marine; use marine_rs_sdk::marine;
use fluence_keypair::error::DecodingError;
use fluence_keypair::{Signature};
use std::convert::TryFrom; use std::convert::TryFrom;
use std::str::FromStr;
use std::time::Duration; use std::time::Duration;
use thiserror::Error as ThisError; use thiserror::Error as ThisError;
use libp2p_core::PeerId;
use fluence_keypair::public_key::peer_id_to_fluence_pk;
use std::str::FromStr;
use fluence_keypair::signature::RawSignature;
use crate::dto::DtoConversionError::PeerIdDecodeError;
#[derive(ThisError, Debug)] #[derive(ThisError, Debug)]
pub enum DtoConversionError { pub enum DtoConversionError {
@ -25,12 +26,6 @@ pub enum DtoConversionError {
), ),
#[error("Cannot decode peer id from string: {0}")] #[error("Cannot decode peer id from string: {0}")]
PeerIdDecodeError(String), PeerIdDecodeError(String),
#[error("{0}")]
InvalidKeyFormat(
#[from]
#[source]
fluence_keypair::error::Error,
),
} }
#[marine] #[marine]
@ -78,12 +73,11 @@ impl TryFrom<Trust> for trust_graph::Trust {
type Error = DtoConversionError; type Error = DtoConversionError;
fn try_from(t: Trust) -> Result<Self, Self::Error> { fn try_from(t: Trust) -> Result<Self, Self::Error> {
let issued_for = PublicKey::try_from( let issued_for = peer_id_to_fluence_pk(PeerId::from_str(&t.issued_for)
PeerId::from_str(&t.issued_for).map_err(|e| PeerIdDecodeError(format!("{:?}", e)))?, .map_err(|e| PeerIdDecodeError(format!("{:?}", e)))?)
)
.map_err(|e| DtoConversionError::PeerIdDecodeError(e.to_string()))?; .map_err(|e| DtoConversionError::PeerIdDecodeError(e.to_string()))?;
let signature = bs58::decode(&t.signature).into_vec()?; let signature = bs58::decode(&t.signature).into_vec()?;
let signature = Signature::from_bytes(KeyFormat::from_str(&t.sig_type)?, signature); let signature = Signature::from_raw_signature(RawSignature { bytes: signature, sig_type: t.sig_type })?;
let expires_at = Duration::from_secs(t.expires_at); let expires_at = Duration::from_secs(t.expires_at);
let issued_at = Duration::from_secs(t.issued_at); let issued_at = Duration::from_secs(t.issued_at);
return Ok(trust_graph::Trust { return Ok(trust_graph::Trust {
@ -106,65 +100,8 @@ impl From<trust_graph::Trust> for Trust {
issued_for, issued_for,
expires_at, expires_at,
signature, signature,
sig_type: raw_signature.sig_type.into(), sig_type: raw_signature.sig_type,
issued_at, issued_at,
}; };
} }
} }
#[marine]
#[derive(Default)]
pub struct Revoke {
/// who is revoked
pub revoked_peer_id: String,
/// date when revocation was created
pub revoked_at: u64,
/// Signature of a previous trust in a chain.
/// Signature is self-signed if it is a root trust, base58
pub signature: String,
pub sig_type: String,
/// the issuer of this revocation, base58 peer id
pub revoked_by: String,
}
impl TryFrom<Revoke> for trust_graph::Revoke {
type Error = DtoConversionError;
fn try_from(r: Revoke) -> Result<Self, Self::Error> {
let revoked_pk = PublicKey::try_from(
PeerId::from_str(&r.revoked_peer_id)
.map_err(|e| PeerIdDecodeError(format!("{:?}", e)))?,
)
.map_err(|e| DtoConversionError::PeerIdDecodeError(e.to_string()))?;
let revoked_by_pk = PublicKey::try_from(
PeerId::from_str(&r.revoked_by).map_err(|e| PeerIdDecodeError(format!("{:?}", e)))?,
)
.map_err(|e| DtoConversionError::PeerIdDecodeError(e.to_string()))?;
let signature = bs58::decode(&r.signature).into_vec()?;
let signature = Signature::from_bytes(KeyFormat::from_str(&r.sig_type)?, signature);
let revoked_at = Duration::from_secs(r.revoked_at);
return Ok(trust_graph::Revoke {
pk: revoked_pk,
revoked_at,
revoked_by: revoked_by_pk,
signature,
});
}
}
impl From<trust_graph::Revoke> for Revoke {
fn from(r: trust_graph::Revoke) -> Self {
let revoked_by = r.revoked_by.to_peer_id().to_base58();
let revoked_peer_id = r.pk.to_peer_id().to_base58();
let raw_signature = r.signature.get_raw_signature();
let signature = bs58::encode(raw_signature.bytes).into_string();
let revoked_at = r.revoked_at.as_secs();
return Revoke {
revoked_peer_id,
revoked_at,
signature,
sig_type: raw_signature.sig_type.into(),
revoked_by,
};
}
}

View File

@ -1,4 +1,4 @@
use crate::dto::{Certificate, Revoke, Trust}; use crate::dto::{Certificate, Trust};
use crate::service_impl::ServiceError; use crate::service_impl::ServiceError;
use marine_rs_sdk::marine; use marine_rs_sdk::marine;
@ -96,21 +96,21 @@ impl From<Result<(), ServiceError>> for AddRootResult {
} }
#[marine] #[marine]
pub struct GetTrustBytesResult { pub struct GetTrustMetadataResult {
pub success: bool, pub success: bool,
pub error: String, pub error: String,
pub result: Vec<u8>, pub result: Vec<u8>,
} }
impl From<Result<Vec<u8>, ServiceError>> for GetTrustBytesResult { impl From<Result<Vec<u8>, ServiceError>> for GetTrustMetadataResult {
fn from(result: Result<Vec<u8>, ServiceError>) -> Self { fn from(result: Result<Vec<u8>, ServiceError>) -> Self {
match result { match result {
Ok(res) => GetTrustBytesResult { Ok(res) => GetTrustMetadataResult {
success: true, success: true,
error: "".to_string(), error: "".to_string(),
result: res, result: res,
}, },
Err(e) => GetTrustBytesResult { Err(e) => GetTrustMetadataResult {
success: false, success: false,
error: format!("{}", e), error: format!("{}", e),
result: vec![], result: vec![],
@ -187,72 +187,3 @@ impl From<Result<u32, ServiceError>> for AddTrustResult {
} }
} }
} }
#[marine]
pub struct GetRevokeBytesResult {
pub success: bool,
pub error: String,
pub result: Vec<u8>,
}
impl From<Result<Vec<u8>, ServiceError>> for GetRevokeBytesResult {
fn from(result: Result<Vec<u8>, ServiceError>) -> Self {
match result {
Ok(res) => GetRevokeBytesResult {
success: true,
error: "".to_string(),
result: res,
},
Err(e) => GetRevokeBytesResult {
success: false,
error: format!("{}", e),
result: vec![],
},
}
}
}
#[marine]
pub struct IssueRevocationResult {
pub success: bool,
pub error: String,
pub revoke: Revoke,
}
impl From<Result<Revoke, ServiceError>> for IssueRevocationResult {
fn from(result: Result<Revoke, ServiceError>) -> Self {
match result {
Ok(revoke) => IssueRevocationResult {
success: true,
error: "".to_string(),
revoke,
},
Err(e) => IssueRevocationResult {
success: false,
error: format!("{}", e),
revoke: Revoke::default(),
},
}
}
}
#[marine]
pub struct RevokeResult {
pub success: bool,
pub error: String,
}
impl From<Result<(), ServiceError>> for RevokeResult {
fn from(result: Result<(), ServiceError>) -> Self {
match result {
Ok(()) => RevokeResult {
success: true,
error: "".to_string(),
},
Err(e) => RevokeResult {
success: false,
error: format!("{}", e),
},
}
}
}

View File

@ -1,13 +1,11 @@
use crate::dto::{Certificate, Revoke, Trust}; use crate::dto::{Certificate, Trust};
use crate::results::{ use crate::results::{
AddRootResult, AddTrustResult, AllCertsResult, GetRevokeBytesResult, GetTrustBytesResult, AddRootResult, AddTrustResult, AllCertsResult, GetTrustMetadataResult, InsertResult,
InsertResult, IssueRevocationResult, IssueTrustResult, RevokeResult, VerifyTrustResult, IssueTrustResult, VerifyTrustResult, WeightResult,
WeightResult,
}; };
use crate::service_impl::{ use crate::service_impl::{
add_root_impl, add_trust_impl, get_all_certs_impl, get_revoke_bytes_impl, get_trust_bytes_imp, add_root_impl, add_trust_impl, get_all_certs_impl, get_trust_metadata_imp, get_weight_impl,
get_weight_impl, insert_cert_impl, insert_cert_impl_raw, issue_revocation_impl, insert_cert_impl, insert_cert_impl_raw, issue_trust_impl, verify_trust_impl,
issue_trust_impl, revoke_impl, verify_trust_impl,
}; };
use marine_rs_sdk::{marine, CallParameters}; use marine_rs_sdk::{marine, CallParameters};
@ -25,6 +23,7 @@ fn insert_cert(certificate: Certificate, timestamp_sec: u64) -> InsertResult {
insert_cert_impl(certificate, timestamp_sec).into() insert_cert_impl(certificate, timestamp_sec).into()
} }
// TODO: return only valid, delete expired, return max weight
#[marine] #[marine]
fn get_weight(peer_id: String, timestamp_sec: u64) -> WeightResult { fn get_weight(peer_id: String, timestamp_sec: u64) -> WeightResult {
get_weight_impl(peer_id.clone(), timestamp_sec) get_weight_impl(peer_id.clone(), timestamp_sec)
@ -32,34 +31,34 @@ fn get_weight(peer_id: String, timestamp_sec: u64) -> WeightResult {
.into() .into()
} }
// TODO: delete expired // TODO: return only valid, delete expired
#[marine] #[marine]
fn get_all_certs(issued_for: String, timestamp_sec: u64) -> AllCertsResult { fn get_all_certs(issued_for: String, timestamp_sec: u64) -> AllCertsResult {
get_all_certs_impl(issued_for, timestamp_sec).into() get_all_certs_impl(issued_for, timestamp_sec).into()
} }
#[marine] #[marine]
/// could add only a owner of a trust graph service /// could add only a host of a trust graph service
fn add_root(peer_id: String, weight_factor: u32) -> AddRootResult { fn add_root(peer_id: String, weight: u32) -> AddRootResult {
let call_parameters: CallParameters = marine_rs_sdk::get_call_parameters(); let call_parameters: CallParameters = marine_rs_sdk::get_call_parameters();
let init_peer_id = call_parameters.init_peer_id.clone(); let init_peer_id = call_parameters.init_peer_id.clone();
if call_parameters.service_creator_peer_id == init_peer_id { if call_parameters.host_id == init_peer_id {
add_root_impl(peer_id, weight_factor).into() add_root_impl(peer_id, weight).into()
} else { } else {
return AddRootResult { return AddRootResult {
success: false, success: false,
error: "Root could add only by trust graph service owner".to_string(), error: "Root could add only a host of trust graph service".to_string(),
}; };
} }
} }
#[marine] #[marine]
fn get_trust_bytes( fn get_trust_metadata(
issued_for_peer_id: String, issued_for_peer_id: String,
expires_at_sec: u64, expires_at_sec: u64,
issued_at_sec: u64, issued_at_sec: u64,
) -> GetTrustBytesResult { ) -> GetTrustMetadataResult {
get_trust_bytes_imp(issued_for_peer_id, expires_at_sec, issued_at_sec).into() get_trust_metadata_imp(issued_for_peer_id, expires_at_sec, issued_at_sec).into()
} }
#[marine] #[marine]
@ -67,13 +66,13 @@ fn issue_trust(
issued_for_peer_id: String, issued_for_peer_id: String,
expires_at_sec: u64, expires_at_sec: u64,
issued_at_sec: u64, issued_at_sec: u64,
trust_bytes: Vec<u8>, signed_metadata: Vec<u8>,
) -> IssueTrustResult { ) -> IssueTrustResult {
issue_trust_impl( issue_trust_impl(
issued_for_peer_id, issued_for_peer_id,
expires_at_sec, expires_at_sec,
issued_at_sec, issued_at_sec,
trust_bytes, signed_metadata,
) )
.into() .into()
} }
@ -83,33 +82,8 @@ fn verify_trust(trust: Trust, issuer_peer_id: String, timestamp_sec: u64) -> Ver
verify_trust_impl(trust, issuer_peer_id, timestamp_sec).into() verify_trust_impl(trust, issuer_peer_id, timestamp_sec).into()
} }
// TODO: check issued_at earlier than timestamp_sec
#[marine] #[marine]
fn add_trust(trust: Trust, issuer_peer_id: String, timestamp_sec: u64) -> AddTrustResult { fn add_trust(trust: Trust, issuer_peer_id: String, timestamp_sec: u64) -> AddTrustResult {
add_trust_impl(trust, issuer_peer_id, timestamp_sec).into() add_trust_impl(trust, issuer_peer_id, timestamp_sec).into()
} }
#[marine]
fn get_revoke_bytes(revoked_peer_id: String, revoked_at: u64) -> GetRevokeBytesResult {
get_revoke_bytes_impl(revoked_peer_id, revoked_at).into()
}
#[marine]
fn issue_revocation(
revoked_peer_id: String,
revoked_by_peer_id: String,
revoked_at_sec: u64,
signature_bytes: Vec<u8>,
) -> IssueRevocationResult {
issue_revocation_impl(
revoked_peer_id,
revoked_by_peer_id,
revoked_at_sec,
signature_bytes,
)
.into()
}
#[marine]
fn revoke(revoke: Revoke, timestamp_sec: u64) -> RevokeResult {
revoke_impl(revoke, timestamp_sec).into()
}

View File

@ -1,11 +1,12 @@
use crate::dto::{Certificate, DtoConversionError, Revoke, Trust}; use crate::dto::{Certificate, DtoConversionError, Trust};
use crate::service_impl::ServiceError::InvalidTimestampTetraplet; use crate::service_impl::ServiceError::InvalidTimestampTetraplet;
use crate::storage_impl::get_data; use crate::storage_impl::get_data;
use fluence_keypair::error::DecodingError; use fluence_keypair::error::DecodingError;
use fluence_keypair::public_key::peer_id_to_fluence_pk;
use fluence_keypair::{PublicKey, Signature}; use fluence_keypair::{PublicKey, Signature};
use libp2p_core::PeerId; use libp2p_core::PeerId;
use marine_rs_sdk::CallParameters; use marine_rs_sdk::CallParameters;
use std::convert::{Into, TryFrom, TryInto}; use std::convert::{Into, TryInto};
use std::str::FromStr; use std::str::FromStr;
use std::time::Duration; use std::time::Duration;
use thiserror::Error as ThisError; use thiserror::Error as ThisError;
@ -69,8 +70,6 @@ pub enum ServiceError {
), ),
#[error("you should use host peer.timestamp_sec to pass timestamp")] #[error("you should use host peer.timestamp_sec to pass timestamp")]
InvalidTimestampTetraplet, InvalidTimestampTetraplet,
#[error("Trust can't be issued later than the current timestamp")]
InvalidTrustTimestamp,
} }
fn parse_peer_id(peer_id: String) -> Result<PeerId, ServiceError> { fn parse_peer_id(peer_id: String) -> Result<PeerId, ServiceError> {
@ -79,18 +78,15 @@ fn parse_peer_id(peer_id: String) -> Result<PeerId, ServiceError> {
} }
fn extract_public_key(peer_id: String) -> Result<PublicKey, ServiceError> { fn extract_public_key(peer_id: String) -> Result<PublicKey, ServiceError> {
PublicKey::try_from( peer_id_to_fluence_pk(parse_peer_id(peer_id)?)
parse_peer_id(peer_id) .map_err(|e| ServiceError::PublicKeyExtractionError(e.to_string()))
.map_err(|e| ServiceError::PublicKeyExtractionError(e.to_string()))?,
)
.map_err(ServiceError::PublicKeyDecodeError)
} }
pub fn get_weight_impl(peer_id: String, timestamp_sec: u64) -> Result<u32, ServiceError> { pub fn get_weight_impl(peer_id: String, _timestamp_sec: u64) -> Result<u32, ServiceError> {
check_timestamp_tetraplets(&marine_rs_sdk::get_call_parameters(), 1)?; check_timestamp_tetraplets(&marine_rs_sdk::get_call_parameters(), 1)?;
let tg = get_data().lock(); let tg = get_data().lock();
let public_key = extract_public_key(peer_id)?; let public_key = extract_public_key(peer_id)?;
let weight = tg.weight(public_key, Duration::from_secs(timestamp_sec))?; let weight = tg.weight(public_key)?;
Ok(weight) Ok(weight)
} }
@ -110,13 +106,13 @@ pub fn insert_cert_impl_raw(certificate: String, timestamp_sec: u64) -> Result<(
pub fn get_all_certs_impl( pub fn get_all_certs_impl(
issued_for: String, issued_for: String,
timestamp_sec: u64, _timestamp_sec: u64,
) -> Result<Vec<Certificate>, ServiceError> { ) -> Result<Vec<Certificate>, ServiceError> {
check_timestamp_tetraplets(&marine_rs_sdk::get_call_parameters(), 1)?; check_timestamp_tetraplets(&marine_rs_sdk::get_call_parameters(), 1)?;
let tg = get_data().lock(); let tg = get_data().lock();
let public_key = extract_public_key(issued_for)?; let public_key = extract_public_key(issued_for)?;
let certs = tg.get_all_certs(public_key, Duration::from_secs(timestamp_sec))?; let certs = tg.get_all_certs(public_key)?;
Ok(certs.into_iter().map(|c| c.into()).collect()) Ok(certs.into_iter().map(|c| c.into()).collect())
} }
@ -134,7 +130,7 @@ pub fn add_root_impl(peer_id: String, weight: u32) -> Result<(), ServiceError> {
Ok(()) Ok(())
} }
pub fn get_trust_bytes_imp( pub fn get_trust_metadata_imp(
peer_id: String, peer_id: String,
expires_at_sec: u64, expires_at_sec: u64,
issued_at_sec: u64, issued_at_sec: u64,
@ -151,12 +147,12 @@ pub fn issue_trust_impl(
peer_id: String, peer_id: String,
expires_at_sec: u64, expires_at_sec: u64,
issued_at_sec: u64, issued_at_sec: u64,
trust_bytes: Vec<u8>, signed_metadata: Vec<u8>,
) -> Result<Trust, ServiceError> { ) -> Result<Trust, ServiceError> {
let public_key = extract_public_key(peer_id)?; let public_key = extract_public_key(peer_id)?;
let expires_at_sec = Duration::from_secs(expires_at_sec); let expires_at_sec = Duration::from_secs(expires_at_sec);
let issued_at_sec = Duration::from_secs(issued_at_sec); let issued_at_sec = Duration::from_secs(issued_at_sec);
let signature = Signature::from_bytes(public_key.get_key_format(), trust_bytes); let signature = Signature::from_bytes_with_public_key(&public_key, signed_metadata);
Ok(Trust::from(trust_graph::Trust::new( Ok(Trust::from(trust_graph::Trust::new(
public_key, public_key,
expires_at_sec, expires_at_sec,
@ -188,11 +184,6 @@ pub fn add_trust_impl(
) -> Result<u32, ServiceError> { ) -> Result<u32, ServiceError> {
let public_key = extract_public_key(issuer_peer_id)?; let public_key = extract_public_key(issuer_peer_id)?;
check_timestamp_tetraplets(&marine_rs_sdk::get_call_parameters(), 2)?; check_timestamp_tetraplets(&marine_rs_sdk::get_call_parameters(), 2)?;
if trust.issued_at > timestamp_sec {
return Err(ServiceError::InvalidTrustTimestamp);
}
let mut tg = get_data().lock(); let mut tg = get_data().lock();
tg.add_trust( tg.add_trust(
&trust.try_into()?, &trust.try_into()?,
@ -201,41 +192,3 @@ pub fn add_trust_impl(
) )
.map_err(ServiceError::TGError) .map_err(ServiceError::TGError)
} }
pub fn get_revoke_bytes_impl(
revoked_peer_id: String,
revoked_at: u64,
) -> Result<Vec<u8>, ServiceError> {
let public_key = extract_public_key(revoked_peer_id)?;
Ok(trust_graph::Revoke::signature_bytes(
&public_key,
Duration::from_secs(revoked_at),
))
}
pub fn issue_revocation_impl(
revoked_peer_id: String,
revoked_by_peer_id: String,
revoked_at_sec: u64,
signature_bytes: Vec<u8>,
) -> Result<Revoke, ServiceError> {
let revoked_pk = extract_public_key(revoked_peer_id)?;
let revoked_by_pk = extract_public_key(revoked_by_peer_id)?;
let revoked_at = Duration::from_secs(revoked_at_sec);
let signature = Signature::from_bytes(revoked_by_pk.get_key_format(), signature_bytes);
Ok(trust_graph::Revoke::new(revoked_pk, revoked_by_pk, revoked_at, signature).into())
}
pub fn revoke_impl(revoke: Revoke, timestamp_sec: u64) -> Result<(), ServiceError> {
check_timestamp_tetraplets(&marine_rs_sdk::get_call_parameters(), 1)?;
// TODO: use error for revoke, not trust
if revoke.revoked_at > timestamp_sec {
return Err(ServiceError::InvalidTrustTimestamp);
}
let mut tg = get_data().lock();
tg.revoke(revoke.try_into()?).map_err(ServiceError::TGError)
}

View File

@ -44,8 +44,11 @@ mod tests {
macro_rules! issue_trust { macro_rules! issue_trust {
($trust_graph:expr, $issuer_kp:expr, $issued_peer_id: expr, $expires_at:expr, $issued_at: expr) => {{ ($trust_graph:expr, $issuer_kp:expr, $issued_peer_id: expr, $expires_at:expr, $issued_at: expr) => {{
let trust_metadata_result = let trust_metadata_result = $trust_graph.get_trust_metadata(
$trust_graph.get_trust_bytes($issued_peer_id.to_base58(), $expires_at, $issued_at); $issued_peer_id.to_base58(),
$expires_at,
$issued_at,
);
assert_result!(trust_metadata_result); assert_result!(trust_metadata_result);
let metadata = trust_metadata_result.result; let metadata = trust_metadata_result.result;

View File

@ -19,7 +19,6 @@ use fluence_keypair::key_pair::KeyPair;
use fluence_keypair::public_key::PublicKey; use fluence_keypair::public_key::PublicKey;
use fluence_keypair::signature::Signature; use fluence_keypair::signature::Signature;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::time::Duration; use std::time::Duration;
use thiserror::Error as ThisError; use thiserror::Error as ThisError;
@ -29,7 +28,7 @@ pub enum RevokeError {
IncorrectSignature( IncorrectSignature(
#[from] #[from]
#[source] #[source]
fluence_keypair::error::SigningError, fluence_keypair::error::SigningError
), ),
} }
@ -44,12 +43,12 @@ pub struct Revoke {
/// the issuer of this revocation /// the issuer of this revocation
pub revoked_by: PublicKey, pub revoked_by: PublicKey,
/// proof of this revocation /// proof of this revocation
pub signature: Signature, signature: Signature,
} }
impl Revoke { impl Revoke {
#[allow(dead_code)] #[allow(dead_code)]
pub fn new( fn new(
pk: PublicKey, pk: PublicKey,
revoked_by: PublicKey, revoked_by: PublicKey,
revoked_at: Duration, revoked_at: Duration,
@ -72,14 +71,14 @@ impl Revoke {
Revoke::new(to_revoke, revoker.public(), revoked_at, signature) Revoke::new(to_revoke, revoker.public(), revoked_at, signature)
} }
pub fn signature_bytes(pk: &PublicKey, revoked_at: Duration) -> Vec<u8> { fn signature_bytes(pk: &PublicKey, revoked_at: Duration) -> Vec<u8> {
let mut metadata = Vec::new(); let mut msg = Vec::new();
let pk_bytes = &pk.encode(); let pk_bytes = &pk.encode();
metadata.push(pk_bytes.len() as u8); msg.push(pk_bytes.len() as u8);
metadata.extend(pk_bytes); msg.extend(pk_bytes);
metadata.extend_from_slice(&(revoked_at.as_secs() as u64).to_le_bytes()); msg.extend_from_slice(&(revoked_at.as_secs() as u64).to_le_bytes());
sha2::Sha256::digest(&metadata).to_vec() msg
} }
/// Verifies that revocation is cryptographically correct. /// Verifies that revocation is cryptographically correct.
@ -88,8 +87,7 @@ impl Revoke {
revoke revoke
.revoked_by .revoked_by
.verify(msg.as_slice(), &revoke.signature) .verify(msg.as_slice(), &revoke.signature).map_err(IncorrectSignature)
.map_err(IncorrectSignature)
} }
} }

View File

@ -14,9 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::trust::TrustError::{ use crate::trust::TrustError::{Base58DecodeError, DecodePublicKeyError, ParseError, SignatureError, DecodeErrorInvalidSize};
Base58DecodeError, DecodeErrorInvalidSize, DecodePublicKeyError, ParseError, SignatureError,
};
use derivative::Derivative; use derivative::Derivative;
use fluence_keypair::key_pair::KeyPair; use fluence_keypair::key_pair::KeyPair;
use fluence_keypair::public_key::PublicKey; use fluence_keypair::public_key::PublicKey;

View File

@ -131,7 +131,7 @@ where
{ {
Trust::verify(trust.borrow(), issued_by.borrow(), cur_time)?; Trust::verify(trust.borrow(), issued_by.borrow(), cur_time)?;
let issued_by_weight = self.weight(issued_by.borrow().clone().borrow(), cur_time)?; let issued_by_weight = self.weight(issued_by.borrow().clone().borrow())?;
if issued_by_weight == 0u32 { if issued_by_weight == 0u32 {
return Ok(0u32); return Ok(0u32);
@ -188,7 +188,7 @@ where
} }
/// Get the maximum weight of trust for one public key. /// Get the maximum weight of trust for one public key.
pub fn weight<P>(&self, pk: P, cur_time: Duration) -> Result<u32, TrustGraphError> pub fn weight<P>(&self, pk: P) -> Result<u32, TrustGraphError>
where where
P: Borrow<PublicKey>, P: Borrow<PublicKey>,
{ {
@ -197,7 +197,7 @@ where
} }
// get all possible certificates from the given public key to all roots in the graph // get all possible certificates from the given public key to all roots in the graph
let certs = self.get_all_certs(pk, cur_time)?; let certs = self.get_all_certs(pk)?;
self.certificates_weight_factor(certs) self.certificates_weight_factor(certs)
.map(|wf| wf.map(get_weight_from_factor).unwrap_or(0u32)) .map(|wf| wf.map(get_weight_from_factor).unwrap_or(0u32))
} }
@ -251,16 +251,11 @@ where
&self, &self,
node: &TrustNode, node: &TrustNode,
roots: HashSet<&PK>, roots: HashSet<&PK>,
cur_time: Duration,
) -> Result<Vec<Vec<Auth>>, TrustGraphError> { ) -> Result<Vec<Vec<Auth>>, TrustGraphError> {
// queue to collect all chains in the trust graph (each chain is a path in the trust graph) // queue to collect all chains in the trust graph (each chain is a path in the trust graph)
let mut chains_queue: VecDeque<Vec<Auth>> = VecDeque::new(); let mut chains_queue: VecDeque<Vec<Auth>> = VecDeque::new();
let node_auths: Vec<Auth> = node let node_auths: Vec<Auth> = node.authorizations().cloned().collect();
.authorizations()
.cloned()
.filter(|auth| auth.trust.expires_at > cur_time)
.collect();
// put all auth in the queue as the first possible paths through the graph // put all auth in the queue as the first possible paths through the graph
for auth in node_auths { for auth in node_auths {
chains_queue.push_back(vec![auth]); chains_queue.push_back(vec![auth]);
@ -284,7 +279,6 @@ where
.ok_or(CertificateCheckError(Unexpected))? .ok_or(CertificateCheckError(Unexpected))?
.authorizations() .authorizations()
.cloned() .cloned()
.filter(|auth| auth.trust.expires_at > cur_time)
.collect(); .collect();
for auth in auths { for auth in auths {
@ -317,11 +311,7 @@ where
/// Get all possible certificates where `issued_for` will be the last element of the chain /// Get all possible certificates where `issued_for` will be the last element of the chain
/// and one of the destinations is the root of this chain. /// and one of the destinations is the root of this chain.
pub fn get_all_certs<P>( pub fn get_all_certs<P>(&self, issued_for: P) -> Result<Vec<Certificate>, TrustGraphError>
&self,
issued_for: P,
cur_time: Duration,
) -> Result<Vec<Certificate>, TrustGraphError>
where where
P: Borrow<PublicKey>, P: Borrow<PublicKey>,
{ {
@ -333,7 +323,7 @@ where
match issued_for_node { match issued_for_node {
Some(node) => Ok(self Some(node) => Ok(self
.bf_search_paths(&node, roots, cur_time)? .bf_search_paths(&node, roots)?
.iter() .iter()
.map(|auths| { .map(|auths| {
// TODO: can avoid cloning here by returning &Certificate // TODO: can avoid cloning here by returning &Certificate
@ -538,13 +528,13 @@ mod tests {
graph.add(cert1, current_time()).unwrap(); graph.add(cert1, current_time()).unwrap();
let root_weight = get_weight_from_factor(1); let root_weight = get_weight_from_factor(1);
let w1 = graph.weight(key_pairs[0].public(), current_time()).unwrap(); let w1 = graph.weight(key_pairs[0].public()).unwrap();
assert_eq!(w1, root_weight * 2u32.pow(0)); assert_eq!(w1, root_weight * 2u32.pow(0));
let w2 = graph.weight(key_pairs[1].public(), current_time()).unwrap(); let w2 = graph.weight(key_pairs[1].public()).unwrap();
assert_eq!(w2, root_weight / 2u32.pow(1)); assert_eq!(w2, root_weight / 2u32.pow(1));
let w3 = graph.weight(key_pairs[9].public(), current_time()).unwrap(); let w3 = graph.weight(key_pairs[9].public()).unwrap();
assert_eq!(w3, root_weight / 2u32.pow(9)); assert_eq!(w3, root_weight / 2u32.pow(9));
let node = graph.get(key_pairs[9].public()).unwrap().unwrap(); let node = graph.get(key_pairs[9].public()).unwrap().unwrap();
@ -600,12 +590,12 @@ mod tests {
); );
graph.revoke(revoke2).unwrap(); graph.revoke(revoke2).unwrap();
let w1 = graph.weight(key_pair1.public(), current_time()).unwrap(); let w1 = graph.weight(key_pair1.public()).unwrap();
// all upper trusts are revoked for this public key // all upper trusts are revoked for this public key
let w2 = graph.weight(key_pair2.public(), current_time()).unwrap(); let w2 = graph.weight(key_pair2.public()).unwrap();
let w3 = graph.weight(key_pair3.public(), current_time()).unwrap(); let w3 = graph.weight(key_pair3.public()).unwrap();
let w_last1 = graph.weight(last_pk1, current_time()).unwrap(); let w_last1 = graph.weight(last_pk1).unwrap();
let w_last2 = graph.weight(last_pk2, current_time()).unwrap(); let w_last2 = graph.weight(last_pk2).unwrap();
assert_eq!(w1, get_weight_from_factor(4)); assert_eq!(w1, get_weight_from_factor(4));
assert_eq!(w2, 0); // revoked assert_eq!(w2, 0); // revoked
@ -628,7 +618,7 @@ mod tests {
graph.add(cert.clone(), current_time()).unwrap(); graph.add(cert.clone(), current_time()).unwrap();
let certs = graph let certs = graph
.get_all_certs(key_pairs.last().unwrap().public(), current_time()) .get_all_certs(key_pairs.last().unwrap().public())
.unwrap(); .unwrap();
assert_eq!(certs.len(), 1); assert_eq!(certs.len(), 1);
@ -655,7 +645,7 @@ mod tests {
graph.add(cert.clone(), current_time()).unwrap(); graph.add(cert.clone(), current_time()).unwrap();
let t = cert.chain[5].clone(); let t = cert.chain[5].clone();
let certs = graph.get_all_certs(t.issued_for, current_time()).unwrap(); let certs = graph.get_all_certs(t.issued_for).unwrap();
assert_eq!(certs.len(), 1); assert_eq!(certs.len(), 1);
} }
@ -706,23 +696,17 @@ mod tests {
graph.add(cert2, current_time()).unwrap(); graph.add(cert2, current_time()).unwrap();
graph.add(cert3, current_time()).unwrap(); graph.add(cert3, current_time()).unwrap();
let certs1 = graph let certs1 = graph.get_all_certs(key_pair1.public()).unwrap();
.get_all_certs(key_pair1.public(), current_time())
.unwrap();
let lenghts1: Vec<usize> = certs1.iter().map(|c| c.chain.len()).collect(); let lenghts1: Vec<usize> = certs1.iter().map(|c| c.chain.len()).collect();
let check_lenghts1: Vec<usize> = vec![3, 4, 4, 5, 5]; let check_lenghts1: Vec<usize> = vec![3, 4, 4, 5, 5];
assert_eq!(lenghts1, check_lenghts1); assert_eq!(lenghts1, check_lenghts1);
let certs2 = graph let certs2 = graph.get_all_certs(key_pair2.public()).unwrap();
.get_all_certs(key_pair2.public(), current_time())
.unwrap();
let lenghts2: Vec<usize> = certs2.iter().map(|c| c.chain.len()).collect(); let lenghts2: Vec<usize> = certs2.iter().map(|c| c.chain.len()).collect();
let check_lenghts2: Vec<usize> = vec![4, 4, 4, 5, 5]; let check_lenghts2: Vec<usize> = vec![4, 4, 4, 5, 5];
assert_eq!(lenghts2, check_lenghts2); assert_eq!(lenghts2, check_lenghts2);
let certs3 = graph let certs3 = graph.get_all_certs(key_pair3.public()).unwrap();
.get_all_certs(key_pair3.public(), current_time())
.unwrap();
let lenghts3: Vec<usize> = certs3.iter().map(|c| c.chain.len()).collect(); let lenghts3: Vec<usize> = certs3.iter().map(|c| c.chain.len()).collect();
let check_lenghts3: Vec<usize> = vec![3, 3, 5]; let check_lenghts3: Vec<usize> = vec![3, 3, 5];
assert_eq!(lenghts3, check_lenghts3); assert_eq!(lenghts3, check_lenghts3);
@ -753,16 +737,11 @@ mod tests {
let weight = graph let weight = graph
.add_trust(trust.clone(), issued_by.public(), cur_time) .add_trust(trust.clone(), issued_by.public(), cur_time)
.unwrap(); .unwrap();
assert_eq!( assert_eq!(weight, graph.weight(issued_by.public()).unwrap() / 2);
weight,
graph.weight(issued_by.public(), current_time()).unwrap() / 2
);
cert.chain.push(trust); cert.chain.push(trust);
let certs = graph let certs = graph.get_all_certs(trust_kp.public()).unwrap();
.get_all_certs(trust_kp.public(), current_time())
.unwrap();
assert_eq!(certs.len(), 1); assert_eq!(certs.len(), 1);
assert_eq!(certs[0], cert); assert_eq!(certs[0], cert);
} }
@ -792,18 +771,13 @@ mod tests {
let weight = graph let weight = graph
.add_trust(trust.clone(), issued_by.public(), cur_time) .add_trust(trust.clone(), issued_by.public(), cur_time)
.unwrap(); .unwrap();
assert_eq!( assert_eq!(weight, graph.weight(issued_by.public()).unwrap() / 2);
weight,
graph.weight(issued_by.public(), current_time()).unwrap() / 2
);
let target_cert = Certificate { let target_cert = Certificate {
chain: vec![cert.chain[0].clone(), trust], chain: vec![cert.chain[0].clone(), trust],
}; };
let certs = graph let certs = graph.get_all_certs(trust_kp.public()).unwrap();
.get_all_certs(trust_kp.public(), current_time())
.unwrap();
assert_eq!(certs.len(), 1); assert_eq!(certs.len(), 1);
assert_eq!(certs[0], target_cert); assert_eq!(certs[0], target_cert);
} }
@ -830,44 +804,6 @@ mod tests {
); );
graph.revoke(revoke.clone()).unwrap(); graph.revoke(revoke.clone()).unwrap();
assert_eq!(0, graph.weight(revoked.public(), current_time()).unwrap()); assert_eq!(0, graph.weight(revoked.public()).unwrap());
}
#[test]
fn test_expired_trust() {
let (key_pairs, mut cert) = generate_cert_with_len(5, HashMap::new()).unwrap();
let cur_time = current_time();
let st = InMemoryStorage::new();
let mut graph = TrustGraph::new(st);
let root1_pk = key_pairs[0].public();
graph
.add_root_weight_factor(root1_pk.clone().into(), 2)
.unwrap();
graph.add(cert.clone(), cur_time).unwrap();
let issued_by = key_pairs.last().unwrap();
let trust_kp = KeyPair::generate_ed25519();
let expired_time = cur_time.checked_add(one_minute()).unwrap();
let trust = Trust::create(issued_by, trust_kp.public(), expired_time, cur_time);
let weight = graph
.add_trust(trust.clone(), issued_by.public(), cur_time)
.unwrap();
assert_eq!(
weight,
graph.weight(issued_by.public(), cur_time).unwrap() / 2
);
cert.chain.push(trust);
let certs = graph.get_all_certs(trust_kp.public(), cur_time).unwrap();
assert_eq!(certs.len(), 1);
assert_eq!(certs[0], cert);
let certs = graph
.get_all_certs(trust_kp.public(), expired_time)
.unwrap();
assert_eq!(certs.len(), 0);
} }
} }