Skip to content

Commit

Permalink
restructure export data structures and functions
Browse files Browse the repository at this point in the history
  • Loading branch information
simonjiao committed Apr 22, 2023
1 parent b2a7185 commit 61f2971
Show file tree
Hide file tree
Showing 3 changed files with 141 additions and 64 deletions.
84 changes: 84 additions & 0 deletions src/components/zkcards_wasm/src/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,88 @@
#![deny(missing_docs)]
#![allow(clippy::needless_borrow)]

//todo: remove `unwrap`
//todo: more comments

mod zkcards;

use crate::zkcards::{
AggregatePublicKey, Card, CardParameters, MaskedCard, Player, ProofShuffle,
RevealedToken, Surrogate,
};
use rand::thread_rng;
use std::collections::HashMap;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
/// create a new player with `name` and `card parameters` received from contract
pub fn new_player(pp: CardParameters, name: Vec<u8>) -> Player {
let rng = &mut thread_rng();
Player::new(rng, &pp, &name).unwrap()
}

#[wasm_bindgen]
/// generate a `surrogate` with `ProofKeyOwnerShip` as this player's behave
pub fn new_surrogate(player: &Player, pp: &CardParameters) -> Surrogate {
player.new_surrogate(pp)
}

#[wasm_bindgen]
/// verify a player
pub fn verify_proof_pk(player: Surrogate, pp: &CardParameters) -> bool {
player.verify(&pp)
}

#[wasm_bindgen]
/// Perform a shuffle operation
pub fn shuffle(
player: &Player,
pp: &CardParameters,
deck: &Vec<MaskedCard>,
joint_pk: &AggregatePublicKey,
nums_of_cards: usize,
) -> (Vec<MaskedCard>, ProofShuffle) {
player.shuffle(pp, deck, joint_pk, nums_of_cards).unwrap()
}

#[wasm_bindgen]
/// verify shuffled deck from another player
pub fn verify_shuffle(
parameters: &CardParameters,
joint_pk: &AggregatePublicKey,
original_deck: &Vec<MaskedCard>,
shuffled_deck: &Vec<MaskedCard>,
proof_shuffle: &ProofShuffle,
) -> bool {
Player::verify_shuffle(
parameters,
joint_pk,
original_deck,
shuffled_deck,
proof_shuffle,
)
.is_ok()
}

#[wasm_bindgen]
/// reveal a card
pub fn compute_reveal_token(
player: &Player,
card: &MaskedCard,
pp: &CardParameters,
) -> RevealedToken {
let rng = &mut thread_rng();
player.compute_reveal_token(rng, pp, card).unwrap()
}

#[wasm_bindgen]
/// open a card
pub fn open_card(
parameters: &CardParameters,
reveal_tokens: &Vec<RevealedToken>,
card_mappings: &HashMap<Card, Vec<u8>>,
card: &MaskedCard,
cards: &Vec<MaskedCard>,
) -> Vec<u8> {
Player::peek_at_card(parameters, reveal_tokens, card_mappings, card, cards).unwrap()
}
35 changes: 26 additions & 9 deletions src/components/zkcards_wasm/src/zkcards/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ mod error;
mod player;
mod user_card;

pub use player::*;
pub use user_card::*;

use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use barnett::discrete_log_cards;
use proof_essentials::{
Expand Down Expand Up @@ -51,9 +54,20 @@ impl<'a> From<&'a CardParameters> for &'a discrete_log_cards::Parameters<Curve>
}
}

pub type PlayerPublicKey = discrete_log_cards::PublicKey<Curve>;
pub type PlayerSecretKey = discrete_log_cards::PlayerSecretKey<Curve>;
pub type AggregatePublicKey = discrete_log_cards::PublicKey<Curve>;
type PlayerSecretKey = discrete_log_cards::PlayerSecretKey<Curve>;

#[wasm_bindgen]
#[derive(Clone, Copy, Serialize, Deserialize)]
pub struct PlayerPublicKey(
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
pub(crate) discrete_log_cards::PublicKey<Curve>,
);
#[wasm_bindgen]
#[derive(Clone, Serialize, Deserialize)]
pub struct AggregatePublicKey(
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
pub(crate) discrete_log_cards::PublicKey<Curve>,
);

#[wasm_bindgen]
#[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize)]
Expand All @@ -72,6 +86,11 @@ impl From<Card> for discrete_log_cards::Card<Curve> {
}
}

#[wasm_bindgen]
pub struct MaskedCards {
inner: Vec<MaskedCard>,
}

#[wasm_bindgen]
#[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Serialize, Deserialize)]
pub struct MaskedCard(
Expand Down Expand Up @@ -167,7 +186,6 @@ impl<'a> From<&'a ProofShuffle> for &'a shuffle::proof::Proof<Scalar, Enc, Comm>
}
}

#[wasm_bindgen]
//pub struct ProofMasking(chaum_pedersen_dl_equality::proof::Proof<Curve>);
#[derive(Clone, Copy, Eq, Hash, PartialEq, Debug, Deserialize, Serialize)]
pub struct ProofRemasking(
Expand All @@ -185,13 +203,12 @@ impl From<ProofRemasking> for chaum_pedersen_dl_equality::proof::Proof<Curve> {
}
}

//#[wasm_bindgen]
#[wasm_bindgen]
#[derive(Serialize, Deserialize)]
pub struct RevealedToken {
pub token: RevealToken,
pub proof: ProofReveal,
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
pub player: PlayerPublicKey,
pub(crate) token: RevealToken,
pub(crate) proof: ProofReveal,
pub(crate) player: PlayerPublicKey,
}

