Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 82 additions & 74 deletions Cargo.lock

Large diffs are not rendered by default.

26 changes: 25 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ use rust_decimal::Decimal;
use serde::Deserialize;
use tracing::Level;

use crate::{keys, network::NodeId};
use crate::{
keys,
network::{ChannelRole, NodeId},
};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Asset {
Expand Down Expand Up @@ -339,11 +342,30 @@ pub struct KeygenConfig {
pub min_signers: Option<u16>,
}

#[derive(Debug, Default, Deserialize, Clone)]
pub enum PeerRole {
#[default]
Full,
Dkg,
Oracle,
}
impl PeerRole {
pub fn matches(&self, role: ChannelRole) -> bool {
match self {
Self::Full => true,
Self::Dkg => matches!(role, ChannelRole::Dkg),
Self::Oracle => matches!(role, ChannelRole::Oracle),
}
}
}

#[derive(Debug, Deserialize, Clone)]
pub struct RawPeerConfig {
pub label: Option<String>,
pub address: String,
pub public_key: String,
#[serde(default)]
pub role: PeerRole,
}

#[derive(Debug, Clone)]
Expand All @@ -352,6 +374,7 @@ pub struct Peer {
pub public_key: VerifyingKey,
pub label: String,
pub address: String,
pub role: PeerRole,
}
impl TryFrom<RawPeerConfig> for Peer {
type Error = anyhow::Error;
Expand All @@ -368,6 +391,7 @@ impl TryFrom<RawPeerConfig> for Peer {
public_key,
label,
address: raw.address,
role: raw.role,
})
}
}
Expand Down
111 changes: 69 additions & 42 deletions src/dkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,79 @@ mod logic;
#[cfg(test)]
mod tests;

use std::path::PathBuf;

use logic::GeneratedKeys;
pub use logic::KeygenMessage;

use crate::{config::OracleConfig, health::HealthSink, keys, network::Network};
use anyhow::{Context, Result, anyhow};
use tokio::{select, task::spawn_blocking};
use tracing::info;

