Skip to content

Commit

Permalink
Merge pull request anoma#27 from nucypher/dkg-pvss-flow
Browse files Browse the repository at this point in the history
  • Loading branch information
piotr-roslaniec committed Jan 23, 2023
2 parents 185822b + 6181179 commit e842b8a
Show file tree
Hide file tree
Showing 20 changed files with 569 additions and 657 deletions.
12 changes: 6 additions & 6 deletions .github/workflows/workspace.yml
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,12 @@ jobs:
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
restore-keys: ${{ runner.os }}-cargo-

- name: Run benchmarks
uses: boa-dev/criterion-compare-action@v3
if: github.event_name == 'pull_request'
with:
cwd: ${{ matrix.component }}
branchName: ${{ github.base_ref }}
# - name: Run benchmarks
# uses: boa-dev/criterion-compare-action@v3
# if: github.event_name == 'pull_request'
# with:
# cwd: ${{ matrix.component }}
# branchName: ${{ github.base_ref }}

# The next steps have been adapted from https://raw.githubusercontent.com/unicode-org/icu4x/main/.github/workflows/build-test.yml

Expand Down
91 changes: 7 additions & 84 deletions ferveo-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,97 +6,20 @@ use ark_serialize::{

pub mod keypair;
pub use keypair::*;
use std::cmp::Ordering;

#[derive(Clone, Debug, CanonicalSerialize, CanonicalDeserialize)]
/// Represents a tendermint validator
pub struct TendermintValidator<E: PairingEngine> {
/// Total voting power in tendermint consensus
pub power: u64,
#[derive(Clone, Debug, CanonicalSerialize, CanonicalDeserialize, PartialEq)]
/// Represents an external validator
pub struct ExternalValidator<E: PairingEngine> {
/// The established address of the validator
pub address: String,
/// The Public key
pub public_key: PublicKey<E>,
}

impl<E: PairingEngine> PartialEq for TendermintValidator<E> {
fn eq(&self, other: &Self) -> bool {
(self.power, &self.address) == (other.power, &other.address)
}
}

impl<E: PairingEngine> Eq for TendermintValidator<E> {}

impl<E: PairingEngine> PartialOrd for TendermintValidator<E> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some((self.power, &self.address).cmp(&(other.power, &other.address)))
}
}

impl<E: PairingEngine> Ord for TendermintValidator<E> {
fn cmp(&self, other: &Self) -> Ordering {
(self.power, &self.address).cmp(&(other.power, &other.address))
}
}

#[derive(Clone, Debug, CanonicalSerialize, CanonicalDeserialize)]
/// The set of tendermint validators for a dkg instance
pub struct ValidatorSet<E: PairingEngine> {
pub validators: Vec<TendermintValidator<E>>,
}

impl<E: PairingEngine> ValidatorSet<E> {
/// Sorts the validators from highest to lowest. This ordering
/// first considers staking weight and breaks ties on established
/// address
pub fn new(mut validators: Vec<TendermintValidator<E>>) -> Self {
// reverse the ordering here
validators.sort_by(|a, b| b.cmp(a));
Self { validators }
}

/// Get the total voting power of the validator set
pub fn total_voting_power(&self) -> u64 {
self.validators.iter().map(|v| v.power).sum()
}
}

#[derive(Clone, Debug, CanonicalSerialize, CanonicalDeserialize)]
pub struct Validator<E: PairingEngine> {
pub validator: TendermintValidator<E>,
pub weight: u32,
pub share_start: usize,
pub share_end: usize,
}

impl<E: PairingEngine> PartialEq for Validator<E> {
fn eq(&self, other: &Self) -> bool {
(
&self.validator,
self.weight,
self.share_start,
self.share_end,
) == (
&other.validator,
other.weight,
other.share_start,
other.share_end,
)
}
}

impl<E: PairingEngine> Eq for Validator<E> {}

impl<E: PairingEngine> PartialOrd for Validator<E> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.validator.cmp(&other.validator))
}
}

