Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor messages, distinguish broadcast and unicast #3

Merged
merged 8 commits into from
Sep 9, 2024
Merged
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "meesign-crypto"
version = "0.2.0"
version = "0.3.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
11 changes: 9 additions & 2 deletions proto/meesign.proto
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,14 @@ message ProtocolInit {
bytes data = 4;
}

message ProtocolMessage {
message ClientMessage {
ProtocolType protocol_type = 1;
repeated bytes message = 2;
map<uint32, bytes> unicasts = 2;
optional bytes broadcast = 3;
}

message ServerMessage {
ProtocolType protocol_type = 1;
map<uint32, bytes> unicasts = 2;
map<uint32, bytes> broadcasts = 3;
}
134 changes: 57 additions & 77 deletions src/protocol/elgamal.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::proto::{ProtocolGroupInit, ProtocolInit, ProtocolType};
use crate::proto::{ProtocolGroupInit, ProtocolInit, ProtocolType, ServerMessage};
use crate::protocol::*;
use curve25519_dalek::{
ristretto::{CompressedRistretto, RistrettoPoint},
Expand All @@ -19,6 +19,8 @@ use aes_gcm::{
use prost::Message;
use serde::{Deserialize, Serialize};

use std::collections::HashMap;

#[derive(Serialize, Deserialize)]
pub(crate) struct KeygenContext {
round: KeygenRound,
Expand All @@ -27,9 +29,9 @@ pub(crate) struct KeygenContext {
#[derive(Serialize, Deserialize)]
enum KeygenRound {
R0,
R1(ParticipantCollectingCommitments<Ristretto>, u16),
R2(ParticipantCollectingPolynomials<Ristretto>, u16),
R3(ParticipantExchangingSecrets<Ristretto>, u16),
R1(ParticipantCollectingCommitments<Ristretto>),
R2(ParticipantCollectingPolynomials<Ristretto>),
R3(ParticipantExchangingSecrets<Ristretto>),
Done(ActiveParticipant<Ristretto>),
}

Expand All @@ -49,83 +51,73 @@ impl KeygenContext {
let dkg =
ParticipantCollectingCommitments::<Ristretto>::new(params, index.into(), &mut OsRng);
let c = dkg.commitment();
let ser = serialize_bcast(&c, msg.parties as usize - 1)?;
self.round = KeygenRound::R1(dkg, index);
Ok(pack(ser, ProtocolType::Elgamal))
let msg = serialize_bcast(&c, ProtocolType::Elgamal)?;
self.round = KeygenRound::R1(dkg);
Ok(msg)
}

fn update(&mut self, data: &[u8]) -> Result<Vec<u8>> {
let msgs = unpack(data)?;
let n = msgs.len();
let msgs = ServerMessage::decode(data)?;

let (c, ser) = match &self.round {
let (c, msg) = match &self.round {
KeygenRound::R0 => return Err("protocol not initialized".into()),
KeygenRound::R1(dkg, idx) => {
KeygenRound::R1(dkg) => {
let mut dkg = dkg.clone();
let data = deserialize_vec(&msgs)?;
for (mut i, msg) in data.into_iter().enumerate() {
if i >= *idx as usize {
i += 1;
}
dkg.insert_commitment(i, msg);
let data = deserialize_map(&msgs.broadcasts)?;
for (i, msg) in data {
dkg.insert_commitment(i as usize, msg);
}
if dkg.missing_commitments().next().is_some() {
return Err("not enough commitments".into());
}
let dkg = dkg.finish_commitment_phase();
let public_info = dkg.public_info();
let ser = serialize_bcast(&public_info, n)?;
let msg = serialize_bcast(&public_info, ProtocolType::Elgamal)?;

(KeygenRound::R2(dkg, *idx), ser)
(KeygenRound::R2(dkg), msg)
}
KeygenRound::R2(dkg, idx) => {
KeygenRound::R2(dkg) => {
let mut dkg = dkg.clone();
let data = deserialize_vec(&msgs)?;
for (mut i, msg) in data.into_iter().enumerate() {
if i >= *idx as usize {
i += 1;
}
dkg.insert_public_polynomial(i, msg)?
let data = deserialize_map(&msgs.broadcasts)?;
for (i, msg) in data {
dkg.insert_public_polynomial(i as usize, msg)?
}
if dkg.missing_public_polynomials().next().is_some() {
return Err("not enough polynomials".into());
}
let dkg = dkg.finish_polynomials_phase();

let mut shares = Vec::new();
for mut i in 0..n {
if i >= *idx as usize {
i += 1;
}
let secret_share = dkg.secret_share_for_participant(i);
shares.push(secret_share);
}
let ser = serialize_uni(shares)?;
let shares = msgs
.broadcasts
.into_keys()
.map(|i| (i, dkg.secret_share_for_participant(i as usize)));

let msg = serialize_uni(shares, ProtocolType::Elgamal)?;

(KeygenRound::R3(dkg, *idx), ser)
(KeygenRound::R3(dkg), msg)
}
KeygenRound::R3(dkg, idx) => {
KeygenRound::R3(dkg) => {
let mut dkg = dkg.clone();
let data = deserialize_vec(&msgs)?;
for (mut i, msg) in data.into_iter().enumerate() {
if i >= *idx as usize {
i += 1;
}
dkg.insert_secret_share(i, msg)?;
let data = deserialize_map(&msgs.unicasts)?;
for (i, msg) in data {
dkg.insert_secret_share(i as usize, msg)?;
}
if dkg.missing_shares().next().is_some() {
return Err("not enough shares".into());
}
let dkg = dkg.complete()?;
let ser = inflate(dkg.key_set().shared_key().as_bytes().to_vec(), n);

(KeygenRound::Done(dkg), ser)
let msg = encode_raw_bcast(
dkg.key_set().shared_key().as_bytes().to_vec(),
ProtocolType::Elgamal,
);
(KeygenRound::Done(dkg), msg)
}
KeygenRound::Done(_) => return Err("protocol already finished".into()),
};

self.round = c;
Ok(pack(ser, ProtocolType::Elgamal))
Ok(msg)
}
}

Expand Down Expand Up @@ -160,7 +152,6 @@ pub(crate) struct DecryptContext {
ctx: ActiveParticipant<Ristretto>,
encrypted_key: Ciphertext<Ristretto>,
data: (Vec<u8>, Vec<u8>, Vec<u8>),
indices: Vec<u16>,
shares: Vec<(usize, VerifiableDecryption<Ristretto>)>,
result: Option<Vec<u8>>,
}
Expand All @@ -173,21 +164,20 @@ impl DecryptContext {
return Err("wrong protocol type".into());
}

self.indices = msg.indices.clone().into_iter().map(|i| i as u16).collect();
self.data = serde_json::from_slice(&msg.data)?;
self.encrypted_key = serde_json::from_slice(&self.data.0)?;

let (share, proof) = self.ctx.decrypt_share(self.encrypted_key, &mut OsRng);

let ser = serialize_bcast(
let msg = serialize_bcast(
&serde_json::to_string(&(share, proof))?.as_bytes(),
self.indices.len() - 1,
ProtocolType::Elgamal,
)?;

let share = (self.ctx.index(), share);
self.shares.push(share);

Ok(pack(ser, ProtocolType::Elgamal))
Ok(msg)
}

fn update(&mut self, data: &[u8]) -> Result<Vec<u8>> {
Expand All @@ -198,32 +188,17 @@ impl DecryptContext {
return Err("protocol already finished".into());
}

let msgs = unpack(data)?;
let msgs = ServerMessage::decode(data)?;

let data: Vec<Vec<u8>> = deserialize_vec(&msgs)?;
let local_index = self
.indices
.iter()
.position(|x| *x as usize == self.ctx.index())
.ok_or("participant index not included")?;
assert_eq!(self.ctx.index(), self.indices[local_index] as usize);

for (mut i, msg) in data.into_iter().enumerate() {
if i >= local_index {
i += 1;
}
let data: HashMap<u32, Vec<u8>> = deserialize_map(&msgs.broadcasts)?;
for (i, msg) in data {
let msg: (VerifiableDecryption<Ristretto>, LogEqualityProof<Ristretto>) =
serde_json::from_slice(&msg)?;
self.ctx
.key_set()
.verify_share(
msg.0.into(),
self.encrypted_key,
self.indices[i].into(),
&msg.1,
)
.verify_share(msg.0.into(), self.encrypted_key, i as usize, &msg.1)
.unwrap();
self.shares.push((self.indices[i].into(), msg.0));
self.shares.push((i as usize, msg.0));
}

let mut key = [0u8; 16];
Expand Down Expand Up @@ -254,8 +229,8 @@ impl DecryptContext {

self.result = Some(msg.clone());

let ser = inflate(msg, self.indices.len() - 1);
Ok(pack(ser, ProtocolType::Elgamal))
let msg = encode_raw_bcast(msg, ProtocolType::Elgamal);
Ok(msg)
}
}

Expand Down Expand Up @@ -284,7 +259,6 @@ impl ThresholdProtocol for DecryptContext {
ctx: serde_json::from_slice(group).expect("could not deserialize group context"),
encrypted_key: Ciphertext::zero(),
data: (Vec::new(), Vec::new(), Vec::new()),
indices: Vec::new(),
shares: Vec::new(),
result: None,
}
Expand Down Expand Up @@ -374,6 +348,8 @@ mod tests {
let (pks, _) =
<KeygenContext as KeygenProtocolTest>::run(threshold as u32, parties as u32);

let pks: Vec<_> = pks.into_values().collect();

for i in 1..parties {
assert_eq!(pks[0], pks[i])
}
Expand All @@ -387,13 +363,17 @@ mod tests {
for parties in threshold..6 {
let (pks, ctxs) =
<KeygenContext as KeygenProtocolTest>::run(threshold as u32, parties as u32);
let pks: Vec<_> = pks.into_values().collect();
let msg = b"hello";
let ct = encrypt(msg, &pks[0]).unwrap();

let mut indices = (0..parties as u16).choose_multiple(&mut OsRng, threshold);
indices.sort();
let ctxs = ctxs
.into_iter()
.choose_multiple(&mut OsRng, threshold)
.into_iter()
.collect();
let results =
<DecryptContext as ThresholdProtocolTest>::run(ctxs, indices, ct.to_vec());
<DecryptContext as ThresholdProtocolTest>::run(ctxs, ct.to_vec());

for result in results {
assert_eq!(&msg.to_vec(), &result);
Expand Down
Loading
Loading