Skip to content

Commit

Permalink
Merge pull request #192 from gnosisguild/ry/180-save-keypair
Browse files Browse the repository at this point in the history
Save keypair to and from repository
  • Loading branch information
hmzakhalid authored Dec 2, 2024
2 parents 95af527 + 60f65c9 commit 31de6e5
Show file tree
Hide file tree
Showing 23 changed files with 186 additions and 34 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"preciphernode:build": "yarn evm:compile",
"committee:new": "cd packages/evm && yarn committee:new",
"committee:publish": "cd packages/evm && yarn hardhat committee:publish",
"e3:activate": "cd packages/evm && yarn hardhat e3:activate",
"e3:activate": "cd packages/evm && yarn -s hardhat e3:activate",
"e3:publishInput": "cd packages/evm && yarn hardhat e3:publishInput",
"e3:publishCiphertext": "cd packages/evm && yarn hardhat e3:publishCiphertext",
"evm:install": "cd packages/evm && yarn install",
Expand Down
3 changes: 3 additions & 0 deletions packages/ciphernode/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions packages/ciphernode/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ bincode = "1.3.3"
bs58 = "0.5.1"
base64 = "0.22.1"
clap = { version = "4.5.17", features = ["derive"] }
cipher = { path = "./cipher" }
dirs = "5.0.1"
data = { path = "./data" }
figment = { version = "0.10.19", features = ["yaml", "test"] }
fhe_rs = { package = "fhe", git = "https://github.com/gnosisguild/fhe.rs", version = "0.1.0-beta.7" }
fhe-traits = { git = "https://github.com/gnosisguild/fhe.rs", version = "0.1.0-beta.7" }
Expand Down
1 change: 1 addition & 0 deletions packages/ciphernode/cipher/src/cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ impl Cipher {
Ok(Self::new(FilePasswordManager::new(config.key_file())).await?)
}