impl<E: PairingEngine> Ord for Validator<E> {
fn cmp(&self, other: &Self) -> Ordering {
self.validator.cmp(&other.validator)
}
pub validator: ExternalValidator<E>,
pub share_index: usize,
}

impl Rng for ark_std::rand::prelude::StdRng {}
Expand All @@ -115,7 +38,7 @@ pub mod ark_serde {
{
use serde::ser::Error;
let mut bytes = vec![];
data.serialize(&mut bytes).map_err(S::Error::custom)?;
data.serialize(&mut bytes).map_err(Error::custom)?;
serde_bytes::Bytes::new(&bytes).serialize(serializer)
}
/// Deserialize an ark type with serde
Expand All @@ -126,7 +49,7 @@ pub mod ark_serde {
{
use serde::de::Error;
let bytes = <serde_bytes::ByteBuf>::deserialize(deserializer)?;
T::deserialize(bytes.as_slice()).map_err(D::Error::custom)
T::deserialize(bytes.as_slice()).map_err(Error::custom)
}
}

Expand Down
28 changes: 13 additions & 15 deletions ferveo/benches/benchmarks/pvdkg.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub use ark_bls12_381::Bls12_381 as EllipticCurve;
use criterion::{criterion_group, criterion_main, Criterion};
use ferveo_common::{TendermintValidator, ValidatorSet};
use ferveo_common::ExternalValidator;
use pprof::criterion::{Output, PProfProfiler};

use ferveo::*;
Expand Down Expand Up @@ -47,16 +47,13 @@ pub fn gen_keypairs(num: u64) -> Vec<ferveo_common::Keypair<EllipticCurve>> {
/// Generate a few validators
pub fn gen_validators(
keypairs: &[ferveo_common::Keypair<EllipticCurve>],
) -> ValidatorSet<EllipticCurve> {
ValidatorSet::new(
(0..keypairs.len())
.map(|i| TendermintValidator {
power: i as u64,
address: format!("validator_{}", i),
public_key: keypairs[i].public(),
})
.collect(),
)
) -> Vec<ExternalValidator<EllipticCurve>> {
(0..keypairs.len())
.map(|i| ExternalValidator {
address: format!("validator_{}", i),
public_key: keypairs[i].public(),
})
.collect()
}

/// Create a test dkg in state [`DkgState::Init`]
Expand All @@ -66,16 +63,17 @@ pub fn setup_dkg(
) -> PubliclyVerifiableDkg<EllipticCurve> {
let keypairs = gen_keypairs(num);
let validators = gen_validators(&keypairs);
let me = validators.validators[validator].clone();
let me = validators[validator].clone();
let shares_num = 300;
PubliclyVerifiableDkg::new(
validators,
Params {
tau: 0,
security_threshold: 300 / 3,
total_weight: 300,
security_threshold: shares_num / 3,
shares_num,
retry_after: 2,
},
me,
&me,
keypairs[validator],
)
.expect("Setup failed")
Expand Down
31 changes: 14 additions & 17 deletions ferveo/examples/pvdkg.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub use ark_bls12_381::Bls12_381 as EllipticCurve;
use ferveo::*;
use ferveo_common::{TendermintValidator, ValidatorSet};
use ferveo_common::ExternalValidator;
use measure_time::print_time;

pub fn main() {
Expand All @@ -21,36 +21,33 @@ pub fn gen_keypairs(num: u64) -> Vec<ferveo_common::Keypair<EllipticCurve>> {
/// Generate a few validators
pub fn gen_validators(
keypairs: &[ferveo_common::Keypair<EllipticCurve>],
) -> ValidatorSet<EllipticCurve> {
ValidatorSet::new(
(0..keypairs.len())
.map(|i| TendermintValidator {
power: i as u64,
address: format!("validator_{}", i),
public_key: keypairs[i].public(),
})
.collect(),
)
) -> Vec<ExternalValidator<EllipticCurve>> {
(0..keypairs.len())
.map(|i| ExternalValidator {
address: format!("validator_{}", i),
public_key: keypairs[i].public(),
})
.collect()
}

/// Create a test dkg in state [`DkgState::Init`]
pub fn setup_dkg(
validator: usize,
num: u64,
shares: u32,
shares_num: u32,
) -> PubliclyVerifiableDkg<EllipticCurve> {
let keypairs = gen_keypairs(num);
let validators = gen_validators(&keypairs);
let me = validators.validators[validator].clone();
let me = validators[validator].clone();
PubliclyVerifiableDkg::new(
validators,
Params {
tau: 0,
security_threshold: shares / 3,
total_weight: shares,
security_threshold: shares_num / 3,
shares_num,
retry_after: 1,
},
me,
&me,
keypairs[validator],
)
.expect("Setup failed")
Expand All @@ -71,7 +68,7 @@ pub fn setup_dealt_dkg(num: u64, shares: u32) {
for (sender, pvss) in transcripts.into_iter().rev().enumerate() {
if let Message::Deal(ss) = pvss.clone() {
print_time!("PVSS verify pvdkg");
ss.verify_full(&dkg, rng);
ss.verify_full(&dkg);
}
dkg.apply_message(
dkg.validators[num as usize - 1 - sender].validator.clone(),
Expand Down
22 changes: 12 additions & 10 deletions ferveo/src/dkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,22 @@ use ark_poly::{
EvaluationDomain, Polynomial,
};
use ark_serialize::*;
use bincode::Options;
use ed25519_dalek as ed25519;

pub mod common;
pub mod pv;

pub use common::*;
pub use pv::*;

// DKG parameters
#[derive(Copy, Clone, Debug, CanonicalSerialize, CanonicalDeserialize)]
pub struct Params {
pub tau: u64,
pub security_threshold: u32, // threshold
pub total_weight: u32, // total weight
pub retry_after: u32,
pub security_threshold: u32,
pub shares_num: u32,
pub retry_after: u32, // TODO: Remove. Not relevant in our scheme.
}

#[derive(Clone, Debug, Eq, PartialEq)]
Expand All @@ -36,7 +38,7 @@ pub enum PvssScheduler {

#[derive(Debug, Clone)]
pub enum DkgState<E: PairingEngine> {
Sharing { accumulated_weight: u32, block: u32 },
Sharing { accumulated_shares: u32, block: u32 },
Dealt,
Success { final_key: E::G1Affine },
Invalid,
Expand All @@ -50,12 +52,12 @@ impl<E: PairingEngine> CanonicalSerialize for DkgState<E> {
) -> Result<(), SerializationError> {
match self {
Self::Sharing {
accumulated_weight,
accumulated_shares,
block,
} => {
CanonicalSerialize::serialize(&0u8, &mut writer)?;
CanonicalSerialize::serialize(
&(*accumulated_weight, *block),
&(*accumulated_shares, *block),
&mut writer,
)
}
Expand All @@ -72,11 +74,11 @@ impl<E: PairingEngine> CanonicalSerialize for DkgState<E> {
fn serialized_size(&self) -> usize {
match self {
Self::Sharing {
accumulated_weight,
accumulated_shares,
block,
} => {
0u8.serialized_size()
+ (*accumulated_weight, *block).serialized_size()
+ (*accumulated_shares, *block).serialized_size()
}
Self::Dealt => 1u8.serialized_size(),
Self::Success { final_key } => {
Expand All @@ -93,12 +95,12 @@ impl<E: PairingEngine> CanonicalDeserialize for DkgState<E> {
let variant = <u8 as CanonicalDeserialize>::deserialize(&mut reader)?;
match variant {
0 => {
let (accumulated_weight, block) =
let (accumulated_shares, block) =
<(u32, u32) as CanonicalDeserialize>::deserialize(
&mut reader,
)?;
Ok(Self::Sharing {
accumulated_weight,
accumulated_shares,
block,
})
}
Expand Down
Loading

0 comments on commit e842b8a

Please sign in to comment.