| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871 |
- // We want to allow Point variables to be uppercase
- #![allow(non_snake_case)]
- //! The core functionality of the CMZ protocol macros
- //!
- //! You should not need to use this crate directly. The [`cmz_core`]
- //! function is called by the `cmz_derive` crate to implement the
- //! `CMZProtocol` family of macros.
- use proc_macro2::TokenStream;
- use quote::{format_ident, quote, ToTokens};
- use std::collections::{BTreeMap, HashMap};
- use syn::parse::{Parse, ParseStream, Result};
- use syn::punctuated::Punctuated;
- use syn::visit_mut::{self, VisitMut};
- use syn::{braced, bracketed, parse_quote, token, Expr, Ident, Member, Token};
- // The possible attribute specifications for a credential to be shown
- #[derive(Copy, Clone, Debug, PartialEq)]
- enum ShowSpec {
- Hide,
- Reveal,
- Implicit,
- }
- impl Parse for ShowSpec {
- fn parse(input: ParseStream) -> Result<Self> {
- let spec: Ident = input.parse()?;
- match spec.to_string().to_uppercase().as_str() {
- "H" | "HIDE" => Ok(Self::Hide),
- "R" | "REVEAL" => Ok(Self::Reveal),
- "I" | "IMPLICIT" => Ok(Self::Implicit),
- _ => Err(input.error("Unknown attribute spec for shown credential")),
- }
- }
- }
- impl ShowSpec {
- fn abbr(&self) -> &'static str {
- match self {
- Self::Hide => "H",
- Self::Reveal => "R",
- Self::Implicit => "I",
- }
- }
- }
- // The possible attribute specifications for a credential to be issued
- #[derive(Copy, Clone, Debug, PartialEq)]
- enum IssueSpec {
- Hide,
- Reveal,
- Implicit,
- Set,
- Joint,
- }
- impl Parse for IssueSpec {
- fn parse(input: ParseStream) -> Result<Self> {
- let spec: Ident = input.parse()?;
- match spec.to_string().to_uppercase().as_str() {
- "H" | "HIDE" => Ok(Self::Hide),
- "R" | "REVEAL" => Ok(Self::Reveal),
- "I" | "IMPLICIT" => Ok(Self::Implicit),
- "S" | "SET" => Ok(Self::Set),
- "J" | "JOINT" => Ok(Self::Joint),
- _ => Err(input.error("Unknown attribute spec for issued credential")),
- }
- }
- }
- impl IssueSpec {
- fn abbr(&self) -> &'static str {
- match self {
- Self::Hide => "H",
- Self::Reveal => "R",
- Self::Implicit => "I",
- Self::Set => "S",
- Self::Joint => "J",
- }
- }
- }
- // An attribute specification like "attr1: Reveal"
- #[derive(Clone)]
- struct AttrSpec<ShowOrIssue: Parse> {
- attr: Ident,
- spec: ShowOrIssue,
- }
- impl<ShowOrIssue: Parse> Parse for AttrSpec<ShowOrIssue> {
- fn parse(input: ParseStream) -> Result<Self> {
- let attr: Ident = input.parse()?;
- input.parse::<Token![:]>()?;
- let spec: ShowOrIssue = input.parse()?;
- Ok(Self { attr, spec })
- }
- }
- // A specification of a credential, either to be shown or issued
- #[derive(Debug)]
- struct CredSpec<ShowOrIssue: Parse, const VALID_OPTIONAL: bool> {
- id: Ident,
- cred_type: Ident,
- // For shown credentials only (not issued credentials): set to true
- // if we want to only optionally (for example, in an "OR" clause)
- // show that this credential is valid. The default state of false
- // means we should always show that the credential is valid.
- valid_optional: bool,
- attrs: BTreeMap<Ident, ShowOrIssue>,
- }
- impl<ShowOrIssue: Parse + Copy, const VALID_OPTIONAL: bool> Parse
- for CredSpec<ShowOrIssue, VALID_OPTIONAL>
- {
- fn parse(input: ParseStream) -> Result<Self> {
- let id: Ident = input.parse()?;
- let valid_optional = if VALID_OPTIONAL && input.peek(Token![?]) {
- input.parse::<Token![?]>()?;
- true
- } else {
- false
- };
- input.parse::<Token![:]>()?;
- let cred_type: Ident = input.parse()?;
- let content;
- braced!(content in input);
- let attrspecs: Punctuated<AttrSpec<ShowOrIssue>, Token![,]> =
- content.parse_terminated(AttrSpec::<ShowOrIssue>::parse, Token![,])?;
- let mut attrs: BTreeMap<Ident, ShowOrIssue> = BTreeMap::new();
- for attrspec in attrspecs.iter() {
- attrs.insert(attrspec.attr.clone(), attrspec.spec);
- }
- Ok(Self {
- id,
- cred_type,
- valid_optional,
- attrs,
- })
- }
- }
- // A vector of credential specifications, which could be empty, a single
- // credential specification, or a bracketed list of credential
- // specifications. We need a newtype here and not just a Vec so that we
- // can implement the Parse trait for it.
- struct CredSpecVec<ShowOrIssue: Parse, const VALID_OPTIONAL: bool>(
- Vec<CredSpec<ShowOrIssue, VALID_OPTIONAL>>,
- );
- impl<ShowOrIssue: Parse + Copy, const VALID_OPTIONAL: bool> Parse
- for CredSpecVec<ShowOrIssue, VALID_OPTIONAL>
- {
- fn parse(input: ParseStream) -> Result<Self> {
- let specvec: Vec<CredSpec<ShowOrIssue, VALID_OPTIONAL>> = if input.peek(Token![,]) {
- // The list is empty
- Vec::new()
- } else if input.peek(token::Bracket) {
- let content;
- bracketed!(content in input);
- let specs: Punctuated<CredSpec<ShowOrIssue, VALID_OPTIONAL>, Token![,]> = content
- .parse_terminated(CredSpec::<ShowOrIssue, VALID_OPTIONAL>::parse, Token![,])?;
- specs.into_iter().collect()
- } else {
- let spec: CredSpec<ShowOrIssue, VALID_OPTIONAL> = input.parse()?;
- vec![spec]
- };
- Ok(Self(specvec))
- }
- }
- /// A parsed protocol specification, following the syntax described in
- /// the documentation for the `muCMZProtocol!` macro in the `cmz` crate.
- #[derive(Debug)]
- pub struct ProtoSpec {
- proto_name: Ident,
- params: Vec<Ident>,
- point_params: Vec<Ident>,
- show_creds: Vec<CredSpec<ShowSpec, true>>,
- issue_creds: Vec<CredSpec<IssueSpec, false>>,
- statements: Vec<Expr>,
- }
- impl Parse for ProtoSpec {
- fn parse(input: ParseStream) -> Result<Self> {
- let mut params: Vec<Ident> = Vec::new();
- let mut point_params: Vec<Ident> = Vec::new();
- let proto_name: Ident = input.parse()?;
- // See if there are optional parameters; Rust does not provide a
- // convenient angle-bracket parser like it does parens, square
- // brackets, and braces, so we just roll our own.
- if input.peek(Token![<]) {
- input.parse::<Token![<]>()?;
- loop {
- if input.peek(Token![>]) {
- break;
- }
- if input.peek(Token![@]) {
- // Param identifiers starting with @ are Points
- // rather than Scalars.
- input.parse::<Token![@]>()?;
- let param: Ident = input.parse()?;
- point_params.push(param);
- } else {
- let param: Ident = input.parse()?;
- params.push(param);
- }
- if input.peek(Token![>]) {
- break;
- }
- input.parse::<Token![,]>()?;
- }
- input.parse::<Token![>]>()?;
- }
- input.parse::<Token![,]>()?;
- let showvec: CredSpecVec<ShowSpec, true> = input.parse()?;
- input.parse::<Token![,]>()?;
- let issuevec: CredSpecVec<IssueSpec, false> = input.parse()?;
- input.parse::<Token![,]>()?;
- let statementpunc: Punctuated<Expr, Token![,]> =
- input.parse_terminated(Expr::parse, Token![,])?;
- let statements: Vec<Expr> = statementpunc.into_iter().collect();
- Ok(ProtoSpec {
- proto_name,
- params,
- point_params,
- show_creds: showvec.0,
- issue_creds: issuevec.0,
- statements,
- })
- }
- }
- // Names and types of fields that might end up in a generated struct
- enum StructField {
- Scalar(Ident),
- Point(Ident),
- EncPoint(Ident),
- Pubkey(Ident),
- ByteVec(Ident),
- }
- // A list of StructField items
- #[derive(Default)]
- struct StructFieldList {
- fields: Vec<StructField>,
- }
- impl StructFieldList {
- pub fn push_scalar(&mut self, s: &Ident) {
- self.fields.push(StructField::Scalar(s.clone()));
- }
- pub fn push_point(&mut self, s: &Ident) {
- self.fields.push(StructField::Point(s.clone()));
- }
- pub fn push_encpoint(&mut self, s: &Ident) {
- self.fields.push(StructField::EncPoint(s.clone()));
- }
- pub fn push_pubkey(&mut self, s: &Ident) {
- self.fields.push(StructField::Pubkey(s.clone()));
- }
- pub fn push_bytevec(&mut self, s: &Ident) {
- self.fields.push(StructField::ByteVec(s.clone()));
- }
- /// Output an iterator consisting of the field names
- pub fn field_iter(&self) -> impl Iterator<Item = &Ident> {
- self.fields.iter().map(|f| match f {
- StructField::Scalar(id) => id,
- StructField::Point(id) => id,
- StructField::EncPoint(id) => id,
- StructField::Pubkey(id) => id,
- StructField::ByteVec(id) => id,
- })
- }
- /// Output a ToTokens of the fields as they would appear in a struct
- /// definition (including the serde_as annotations)
- pub fn field_decls(&self) -> impl ToTokens {
- let decls = self.fields.iter().map(|f| match f {
- StructField::Scalar(id) => quote! {
- #[serde_as(as = "SerdeScalar")]
- pub #id: Scalar,
- },
- StructField::Point(id) => quote! {
- #[serde_as(as = "SerdePoint")]
- pub #id: Point,
- },
- StructField::EncPoint(id) => quote! {
- #[serde_as(as = "(SerdePoint, SerdePoint)")]
- pub #id: (Point, Point),
- },
- StructField::Pubkey(id) => quote! {
- pub #id: CMZPubkey<Point>,
- },
- StructField::ByteVec(id) => quote! {
- #[serde(with = "serde_bytes")]
- pub #id: Vec<u8>,
- },
- });
- quote! { #(#decls)* }
- }
- }
- /// Produce the expansion of the `CMZProtocol` family of macros.
- ///
- /// The six macros in the `CMZProtocol` macro family all call this
- /// function, with different values for the bools.
- pub fn cmz_core(
- proto_spec: &ProtoSpec,
- use_muCMZ: bool,
- emit_client: bool,
- emit_issuer: bool,
- ) -> TokenStream {
- let proto_name = &proto_spec.proto_name;
- let has_params = !proto_spec.params.is_empty() || !proto_spec.point_params.is_empty();
- let tot_num_creds = proto_spec.show_creds.len() + proto_spec.issue_creds.len();
- // Use the group of the first named credential type
- let group_types = if !proto_spec.show_creds.is_empty() {
- let first_cred_type = &proto_spec.show_creds[0].cred_type;
- quote! {
- pub type Scalar = <#first_cred_type as CMZCredential>::Scalar;
- pub type Point = <#first_cred_type as CMZCredential>::Point;
- }
- } else if !proto_spec.issue_creds.is_empty() {
- let first_cred_type = &proto_spec.issue_creds[0].cred_type;
- quote! {
- pub type Scalar = <#first_cred_type as CMZCredential>::Scalar;
- pub type Point = <#first_cred_type as CMZCredential>::Point;
- }
- } else {
- quote! {}
- };
- // The structure of the client's ZKP
- let mut cli_proof_rand_scalars = Vec::<Ident>::default();
- let mut cli_proof_priv_scalars = Vec::<Ident>::default();
- let mut cli_proof_pub_scalars = Vec::<Ident>::default();
- let mut cli_proof_cind_points = Vec::<Ident>::default();
- let mut cli_proof_pub_points = Vec::<Ident>::default();
- let mut cli_proof_const_points = Vec::<Ident>::default();
- let mut cli_proof_statements = Vec::<TokenStream>::default();
- // A map from the credential name and attribute name (as Strings) to
- // the scoped attribute identifier. This map is used to translate
- // expressions like `L.id` in the user-provided statements into the
- // appropriate identifier.
- let mut cli_proof_idmap = HashMap::<(String, String), Ident>::default();
- // The structure of the issuer's ZKP
- let mut iss_proof_rand_scalars = Vec::<Ident>::default();
- let mut iss_proof_priv_scalars = Vec::<Ident>::default();
- let mut iss_proof_pub_scalars = Vec::<Ident>::default();
- // The issuer has no cind_points
- let mut iss_proof_pub_points = Vec::<Ident>::default();
- let mut iss_proof_const_points = Vec::<Ident>::default();
- let mut iss_proof_statements = Vec::<TokenStream>::default();
- /* Credential issuing
- For each attribute of each credential to be issued, handle it
- according to its IssueSpec:
- */
- // The fields that will end up in the ClientState
- let mut clientstate_fields = StructFieldList::default();
- // The fields that will end up in the Request
- let mut request_fields = StructFieldList::default();
- // The fields that will end up in the Reply
- let mut reply_fields = StructFieldList::default();
- // The code that will end up in prepare
- let mut prepare_code = quote! {};
- // The code that will end up in handle, before the call to
- // fill_creds
- let mut handle_code_pre_fill = quote! {};
- // The code that will end up in handle, after the call to
- // fill_creds but before the call to authorize
- let mut handle_code_post_fill = quote! {};
- // The code that will end up in handle, after the call to
- // authorize
- let mut handle_code_post_auth = quote! {};
- // The code that will end up in finalize
- let mut finalize_code = quote! {};
- // Are there any Hide or Joint attributes in _any_ credential to be
- // issued?
- let mut any_hide_joint = false;
- let A_ident = format_ident!("A_generator");
- let B_ident = format_ident!("B_generator");
- let d_ident = format_ident!("d_privkey");
- let D_ident = format_ident!("D_pubkey");
- let iss_proof_sessid_ident = format_ident!("iss_proof_sessid");
- prepare_code = quote! {
- #prepare_code
- let #A_ident = bp.A();
- };
- handle_code_pre_fill = quote! {
- #handle_code_pre_fill
- let #A_ident = bp.A();
- };
- finalize_code = quote! {
- #finalize_code
- let #A_ident = bp.A();
- };
- iss_proof_const_points.push(A_ident.clone());
- prepare_code = quote! {
- #prepare_code
- let #B_ident = bp.B();
- };
- handle_code_pre_fill = quote! {
- #handle_code_pre_fill
- let #B_ident = bp.B();
- };
- if !use_muCMZ || !proto_spec.issue_creds.is_empty() {
- finalize_code = quote! {
- #finalize_code
- let #B_ident = bp.B();
- };
- iss_proof_const_points.push(B_ident.clone());
- }
- // Stash the issue proof session id in prepare so that it can be
- // used in finalize
- clientstate_fields.push_bytevec(&iss_proof_sessid_ident);
- for iss_cred in proto_spec.issue_creds.iter() {
- // Are there any Hide or Joint attributes in this particular
- // credential to be issued?
- let mut cred_hide_joint = false;
- // The credential being issued
- let iss_cred_id = format_ident!("iss_cred_{}", iss_cred.id);
- // The public key for the credential
- let pubkey_cred = format_ident!("pubkey_iss_cred_{}", iss_cred.id);
- // The randomizing factor to generate P
- let b_cred = format_ident!("b_iss_cred_{}", iss_cred.id);
- // The (revealed part of) the MAC
- let P_cred = format_ident!("P_iss_cred_{}", iss_cred.id);
- let Q_cred = format_ident!("Q_iss_cred_{}", iss_cred.id);
- // Only for CMZ14, not µCMZ:
- // The encrypted form of the hidden part of the MAC
- let EQ_cred = format_ident!("EQ_iss_cred_{}", iss_cred.id);
- let EQ0_cred = format_ident!("EQ0_iss_cred_{}", iss_cred.id);
- let EQ1_cred = format_ident!("EQ1_iss_cred_{}", iss_cred.id);
- // The ZKP statements that prove the format of EQ_cred
- let mut eq0_statement = quote! {};
- let mut eq1_statement = quote! {};
- // Only for µCMZ, not CMZ14:
- // The Pedersen commitment to only the Hide and Joint attributes
- let C_cred = format_ident!("C_iss_cred_{}", iss_cred.id);
- // The completed Pedersen commitment to the attributes
- // (including all kinds of attributes)
- let K_cred = format_ident!("K_iss_cred_{}", iss_cred.id);
- // The ZKP statement that proves the format of C
- let mut C_statement = quote! {};
- let iss_cred_type = &iss_cred.cred_type;
- // String version of the credential name
- let cred_str = iss_cred.id.to_string();
- // Check that fill_creds filled in the private key for this
- // credential and that it's for the right protocol (CMZ14 or
- // µCMZ)
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- if #iss_cred_id.get_privkey().x.len() != #iss_cred_type::num_attrs() {
- return Err(CMZError::PrivkeyMissing(#cred_str));
- }
- if #iss_cred_id.get_privkey().muCMZ != #use_muCMZ {
- return Err(CMZError::WrongProtocol(#cred_str));
- }
- };
- // Check that the credential passed to prepare has its public
- // key set and that it's for the right protocol (CMZ14 or µCMZ)
- prepare_code = quote! {
- #prepare_code
- if #iss_cred_id.get_pubkey().X.len() != #iss_cred_type::num_attrs() {
- return Err(CMZError::PubkeyMissing(#cred_str));
- }
- if #iss_cred_id.get_pubkey().Xr.is_some() != #use_muCMZ {
- return Err(CMZError::WrongProtocol(#cred_str));
- }
- };
- // Stash the public key in prepare and use it to fill in the
- // public key of the completed credential in finalize
- clientstate_fields.push_pubkey(&pubkey_cred);
- prepare_code = quote! {
- #prepare_code
- let #pubkey_cred = #iss_cred_id.get_pubkey().clone();
- };
- finalize_code = quote! {
- #finalize_code
- #iss_cred_id.set_pubkey(&self.#pubkey_cred);
- };
- for (attr, &spec) in iss_cred.attrs.iter() {
- // String version of the attribute name
- let attr_str = attr.to_string();
- // The scoped attribute name
- let scoped_attr = format_ident!("iss_{}attr_{}_{}", spec.abbr(), iss_cred.id, attr);
- // Remember the mapping from the credential and attribute
- // name to the scoped attribute
- cli_proof_idmap.insert(
- (iss_cred.id.to_string(), attr.to_string()),
- scoped_attr.clone(),
- );
- // The private and public key for this attribute
- let x_attr = format_ident!("x_{}", scoped_attr);
- let X_attr = format_ident!("X_{}", scoped_attr);
- if spec == IssueSpec::Hide || spec == IssueSpec::Joint {
- cred_hide_joint = true;
- }
- if !use_muCMZ {
- // For CMZ14, we prove that the encrypted MAC is
- // consistent with all components of the credential's
- // public key
- handle_code_post_auth = quote! {
- #handle_code_post_auth
- let #x_attr = #iss_cred_id.privkey_x(#attr_str);
- let #X_attr = #iss_cred_id.pubkey_X(#attr_str);
- };
- finalize_code = quote! {
- #finalize_code
- let #X_attr = #iss_cred_id.pubkey_X(#attr_str);
- };
- iss_proof_priv_scalars.push(x_attr.clone());
- iss_proof_pub_points.push(X_attr.clone());
- iss_proof_statements.push(quote! {
- #X_attr = #x_attr * #A_ident,
- });
- }
- if spec == IssueSpec::Hide {
- /* For each Hide attribute, the attribute (passed in the
- prepare) goes in the ClientState, and from there to
- to the generated credential in finalize.
- */
- clientstate_fields.push_scalar(&scoped_attr);
- prepare_code = quote! {
- #prepare_code
- let #scoped_attr =
- #iss_cred_id.#attr.ok_or(CMZError::HideAttrMissing(#cred_str,
- #attr_str))?;
- };
- finalize_code = quote! {
- #finalize_code
- #iss_cred_id.#attr = Some(self.#scoped_attr);
- }
- }
- if spec == IssueSpec::Joint {
- /* For each Joint attribute, the client's part of the
- attribute (randomly generated) goes in the
- ClientState, and the issuer's part of the attribute
- (randomly generated) goes in the Reply.
- */
- clientstate_fields.push_scalar(&scoped_attr);
- reply_fields.push_scalar(&scoped_attr);
- prepare_code = quote! {
- #prepare_code
- let #scoped_attr = <Scalar as ff::Field>::random(&mut *rng);
- };
- handle_code_pre_fill = quote! {
- #handle_code_pre_fill
- let #scoped_attr = <Scalar as ff::Field>::random(&mut *rng);
- };
- finalize_code = quote! {
- #finalize_code
- let #scoped_attr = reply.#scoped_attr;
- #iss_cred_id.#attr = Some(self.#scoped_attr + reply.#scoped_attr);
- };
- }
- if !use_muCMZ && (spec == IssueSpec::Hide || spec == IssueSpec::Joint) {
- /* For each Hide and Joint attribute (for CMZ14): Compute an
- exponential El Gamal encryption (of the attribute) E_attr =
- (r_attr*B, attr*B + r_attr*D) for random r_attr. Include E_attr
- in the Request, attr in the ClientState, and attr,
- r_attr, and E_attr in the CliProof. Add
- b*x_attr*E_attr to E_Q in handle, for the b chosen on
- a per-issued-credential basis below. Include x_attr,
- X_attr, and t_attr = b*x_attr in IssProof and T_attr
- = b*X_attr = t_attr*A in Reply and IssProof.
- */
- let enc_attr = format_ident!("E_{}", scoped_attr);
- let enc0_attr = format_ident!("E0_{}", scoped_attr);
- let enc1_attr = format_ident!("E1_{}", scoped_attr);
- let r_attr = format_ident!("r_{}", scoped_attr);
- let t_attr = format_ident!("t_{}", scoped_attr);
- let T_attr = format_ident!("T_{}", scoped_attr);
- request_fields.push_encpoint(&enc_attr);
- clientstate_fields.push_encpoint(&enc_attr);
- reply_fields.push_point(&T_attr);
- iss_proof_priv_scalars.push(t_attr.clone());
- iss_proof_pub_points.push(T_attr.clone());
- iss_proof_pub_points.push(enc0_attr.clone());
- iss_proof_pub_points.push(enc1_attr.clone());
- iss_proof_statements.push(quote! {
- #T_attr = #t_attr * #A_ident,
- #T_attr = #b_cred * #X_attr,
- });
- eq0_statement = quote! {
- #eq0_statement + #t_attr * #enc0_attr
- };
- eq1_statement = quote! {
- #eq1_statement + #t_attr * #enc1_attr
- };
- cli_proof_priv_scalars.push(scoped_attr.clone());
- cli_proof_rand_scalars.push(r_attr.clone());
- cli_proof_pub_points.push(enc0_attr.clone());
- cli_proof_pub_points.push(enc1_attr.clone());
- cli_proof_statements.push(quote! {
- #enc0_attr = #r_attr * #B_ident,
- #enc1_attr = #scoped_attr * #B_ident + #r_attr * #D_ident,
- });
- prepare_code = quote! {
- #prepare_code
- let #r_attr = <Scalar as ff::Field>::random(&mut *rng);
- let #enc0_attr = bp.mulB(&#r_attr);
- let #enc1_attr = bp.mulB(&#scoped_attr) +
- #r_attr * #D_ident;
- let #enc_attr = (#enc0_attr, #enc1_attr);
- };
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let #enc0_attr = request.#enc_attr.0;
- let #enc1_attr = request.#enc_attr.1;
- };
- handle_code_post_auth = quote! {
- #handle_code_post_auth
- let #t_attr = #b_cred * #x_attr;
- #EQ_cred.0 += #t_attr * #enc0_attr;
- #EQ_cred.1 += #t_attr * #enc1_attr;
- let #T_attr = bp.mulA(&#t_attr);
- };
- finalize_code = quote! {
- #finalize_code
- let #T_attr = reply.#T_attr;
- let #enc0_attr = self.#enc_attr.0;
- let #enc1_attr = self.#enc_attr.1;
- };
- }
- if use_muCMZ && (spec == IssueSpec::Hide || spec == IssueSpec::Joint) {
- /* For each Hide and Joint attribute (for µCMZ): add
- attr*X_attr to C.
- */
- prepare_code = quote! {
- #prepare_code
- let #X_attr = #pubkey_cred.X[#iss_cred_type::attr_num(#attr_str)];
- #C_cred += #scoped_attr * #X_attr;
- };
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let #X_attr = #iss_cred_id.pubkey_X(#attr_str);
- };
- C_statement = quote! {
- #C_statement + #scoped_attr * #X_attr
- };
- cli_proof_priv_scalars.push(scoped_attr.clone());
- cli_proof_cind_points.push(X_attr.clone());
- }
- /* For each Reveal attribute: include attr in Request (client will
- pass the value into prepare). Also store it in the
- ClientState.
- */
- if spec == IssueSpec::Reveal {
- request_fields.push_scalar(&scoped_attr);
- clientstate_fields.push_scalar(&scoped_attr);
- cli_proof_pub_scalars.push(scoped_attr.clone());
- prepare_code = quote! {
- #prepare_code
- let #scoped_attr =
- #iss_cred_id.#attr.ok_or(CMZError::RevealAttrMissing(#cred_str,
- #attr_str))?;
- };
- handle_code_pre_fill = quote! {
- #handle_code_pre_fill
- let #scoped_attr = request.#scoped_attr;
- #iss_cred_id.#attr = Some(#scoped_attr);
- };
- finalize_code = quote! {
- #finalize_code
- #iss_cred_id.#attr = Some(self.#scoped_attr);
- };
- }
- /* For each Implicit attribute: store it in ClientState
- (will be passed into prepare) on the client side, and
- will be filled in by fill_creds on the issuer side.
- */
- if spec == IssueSpec::Implicit {
- clientstate_fields.push_scalar(&scoped_attr);
- cli_proof_pub_scalars.push(scoped_attr.clone());
- prepare_code = quote! {
- #prepare_code
- let #scoped_attr =
- #iss_cred_id.#attr.ok_or(CMZError::ImplicitAttrCliMissing(#cred_str,
- #attr_str))?;
- };
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let #scoped_attr =
- #iss_cred_id.#attr.ok_or(CMZError::ImplicitAttrIssMissing(#cred_str,
- #attr_str))?;
- };
- finalize_code = quote! {
- #finalize_code
- #iss_cred_id.#attr = Some(self.#scoped_attr);
- };
- }
- /* For each Set attribute: the issuer's value will be set
- by fill_creds. Include the value in Reply.
- */
- if spec == IssueSpec::Set {
- reply_fields.push_scalar(&scoped_attr);
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let #scoped_attr =
- #iss_cred_id.#attr.ok_or(CMZError::SetAttrMissing(#cred_str,
- #attr_str))?;
- };
- finalize_code = quote! {
- #finalize_code
- #iss_cred_id.#attr = Some(reply.#scoped_attr);
- }
- }
- if spec == IssueSpec::Reveal
- || spec == IssueSpec::Implicit
- || spec == IssueSpec::Set
- || spec == IssueSpec::Joint
- {
- if use_muCMZ {
- /* For each Reveal, Implicit, Set, or Joint attribute, add
- attr*X_attr to K in handle and finalize.
- */
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- #K_cred += (#scoped_attr *
- #iss_cred_id.pubkey_X(#attr_str));
- };
- // For a Joint attribute, we only want to use the
- // issuer's contribution (which is in #scoped_attr),
- // not #iss_cred_id.#attr, which is the sum of the
- // client's and issuer's contributions
- let use_attr = if spec == IssueSpec::Joint {
- quote! { #scoped_attr }
- } else {
- quote! { #iss_cred_id.#attr.unwrap() }
- };
- finalize_code = quote! {
- #finalize_code
- #K_cred += (#use_attr *
- #iss_cred_id.pubkey_X(#attr_str));
- };
- } else {
- /* For each Reveal, Implicit, Set, or Joint attribute, add
- attr*x_attr*P to Q in handle.
- */
- handle_code_post_auth = quote! {
- #handle_code_post_auth
- #Q_cred += (#scoped_attr * #x_attr) * #P_cred;
- };
- // For Joint attributes, we only want to use the
- // issuer's contribution. We already set
- // #scoped_attr to the issuer's contribution earlier
- // on.
- if spec != IssueSpec::Joint {
- finalize_code = quote! {
- #finalize_code
- let #scoped_attr = #iss_cred_id.#attr.unwrap();
- };
- }
- eq1_statement = quote! {
- #eq1_statement + #x_attr * ( #scoped_attr * #P_cred )
- };
- iss_proof_pub_scalars.push(scoped_attr.clone());
- }
- }
- }
- if !use_muCMZ {
- /* For all Hide and Joint attributes of a single credential to be
- issued (for CMZ14): the issuer chooses random b and s, computes
- P = b*B, E_Q = (s*B,s*D+b*x_0*B) + \sum_{hide,joint}
- b*x_attr*E_attr + (0,\sum_{implicit,reveal,set,joint}
- b*x_attr*attr*B) (note that E_Q and each E_attr are all
- pairs of Points; the scalar multiplication is
- componentwise). Include P, E_Q in Reply. The client will
- compute Q = E_Q[1] - d*E_Q[0].
- */
- let s_cred = format_ident!("s_iss_cred_{}", iss_cred.id);
- let x0_cred = format_ident!("x0_iss_cred_{}", iss_cred.id);
- let xr_cred = format_ident!("xr_cred{}", iss_cred.id);
- let X0_cred = format_ident!("X0_iss_cred_{}", iss_cred.id);
- reply_fields.push_point(&P_cred);
- if cred_hide_joint {
- reply_fields.push_encpoint(&EQ_cred);
- } else {
- reply_fields.push_point(&Q_cred);
- }
- let EQ_cred_code_pre = if cred_hide_joint {
- quote! {
- let #s_cred = <Scalar as ff::Field>::random(&mut *rng);
- let mut #EQ_cred = (bp.mulB(&#s_cred), #s_cred * #D_ident);
- }
- } else {
- quote! {}
- };
- let EQ_cred_code_post = if cred_hide_joint {
- quote! {
- #EQ_cred.1 += #Q_cred;
- let #EQ0_cred = #EQ_cred.0;
- let #EQ1_cred = #EQ_cred.1;
- }
- } else {
- quote! {}
- };
- if cred_hide_joint {
- iss_proof_pub_points.push(EQ0_cred.clone());
- iss_proof_pub_points.push(EQ1_cred.clone());
- iss_proof_statements.push(quote! {
- #EQ0_cred = #s_cred * #B_ident #eq0_statement,
- #EQ1_cred = #s_cred * #D_ident + #x0_cred * #P_cred #eq1_statement,
- });
- }
- handle_code_post_auth = quote! {
- let #b_cred = <Scalar as ff::Field>::random(&mut *rng);
- let #P_cred = bp.mulB(&#b_cred);
- #iss_cred_id.MAC.P = #P_cred;
- let #x0_cred = #iss_cred_id.get_privkey().x0;
- let #xr_cred = #iss_cred_id.get_privkey().xr;
- let #X0_cred = #iss_cred_id.get_pubkey().X0.unwrap();
- let mut #Q_cred = bp.mulB(&(#b_cred * #iss_cred_id.get_privkey().x0));
- #EQ_cred_code_pre
- #handle_code_post_auth
- #EQ_cred_code_post
- };
- let finalize_Q_code = if cred_hide_joint {
- quote! {
- let #EQ0_cred = reply.#EQ_cred.0;
- let #EQ1_cred = reply.#EQ_cred.1;
- #iss_cred_id.MAC.Q = #EQ1_cred - self.#d_ident * #EQ0_cred;
- }
- } else {
- quote! {
- #iss_cred_id.MAC.Q = reply.#Q_cred;
- }
- };
- finalize_code = quote! {
- #finalize_code
- let #P_cred = reply.#P_cred;
- let #X0_cred = #iss_cred_id.get_pubkey().X0.unwrap();
- #iss_cred_id.MAC.P = #P_cred;
- #finalize_Q_code
- };
- if cred_hide_joint {
- iss_proof_rand_scalars.push(s_cred.clone());
- }
- iss_proof_pub_points.push(P_cred.clone());
- iss_proof_priv_scalars.push(x0_cred.clone());
- iss_proof_rand_scalars.push(xr_cred.clone());
- iss_proof_pub_points.push(X0_cred.clone());
- iss_proof_rand_scalars.push(b_cred.clone());
- iss_proof_statements.push(quote! {
- #X0_cred = #x0_cred * #B_ident + #xr_cred * #A_ident,
- });
- }
- if use_muCMZ {
- /* For all Hide and Joint attributes of a single credential to be
- issued (for µCMZ): The client chooses a random s, computes C =
- (\sum_{hide,joint} attr*X_attr) + s*A, where X_attr is the
- public key for that attribute. Include s and C in the
- ClientState, C in the Request, and the attributes, s, and
- C in the CliProof. Hide attributes will be passed into
- prepare on the client side; Joint attributes (client
- contribution) will be generated randomly by prepare on
- the client side. On the issuer side, handle will pick a
- random b, compute P = b*A, K = C + X_r +
- \sum_{implicit,reveal,set,joint} attr*X_attr, R =
- b*(x_0*A + K). Include P and R in Reply, and x_0, b, P,
- R, K in IssProof. For each implicit,reveal,set,joint
- attribute, include x_attr and P_attr = attr*P in
- IssProof. The client will compute K as above, and Q = R
- - s*P.
- */
- let R_cred = format_ident!("R_iss_cred_{}", iss_cred.id);
- let s_cred = format_ident!("s_iss_cred_{}", iss_cred.id);
- let x0_cred = format_ident!("x0_iss_cred_{}", iss_cred.id);
- let X0_cred = format_ident!("X0_iss_cred_{}", iss_cred.id);
- reply_fields.push_point(&P_cred);
- reply_fields.push_point(&R_cred);
- if cred_hide_joint {
- clientstate_fields.push_scalar(&s_cred);
- clientstate_fields.push_point(&C_cred);
- request_fields.push_point(&C_cred);
- cli_proof_pub_points.push(C_cred.clone());
- cli_proof_rand_scalars.push(s_cred.clone());
- prepare_code = quote! {
- let #s_cred = <Scalar as ff::Field>::random(&mut *rng);
- let mut #C_cred = bp.mulA(&#s_cred);
- #prepare_code
- };
- handle_code_post_fill = quote! {
- let #C_cred = request.#C_cred;
- let mut #K_cred = #C_cred + #iss_cred_id.get_pubkey().Xr.unwrap();
- #handle_code_post_fill
- };
- finalize_code = quote! {
- let mut #K_cred = self.#C_cred + self.#pubkey_cred.Xr.unwrap();
- #finalize_code
- };
- // Construct the client proof for this credential
- cli_proof_statements.push(quote! {
- #C_cred = #s_cred * #A_ident #C_statement,
- });
- } else {
- handle_code_post_fill = quote! {
- let mut #K_cred = #iss_cred_id.get_pubkey().Xr.unwrap();
- #handle_code_post_fill
- };
- finalize_code = quote! {
- let mut #K_cred = self.#pubkey_cred.Xr.unwrap();
- #finalize_code
- };
- }
- handle_code_post_auth = quote! {
- #handle_code_post_auth
- let #b_cred = <Scalar as ff::Field>::random(&mut *rng);
- let #P_cred = bp.mulA(&#b_cred);
- #iss_cred_id.MAC.P = #P_cred;
- let #x0_cred = #iss_cred_id.get_privkey().x0;
- let #X0_cred = #iss_cred_id.get_pubkey().X0.unwrap();
- let #R_cred = #b_cred * (bp.mulA(�_cred) + #K_cred);
- };
- let finalize_Q_code = if cred_hide_joint {
- quote! {
- #iss_cred_id.MAC.Q = reply.#R_cred - self.#s_cred * reply.#P_cred;
- }
- } else {
- quote! {
- #iss_cred_id.MAC.Q = reply.#R_cred;
- }
- };
- finalize_code = quote! {
- #finalize_code
- let #P_cred = reply.#P_cred;
- let #X0_cred = #iss_cred_id.get_pubkey().X0.unwrap();
- let #R_cred = reply.#R_cred;
- #iss_cred_id.MAC.P = #P_cred;
- #finalize_Q_code
- };
- // Construct the issuer proof for this credential
- iss_proof_priv_scalars.push(x0_cred.clone());
- iss_proof_rand_scalars.push(b_cred.clone());
- iss_proof_pub_points.push(P_cred.clone());
- iss_proof_pub_points.push(X0_cred.clone());
- iss_proof_pub_points.push(K_cred.clone());
- iss_proof_pub_points.push(R_cred.clone());
- iss_proof_statements.push(quote! {
- #P_cred = #b_cred * #A_ident,
- #X0_cred = #x0_cred * #B_ident,
- #R_cred = #x0_cred * #P_cred + #b_cred * #K_cred,
- });
- }
- any_hide_joint |= cred_hide_joint;
- }
- /* If there are _any_ Hide or Joint attributes in CMZ14 (as opposed
- to µCMZ), the client generates an El Gamal keypair (d, D=d*B).
- Include d in the ClientState and D in the Request.
- */
- if any_hide_joint && !use_muCMZ {
- clientstate_fields.push_scalar(&d_ident);
- clientstate_fields.push_point(&D_ident);
- cli_proof_rand_scalars.push(d_ident.clone());
- cli_proof_pub_points.push(D_ident.clone());
- request_fields.push_point(&D_ident);
- cli_proof_statements.push(quote! {
- #D_ident = #d_ident * #B_ident,
- });
- prepare_code = quote! {
- let (#d_ident,#D_ident) = bp.keypairB(&mut *rng);
- #prepare_code
- };
- handle_code_post_fill = quote! {
- let #D_ident = request.#D_ident;
- #handle_code_post_fill
- };
- finalize_code = quote! {
- #finalize_code
- let #D_ident = self.#D_ident;
- };
- iss_proof_pub_points.push(D_ident.clone());
- }
- if !proto_spec.issue_creds.is_empty() {
- // The issuer will create a zero-knowledge proof
- let iss_proof_ident = format_ident!("iss_proof");
- reply_fields.push_bytevec(&iss_proof_ident);
- let iss_instance_fields = iss_proof_pub_points
- .iter()
- .chain(iss_proof_const_points.iter())
- .chain(iss_proof_pub_scalars.iter());
- let iss_witness_fields = iss_proof_rand_scalars
- .iter()
- .chain(iss_proof_priv_scalars.iter());
- handle_code_post_auth = quote! {
- #handle_code_post_auth
- let iss_proof_instance = issuer_proof::Instance {
- #(#iss_instance_fields,)*
- };
- let iss_proof_witness = issuer_proof::Witness {
- #(#iss_witness_fields,)*
- };
- // If prove returns Err here, there's an actual bug.
- let #iss_proof_ident =
- issuer_proof::prove(&iss_proof_instance,
- &iss_proof_witness, &iss_proof_sessid, rng).unwrap();
- };
- let cli_iss_instance_fields = iss_proof_pub_points
- .iter()
- .chain(iss_proof_const_points.iter())
- .chain(iss_proof_pub_scalars.iter());
- finalize_code = quote! {
- #finalize_code
- let iss_proof_instance = issuer_proof::Instance {
- #(#cli_iss_instance_fields,)*
- };
- if issuer_proof::verify(&iss_proof_instance,
- &reply.#iss_proof_ident, &self.iss_proof_sessid).is_err() {
- return Err((CMZError::IssProofFailed, self));
- }
- };
- }
- // Validity proofs for shown credentials with valid_optional go here
- let mut validity_proofs: HashMap<String, TokenStream> = HashMap::new();
- for show_cred in proto_spec.show_creds.iter() {
- // The credential being shown
- let show_cred_id = format_ident!("show_cred_{}", show_cred.id);
- // The rerandomizing factor for the MAC
- let t_cred = format_ident!("t_show_cred_{}", show_cred.id);
- // The rerandomized MAC
- let P_cred = format_ident!("P_show_cred_{}", show_cred.id);
- let Q_cred = format_ident!("Q_show_cred_{}", show_cred.id);
- // The randomness for the Pedersen commitment to Q
- let zQ_cred = format_ident!("zQ_show_cred_{}", show_cred.id);
- // The Pedersen commitment to Q
- let CQ_cred = format_ident!("CQ_show_cred_{}", show_cred.id);
- // The verification point
- let V_cred = format_ident!("V_show_cred_{}", show_cred.id);
- // The coefficient (on P) of the MAC on the Reveal and Implicit
- // attributes, computed by the issuer
- let q_cred = format_ident!("q_show_cred_{}", show_cred.id);
- let show_cred_type = &show_cred.cred_type;
- // String version of the credential name
- let cred_str = show_cred.id.to_string();
- // Check that fill_creds filled in the private key for this
- // credential and that it's for the right protocol (CMZ14 or
- // µCMZ)
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- if #show_cred_id.get_privkey().x.len() != #show_cred_type::num_attrs() {
- return Err(CMZError::PrivkeyMissing(#cred_str));
- }
- if #show_cred_id.get_privkey().muCMZ != #use_muCMZ {
- return Err(CMZError::WrongProtocol(#cred_str));
- }
- };
- // Check that the credential passed to prepare has its public
- // key set and that it's for the right protocol (CMZ14 or µCMZ)
- prepare_code = quote! {
- #prepare_code
- if #show_cred_id.get_pubkey().X.len() != #show_cred_type::num_attrs() {
- return Err(CMZError::PubkeyMissing(#cred_str));
- }
- if #show_cred_id.get_pubkey().Xr.is_some() != #use_muCMZ {
- return Err(CMZError::WrongProtocol(#cred_str));
- }
- };
- // Rerandomize the MAC and construct a Pedersen commitment to Q
- // Also start constructing the client's version of the
- // verification point V (which will be updated with each Hide
- // attribute below)
- prepare_code = quote! {
- #prepare_code
- let #t_cred = <Scalar as ff::Field>::random(&mut *rng);
- let #P_cred = #t_cred * #show_cred_id.MAC.P;
- let #Q_cred = #t_cred * #show_cred_id.MAC.Q;
- let #zQ_cred = <Scalar as ff::Field>::random(&mut *rng);
- let #CQ_cred = #Q_cred - bp.mulB(&#zQ_cred);
- let mut #V_cred = bp.mulB(&#zQ_cred);
- };
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let #P_cred = request.#P_cred;
- if bool::from(#P_cred.is_identity()) {
- return Err(CMZError::CliProofFailed);
- }
- };
- request_fields.push_point(&P_cred);
- request_fields.push_point(&CQ_cred);
- cli_proof_rand_scalars.push(zQ_cred.clone());
- // For incomplete credentials (where proving the validity is
- // optional) it's possible that P can be arbitrarily chosen by
- // the client, and so it is not cind.
- if show_cred.valid_optional {
- cli_proof_pub_points.push(P_cred.clone());
- } else {
- cli_proof_cind_points.push(P_cred.clone());
- }
- cli_proof_pub_points.push(V_cred.clone());
- // The ZKP statement that proves the format of V
- let mut V_statement = quote! {
- #V_cred = #zQ_cred * #B_ident
- };
- // Start constructing the issuer's version of the verification
- // point Vi (which will be updated with each Hide attribute below)
- // and the MAC on the Reveal and Implicit attributes
- // µCMZ has the extra xr to add in here
- let q_init = if use_muCMZ {
- quote! { #show_cred_id.get_privkey().x0 + #show_cred_id.get_privkey().xr }
- } else {
- quote! { #show_cred_id.get_privkey().x0 }
- };
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let mut #V_cred = -request.#CQ_cred;
- let mut #q_cred = #q_init;
- };
- for (attr, &spec) in show_cred.attrs.iter() {
- // String version of the attribute name
- let attr_str = attr.to_string();
- // The scoped attribute name
- let scoped_attr = format_ident!("show_{}attr_{}_{}", spec.abbr(), show_cred.id, attr);
- // The public key for this attribute
- let X_attr = format_ident!("X_{}", scoped_attr);
- // Remember the mapping from the credential and attribute
- // name to the scoped attribute
- cli_proof_idmap.insert(
- (show_cred.id.to_string(), attr.to_string()),
- scoped_attr.clone(),
- );
- if spec == ShowSpec::Hide {
- prepare_code = quote! {
- #prepare_code
- let #scoped_attr =
- #show_cred_id.#attr.ok_or(CMZError::HideAttrMissing(#cred_str,
- #attr_str))?;
- };
- // Construct a Pedersen commitment to the Hide attribute
- // and update the verification point
- let z_attr = format_ident!("z_{}", scoped_attr);
- let C_attr = format_ident!("C_{}", scoped_attr);
- request_fields.push_point(&C_attr);
- prepare_code = quote! {
- #prepare_code
- let #z_attr = <Scalar as ff::Field>::random(&mut *rng);
- let #C_attr = #scoped_attr * #P_cred + bp.mulA(&#z_attr);
- let #X_attr = #show_cred_id.pubkey_X(#attr_str);
- #V_cred += #z_attr * #X_attr;
- };
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let #C_attr = request.#C_attr;
- let #X_attr = #show_cred_id.pubkey_X(#attr_str);
- #V_cred += #show_cred_id.privkey_x(#attr_str)
- * #C_attr;
- };
- cli_proof_priv_scalars.push(scoped_attr.clone());
- cli_proof_rand_scalars.push(z_attr.clone());
- cli_proof_pub_points.push(C_attr.clone());
- cli_proof_cind_points.push(X_attr.clone());
- cli_proof_statements.push(quote! {
- #C_attr = #scoped_attr * #P_cred + #z_attr * #A_ident,
- });
- V_statement = quote! {
- #V_statement + #z_attr * #X_attr
- };
- }
- if spec == ShowSpec::Reveal {
- request_fields.push_scalar(&scoped_attr);
- prepare_code = quote! {
- #prepare_code
- let #scoped_attr =
- #show_cred_id.#attr.ok_or(CMZError::RevealAttrMissing(#cred_str,
- #attr_str))?;
- };
- handle_code_pre_fill = quote! {
- #handle_code_pre_fill
- let #scoped_attr = request.#scoped_attr;
- #show_cred_id.#attr = Some(#scoped_attr);
- };
- // Accumulate the coefficient (of P) on the component of
- // Q due to this attribute
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- #q_cred += #scoped_attr *
- #show_cred_id.privkey_x(#attr_str);
- };
- cli_proof_pub_scalars.push(scoped_attr.clone());
- }
- if spec == ShowSpec::Implicit {
- prepare_code = quote! {
- #prepare_code
- let #scoped_attr =
- #show_cred_id.#attr.ok_or(CMZError::ImplicitAttrCliMissing(#cred_str,
- #attr_str))?;
- };
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let #scoped_attr =
- #show_cred_id.#attr.ok_or(CMZError::ImplicitAttrIssMissing(#cred_str,
- #attr_str))?;
- };
- // Accumulate the coefficient (of P) on the component of
- // Q due to this attribute
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- #q_cred += #scoped_attr *
- #show_cred_id.privkey_x(#attr_str);
- };
- cli_proof_pub_scalars.push(scoped_attr.clone());
- }
- }
- // Compute the computation of the issuer's version of the
- // Verification point Vi
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- #V_cred += #q_cred * #P_cred;
- };
- if show_cred.valid_optional {
- validity_proofs.insert(
- cred_str,
- quote! {
- #V_statement
- },
- );
- } else {
- cli_proof_statements.push(quote! {
- #V_statement,
- });
- }
- }
- cli_proof_const_points.push(A_ident.clone());
- cli_proof_const_points.push(B_ident.clone());
- for paramid in proto_spec.params.iter() {
- let scoped_param = format_ident!("param_{}", paramid);
- prepare_code = quote! {
- #prepare_code
- let #scoped_param = params.#paramid;
- };
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let #scoped_param = params.#paramid;
- };
- cli_proof_pub_scalars.push(scoped_param.clone());
- cli_proof_idmap.insert(("".to_string(), paramid.to_string()), scoped_param.clone());
- }
- for paramid in proto_spec.point_params.iter() {
- let scoped_param = format_ident!("param_{}", paramid);
- prepare_code = quote! {
- #prepare_code
- let #scoped_param = params.#paramid;
- };
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let #scoped_param = params.#paramid;
- };
- cli_proof_pub_points.push(scoped_param.clone());
- cli_proof_idmap.insert(("".to_string(), paramid.to_string()), scoped_param.clone());
- }
- // The client will create a zero-knowledge proof
- let cli_proof_ident = format_ident!("cli_proof");
- request_fields.push_bytevec(&cli_proof_ident);
- let cli_instance_fields = cli_proof_pub_points
- .iter()
- .chain(cli_proof_const_points.iter())
- .chain(cli_proof_cind_points.iter())
- .chain(cli_proof_pub_scalars.iter());
- let cli_witness_fields = cli_proof_rand_scalars
- .iter()
- .chain(cli_proof_priv_scalars.iter());
- prepare_code = quote! {
- #prepare_code
- let cli_proof_instance = client_proof::Instance {
- #(#cli_instance_fields,)*
- };
- let cli_proof_witness = client_proof::Witness {
- #(#cli_witness_fields,)*
- };
- // If prove returns Err here, there's an actual bug.
- let #cli_proof_ident = client_proof::prove(&cli_proof_instance,
- &cli_proof_witness, &cli_proof_sessid, rng).unwrap();
- };
- let iss_cli_instance_fields = cli_proof_pub_points
- .iter()
- .chain(cli_proof_const_points.iter())
- .chain(cli_proof_cind_points.iter())
- .chain(cli_proof_pub_scalars.iter());
- handle_code_post_fill = quote! {
- #handle_code_post_fill
- let cli_proof_instance = client_proof::Instance {
- #(#iss_cli_instance_fields,)*
- };
- if client_proof::verify(&cli_proof_instance,
- &request.#cli_proof_ident, &cli_proof_sessid).is_err() {
- return Err(CMZError::CliProofFailed);
- }
- };
- // Build the Params struct, if we have params
- let params_struct = if has_params {
- let param_list = &proto_spec.params;
- let point_param_list = &proto_spec.point_params;
- quote! {
- pub struct Params {
- #( pub #param_list: Scalar, )*
- #( pub #point_param_list: Point, )*
- }
- }
- } else {
- quote! {}
- };
- // Build the ClientState struct
- let client_state = {
- let decls = clientstate_fields.field_decls();
- quote! {
- #[serde_as]
- #[derive(Clone,Debug,serde::Serialize,serde::Deserialize)]
- pub struct ClientState {
- #decls
- }
- impl TryFrom<&[u8]> for ClientState {
- type Error = postcard::Error;
- fn try_from(bytes: &[u8]) -> postcard::Result<ClientState> {
- postcard::from_bytes::<ClientState>(bytes)
- }
- }
- impl From<&ClientState> for Vec<u8> {
- fn from(req: &ClientState) -> Vec<u8> {
- postcard::to_allocvec(req).unwrap()
- }
- }
- impl ClientState {
- pub fn as_bytes(&self) -> Vec<u8> {
- self.into()
- }
- }
- }
- };
- // Build the Request and Reply structs
- let messages = {
- let reqdecls = request_fields.field_decls();
- let repdecls = reply_fields.field_decls();
- quote! {
- #[serde_as]
- #[derive(Clone,Debug,serde::Serialize,serde::Deserialize)]
- pub struct Request {
- #reqdecls
- }
- impl TryFrom<&[u8]> for Request {
- type Error = postcard::Error;
- fn try_from(bytes: &[u8]) -> postcard::Result<Request> {
- postcard::from_bytes::<Request>(bytes)
- }
- }
- impl From<&Request> for Vec<u8> {
- fn from(req: &Request) -> Vec<u8> {
- postcard::to_allocvec(req).unwrap()
- }
- }
- impl Request {
- pub fn as_bytes(&self) -> Vec<u8> {
- self.into()
- }
- }
- #[serde_as]
- #[derive(Clone,Debug,serde::Serialize,serde::Deserialize)]
- pub struct Reply {
- #repdecls
- }
- impl TryFrom<&[u8]> for Reply {
- type Error = postcard::Error;
- fn try_from(bytes: &[u8]) -> postcard::Result<Reply> {
- postcard::from_bytes::<Reply>(bytes)
- }
- }
- impl From<&Reply> for Vec<u8> {
- fn from(rep: &Reply) -> Vec<u8> {
- postcard::to_allocvec(rep).unwrap()
- }
- }
- impl Reply {
- pub fn as_bytes(&self) -> Vec<u8> {
- self.into()
- }
- }
- }
- };
- // Massage the statements provided in the protocol spec to change
- // any expression of the form "L.id" (a credential name and an
- // attribute name) into the corresponding scoped attribute.
- // Bare identifiers that are protocol parameter names also get
- // modified into the corresponding scoped attribute. These names
- // are stored in the idmap with an empty string for the credential
- // name.
- //
- // The expression "valid(A)" for a shown credential A with
- // valid_optional set expands to the proof of validity for that
- // credential.
- struct StatementScoper<'a> {
- idmap: &'a HashMap<(String, String), Ident>,
- validity_proofs: &'a HashMap<String, TokenStream>,
- }
- impl<'a> VisitMut for StatementScoper<'a> {
- fn visit_expr_mut(&mut self, node: &mut Expr) {
- if let Expr::Field(exfld) = node {
- let base = *exfld.base.clone();
- if let Expr::Path(basepath) = base {
- if let Member::Named(attrid) = &exfld.member {
- if let Some(credid) = basepath.path.get_ident() {
- if let Some(scopedid) =
- self.idmap.get(&(credid.to_string(), attrid.to_string()))
- {
- *node = parse_quote! { #scopedid };
- return;
- }
- }
- }
- }
- }
- if let Expr::Path(expath) = node {
- if let Some(id) = expath.path.get_ident() {
- if let Some(scopedparam) = self.idmap.get(&("".to_string(), id.to_string())) {
- *node = parse_quote! { #scopedparam };
- return;
- }
- }
- }
- if let Expr::Call(excall) = node {
- let base = *excall.func.clone();
- if let Expr::Path(basepath) = base {
- if let Some(id) = basepath.path.get_ident() {
- if *id == "valid" && excall.args.len() == 1 {
- let mut validity_statement = quote! {};
- let argexpr = excall.args.first().unwrap();
- if let Expr::Path(argpath) = argexpr {
- if let Some(credid) = argpath.path.get_ident() {
- let credstr = credid.to_string();
- match self.validity_proofs.get(&credstr) {
- Some(tokens) => {
- validity_statement = tokens.clone();
- },
- None => panic!("{} is not a shown credential with optional validity proof", credstr),
- }
- }
- }
- *node = parse_quote! { #validity_statement };
- return;
- }
- }
- }
- }
- // Unless we bailed out above, continue with the default
- // traversal
- visit_mut::visit_expr_mut(self, node);
- }
- }
- let mut statement_scoper = StatementScoper {
- idmap: &cli_proof_idmap,
- validity_proofs: &validity_proofs,
- };
- let mut cli_proof_scoped_statements = proto_spec.statements.clone();
- cli_proof_scoped_statements
- .iter_mut()
- .for_each(|expr| statement_scoper.visit_expr_mut(expr));
- // The client's zero-knowledge proof
- let cli_sigma_compiler_macro = if emit_client && emit_issuer {
- quote! { sigma_compiler }
- } else if emit_client {
- quote! { sigma_compiler_prover }
- } else {
- quote! { sigma_compiler_verifier }
- };
- let cli_proof = {
- quote! {
- #cli_sigma_compiler_macro! { client_proof<Point>,
- (#(rand #cli_proof_rand_scalars,)*
- #(#cli_proof_priv_scalars,)*
- #(pub #cli_proof_pub_scalars,)*),
- (#(cind #cli_proof_cind_points,)*
- #(#cli_proof_pub_points,)*
- #(cind const #cli_proof_const_points,)*),
- #(#cli_proof_scoped_statements,)*
- #(#cli_proof_statements)*
- }
- }
- };
- // The issuer's zero-knowledge proof
- let iss_sigma_compiler_macro = if emit_client && emit_issuer {
- quote! { sigma_compiler }
- } else if emit_issuer {
- quote! { sigma_compiler_prover }
- } else {
- quote! { sigma_compiler_verifier }
- };
- let iss_proof = {
- quote! {
- #iss_sigma_compiler_macro! { issuer_proof<Point>,
- (#(rand #iss_proof_rand_scalars,)*
- #(#iss_proof_priv_scalars,)*
- #(pub #iss_proof_pub_scalars,)*),
- // no cind_points
- (#(#iss_proof_pub_points,)*
- #(cind const #iss_proof_const_points,)*),
- #(#iss_proof_statements)*
- }
- }
- };
- // The argument list for the client's prepare function. There is an
- // immutable reference for each credential to be shown, and an owned
- // value for each credential to be issued.
- let client_show_args = proto_spec.show_creds.iter().map(|c| {
- let id = format_ident!("show_cred_{}", c.id);
- let cred_type = &c.cred_type;
- quote! { #id: &#cred_type, }
- });
- let client_issue_args = proto_spec.issue_creds.iter().map(|c| {
- let id = format_ident!("iss_cred_{}", c.id);
- let cred_type = &c.cred_type;
- quote! { #id: #cred_type, }
- });
- let client_params_arg = if has_params {
- quote! { params: &Params, }
- } else {
- quote! {}
- };
- // Build the client's prepare function
- let client_func = {
- let reqf = request_fields.field_iter();
- let csf = clientstate_fields.field_iter();
- quote! {
- pub fn prepare(rng: &mut (impl CryptoRng + Rng),
- session_id: &[u8],
- #(#client_show_args)* #(#client_issue_args)* #client_params_arg)
- -> Result<(Request, ClientState),CMZError> {
- let bp = cmz_basepoints::<Point>();
- let mut cli_proof_sessid: Vec<u8> = Vec::new();
- cli_proof_sessid.extend(b"cli_");
- cli_proof_sessid.extend(session_id);
- let mut iss_proof_sessid: Vec<u8> = Vec::new();
- iss_proof_sessid.extend(b"iss_");
- iss_proof_sessid.extend(session_id);
- #prepare_code
- Ok((Request{#(#reqf,)*}, ClientState{#(#csf,)*}))
- }
- }
- };
- // Build the issuer's handle function
- let issuer_func = {
- // The credential declarations for the issuer's handle function
- let cred_decls = proto_spec
- .show_creds
- .iter()
- .map(|c| {
- let id = format_ident!("show_cred_{}", c.id);
- let cred_type = &c.cred_type;
- quote! { let mut #id = #cred_type::default(); }
- })
- .chain(proto_spec.issue_creds.iter().map(|c| {
- let id = format_ident!("iss_cred_{}", c.id);
- let cred_type = &c.cred_type;
- quote! { let mut #id = #cred_type::default(); }
- }));
- // The type of the returned credentials from handle
- let cred_rettypes = proto_spec
- .show_creds
- .iter()
- .map(|c| {
- let cred_type = &c.cred_type;
- quote! { #cred_type }
- })
- .chain(proto_spec.issue_creds.iter().map(|c| {
- let cred_type = &c.cred_type;
- quote! { #cred_type }
- }));
- // The return type
- let rettype = match tot_num_creds {
- 0 => quote! { Result<Reply,CMZError> },
- 1 => quote! { Result<(Reply, #(#cred_rettypes)*),CMZError> },
- _ => quote! { Result<(Reply, (#(#cred_rettypes),*)),CMZError> },
- };
- // The return value
- let cred_retvals = proto_spec
- .show_creds
- .iter()
- .map(|c| {
- let id = format_ident!("show_cred_{}", c.id);
- quote! { #id }
- })
- .chain(proto_spec.issue_creds.iter().map(|c| {
- let id = format_ident!("iss_cred_{}", c.id);
- quote! { #id }
- }));
- // The argument list for the issuer's fill_creds callback
- let fill_creds_args = proto_spec
- .show_creds
- .iter()
- .map(|c| {
- let cred_type = &c.cred_type;
- quote! { &mut #cred_type, }
- })
- .chain(proto_spec.issue_creds.iter().map(|c| {
- let cred_type = &c.cred_type;
- quote! { &mut #cred_type, }
- }));
- // The parameters for the fill_creds callback
- let fill_creds_params = proto_spec
- .show_creds
- .iter()
- .map(|c| {
- let id = format_ident!("show_cred_{}", c.id);
- quote! { &mut #id, }
- })
- .chain(proto_spec.issue_creds.iter().map(|c| {
- let id = format_ident!("iss_cred_{}", c.id);
- quote! { &mut #id, }
- }));
- // The return value of the callback
- let fill_creds_params_ret = if has_params {
- quote! { Params }
- } else {
- quote! { () }
- };
- // The assignment of the return value of the callback
- let fill_creds_assign = if has_params {
- quote! { let params = }
- } else {
- quote! {}
- };
- // The argument list for the issuer's authorize callback
- let authorize_args = proto_spec
- .show_creds
- .iter()
- .map(|c| {
- let cred_type = &c.cred_type;
- quote! { &#cred_type, }
- })
- .chain(proto_spec.issue_creds.iter().map(|c| {
- let cred_type = &c.cred_type;
- quote! { &#cred_type, }
- }));
- // The parameters for the authorize callback
- let authorize_params = proto_spec
- .show_creds
- .iter()
- .map(|c| {
- let id = format_ident!("show_cred_{}", c.id);
- quote! { &#id, }
- })
- .chain(proto_spec.issue_creds.iter().map(|c| {
- let id = format_ident!("iss_cred_{}", c.id);
- quote! { &#id, }
- }));
- let repf = reply_fields.field_iter();
- let retval = match tot_num_creds {
- 0 => quote! { Ok(Reply{#(#repf,)*}) },
- 1 => quote! { Ok((Reply{#(#repf,)*}, #(#cred_retvals)*)) },
- _ => quote! { Ok((Reply{#(#repf,)*}, (#(#cred_retvals),*))) },
- };
- quote! {
- pub fn handle<F,A>(rng: &mut (impl CryptoRng + Rng),
- session_id: &[u8],
- request: Request, fill_creds: F, authorize: A)
- -> #rettype
- where
- F: FnOnce(#(#fill_creds_args)*) ->
- Result<#fill_creds_params_ret, CMZError>,
- A: FnOnce(#(#authorize_args)*) ->
- Result<(),CMZError>
- {
- let bp = cmz_basepoints::<Point>();
- let mut cli_proof_sessid: Vec<u8> = Vec::new();
- cli_proof_sessid.extend(b"cli_");
- cli_proof_sessid.extend(session_id);
- let mut iss_proof_sessid: Vec<u8> = Vec::new();
- iss_proof_sessid.extend(b"iss_");
- iss_proof_sessid.extend(session_id);
- #(#cred_decls)*
- #handle_code_pre_fill
- #fill_creds_assign fill_creds(#(#fill_creds_params)*)?;
- #handle_code_post_fill
- authorize(#(#authorize_params)*)?;
- #handle_code_post_auth
- #retval
- }
- }
- };
- // Build the ClientState's finalize function
- let clientstate_finalize_func = {
- // The credential declarations for the client's finalize function
- let cred_decls = proto_spec.issue_creds.iter().map(|c| {
- let id = format_ident!("iss_cred_{}", c.id);
- let cred_type = &c.cred_type;
- quote! { let mut #id = #cred_type::default(); }
- });
- // The type of the returned credentials from finalize
- let cred_rettypes = proto_spec.issue_creds.iter().map(|c| {
- let cred_type = &c.cred_type;
- quote! { #cred_type }
- });
- let rettype = match proto_spec.issue_creds.len() {
- 0 => quote! { Result<(),(CMZError,Self)> },
- 1 => quote! { Result<#(#cred_rettypes)*,(CMZError,Self)> },
- _ => quote! { Result<(#(#cred_rettypes),*),(CMZError,Self)> },
- };
- // Return value for ClientState's finalize function
- let cred_retvals = proto_spec.issue_creds.iter().map(|c| {
- let id = format_ident!("iss_cred_{}", c.id);
- quote! { #id }
- });
- let retval = match proto_spec.issue_creds.len() {
- 0 => quote! { Ok(()) },
- 1 => quote! { Ok(#(#cred_retvals)*) },
- _ => quote! { Ok((#(#cred_retvals),*)) },
- };
- quote! {
- impl ClientState {
- pub fn finalize(
- self,
- reply: Reply,
- ) -> #rettype {
- let bp = cmz_basepoints::<Point>();
- #(#cred_decls)*
- #finalize_code
- #retval
- }
- }
- }
- };
- let client_side = if emit_client {
- quote! { #client_state #client_func #clientstate_finalize_func }
- } else {
- quote! {}
- };
- let issuer_side = if emit_issuer {
- issuer_func
- } else {
- quote! {}
- };
- // Output the generated module for this protocol
- quote! {
- #[allow(non_snake_case)]
- pub mod #proto_name {
- use super::*;
- use sigma_compiler::*;
- use group::GroupEncoding;
- #group_types
- #params_struct
- #messages
- #cli_proof
- #iss_proof
- #client_side
- #issuer_side
- }
- }
- }
|