use std::collections::BTreeMap;
use std::sync::Arc;
use std::{fmt, result};
use crate::crypto::{self, hash_g2, Signature, SignatureShare, G2};
use failure::Fail;
use log::debug;
use rand::Rng;
use rand_derive::Rand;
use serde::{Deserialize, Serialize};
use crate::fault_log::{Fault, FaultLog};
use crate::{ConsensusProtocol, NetworkInfo, NodeIdT, Target};
#[derive(Clone, Eq, PartialEq, Debug, Fail)]
pub enum Error {
#[fail(display = "Redundant input provided")]
MultipleMessagesToSign,
#[fail(display = "Error combining and verifying signature shares: {}", _0)]
CombineAndVerifySigCrypto(crypto::error::Error),
#[fail(display = "Unknown sender")]
UnknownSender,
#[fail(display = "Signature verification failed")]
VerificationFailed,
#[fail(display = "Document hash is not set, cannot sign or verify signatures")]
DocumentHashIsNone,
}
pub type Result<T> = ::std::result::Result<T, Error>;
#[derive(Clone, Debug, Fail, PartialEq)]
pub enum FaultKind {
#[fail(
display = "`ThresholdSign` (`Coin`) received a signature share from an unverified sender."
)]
UnverifiedSignatureShareSender,
#[fail(
display = "`HoneyBadger` received a signatures share for the random value even though it
is disabled."
)]
UnexpectedSignatureShare,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Rand)]
pub struct Message(pub SignatureShare);
#[derive(Debug)]
pub struct ThresholdSign<N> {
netinfo: Arc<NetworkInfo<N>>,
doc_hash: Option<G2>,
received_shares: BTreeMap<N, (usize, SignatureShare)>,
had_input: bool,
terminated: bool,
}
pub type Step<N> = crate::CpStep<ThresholdSign<N>>;
impl<N: NodeIdT> ConsensusProtocol for ThresholdSign<N> {
type NodeId = N;
type Input = ();
type Output = Signature;
type Message = Message;
type Error = Error;
type FaultKind = FaultKind;
fn handle_input<R: Rng>(&mut self, _input: (), _rng: &mut R) -> Result<Step<N>> {
self.sign()
}
fn handle_message<R: Rng>(
&mut self,
sender_id: &Self::NodeId,
message: Message,
_rng: &mut R,
) -> Result<Step<N>> {
self.handle_message(sender_id, message)
}
fn terminated(&self) -> bool {
self.terminated
}
fn our_id(&self) -> &Self::NodeId {
self.netinfo.our_id()
}
}
impl<N: NodeIdT> ThresholdSign<N> {
pub fn new(netinfo: Arc<NetworkInfo<N>>) -> Self {
ThresholdSign {
netinfo,
doc_hash: None,
received_shares: BTreeMap::new(),
had_input: false,
terminated: false,
}
}
pub fn new_with_document<M: AsRef<[u8]>>(netinfo: Arc<NetworkInfo<N>>, doc: M) -> Result<Self> {
let mut ts = ThresholdSign::new(netinfo);
ts.set_document(doc)?;
Ok(ts)
}
pub fn set_document<M: AsRef<[u8]>>(&mut self, doc: M) -> Result<()> {
if self.doc_hash.is_some() {
return Err(Error::MultipleMessagesToSign);
}
self.doc_hash = Some(hash_g2(doc));
Ok(())
}
pub fn sign(&mut self) -> Result<Step<N>> {
if self.had_input {
return Ok(Step::default());
}
let hash = self.doc_hash.ok_or(Error::DocumentHashIsNone)?;
self.had_input = true;
let mut step = Step::default();
step.fault_log.extend(self.remove_invalid_shares());
let msg = match self.netinfo.secret_key_share() {
Some(sks) => Message(sks.sign_g2(hash)),
None => return Ok(step.join(self.try_output()?)), };
step.messages.push(Target::All.message(msg.clone()));
let id = self.our_id().clone();
step.extend(self.handle_message(&id, msg)?);
Ok(step)
}
pub fn handle_message(&mut self, sender_id: &N, message: Message) -> Result<Step<N>> {
if self.terminated {
return Ok(Step::default());
}
let Message(share) = message;
let idx = self
.netinfo
.node_index(sender_id)
.ok_or(Error::UnknownSender)?;
if !self.is_share_valid(sender_id, &share) {
let fault_kind = FaultKind::UnverifiedSignatureShareSender;
return Ok(Fault::new(sender_id.clone(), fault_kind).into());
}
self.received_shares.insert(sender_id.clone(), (idx, share));
self.try_output()
}
fn remove_invalid_shares(&mut self) -> FaultLog<N, FaultKind> {
let faulty_senders: Vec<N> = self
.received_shares
.iter()
.filter(|(id, (_, ref share))| !self.is_share_valid(id, share))
.map(|(id, _)| id.clone())
.collect();
let mut fault_log = FaultLog::default();
for id in faulty_senders {
self.received_shares.remove(&id);
fault_log.append(id, FaultKind::UnverifiedSignatureShareSender);
}
fault_log
}
fn is_share_valid(&self, id: &N, share: &SignatureShare) -> bool {
let hash = match self.doc_hash {
None => return true, Some(ref doc_hash) => doc_hash,
};
match self.netinfo.public_key_share(id) {
None => false, Some(pk_i) => pk_i.verify_g2(&share, *hash),
}
}
fn try_output(&mut self) -> Result<Step<N>> {
let hash = match self.doc_hash {
Some(hash) => hash,
None => return Ok(Step::default()),
};
if !self.terminated && self.received_shares.len() > self.netinfo.num_faulty() {
let sig = self.combine_and_verify_sig(hash)?;
self.terminated = true;
let step = self.sign()?; debug!("{} output {:?}", self, sig);
Ok(step.with_output(sig))
} else {
debug!(
"{} received {} shares, {}",
self,
self.received_shares.len(),
if self.had_input { ", had input" } else { "" }
);
Ok(Step::default())
}
}
fn combine_and_verify_sig(&self, hash: G2) -> Result<Signature> {
let shares_itr = self
.received_shares
.values()
.map(|&(ref idx, ref share)| (idx, share));
let sig = self
.netinfo
.public_key_set()
.combine_signatures(shares_itr)
.map_err(Error::CombineAndVerifySigCrypto)?;
if !self
.netinfo
.public_key_set()
.public_key()
.verify_g2(&sig, hash)
{
Err(Error::VerificationFailed)
} else {
Ok(sig)
}
}
}
impl<N: NodeIdT> fmt::Display for ThresholdSign<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> result::Result<(), fmt::Error> {
write!(f, "{:?} TS({:?})", self.our_id(), self.doc_hash)
}
}