pub async fn run(config: &OracleConfig) -> Result<()> {
let keys_dir = keys::get_keys_directory()?;

// Log where the keys will be saved
info!(
"Running in DKG mode. Will generate frost keys into {}.",
keys_dir.display()
);

let mut network = Network::new(&config.network, HealthSink::noop());

let id = network.id.clone();
let channel = network.keygen_channel();
let max_signers = config.network.peers.len() as u16 + 1;
let min_signers = config
.keygen
.min_signers
.ok_or_else(|| anyhow!("Must specify min_signers"))?;

select! {
result = network.listen() => {
result?;
return Err(anyhow!("Network shut down prematurely"));
}
result = logic::run(id, channel, max_signers, min_signers) => {
let GeneratedKeys(private_key, public_key) = result?;
let address = keys::write_frost_keys(&keys_dir, private_key, public_key).context("Could not save frost keys")?;
info!("The new frost address is: {}", address);

// Wait for keyboard input, so these are convenient to shut down while testing locally.
// On a real server, this just waits "forever".
spawn_blocking(|| {
info!("Press enter to shut down.");
std::io::stdin().read_line(&mut String::new()).unwrap();
})
.await?;
}
use crate::{
config::OracleConfig,
health::HealthSink,
keys,
network::{ChannelRole, Network, NetworkChannel, NodeId},
};
use anyhow::{Result, anyhow};

pub struct Keygen {
id: NodeId,
channel: NetworkChannel<KeygenMessage>,
max_signers: u16,
min_signers: u16,
keys_dir: PathBuf,
health: HealthSink,
}

impl Keygen {
pub fn new(
config: &OracleConfig,
network: &mut Network,
health_sink: HealthSink,
) -> Result<Self> {
let id = network.id.clone();
let channel = network.keygen_channel();
let max_signers = config
.network
.peers
.iter()
.filter(|peer| peer.role.matches(ChannelRole::Dkg))
.count() as u16
+ 1;
let min_signers = config
.keygen
.min_signers
.ok_or_else(|| anyhow!("Must specify min_signers"))?;
let keys_dir = keys::get_keys_directory()?;
Ok(Self {
id,
channel,
max_signers,
min_signers,
keys_dir,
health: health_sink,
})
}

Ok(())
pub async fn run(self) -> Result<()> {
let Self {
id,
channel,
max_signers,
min_signers,
keys_dir,
health,
} = self;

info!(
"Running in DKG mode. Will generate frost keys into {}.",
keys_dir.display()
);

let GeneratedKeys(private_key, public_key) =
logic::run(id, channel, max_signers, min_signers, health).await?;
let address = keys::write_frost_keys(&keys_dir, private_key, public_key)?;
info!("The new frost address is: {address}");

Ok(())
}
}
8 changes: 8 additions & 0 deletions src/dkg/logic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{

use crate::{
cbor::{CborDkgRound1Package, CborDkgRound2Package},
health::HealthSink,
network::{NetworkChannel, NetworkSender, NodeId},
};
use anyhow::{Result, anyhow};
Expand Down Expand Up @@ -142,6 +143,7 @@ pub async fn run(
channel: NetworkChannel<KeygenMessage>,
max_signers: u16,
min_signers: u16,
health: HealthSink,
) -> Result<GeneratedKeys> {
let peers_count = max_signers as usize - 1;

Expand All @@ -155,6 +157,7 @@ pub async fn run(
let rng = thread_rng();
part1(identifier, max_signers, min_signers, rng)?
};
health.update_dkg(&id, "Round 1".to_string());

let broadcast_state = Arc::new(RwLock::new(BroadcastState::new(
sender.clone(),
Expand Down Expand Up @@ -212,6 +215,7 @@ pub async fn run(
continue;
}
debug!(%from, "Received new round 1 package");
health.update_dkg(&from, "Round 1".to_string());

round1_hashes.insert(
from_id,
Expand All @@ -225,6 +229,7 @@ pub async fn run(
session_id,
"Round 1 complete! Beginning round 2, waiting for all peers to send round 2 packages"
);
health.update_dkg(&id, format!("Round 2 (session {session_id})"));

round2_packages.clear();

Expand Down Expand Up @@ -265,6 +270,7 @@ pub async fn run(
continue;
}
debug!(%from, session_id, "Received new round 2 package");
health.update_dkg(&from, format!("Round 2 (session {session_id})"));

round2_packages.insert(from_id, package);
if round2_packages.len() == peers_count {
Expand All @@ -276,6 +282,7 @@ pub async fn run(
session_id,
"Key generation complete! Waiting for all peers to confirm they have generated keys as well"
);
health.update_dkg(&id, format!("Done (session {session_id})"));

generated_keys.replace(GeneratedKeys(key_package, public_key_package));
done_sets
Expand All @@ -291,6 +298,7 @@ pub async fn run(
}
KeygenMessage::Done(DoneMessage { session_id }) => {
debug!(%from, session_id, "Received new done message");
health.update_dkg(&from, format!("Done (session {session_id})"));
done_sets.entry(session_id).or_default().insert(from);
}
}
Expand Down
23 changes: 20 additions & 3 deletions src/dkg/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ use anyhow::Result;
use futures::{Future, FutureExt};
use tokio::select;

use crate::network::{NodeId, OutgoingMessage};
use crate::{
health::HealthSink,
network::{NodeId, OutgoingMessage},
};

use super::{
KeygenMessage,
Expand All @@ -24,7 +27,14 @@ struct Participant {
impl Participant {
pub fn new(network: &mut TestNetwork, max_signers: u16, min_signers: u16) -> Self {
let (id, channel) = network.connect();
let task = logic::run(id.clone(), channel, max_signers, min_signers).boxed();
let task = logic::run(
id.clone(),
channel,
max_signers,
min_signers,
HealthSink::noop(),
)
.boxed();
Self {
id,
max_signers,
Expand Down Expand Up @@ -90,7 +100,14 @@ impl Participant {

pub async fn reconnect(&mut self, network: &mut TestNetwork) {
let channel = network.reconnect(&self.id);
let task = logic::run(self.id.clone(), channel, self.max_signers, self.min_signers).boxed();
let task = logic::run(
self.id.clone(),
channel,
self.max_signers,
self.min_signers,
HealthSink::noop(),
)
.boxed();
self.task = task;
}

Expand Down
Loading
Loading