Skip to content

Commit

Permalink
Cleanup with fmt and clippy
Browse files Browse the repository at this point in the history
Signed-off-by: Jacinta Ferrant <[email protected]>
  • Loading branch information
jferrant committed Sep 13, 2023
1 parent 1ea77a1 commit 176a9b2
Show file tree
Hide file tree
Showing 10 changed files with 174 additions and 95 deletions.
51 changes: 37 additions & 14 deletions libsigner/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ use libstackerdb::StackerDBChunkData;

use serde::{Deserialize, Serialize};

use tiny_http::{Server as HttpServer, Request as HttpRequest, Response as HttpResponse, Method as HttpMethod};
use tiny_http::{
Method as HttpMethod, Request as HttpRequest, Response as HttpResponse, Server as HttpServer,
};

use crate::http::{decode_http_body, decode_http_request};
use crate::EventError;
Expand Down Expand Up @@ -194,11 +196,18 @@ impl EventReceiver for StackerDBEventReceiver {
info!("[{:?}] next_event recv request", event_receiver.local_addr);
let mut request = http_server.recv()?;

info!("[{:?}] next_event got request for {}", event_receiver.local_addr, request.url());
info!(
"[{:?}] next_event got request for {}",
event_receiver.local_addr,
request.url()
);

// were we asked to terminate?
if event_receiver.is_stopped() {
info!("[{:?}] next_event we were terminated", event_receiver.local_addr);
info!(
"[{:?}] next_event we were terminated",
event_receiver.local_addr
);
return Err(EventError::Terminated);
}

Expand All @@ -211,23 +220,37 @@ impl EventReceiver for StackerDBEventReceiver {
}
if request.url() != "/stackerdb_chunks" {
let url = request.url().to_string();
request.respond(HttpResponse::empty(200u16)).expect("response failed");
request
.respond(HttpResponse::empty(200u16))
.expect("response failed");
Err(EventError::UnrecognizedEvent(url))
} else {

info!("[{:?}] next_event get body", event_receiver.local_addr);
let mut body = String::new();
request.as_reader().read_to_string(&mut body).expect("failed to read body");

info!("[{:?}] next_event body {} bytes", event_receiver.local_addr, body.len());

let event: StackerDBChunksEvent = serde_json::from_slice(body.as_bytes()).map_err(|e| {
EventError::Deserialize(format!("Could not decode body to JSON: {:?}", &e))
})?;
request
.as_reader()
.read_to_string(&mut body)
.expect("failed to read body");

info!(
"[{:?}] next_event body {} bytes",
event_receiver.local_addr,
body.len()
);

let event: StackerDBChunksEvent =
serde_json::from_slice(body.as_bytes()).map_err(|e| {
EventError::Deserialize(format!("Could not decode body to JSON: {:?}", &e))
})?;

info!("[{:?}] next_event responding", event_receiver.local_addr);
request.respond(HttpResponse::empty(200u16)).expect("response failed");
info!("[{:?}] next_event response sent returning event", event_receiver.local_addr);
request
.respond(HttpResponse::empty(200u16))
.expect("response failed");
info!(
"[{:?}] next_event response sent returning event",
event_receiver.local_addr
);

Ok(event)
}
Expand Down
12 changes: 8 additions & 4 deletions libsigner/src/runloop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ pub trait SignerRunLoop<R, CMD: Send> {
mut event_stop_signaler: EVST,
) -> Option<R> {
loop {
let poll_timeout = Duration::from_millis(128);//self.get_event_timeout();
//info!("SignerRunLoop::main_loop: poll_timeout {:?}", poll_timeout);
//info!("SignerRunLoop::main_loop: event_recv");
let poll_timeout = Duration::from_millis(128); //self.get_event_timeout();
//info!("SignerRunLoop::main_loop: poll_timeout {:?}", poll_timeout);
//info!("SignerRunLoop::main_loop: event_recv");
let next_event_opt = match event_recv.recv_timeout(poll_timeout) {
Ok(event) => Some(event),
Err(RecvTimeoutError::Timeout) => None,
Expand Down Expand Up @@ -196,7 +196,11 @@ impl<
EV: EventReceiver + Send + 'static,
> Signer<CMD, R, SL, EV>
{
pub fn new(runloop: SL, event_receiver: EV, command_receiver: Receiver<CMD>) -> Signer<CMD, R, SL, EV> {
pub fn new(
runloop: SL,
event_receiver: EV,
command_receiver: Receiver<CMD>,
) -> Signer<CMD, R, SL, EV> {
Signer {
signer_loop: Some(runloop),
event_receiver: Some(event_receiver),
Expand Down
2 changes: 1 addition & 1 deletion libsigner/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl StackerDBSession {
F: FnOnce(&mut StackerDBSession, &mut TcpStream) -> R,
{
//if self.sock.is_none() {
self.connect_or_reconnect()?;
self.connect_or_reconnect()?;
//}

let mut sock = if let Some(s) = self.sock.take() {
Expand Down
125 changes: 78 additions & 47 deletions stacks-signer/src/crypto/frost.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,19 @@ use std::collections::BTreeMap;
use crate::crypto::{Coordinatable, Error as CryptoError, OperationResult};
use frost_signer::{
net::Message,
signing_round::{DkgBegin, DkgPublicShare, MessageTypes, Signable, NonceRequest, NonceResponse, SignatureShareRequest},
signing_round::{
DkgBegin, DkgPublicShare, MessageTypes, NonceRequest, NonceResponse, Signable,
SignatureShareRequest,
},
};
use hashbrown::HashSet;
use slog::{slog_info, slog_warn};
use stacks_common::{error, info, warn};
use wsts::{
Point, Scalar,
common::{PolyCommitment, PublicNonce, Signature, SignatureShare},
errors::AggregatorError,
taproot::{
Error as TaprootError, SchnorrProof,
},
common::{
PolyCommitment, PublicNonce, Signature, SignatureShare,
},
v1,
taproot::{Error as TaprootError, SchnorrProof},
v1, Point, Scalar,
};

#[derive(thiserror::Error, Debug)]
Expand Down Expand Up @@ -72,7 +70,12 @@ pub struct Coordinator {

impl Coordinator {
/// Create a new coordinator
pub fn new(total_signers: u32, total_keys: u32, threshold: u32, message_private_key: Scalar) -> Self {
pub fn new(
total_signers: u32,
total_keys: u32,
threshold: u32,
message_private_key: Scalar,
) -> Self {
Self {
current_dkg_id: 0,
current_dkg_public_id: 0,
Expand Down Expand Up @@ -161,7 +164,19 @@ impl Coordinator {
return Ok((None, None));
} else if self.state == State::Idle {
// We are done with the DKG round! Return the operation result
return Ok((None, Some(OperationResult::Sign(Signature { R: self.signature.R, z: self.signature.z }, SchnorrProof{ r: self.schnorr_proof.r, s: self.schnorr_proof.s }))));
return Ok((
None,
Some(OperationResult::Sign(
Signature {
R: self.signature.R,
z: self.signature.z,
},
SchnorrProof {
r: self.schnorr_proof.r,
s: self.schnorr_proof.s,
},
)),
));
}
}
}
Expand Down Expand Up @@ -282,7 +297,7 @@ impl Coordinator {
fn request_nonces(&mut self) -> Result<Message, Error> {
info!(
"Sign Round #{} Nonce round #{} Requesting Nonces",
self.current_sign_id, self.current_sign_nonce_id,
self.current_sign_id, self.current_sign_nonce_id,
);
let nonce_request = NonceRequest {
dkg_id: self.current_dkg_id,
Expand All @@ -299,18 +314,18 @@ impl Coordinator {
}

fn gather_nonces(&mut self, message: &Message) -> Result<(), Error> {
match &message.msg {
MessageTypes::NonceResponse(nonce_response) => {
// TODO: check sign_id and sign_nonce_id
self.public_nonces
.insert(nonce_response.signer_id, nonce_response.clone());
self.ids_to_await.remove(&nonce_response.signer_id);
info!(
"Sign round #{} nonce round #{} NonceResponse from signer #{}. Waiting on {:?}",
nonce_response.sign_id, nonce_response.sign_nonce_id, nonce_response.signer_id, self.ids_to_await
);
}
_ => {}
if let MessageTypes::NonceResponse(nonce_response) = &message.msg {
// TODO: check sign_id and sign_nonce_id
self.public_nonces
.insert(nonce_response.signer_id, nonce_response.clone());
self.ids_to_await.remove(&nonce_response.signer_id);
info!(
"Sign round #{} nonce round #{} NonceResponse from signer #{}. Waiting on {:?}",
nonce_response.sign_id,
nonce_response.sign_nonce_id,
nonce_response.signer_id,
self.ids_to_await
);
}
if self.ids_to_await.is_empty() {
// Calculate the aggregate nonce
Expand All @@ -335,9 +350,11 @@ impl Coordinator {
fn request_sig_shares(&mut self) -> Result<Message, Error> {
info!(
"Sign Round #{} Requesting Signature Shares",
self.current_sign_id,
self.current_sign_id,
);
let nonce_responses = (0..self.total_signers).map(|i| self.public_nonces[&i].clone()).collect::<Vec<NonceResponse>>();
let nonce_responses = (0..self.total_signers)
.map(|i| self.public_nonces[&i].clone())
.collect::<Vec<NonceResponse>>();
let sig_share_request = SignatureShareRequest {
dkg_id: self.current_dkg_id,
sign_id: self.current_sign_id,
Expand All @@ -355,18 +372,17 @@ impl Coordinator {
}

fn gather_sig_shares(&mut self, message: &Message) -> Result<(), Error> {
match &message.msg {
MessageTypes::SignShareResponse(sig_share_response) => {
// TODO: check sign_id
self.signature_shares
.insert(sig_share_response.signer_id, sig_share_response.signature_shares.clone());
self.ids_to_await.remove(&sig_share_response.signer_id);
info!(
"Sign round #{} SignShareResponse from signer #{}. Waiting on {:?}",
sig_share_response.sign_id, sig_share_response.signer_id, self.ids_to_await
);
}
_ => {}
if let MessageTypes::SignShareResponse(sig_share_response) = &message.msg {
// TODO: check sign_id
self.signature_shares.insert(
sig_share_response.signer_id,
sig_share_response.signature_shares.clone(),
);
self.ids_to_await.remove(&sig_share_response.signer_id);
info!(
"Sign round #{} SignShareResponse from signer #{}. Waiting on {:?}",
sig_share_response.sign_id, sig_share_response.signer_id, self.ids_to_await
);
}
if self.ids_to_await.is_empty() {
// Calculate the aggregate signature
Expand All @@ -376,7 +392,9 @@ impl Coordinator {
.map(|ps| ps.public_share.clone())
.collect();

let nonce_responses = (0..self.total_signers).map(|i| self.public_nonces[&i].clone()).collect::<Vec<NonceResponse>>();
let nonce_responses = (0..self.total_signers)
.map(|i| self.public_nonces[&i].clone())
.collect::<Vec<NonceResponse>>();

let nonces = nonce_responses
.iter()
Expand All @@ -396,7 +414,8 @@ impl Coordinator {
shares.len()
);

let mut aggregator = v1::SignatureAggregator::new(self.total_keys, self.threshold, polys)?;
let mut aggregator =
v1::SignatureAggregator::new(self.total_keys, self.threshold, polys)?;

let sig = aggregator.sign(&self.message, &nonces, shares)?;

Expand Down Expand Up @@ -469,10 +488,18 @@ impl StateMachine for Coordinator {
}
State::DkgPrivateDistribute => prev_state == &State::DkgPublicGather,
State::DkgEndGather => prev_state == &State::DkgPrivateDistribute,
State::NonceRequest => prev_state == &State::Idle || prev_state == &State::DkgEndGather || prev_state == &State::NonceGather,
State::NonceGather => prev_state == &State::NonceRequest || prev_state == &State::NonceGather,
State::NonceRequest => {
prev_state == &State::Idle
|| prev_state == &State::DkgEndGather
|| prev_state == &State::NonceGather
}
State::NonceGather => {
prev_state == &State::NonceRequest || prev_state == &State::NonceGather
}
State::SigShareRequest => prev_state == &State::NonceGather,
State::SigShareGather => prev_state == &State::SigShareRequest || prev_state == &State::SigShareGather,
State::SigShareGather => {
prev_state == &State::SigShareRequest || prev_state == &State::SigShareGather
}
};
if accepted {
info!("state change from {:?} to {:?}", prev_state, state);
Expand Down Expand Up @@ -593,7 +620,8 @@ mod test {
let mut rng = OsRng::default();
let message_private_key = Scalar::random(&mut rng);

let coordinator = Coordinator::new(total_signers, total_keys, threshold, message_private_key);
let coordinator =
Coordinator::new(total_signers, total_keys, threshold, message_private_key);

assert_eq!(coordinator.total_signers, total_signers);
assert_eq!(coordinator.total_keys, total_keys);
Expand All @@ -610,7 +638,8 @@ mod test {
let threshold = 28;
let mut rng = OsRng::default();
let message_private_key = Scalar::random(&mut rng);
let mut coordinator = Coordinator::new(total_signers, total_keys, threshold, message_private_key);
let mut coordinator =
Coordinator::new(total_signers, total_keys, threshold, message_private_key);

let result = coordinator.start_dkg_round();

Expand All @@ -630,7 +659,8 @@ mod test {
let threshold = 28;
let mut rng = OsRng::default();
let message_private_key = Scalar::random(&mut rng);
let mut coordinator = Coordinator::new(total_signers, total_keys, threshold, message_private_key);
let mut coordinator =
Coordinator::new(total_signers, total_keys, threshold, message_private_key);
coordinator.state = State::DkgPublicDistribute; // Must be in this state before calling start public shares

let result = coordinator.start_public_shares().unwrap();
Expand All @@ -650,7 +680,8 @@ mod test {
let threshold = 28;
let mut rng = OsRng::default();
let message_private_key = Scalar::random(&mut rng);
let mut coordinator = Coordinator::new(total_signers, total_keys, threshold, message_private_key);
let mut coordinator =
Coordinator::new(total_signers, total_keys, threshold, message_private_key);
coordinator.state = State::DkgPrivateDistribute; // Must be in this state before calling start private shares

let message = coordinator.start_private_shares().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion stacks-signer/src/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ pub mod frost;

use frost::Error as FrostError;
use frost_signer::net::Message;
use wsts::{taproot::SchnorrProof, common::Signature, Point};
use wsts::{common::Signature, taproot::SchnorrProof, Point};

#[derive(thiserror::Error, Debug)]
/// Error type for the crypto module
Expand Down
22 changes: 16 additions & 6 deletions stacks-signer/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,12 @@ fn spawn_running_signer(
let config = Config::try_from(path).unwrap();
let ev = StackerDBEventReceiver::new(vec![config.stackerdb_contract_id.clone()]);
let runloop: RunLoop<FrostCoordinator> = RunLoop::new(&config, command);
let mut signer: Signer<RunLoopCommand, Vec<Point>, RunLoop<FrostCoordinator>, StackerDBEventReceiver> =
Signer::new(runloop, ev, cmd_recv);
let mut signer: Signer<
RunLoopCommand,
Vec<Point>,
RunLoop<FrostCoordinator>,
StackerDBEventReceiver,
> = Signer::new(runloop, ev, cmd_recv);
let endpoint = config.node_host;
signer.spawn(endpoint).unwrap()
}
Expand Down Expand Up @@ -232,16 +236,22 @@ fn main() {
}
Command::DkgSign(args) => {
if let Some(config) = &cli.config {
let _running_signer =
spawn_running_signer(config, RunLoopCommand::DkgSign { message: args.data }, cmd_recv);
let _running_signer = spawn_running_signer(
config,
RunLoopCommand::DkgSign { message: args.data },
cmd_recv,
);
} else {
panic!("dkg-sign is currently only supported when using a config file");
}
}
Command::Sign(args) => {
if let Some(config) = &cli.config {
let _running_signer =
spawn_running_signer(config, RunLoopCommand::Sign { message: args.data }, cmd_recv);
let _running_signer = spawn_running_signer(
config,
RunLoopCommand::Sign { message: args.data },
cmd_recv,
);
} else {
panic!("dkg-sign is currently only supported when using a config file");
}
Expand Down
Loading

0 comments on commit 176a9b2

Please sign in to comment.