/// Encrypt the given data and zeroize the data after encryption
pub fn encrypt_data(&self, data: &mut Vec<u8>) -> Result<Vec<u8>> {
encrypt_data(&self.key, data)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/ciphernode/core/src/eventbus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub struct ResetHistory;

/// Central EventBus for each node. Actors publish events to this bus by sending it EnclaveEvents.
/// All events sent to this bus are assumed to be published over the network via pubsub.
/// Other actors such as the NetworkRelay and Evm actor connect to outside services and control which events
/// Other actors such as the NetworkManager and Evm actor connect to outside services and control which events
/// actually get published as well as ensure that local events are not rebroadcast locally after
/// being published.
pub struct EventBus {
Expand Down
23 changes: 23 additions & 0 deletions packages/ciphernode/data/src/data_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,26 @@ impl Get {
}
}

#[derive(Message, Clone, Debug, PartialEq, Eq, Hash)]
#[rtype(result = "()")]
pub struct Remove(pub Vec<u8>);
impl Remove {
pub fn new<K: IntoKey>(key: K) -> Self {
Self(key.into_key())
}

pub fn key(&self) -> &Vec<u8> {
&self.0
}
}

/// Generate proxy for the DB
#[derive(Clone, Debug)]
pub struct DataStore {
scope: Vec<u8>,
get: Recipient<Get>,
insert: Recipient<Insert>,
remove: Recipient<Remove>,
}

impl DataStore {
Expand Down Expand Up @@ -69,6 +83,11 @@ impl DataStore {
self.insert.do_send(msg)
}

/// Removes data from the scope location
pub fn clear(&self) {
self.remove.do_send(Remove::new(&self.scope))
}

/// Get the scope as a string
pub fn get_scope(&self) -> Result<Cow<str>> {
Ok(String::from_utf8_lossy(&self.scope))
Expand Down Expand Up @@ -103,6 +122,7 @@ impl DataStore {
Self {
get: self.get.clone(),
insert: self.insert.clone(),
remove: self.remove.clone(),
scope,
}
}
Expand All @@ -111,6 +131,7 @@ impl DataStore {
Self {
get: self.get.clone(),
insert: self.insert.clone(),
remove: self.remove.clone(),
scope: key.into_key(),
}
}
Expand All @@ -121,6 +142,7 @@ impl From<&Addr<SledStore>> for DataStore {
Self {
get: addr.clone().recipient(),
insert: addr.clone().recipient(),
remove: addr.clone().recipient(),
scope: vec![],
}
}
Expand All @@ -131,6 +153,7 @@ impl From<&Addr<InMemStore>> for DataStore {
Self {
get: addr.clone().recipient(),
insert: addr.clone().recipient(),
remove: addr.clone().recipient(),
scope: vec![],
}
}
Expand Down
15 changes: 14 additions & 1 deletion packages/ciphernode/data/src/in_mem.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use actix::{Actor, Context, Handler, Message};
use std::collections::BTreeMap;

use crate::{Get, Insert};
use crate::{Get, Insert, Remove};

#[derive(Message, Clone, Debug, PartialEq, Eq, Hash)]
#[rtype(result = "Vec<DataOp>")]
Expand All @@ -10,6 +10,7 @@ pub struct GetLog;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum DataOp {
Insert(Insert),
Remove(Remove),
}

pub struct InMemStore {
Expand Down Expand Up @@ -44,6 +45,18 @@ impl Handler<Insert> for InMemStore {
}
}

impl Handler<Remove> for InMemStore {
type Result = ();
fn handle(&mut self, event: Remove, _: &mut Self::Context) {
// insert data into sled
self.db.remove(&event.key().to_vec());

if self.capture {
self.log.push(DataOp::Remove(event));
}
}
}

impl Handler<Get> for InMemStore {
type Result = Option<Vec<u8>>;
fn handle(&mut self, event: Get, _: &mut Self::Context) -> Option<Vec<u8>> {
Expand Down
6 changes: 5 additions & 1 deletion packages/ciphernode/data/src/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ where
}

pub fn write(&self, value: &T) {
self.store.write(value)
self.store.write(value);
}

pub fn clear(&self) {
self.store.clear();
}
}
22 changes: 21 additions & 1 deletion packages/ciphernode/data/src/sled_store.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::path::PathBuf;

use crate::{Get, Insert};
use crate::{Get, Insert, Remove};
use actix::{Actor, ActorContext, Addr, Handler};
use anyhow::{Context, Result};
use enclave_core::{BusError, EnclaveErrorType, EnclaveEvent, EventBus, Subscribe};
Expand Down Expand Up @@ -53,6 +53,19 @@ impl Handler<Insert> for SledStore {
}
}

impl Handler<Remove> for SledStore {
type Result = ();

fn handle(&mut self, event: Remove, _: &mut Self::Context) -> Self::Result {
if let Some(ref mut db) = &mut self.db {
match db.remove(event) {
Err(err) => self.bus.err(EnclaveErrorType::Data, err),
_ => (),
}
}
}
}

impl Handler<Get> for SledStore {
type Result = Option<Vec<u8>>;

Expand Down Expand Up @@ -105,6 +118,13 @@ impl SledDb {
Ok(())
}

pub fn remove(&mut self, msg: Remove) -> Result<()> {
self.db
.remove(msg.key())
.context("Could not remove data from db")?;
Ok(())
}

pub fn get(&mut self, event: Get) -> Result<Option<Vec<u8>>> {
let key = event.key();
let str_key = String::from_utf8_lossy(&key).into_owned();
Expand Down
8 changes: 8 additions & 0 deletions packages/ciphernode/enclave/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
pub mod aggregator;
pub mod net;
pub mod password;
pub mod start;
pub mod wallet;

use self::password::PasswordCommands;
use aggregator::AggregatorCommands;
use clap::Subcommand;
use net::NetCommands;
use wallet::WalletCommands;

#[derive(Subcommand, Debug)]
Expand All @@ -30,4 +32,10 @@ pub enum Commands {
#[command(subcommand)]
command: WalletCommands,
},

/// Networking related commands
Net {
#[command(subcommand)]
command: NetCommands,
},
}
18 changes: 18 additions & 0 deletions packages/ciphernode/enclave/src/commands/net/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
mod purge;
use anyhow::*;
use clap::Subcommand;
use config::AppConfig;

#[derive(Subcommand, Debug)]
pub enum NetCommands {
/// Purge the current peer ID from the database.
PurgeId,
}

pub async fn execute(command: NetCommands, config: AppConfig) -> Result<()> {
match command {
NetCommands::PurgeId => purge::execute(&config).await?,
};

Ok(())
}
13 changes: 13 additions & 0 deletions packages/ciphernode/enclave/src/commands/net/purge.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use actix::Actor;
use anyhow::*;
use config::AppConfig;
use enclave_core::EventBus;
use enclave_node::get_repositories;

pub async fn execute(config: &AppConfig) -> Result<()> {
let bus = EventBus::new(true).start();
let repositories = get_repositories(&config, &bus)?;
repositories.libp2pid().clear();
println!("Peer ID has been purged. A new Peer ID will be generated upon restart.");
Ok(())
}
3 changes: 2 additions & 1 deletion packages/ciphernode/enclave/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::Result;
use clap::Parser;
use commands::{aggregator, password, start, wallet, Commands};
use commands::{aggregator, net, password, start, wallet, Commands};
use config::load_config;
use enclave_core::{get_tag, set_tag};
use tracing::instrument;
Expand Down Expand Up @@ -53,6 +53,7 @@ impl Cli {
Commands::Password { command } => password::execute(command, config).await?,
Commands::Aggregator { command } => aggregator::execute(command, config).await?,
Commands::Wallet { command } => wallet::execute(command, config).await?,
Commands::Net { command } => net::execute(command, config).await?,
}

Ok(())
Expand Down
10 changes: 8 additions & 2 deletions packages/ciphernode/enclave_node/src/aggregator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use evm::{
CiphernodeRegistrySol, EnclaveSol, RegistryFilterSol,
};
use logger::SimpleLogger;
use net::NetworkRelay;
use net::NetworkManager;
use rand::SeedableRng;
use rand_chacha::{rand_core::OsRng, ChaCha20Rng};
use router::{
Expand Down Expand Up @@ -81,7 +81,13 @@ pub async fn setup_aggregator(
.build()
.await?;

let (_, join_handle, peer_id) = NetworkRelay::setup_with_peer(bus.clone(), config.peers())?;
let (_, join_handle, peer_id) = NetworkManager::setup_with_peer(
bus.clone(),
config.peers(),
&cipher,
repositories.libp2pid(),
)
.await?;

if let Some(path) = pubkey_write_path {
PublicKeyWriter::attach(path, bus.clone());
Expand Down
10 changes: 8 additions & 2 deletions packages/ciphernode/enclave_node/src/ciphernode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use evm::{
CiphernodeRegistrySol, EnclaveSolReader,
};
use logger::SimpleLogger;
use net::NetworkRelay;
use net::NetworkManager;
use rand::SeedableRng;
use rand_chacha::rand_core::OsRng;
use router::{
Expand Down Expand Up @@ -73,7 +73,13 @@ pub async fn setup_ciphernode(
.build()
.await?;

let (_, join_handle, peer_id) = NetworkRelay::setup_with_peer(bus.clone(), config.peers())?;
let (_, join_handle, peer_id) = NetworkManager::setup_with_peer(
bus.clone(),
config.peers(),
&cipher,
repositories.libp2pid(),
)
.await?;

let nm = format!("CIPHER({})", &address.to_string()[0..5]);
SimpleLogger::attach(&nm, bus.clone());
Expand Down
3 changes: 3 additions & 0 deletions packages/ciphernode/net/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ repository = "https://github.com/gnosisguild/enclave/packages/ciphernode"
async-std = { workspace = true, features = ["attributes"] }
async-trait = { workspace = true }
futures = { workspace = true }
cipher = { workspace = true }
data = { workspace = true }
libp2p = { workspace = true, features = [
"async-std",
"gossipsub",
Expand All @@ -28,3 +30,4 @@ tracing-subscriber = { workspace = true, features = ["env-filter"] }
enclave-core = { path = "../core" }
anyhow = { workspace = true }
actix = { workspace = true }
zeroize = { workspace = true }
4 changes: 2 additions & 2 deletions packages/ciphernode/net/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#![crate_name = "net"]
#![crate_type = "lib"]

mod network_manager;
mod network_peer;
mod network_relay;

pub use network_manager::*;
pub use network_peer::*;
pub use network_relay::*;
Loading

0 comments on commit 31de6e5

Please sign in to comment.