fn ark_se<S, A: CanonicalSerialize>(a: &A, s: S) -> Result<S::Ok, S::Error>
Expand Down
86 changes: 31 additions & 55 deletions src/components/zkcards_wasm/src/zkcards/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,34 @@ use super::{
RevealedToken, Scalar,
};
use ark_std::rand::Rng;
use barnett::BarnettSmartProtocol;
use barnett::{BarnettSmartProtocol, Mask};
use proof_essentials::utils::{permutation::Permutation, rand::sample_vector};
use rand::thread_rng;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
#[derive(Clone)]
pub struct Player {
name: Vec<u8>,
sk: PlayerSecretKey,
pk: PlayerPublicKey,
proof_key: ProofKeyOwnership,
cards: Vec<MaskedCard>,
opened_cards: Vec<Option<ClassicPlayingCard>>,
}

#[wasm_bindgen]
#[derive(Serialize, Deserialize)]
pub struct Surrogate {
pub name: Vec<u8>,
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
pub pk: PlayerPublicKey,
pub proof_key: ProofKeyOwnership,
pub(crate) name: Vec<u8>,
pub(crate) pk: PlayerPublicKey,
pub(crate) proof_key: ProofKeyOwnership,
}

impl Surrogate {
pub fn verify(&self, pp: &CardParameters) -> bool {
CardProtocol::verify_key_ownership(
pp.into(),
&self.pk,
&self.pk.0,
&self.name,
&self.proof_key.into(),
)
Expand All @@ -50,15 +49,10 @@ impl Player {
name: &Vec<u8>,
) -> Result<Self> {
let (pk, sk) = CardProtocol::player_keygen(rng, pp.into())?;
let proof_key =
CardProtocol::prove_key_ownership(rng, pp.into(), &pk, &sk, name)?;
Ok(Self {
name: name.clone(),
sk,
pk,
proof_key: proof_key.into(),
cards: vec![],
opened_cards: vec![],
pk: PlayerPublicKey(pk),
})
}

Expand All @@ -67,7 +61,7 @@ impl Player {
let proof_key = CardProtocol::prove_key_ownership(
rng,
pp.into(),
&self.pk,
&self.pk.0,
&self.sk,
&self.name,
)
Expand All @@ -80,14 +74,6 @@ impl Player {
}
}

pub fn surrogate(&self) -> Surrogate {
Surrogate {
name: self.name.clone(),
pk: self.pk,
proof_key: self.proof_key,
}
}

pub fn shuffle(
&self,
parameters: &CardParameters,
Expand All @@ -103,7 +89,7 @@ impl Player {
let (shuffled_deck, shuffle_proof) = CardProtocol::shuffle_and_remask(
&mut rng,
parameters.into(),
joint_pk,
&joint_pk.0,
&deck,
&masking_factors,
&permutation,
Expand All @@ -118,7 +104,6 @@ impl Player {
}

pub fn verify_shuffle(
&self,
parameters: &CardParameters,
joint_pk: &AggregatePublicKey,
original_deck: &Vec<MaskedCard>,
Expand All @@ -135,67 +120,58 @@ impl Player {
.collect::<Vec<_>>();
CardProtocol::verify_shuffle(
parameters.into(),
joint_pk,
&joint_pk.0,
&original_deck,
&shuffled_deck,
proof_shuffle.into(),
)
.map_err(|e| GameErrors::CryptoError(e))
}

pub fn receive_card(&mut self, card: MaskedCard) {
self.cards.push(card);
self.opened_cards.push(None);
}

pub fn peek_at_card(
&mut self,
parameters: &CardParameters,
reveal_tokens: &mut Vec<RevealedToken>,
reveal_tokens: &Vec<RevealedToken>,
card_mappings: &HashMap<Card, Vec<u8>>,
card: &MaskedCard,
) -> Result<()> {
let i = self.cards.iter().position(|&x| x == *card);

let i = i.ok_or(GameErrors::CardNotFound)?;

//TODO add function to create that without the proof
let rng = &mut thread_rng();
let own_reveal_token = self.compute_reveal_token(rng, parameters, card)?;
reveal_tokens.push(RevealedToken {
token: own_reveal_token.0,
proof: own_reveal_token.1,
player: own_reveal_token.2,
});
cards: &Vec<MaskedCard>,
) -> Result<Vec<u8>> {
let _ = cards
.iter()
.position(|&x| x == *card)
.ok_or(GameErrors::CardNotFound)?;

let raw_reveal_tokens = reveal_tokens
.iter()
.map(|t| (t.token.into(), t.proof.into(), t.player))
.map(|t| (t.token.into(), t.proof.into(), t.player.0))
.collect::<Vec<_>>();

let unmasked_card =
CardProtocol::unmask(parameters.into(), &raw_reveal_tokens, card.into())?;
let opened_card = card_mappings.get(&unmasked_card.into());
let opened_card = opened_card.ok_or(GameErrors::InvalidCard)?;
let opened_card = card_mappings
.get(&unmasked_card.into())
.ok_or(GameErrors::InvalidCard)?;

self.opened_cards[i] = Some(serde_json::from_slice(opened_card).unwrap());
Ok(())
Ok(opened_card.to_owned())
}

pub fn compute_reveal_token<R: Rng>(
&self,
rng: &mut R,
pp: &CardParameters,
card: &MaskedCard,
) -> Result<(RevealToken, ProofReveal, PlayerPublicKey)> {
) -> Result<RevealedToken> {
let (reveal_token, reveal_proof) = CardProtocol::compute_reveal_token(
rng,
pp.into(),
&self.sk,
&self.pk,
&self.pk.0,
card.into(),
)?;

Ok((reveal_token.into(), reveal_proof.into(), self.pk))
Ok(RevealedToken {
token: reveal_token.into(),
proof: reveal_proof.into(),
player: self.pk,
})
}
}

0 comments on commit 61f2971

Please sign in to comment.