lib.rs 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871
  1. // We want to allow Point variables to be uppercase
  2. #![allow(non_snake_case)]
  3. //! The core functionality of the CMZ protocol macros
  4. //!
  5. //! You should not need to use this crate directly. The [`cmz_core`]
  6. //! function is called by the `cmz_derive` crate to implement the
  7. //! `CMZProtocol` family of macros.
  8. use proc_macro2::TokenStream;
  9. use quote::{format_ident, quote, ToTokens};
  10. use std::collections::{BTreeMap, HashMap};
  11. use syn::parse::{Parse, ParseStream, Result};
  12. use syn::punctuated::Punctuated;
  13. use syn::visit_mut::{self, VisitMut};
  14. use syn::{braced, bracketed, parse_quote, token, Expr, Ident, Member, Token};
  15. // The possible attribute specifications for a credential to be shown
  16. #[derive(Copy, Clone, Debug, PartialEq)]
  17. enum ShowSpec {
  18. Hide,
  19. Reveal,
  20. Implicit,
  21. }
  22. impl Parse for ShowSpec {
  23. fn parse(input: ParseStream) -> Result<Self> {
  24. let spec: Ident = input.parse()?;
  25. match spec.to_string().to_uppercase().as_str() {
  26. "H" | "HIDE" => Ok(Self::Hide),
  27. "R" | "REVEAL" => Ok(Self::Reveal),
  28. "I" | "IMPLICIT" => Ok(Self::Implicit),
  29. _ => Err(input.error("Unknown attribute spec for shown credential")),
  30. }
  31. }
  32. }
  33. impl ShowSpec {
  34. fn abbr(&self) -> &'static str {
  35. match self {
  36. Self::Hide => "H",
  37. Self::Reveal => "R",
  38. Self::Implicit => "I",
  39. }
  40. }
  41. }
  42. // The possible attribute specifications for a credential to be issued
  43. #[derive(Copy, Clone, Debug, PartialEq)]
  44. enum IssueSpec {
  45. Hide,
  46. Reveal,
  47. Implicit,
  48. Set,
  49. Joint,
  50. }
  51. impl Parse for IssueSpec {
  52. fn parse(input: ParseStream) -> Result<Self> {
  53. let spec: Ident = input.parse()?;
  54. match spec.to_string().to_uppercase().as_str() {
  55. "H" | "HIDE" => Ok(Self::Hide),
  56. "R" | "REVEAL" => Ok(Self::Reveal),
  57. "I" | "IMPLICIT" => Ok(Self::Implicit),
  58. "S" | "SET" => Ok(Self::Set),
  59. "J" | "JOINT" => Ok(Self::Joint),
  60. _ => Err(input.error("Unknown attribute spec for issued credential")),
  61. }
  62. }
  63. }
  64. impl IssueSpec {
  65. fn abbr(&self) -> &'static str {
  66. match self {
  67. Self::Hide => "H",
  68. Self::Reveal => "R",
  69. Self::Implicit => "I",
  70. Self::Set => "S",
  71. Self::Joint => "J",
  72. }
  73. }
  74. }
  75. // An attribute specification like "attr1: Reveal"
  76. #[derive(Clone)]
  77. struct AttrSpec<ShowOrIssue: Parse> {
  78. attr: Ident,
  79. spec: ShowOrIssue,
  80. }
  81. impl<ShowOrIssue: Parse> Parse for AttrSpec<ShowOrIssue> {
  82. fn parse(input: ParseStream) -> Result<Self> {
  83. let attr: Ident = input.parse()?;
  84. input.parse::<Token![:]>()?;
  85. let spec: ShowOrIssue = input.parse()?;
  86. Ok(Self { attr, spec })
  87. }
  88. }
  89. // A specification of a credential, either to be shown or issued
  90. #[derive(Debug)]
  91. struct CredSpec<ShowOrIssue: Parse, const VALID_OPTIONAL: bool> {
  92. id: Ident,
  93. cred_type: Ident,
  94. // For shown credentials only (not issued credentials): set to true
  95. // if we want to only optionally (for example, in an "OR" clause)
  96. // show that this credential is valid. The default state of false
  97. // means we should always show that the credential is valid.
  98. valid_optional: bool,
  99. attrs: BTreeMap<Ident, ShowOrIssue>,
  100. }
  101. impl<ShowOrIssue: Parse + Copy, const VALID_OPTIONAL: bool> Parse
  102. for CredSpec<ShowOrIssue, VALID_OPTIONAL>
  103. {
  104. fn parse(input: ParseStream) -> Result<Self> {
  105. let id: Ident = input.parse()?;
  106. let valid_optional = if VALID_OPTIONAL && input.peek(Token![?]) {
  107. input.parse::<Token![?]>()?;
  108. true
  109. } else {
  110. false
  111. };
  112. input.parse::<Token![:]>()?;
  113. let cred_type: Ident = input.parse()?;
  114. let content;
  115. braced!(content in input);
  116. let attrspecs: Punctuated<AttrSpec<ShowOrIssue>, Token![,]> =
  117. content.parse_terminated(AttrSpec::<ShowOrIssue>::parse, Token![,])?;
  118. let mut attrs: BTreeMap<Ident, ShowOrIssue> = BTreeMap::new();
  119. for attrspec in attrspecs.iter() {
  120. attrs.insert(attrspec.attr.clone(), attrspec.spec);
  121. }
  122. Ok(Self {
  123. id,
  124. cred_type,
  125. valid_optional,
  126. attrs,
  127. })
  128. }
  129. }
  130. // A vector of credential specifications, which could be empty, a single
  131. // credential specification, or a bracketed list of credential
  132. // specifications. We need a newtype here and not just a Vec so that we
  133. // can implement the Parse trait for it.
  134. struct CredSpecVec<ShowOrIssue: Parse, const VALID_OPTIONAL: bool>(
  135. Vec<CredSpec<ShowOrIssue, VALID_OPTIONAL>>,
  136. );
  137. impl<ShowOrIssue: Parse + Copy, const VALID_OPTIONAL: bool> Parse
  138. for CredSpecVec<ShowOrIssue, VALID_OPTIONAL>
  139. {
  140. fn parse(input: ParseStream) -> Result<Self> {
  141. let specvec: Vec<CredSpec<ShowOrIssue, VALID_OPTIONAL>> = if input.peek(Token![,]) {
  142. // The list is empty
  143. Vec::new()
  144. } else if input.peek(token::Bracket) {
  145. let content;
  146. bracketed!(content in input);
  147. let specs: Punctuated<CredSpec<ShowOrIssue, VALID_OPTIONAL>, Token![,]> = content
  148. .parse_terminated(CredSpec::<ShowOrIssue, VALID_OPTIONAL>::parse, Token![,])?;
  149. specs.into_iter().collect()
  150. } else {
  151. let spec: CredSpec<ShowOrIssue, VALID_OPTIONAL> = input.parse()?;
  152. vec![spec]
  153. };
  154. Ok(Self(specvec))
  155. }
  156. }
  157. /// A parsed protocol specification, following the syntax described in
  158. /// the documentation for the `muCMZProtocol!` macro in the `cmz` crate.
  159. #[derive(Debug)]
  160. pub struct ProtoSpec {
  161. proto_name: Ident,
  162. params: Vec<Ident>,
  163. point_params: Vec<Ident>,
  164. show_creds: Vec<CredSpec<ShowSpec, true>>,
  165. issue_creds: Vec<CredSpec<IssueSpec, false>>,
  166. statements: Vec<Expr>,
  167. }
  168. impl Parse for ProtoSpec {
  169. fn parse(input: ParseStream) -> Result<Self> {
  170. let mut params: Vec<Ident> = Vec::new();
  171. let mut point_params: Vec<Ident> = Vec::new();
  172. let proto_name: Ident = input.parse()?;
  173. // See if there are optional parameters; Rust does not provide a
  174. // convenient angle-bracket parser like it does parens, square
  175. // brackets, and braces, so we just roll our own.
  176. if input.peek(Token![<]) {
  177. input.parse::<Token![<]>()?;
  178. loop {
  179. if input.peek(Token![>]) {
  180. break;
  181. }
  182. if input.peek(Token![@]) {
  183. // Param identifiers starting with @ are Points
  184. // rather than Scalars.
  185. input.parse::<Token![@]>()?;
  186. let param: Ident = input.parse()?;
  187. point_params.push(param);
  188. } else {
  189. let param: Ident = input.parse()?;
  190. params.push(param);
  191. }
  192. if input.peek(Token![>]) {
  193. break;
  194. }
  195. input.parse::<Token![,]>()?;
  196. }
  197. input.parse::<Token![>]>()?;
  198. }
  199. input.parse::<Token![,]>()?;
  200. let showvec: CredSpecVec<ShowSpec, true> = input.parse()?;
  201. input.parse::<Token![,]>()?;
  202. let issuevec: CredSpecVec<IssueSpec, false> = input.parse()?;
  203. input.parse::<Token![,]>()?;
  204. let statementpunc: Punctuated<Expr, Token![,]> =
  205. input.parse_terminated(Expr::parse, Token![,])?;
  206. let statements: Vec<Expr> = statementpunc.into_iter().collect();
  207. Ok(ProtoSpec {
  208. proto_name,
  209. params,
  210. point_params,
  211. show_creds: showvec.0,
  212. issue_creds: issuevec.0,
  213. statements,
  214. })
  215. }
  216. }
  217. // Names and types of fields that might end up in a generated struct
  218. enum StructField {
  219. Scalar(Ident),
  220. Point(Ident),
  221. EncPoint(Ident),
  222. Pubkey(Ident),
  223. ByteVec(Ident),
  224. }
  225. // A list of StructField items
  226. #[derive(Default)]
  227. struct StructFieldList {
  228. fields: Vec<StructField>,
  229. }
  230. impl StructFieldList {
  231. pub fn push_scalar(&mut self, s: &Ident) {
  232. self.fields.push(StructField::Scalar(s.clone()));
  233. }
  234. pub fn push_point(&mut self, s: &Ident) {
  235. self.fields.push(StructField::Point(s.clone()));
  236. }
  237. pub fn push_encpoint(&mut self, s: &Ident) {
  238. self.fields.push(StructField::EncPoint(s.clone()));
  239. }
  240. pub fn push_pubkey(&mut self, s: &Ident) {
  241. self.fields.push(StructField::Pubkey(s.clone()));
  242. }
  243. pub fn push_bytevec(&mut self, s: &Ident) {
  244. self.fields.push(StructField::ByteVec(s.clone()));
  245. }
  246. /// Output an iterator consisting of the field names
  247. pub fn field_iter(&self) -> impl Iterator<Item = &Ident> {
  248. self.fields.iter().map(|f| match f {
  249. StructField::Scalar(id) => id,
  250. StructField::Point(id) => id,
  251. StructField::EncPoint(id) => id,
  252. StructField::Pubkey(id) => id,
  253. StructField::ByteVec(id) => id,
  254. })
  255. }
  256. /// Output a ToTokens of the fields as they would appear in a struct
  257. /// definition (including the serde_as annotations)
  258. pub fn field_decls(&self) -> impl ToTokens {
  259. let decls = self.fields.iter().map(|f| match f {
  260. StructField::Scalar(id) => quote! {
  261. #[serde_as(as = "SerdeScalar")]
  262. pub #id: Scalar,
  263. },
  264. StructField::Point(id) => quote! {
  265. #[serde_as(as = "SerdePoint")]
  266. pub #id: Point,
  267. },
  268. StructField::EncPoint(id) => quote! {
  269. #[serde_as(as = "(SerdePoint, SerdePoint)")]
  270. pub #id: (Point, Point),
  271. },
  272. StructField::Pubkey(id) => quote! {
  273. pub #id: CMZPubkey<Point>,
  274. },
  275. StructField::ByteVec(id) => quote! {
  276. #[serde(with = "serde_bytes")]
  277. pub #id: Vec<u8>,
  278. },
  279. });
  280. quote! { #(#decls)* }
  281. }
  282. }
  283. /// Produce the expansion of the `CMZProtocol` family of macros.
  284. ///
  285. /// The six macros in the `CMZProtocol` macro family all call this
  286. /// function, with different values for the bools.
  287. pub fn cmz_core(
  288. proto_spec: &ProtoSpec,
  289. use_muCMZ: bool,
  290. emit_client: bool,
  291. emit_issuer: bool,
  292. ) -> TokenStream {
  293. let proto_name = &proto_spec.proto_name;
  294. let has_params = !proto_spec.params.is_empty() || !proto_spec.point_params.is_empty();
  295. let tot_num_creds = proto_spec.show_creds.len() + proto_spec.issue_creds.len();
  296. // Use the group of the first named credential type
  297. let group_types = if !proto_spec.show_creds.is_empty() {
  298. let first_cred_type = &proto_spec.show_creds[0].cred_type;
  299. quote! {
  300. pub type Scalar = <#first_cred_type as CMZCredential>::Scalar;
  301. pub type Point = <#first_cred_type as CMZCredential>::Point;
  302. }
  303. } else if !proto_spec.issue_creds.is_empty() {
  304. let first_cred_type = &proto_spec.issue_creds[0].cred_type;
  305. quote! {
  306. pub type Scalar = <#first_cred_type as CMZCredential>::Scalar;
  307. pub type Point = <#first_cred_type as CMZCredential>::Point;
  308. }
  309. } else {
  310. quote! {}
  311. };
  312. // The structure of the client's ZKP
  313. let mut cli_proof_rand_scalars = Vec::<Ident>::default();
  314. let mut cli_proof_priv_scalars = Vec::<Ident>::default();
  315. let mut cli_proof_pub_scalars = Vec::<Ident>::default();
  316. let mut cli_proof_cind_points = Vec::<Ident>::default();
  317. let mut cli_proof_pub_points = Vec::<Ident>::default();
  318. let mut cli_proof_const_points = Vec::<Ident>::default();
  319. let mut cli_proof_statements = Vec::<TokenStream>::default();
  320. // A map from the credential name and attribute name (as Strings) to
  321. // the scoped attribute identifier. This map is used to translate
  322. // expressions like `L.id` in the user-provided statements into the
  323. // appropriate identifier.
  324. let mut cli_proof_idmap = HashMap::<(String, String), Ident>::default();
  325. // The structure of the issuer's ZKP
  326. let mut iss_proof_rand_scalars = Vec::<Ident>::default();
  327. let mut iss_proof_priv_scalars = Vec::<Ident>::default();
  328. let mut iss_proof_pub_scalars = Vec::<Ident>::default();
  329. // The issuer has no cind_points
  330. let mut iss_proof_pub_points = Vec::<Ident>::default();
  331. let mut iss_proof_const_points = Vec::<Ident>::default();
  332. let mut iss_proof_statements = Vec::<TokenStream>::default();
  333. /* Credential issuing
  334. For each attribute of each credential to be issued, handle it
  335. according to its IssueSpec:
  336. */
  337. // The fields that will end up in the ClientState
  338. let mut clientstate_fields = StructFieldList::default();
  339. // The fields that will end up in the Request
  340. let mut request_fields = StructFieldList::default();
  341. // The fields that will end up in the Reply
  342. let mut reply_fields = StructFieldList::default();
  343. // The code that will end up in prepare
  344. let mut prepare_code = quote! {};
  345. // The code that will end up in handle, before the call to
  346. // fill_creds
  347. let mut handle_code_pre_fill = quote! {};
  348. // The code that will end up in handle, after the call to
  349. // fill_creds but before the call to authorize
  350. let mut handle_code_post_fill = quote! {};
  351. // The code that will end up in handle, after the call to
  352. // authorize
  353. let mut handle_code_post_auth = quote! {};
  354. // The code that will end up in finalize
  355. let mut finalize_code = quote! {};
  356. // Are there any Hide or Joint attributes in _any_ credential to be
  357. // issued?
  358. let mut any_hide_joint = false;
  359. let A_ident = format_ident!("A_generator");
  360. let B_ident = format_ident!("B_generator");
  361. let d_ident = format_ident!("d_privkey");
  362. let D_ident = format_ident!("D_pubkey");
  363. let iss_proof_sessid_ident = format_ident!("iss_proof_sessid");
  364. prepare_code = quote! {
  365. #prepare_code
  366. let #A_ident = bp.A();
  367. };
  368. handle_code_pre_fill = quote! {
  369. #handle_code_pre_fill
  370. let #A_ident = bp.A();
  371. };
  372. finalize_code = quote! {
  373. #finalize_code
  374. let #A_ident = bp.A();
  375. };
  376. iss_proof_const_points.push(A_ident.clone());
  377. prepare_code = quote! {
  378. #prepare_code
  379. let #B_ident = bp.B();
  380. };
  381. handle_code_pre_fill = quote! {
  382. #handle_code_pre_fill
  383. let #B_ident = bp.B();
  384. };
  385. if !use_muCMZ || !proto_spec.issue_creds.is_empty() {
  386. finalize_code = quote! {
  387. #finalize_code
  388. let #B_ident = bp.B();
  389. };
  390. iss_proof_const_points.push(B_ident.clone());
  391. }
  392. // Stash the issue proof session id in prepare so that it can be
  393. // used in finalize
  394. clientstate_fields.push_bytevec(&iss_proof_sessid_ident);
  395. for iss_cred in proto_spec.issue_creds.iter() {
  396. // Are there any Hide or Joint attributes in this particular
  397. // credential to be issued?
  398. let mut cred_hide_joint = false;
  399. // The credential being issued
  400. let iss_cred_id = format_ident!("iss_cred_{}", iss_cred.id);
  401. // The public key for the credential
  402. let pubkey_cred = format_ident!("pubkey_iss_cred_{}", iss_cred.id);
  403. // The randomizing factor to generate P
  404. let b_cred = format_ident!("b_iss_cred_{}", iss_cred.id);
  405. // The (revealed part of) the MAC
  406. let P_cred = format_ident!("P_iss_cred_{}", iss_cred.id);
  407. let Q_cred = format_ident!("Q_iss_cred_{}", iss_cred.id);
  408. // Only for CMZ14, not µCMZ:
  409. // The encrypted form of the hidden part of the MAC
  410. let EQ_cred = format_ident!("EQ_iss_cred_{}", iss_cred.id);
  411. let EQ0_cred = format_ident!("EQ0_iss_cred_{}", iss_cred.id);
  412. let EQ1_cred = format_ident!("EQ1_iss_cred_{}", iss_cred.id);
  413. // The ZKP statements that prove the format of EQ_cred
  414. let mut eq0_statement = quote! {};
  415. let mut eq1_statement = quote! {};
  416. // Only for µCMZ, not CMZ14:
  417. // The Pedersen commitment to only the Hide and Joint attributes
  418. let C_cred = format_ident!("C_iss_cred_{}", iss_cred.id);
  419. // The completed Pedersen commitment to the attributes
  420. // (including all kinds of attributes)
  421. let K_cred = format_ident!("K_iss_cred_{}", iss_cred.id);
  422. // The ZKP statement that proves the format of C
  423. let mut C_statement = quote! {};
  424. let iss_cred_type = &iss_cred.cred_type;
  425. // String version of the credential name
  426. let cred_str = iss_cred.id.to_string();
  427. // Check that fill_creds filled in the private key for this
  428. // credential and that it's for the right protocol (CMZ14 or
  429. // µCMZ)
  430. handle_code_post_fill = quote! {
  431. #handle_code_post_fill
  432. if #iss_cred_id.get_privkey().x.len() != #iss_cred_type::num_attrs() {
  433. return Err(CMZError::PrivkeyMissing(#cred_str));
  434. }
  435. if #iss_cred_id.get_privkey().muCMZ != #use_muCMZ {
  436. return Err(CMZError::WrongProtocol(#cred_str));
  437. }
  438. };
  439. // Check that the credential passed to prepare has its public
  440. // key set and that it's for the right protocol (CMZ14 or µCMZ)
  441. prepare_code = quote! {
  442. #prepare_code
  443. if #iss_cred_id.get_pubkey().X.len() != #iss_cred_type::num_attrs() {
  444. return Err(CMZError::PubkeyMissing(#cred_str));
  445. }
  446. if #iss_cred_id.get_pubkey().Xr.is_some() != #use_muCMZ {
  447. return Err(CMZError::WrongProtocol(#cred_str));
  448. }
  449. };
  450. // Stash the public key in prepare and use it to fill in the
  451. // public key of the completed credential in finalize
  452. clientstate_fields.push_pubkey(&pubkey_cred);
  453. prepare_code = quote! {
  454. #prepare_code
  455. let #pubkey_cred = #iss_cred_id.get_pubkey().clone();
  456. };
  457. finalize_code = quote! {
  458. #finalize_code
  459. #iss_cred_id.set_pubkey(&self.#pubkey_cred);
  460. };
  461. for (attr, &spec) in iss_cred.attrs.iter() {
  462. // String version of the attribute name
  463. let attr_str = attr.to_string();
  464. // The scoped attribute name
  465. let scoped_attr = format_ident!("iss_{}attr_{}_{}", spec.abbr(), iss_cred.id, attr);
  466. // Remember the mapping from the credential and attribute
  467. // name to the scoped attribute
  468. cli_proof_idmap.insert(
  469. (iss_cred.id.to_string(), attr.to_string()),
  470. scoped_attr.clone(),
  471. );
  472. // The private and public key for this attribute
  473. let x_attr = format_ident!("x_{}", scoped_attr);
  474. let X_attr = format_ident!("X_{}", scoped_attr);
  475. if spec == IssueSpec::Hide || spec == IssueSpec::Joint {
  476. cred_hide_joint = true;
  477. }
  478. if !use_muCMZ {
  479. // For CMZ14, we prove that the encrypted MAC is
  480. // consistent with all components of the credential's
  481. // public key
  482. handle_code_post_auth = quote! {
  483. #handle_code_post_auth
  484. let #x_attr = #iss_cred_id.privkey_x(#attr_str);
  485. let #X_attr = #iss_cred_id.pubkey_X(#attr_str);
  486. };
  487. finalize_code = quote! {
  488. #finalize_code
  489. let #X_attr = #iss_cred_id.pubkey_X(#attr_str);
  490. };
  491. iss_proof_priv_scalars.push(x_attr.clone());
  492. iss_proof_pub_points.push(X_attr.clone());
  493. iss_proof_statements.push(quote! {
  494. #X_attr = #x_attr * #A_ident,
  495. });
  496. }
  497. if spec == IssueSpec::Hide {
  498. /* For each Hide attribute, the attribute (passed in the
  499. prepare) goes in the ClientState, and from there to
  500. to the generated credential in finalize.
  501. */
  502. clientstate_fields.push_scalar(&scoped_attr);
  503. prepare_code = quote! {
  504. #prepare_code
  505. let #scoped_attr =
  506. #iss_cred_id.#attr.ok_or(CMZError::HideAttrMissing(#cred_str,
  507. #attr_str))?;
  508. };
  509. finalize_code = quote! {
  510. #finalize_code
  511. #iss_cred_id.#attr = Some(self.#scoped_attr);
  512. }
  513. }
  514. if spec == IssueSpec::Joint {
  515. /* For each Joint attribute, the client's part of the
  516. attribute (randomly generated) goes in the
  517. ClientState, and the issuer's part of the attribute
  518. (randomly generated) goes in the Reply.
  519. */
  520. clientstate_fields.push_scalar(&scoped_attr);
  521. reply_fields.push_scalar(&scoped_attr);
  522. prepare_code = quote! {
  523. #prepare_code
  524. let #scoped_attr = <Scalar as ff::Field>::random(&mut *rng);
  525. };
  526. handle_code_pre_fill = quote! {
  527. #handle_code_pre_fill
  528. let #scoped_attr = <Scalar as ff::Field>::random(&mut *rng);
  529. };
  530. finalize_code = quote! {
  531. #finalize_code
  532. let #scoped_attr = reply.#scoped_attr;
  533. #iss_cred_id.#attr = Some(self.#scoped_attr + reply.#scoped_attr);
  534. };
  535. }
  536. if !use_muCMZ && (spec == IssueSpec::Hide || spec == IssueSpec::Joint) {
  537. /* For each Hide and Joint attribute (for CMZ14): Compute an
  538. exponential El Gamal encryption (of the attribute) E_attr =
  539. (r_attr*B, attr*B + r_attr*D) for random r_attr. Include E_attr
  540. in the Request, attr in the ClientState, and attr,
  541. r_attr, and E_attr in the CliProof. Add
  542. b*x_attr*E_attr to E_Q in handle, for the b chosen on
  543. a per-issued-credential basis below. Include x_attr,
  544. X_attr, and t_attr = b*x_attr in IssProof and T_attr
  545. = b*X_attr = t_attr*A in Reply and IssProof.
  546. */
  547. let enc_attr = format_ident!("E_{}", scoped_attr);
  548. let enc0_attr = format_ident!("E0_{}", scoped_attr);
  549. let enc1_attr = format_ident!("E1_{}", scoped_attr);
  550. let r_attr = format_ident!("r_{}", scoped_attr);
  551. let t_attr = format_ident!("t_{}", scoped_attr);
  552. let T_attr = format_ident!("T_{}", scoped_attr);
  553. request_fields.push_encpoint(&enc_attr);
  554. clientstate_fields.push_encpoint(&enc_attr);
  555. reply_fields.push_point(&T_attr);
  556. iss_proof_priv_scalars.push(t_attr.clone());
  557. iss_proof_pub_points.push(T_attr.clone());
  558. iss_proof_pub_points.push(enc0_attr.clone());
  559. iss_proof_pub_points.push(enc1_attr.clone());
  560. iss_proof_statements.push(quote! {
  561. #T_attr = #t_attr * #A_ident,
  562. #T_attr = #b_cred * #X_attr,
  563. });
  564. eq0_statement = quote! {
  565. #eq0_statement + #t_attr * #enc0_attr
  566. };
  567. eq1_statement = quote! {
  568. #eq1_statement + #t_attr * #enc1_attr
  569. };
  570. cli_proof_priv_scalars.push(scoped_attr.clone());
  571. cli_proof_rand_scalars.push(r_attr.clone());
  572. cli_proof_pub_points.push(enc0_attr.clone());
  573. cli_proof_pub_points.push(enc1_attr.clone());
  574. cli_proof_statements.push(quote! {
  575. #enc0_attr = #r_attr * #B_ident,
  576. #enc1_attr = #scoped_attr * #B_ident + #r_attr * #D_ident,
  577. });
  578. prepare_code = quote! {
  579. #prepare_code
  580. let #r_attr = <Scalar as ff::Field>::random(&mut *rng);
  581. let #enc0_attr = bp.mulB(&#r_attr);
  582. let #enc1_attr = bp.mulB(&#scoped_attr) +
  583. #r_attr * #D_ident;
  584. let #enc_attr = (#enc0_attr, #enc1_attr);
  585. };
  586. handle_code_post_fill = quote! {
  587. #handle_code_post_fill
  588. let #enc0_attr = request.#enc_attr.0;
  589. let #enc1_attr = request.#enc_attr.1;
  590. };
  591. handle_code_post_auth = quote! {
  592. #handle_code_post_auth
  593. let #t_attr = #b_cred * #x_attr;
  594. #EQ_cred.0 += #t_attr * #enc0_attr;
  595. #EQ_cred.1 += #t_attr * #enc1_attr;
  596. let #T_attr = bp.mulA(&#t_attr);
  597. };
  598. finalize_code = quote! {
  599. #finalize_code
  600. let #T_attr = reply.#T_attr;
  601. let #enc0_attr = self.#enc_attr.0;
  602. let #enc1_attr = self.#enc_attr.1;
  603. };
  604. }
  605. if use_muCMZ && (spec == IssueSpec::Hide || spec == IssueSpec::Joint) {
  606. /* For each Hide and Joint attribute (for µCMZ): add
  607. attr*X_attr to C.
  608. */
  609. prepare_code = quote! {
  610. #prepare_code
  611. let #X_attr = #pubkey_cred.X[#iss_cred_type::attr_num(#attr_str)];
  612. #C_cred += #scoped_attr * #X_attr;
  613. };
  614. handle_code_post_fill = quote! {
  615. #handle_code_post_fill
  616. let #X_attr = #iss_cred_id.pubkey_X(#attr_str);
  617. };
  618. C_statement = quote! {
  619. #C_statement + #scoped_attr * #X_attr
  620. };
  621. cli_proof_priv_scalars.push(scoped_attr.clone());
  622. cli_proof_cind_points.push(X_attr.clone());
  623. }
  624. /* For each Reveal attribute: include attr in Request (client will
  625. pass the value into prepare). Also store it in the
  626. ClientState.
  627. */
  628. if spec == IssueSpec::Reveal {
  629. request_fields.push_scalar(&scoped_attr);
  630. clientstate_fields.push_scalar(&scoped_attr);
  631. cli_proof_pub_scalars.push(scoped_attr.clone());
  632. prepare_code = quote! {
  633. #prepare_code
  634. let #scoped_attr =
  635. #iss_cred_id.#attr.ok_or(CMZError::RevealAttrMissing(#cred_str,
  636. #attr_str))?;
  637. };
  638. handle_code_pre_fill = quote! {
  639. #handle_code_pre_fill
  640. let #scoped_attr = request.#scoped_attr;
  641. #iss_cred_id.#attr = Some(#scoped_attr);
  642. };
  643. finalize_code = quote! {
  644. #finalize_code
  645. #iss_cred_id.#attr = Some(self.#scoped_attr);
  646. };
  647. }
  648. /* For each Implicit attribute: store it in ClientState
  649. (will be passed into prepare) on the client side, and
  650. will be filled in by fill_creds on the issuer side.
  651. */
  652. if spec == IssueSpec::Implicit {
  653. clientstate_fields.push_scalar(&scoped_attr);
  654. cli_proof_pub_scalars.push(scoped_attr.clone());
  655. prepare_code = quote! {
  656. #prepare_code
  657. let #scoped_attr =
  658. #iss_cred_id.#attr.ok_or(CMZError::ImplicitAttrCliMissing(#cred_str,
  659. #attr_str))?;
  660. };
  661. handle_code_post_fill = quote! {
  662. #handle_code_post_fill
  663. let #scoped_attr =
  664. #iss_cred_id.#attr.ok_or(CMZError::ImplicitAttrIssMissing(#cred_str,
  665. #attr_str))?;
  666. };
  667. finalize_code = quote! {
  668. #finalize_code
  669. #iss_cred_id.#attr = Some(self.#scoped_attr);
  670. };
  671. }
  672. /* For each Set attribute: the issuer's value will be set
  673. by fill_creds. Include the value in Reply.
  674. */
  675. if spec == IssueSpec::Set {
  676. reply_fields.push_scalar(&scoped_attr);
  677. handle_code_post_fill = quote! {
  678. #handle_code_post_fill
  679. let #scoped_attr =
  680. #iss_cred_id.#attr.ok_or(CMZError::SetAttrMissing(#cred_str,
  681. #attr_str))?;
  682. };
  683. finalize_code = quote! {
  684. #finalize_code
  685. #iss_cred_id.#attr = Some(reply.#scoped_attr);
  686. }
  687. }
  688. if spec == IssueSpec::Reveal
  689. || spec == IssueSpec::Implicit
  690. || spec == IssueSpec::Set
  691. || spec == IssueSpec::Joint
  692. {
  693. if use_muCMZ {
  694. /* For each Reveal, Implicit, Set, or Joint attribute, add
  695. attr*X_attr to K in handle and finalize.
  696. */
  697. handle_code_post_fill = quote! {
  698. #handle_code_post_fill
  699. #K_cred += (#scoped_attr *
  700. #iss_cred_id.pubkey_X(#attr_str));
  701. };
  702. // For a Joint attribute, we only want to use the
  703. // issuer's contribution (which is in #scoped_attr),
  704. // not #iss_cred_id.#attr, which is the sum of the
  705. // client's and issuer's contributions
  706. let use_attr = if spec == IssueSpec::Joint {
  707. quote! { #scoped_attr }
  708. } else {
  709. quote! { #iss_cred_id.#attr.unwrap() }
  710. };
  711. finalize_code = quote! {
  712. #finalize_code
  713. #K_cred += (#use_attr *
  714. #iss_cred_id.pubkey_X(#attr_str));
  715. };
  716. } else {
  717. /* For each Reveal, Implicit, Set, or Joint attribute, add
  718. attr*x_attr*P to Q in handle.
  719. */
  720. handle_code_post_auth = quote! {
  721. #handle_code_post_auth
  722. #Q_cred += (#scoped_attr * #x_attr) * #P_cred;
  723. };
  724. // For Joint attributes, we only want to use the
  725. // issuer's contribution. We already set
  726. // #scoped_attr to the issuer's contribution earlier
  727. // on.
  728. if spec != IssueSpec::Joint {
  729. finalize_code = quote! {
  730. #finalize_code
  731. let #scoped_attr = #iss_cred_id.#attr.unwrap();
  732. };
  733. }
  734. eq1_statement = quote! {
  735. #eq1_statement + #x_attr * ( #scoped_attr * #P_cred )
  736. };
  737. iss_proof_pub_scalars.push(scoped_attr.clone());
  738. }
  739. }
  740. }
  741. if !use_muCMZ {
  742. /* For all Hide and Joint attributes of a single credential to be
  743. issued (for CMZ14): the issuer chooses random b and s, computes
  744. P = b*B, E_Q = (s*B,s*D+b*x_0*B) + \sum_{hide,joint}
  745. b*x_attr*E_attr + (0,\sum_{implicit,reveal,set,joint}
  746. b*x_attr*attr*B) (note that E_Q and each E_attr are all
  747. pairs of Points; the scalar multiplication is
  748. componentwise). Include P, E_Q in Reply. The client will
  749. compute Q = E_Q[1] - d*E_Q[0].
  750. */
  751. let s_cred = format_ident!("s_iss_cred_{}", iss_cred.id);
  752. let x0_cred = format_ident!("x0_iss_cred_{}", iss_cred.id);
  753. let xr_cred = format_ident!("xr_cred{}", iss_cred.id);
  754. let X0_cred = format_ident!("X0_iss_cred_{}", iss_cred.id);
  755. reply_fields.push_point(&P_cred);
  756. if cred_hide_joint {
  757. reply_fields.push_encpoint(&EQ_cred);
  758. } else {
  759. reply_fields.push_point(&Q_cred);
  760. }
  761. let EQ_cred_code_pre = if cred_hide_joint {
  762. quote! {
  763. let #s_cred = <Scalar as ff::Field>::random(&mut *rng);
  764. let mut #EQ_cred = (bp.mulB(&#s_cred), #s_cred * #D_ident);
  765. }
  766. } else {
  767. quote! {}
  768. };
  769. let EQ_cred_code_post = if cred_hide_joint {
  770. quote! {
  771. #EQ_cred.1 += #Q_cred;
  772. let #EQ0_cred = #EQ_cred.0;
  773. let #EQ1_cred = #EQ_cred.1;
  774. }
  775. } else {
  776. quote! {}
  777. };
  778. if cred_hide_joint {
  779. iss_proof_pub_points.push(EQ0_cred.clone());
  780. iss_proof_pub_points.push(EQ1_cred.clone());
  781. iss_proof_statements.push(quote! {
  782. #EQ0_cred = #s_cred * #B_ident #eq0_statement,
  783. #EQ1_cred = #s_cred * #D_ident + #x0_cred * #P_cred #eq1_statement,
  784. });
  785. }
  786. handle_code_post_auth = quote! {
  787. let #b_cred = <Scalar as ff::Field>::random(&mut *rng);
  788. let #P_cred = bp.mulB(&#b_cred);
  789. #iss_cred_id.MAC.P = #P_cred;
  790. let #x0_cred = #iss_cred_id.get_privkey().x0;
  791. let #xr_cred = #iss_cred_id.get_privkey().xr;
  792. let #X0_cred = #iss_cred_id.get_pubkey().X0.unwrap();
  793. let mut #Q_cred = bp.mulB(&(#b_cred * #iss_cred_id.get_privkey().x0));
  794. #EQ_cred_code_pre
  795. #handle_code_post_auth
  796. #EQ_cred_code_post
  797. };
  798. let finalize_Q_code = if cred_hide_joint {
  799. quote! {
  800. let #EQ0_cred = reply.#EQ_cred.0;
  801. let #EQ1_cred = reply.#EQ_cred.1;
  802. #iss_cred_id.MAC.Q = #EQ1_cred - self.#d_ident * #EQ0_cred;
  803. }
  804. } else {
  805. quote! {
  806. #iss_cred_id.MAC.Q = reply.#Q_cred;
  807. }
  808. };
  809. finalize_code = quote! {
  810. #finalize_code
  811. let #P_cred = reply.#P_cred;
  812. let #X0_cred = #iss_cred_id.get_pubkey().X0.unwrap();
  813. #iss_cred_id.MAC.P = #P_cred;
  814. #finalize_Q_code
  815. };
  816. if cred_hide_joint {
  817. iss_proof_rand_scalars.push(s_cred.clone());
  818. }
  819. iss_proof_pub_points.push(P_cred.clone());
  820. iss_proof_priv_scalars.push(x0_cred.clone());
  821. iss_proof_rand_scalars.push(xr_cred.clone());
  822. iss_proof_pub_points.push(X0_cred.clone());
  823. iss_proof_rand_scalars.push(b_cred.clone());
  824. iss_proof_statements.push(quote! {
  825. #X0_cred = #x0_cred * #B_ident + #xr_cred * #A_ident,
  826. });
  827. }
  828. if use_muCMZ {
  829. /* For all Hide and Joint attributes of a single credential to be
  830. issued (for µCMZ): The client chooses a random s, computes C =
  831. (\sum_{hide,joint} attr*X_attr) + s*A, where X_attr is the
  832. public key for that attribute. Include s and C in the
  833. ClientState, C in the Request, and the attributes, s, and
  834. C in the CliProof. Hide attributes will be passed into
  835. prepare on the client side; Joint attributes (client
  836. contribution) will be generated randomly by prepare on
  837. the client side. On the issuer side, handle will pick a
  838. random b, compute P = b*A, K = C + X_r +
  839. \sum_{implicit,reveal,set,joint} attr*X_attr, R =
  840. b*(x_0*A + K). Include P and R in Reply, and x_0, b, P,
  841. R, K in IssProof. For each implicit,reveal,set,joint
  842. attribute, include x_attr and P_attr = attr*P in
  843. IssProof. The client will compute K as above, and Q = R
  844. - s*P.
  845. */
  846. let R_cred = format_ident!("R_iss_cred_{}", iss_cred.id);
  847. let s_cred = format_ident!("s_iss_cred_{}", iss_cred.id);
  848. let x0_cred = format_ident!("x0_iss_cred_{}", iss_cred.id);
  849. let X0_cred = format_ident!("X0_iss_cred_{}", iss_cred.id);
  850. reply_fields.push_point(&P_cred);
  851. reply_fields.push_point(&R_cred);
  852. if cred_hide_joint {
  853. clientstate_fields.push_scalar(&s_cred);
  854. clientstate_fields.push_point(&C_cred);
  855. request_fields.push_point(&C_cred);
  856. cli_proof_pub_points.push(C_cred.clone());
  857. cli_proof_rand_scalars.push(s_cred.clone());
  858. prepare_code = quote! {
  859. let #s_cred = <Scalar as ff::Field>::random(&mut *rng);
  860. let mut #C_cred = bp.mulA(&#s_cred);
  861. #prepare_code
  862. };
  863. handle_code_post_fill = quote! {
  864. let #C_cred = request.#C_cred;
  865. let mut #K_cred = #C_cred + #iss_cred_id.get_pubkey().Xr.unwrap();
  866. #handle_code_post_fill
  867. };
  868. finalize_code = quote! {
  869. let mut #K_cred = self.#C_cred + self.#pubkey_cred.Xr.unwrap();
  870. #finalize_code
  871. };
  872. // Construct the client proof for this credential
  873. cli_proof_statements.push(quote! {
  874. #C_cred = #s_cred * #A_ident #C_statement,
  875. });
  876. } else {
  877. handle_code_post_fill = quote! {
  878. let mut #K_cred = #iss_cred_id.get_pubkey().Xr.unwrap();
  879. #handle_code_post_fill
  880. };
  881. finalize_code = quote! {
  882. let mut #K_cred = self.#pubkey_cred.Xr.unwrap();
  883. #finalize_code
  884. };
  885. }
  886. handle_code_post_auth = quote! {
  887. #handle_code_post_auth
  888. let #b_cred = <Scalar as ff::Field>::random(&mut *rng);
  889. let #P_cred = bp.mulA(&#b_cred);
  890. #iss_cred_id.MAC.P = #P_cred;
  891. let #x0_cred = #iss_cred_id.get_privkey().x0;
  892. let #X0_cred = #iss_cred_id.get_pubkey().X0.unwrap();
  893. let #R_cred = #b_cred * (bp.mulA(&#x0_cred) + #K_cred);
  894. };
  895. let finalize_Q_code = if cred_hide_joint {
  896. quote! {
  897. #iss_cred_id.MAC.Q = reply.#R_cred - self.#s_cred * reply.#P_cred;
  898. }
  899. } else {
  900. quote! {
  901. #iss_cred_id.MAC.Q = reply.#R_cred;
  902. }
  903. };
  904. finalize_code = quote! {
  905. #finalize_code
  906. let #P_cred = reply.#P_cred;
  907. let #X0_cred = #iss_cred_id.get_pubkey().X0.unwrap();
  908. let #R_cred = reply.#R_cred;
  909. #iss_cred_id.MAC.P = #P_cred;
  910. #finalize_Q_code
  911. };
  912. // Construct the issuer proof for this credential
  913. iss_proof_priv_scalars.push(x0_cred.clone());
  914. iss_proof_rand_scalars.push(b_cred.clone());
  915. iss_proof_pub_points.push(P_cred.clone());
  916. iss_proof_pub_points.push(X0_cred.clone());
  917. iss_proof_pub_points.push(K_cred.clone());
  918. iss_proof_pub_points.push(R_cred.clone());
  919. iss_proof_statements.push(quote! {
  920. #P_cred = #b_cred * #A_ident,
  921. #X0_cred = #x0_cred * #B_ident,
  922. #R_cred = #x0_cred * #P_cred + #b_cred * #K_cred,
  923. });
  924. }
  925. any_hide_joint |= cred_hide_joint;
  926. }
  927. /* If there are _any_ Hide or Joint attributes in CMZ14 (as opposed
  928. to µCMZ), the client generates an El Gamal keypair (d, D=d*B).
  929. Include d in the ClientState and D in the Request.
  930. */
  931. if any_hide_joint && !use_muCMZ {
  932. clientstate_fields.push_scalar(&d_ident);
  933. clientstate_fields.push_point(&D_ident);
  934. cli_proof_rand_scalars.push(d_ident.clone());
  935. cli_proof_pub_points.push(D_ident.clone());
  936. request_fields.push_point(&D_ident);
  937. cli_proof_statements.push(quote! {
  938. #D_ident = #d_ident * #B_ident,
  939. });
  940. prepare_code = quote! {
  941. let (#d_ident,#D_ident) = bp.keypairB(&mut *rng);
  942. #prepare_code
  943. };
  944. handle_code_post_fill = quote! {
  945. let #D_ident = request.#D_ident;
  946. #handle_code_post_fill
  947. };
  948. finalize_code = quote! {
  949. #finalize_code
  950. let #D_ident = self.#D_ident;
  951. };
  952. iss_proof_pub_points.push(D_ident.clone());
  953. }
  954. if !proto_spec.issue_creds.is_empty() {
  955. // The issuer will create a zero-knowledge proof
  956. let iss_proof_ident = format_ident!("iss_proof");
  957. reply_fields.push_bytevec(&iss_proof_ident);
  958. let iss_instance_fields = iss_proof_pub_points
  959. .iter()
  960. .chain(iss_proof_const_points.iter())
  961. .chain(iss_proof_pub_scalars.iter());
  962. let iss_witness_fields = iss_proof_rand_scalars
  963. .iter()
  964. .chain(iss_proof_priv_scalars.iter());
  965. handle_code_post_auth = quote! {
  966. #handle_code_post_auth
  967. let iss_proof_instance = issuer_proof::Instance {
  968. #(#iss_instance_fields,)*
  969. };
  970. let iss_proof_witness = issuer_proof::Witness {
  971. #(#iss_witness_fields,)*
  972. };
  973. // If prove returns Err here, there's an actual bug.
  974. let #iss_proof_ident =
  975. issuer_proof::prove(&iss_proof_instance,
  976. &iss_proof_witness, &iss_proof_sessid, rng).unwrap();
  977. };
  978. let cli_iss_instance_fields = iss_proof_pub_points
  979. .iter()
  980. .chain(iss_proof_const_points.iter())
  981. .chain(iss_proof_pub_scalars.iter());
  982. finalize_code = quote! {
  983. #finalize_code
  984. let iss_proof_instance = issuer_proof::Instance {
  985. #(#cli_iss_instance_fields,)*
  986. };
  987. if issuer_proof::verify(&iss_proof_instance,
  988. &reply.#iss_proof_ident, &self.iss_proof_sessid).is_err() {
  989. return Err((CMZError::IssProofFailed, self));
  990. }
  991. };
  992. }
  993. // Validity proofs for shown credentials with valid_optional go here
  994. let mut validity_proofs: HashMap<String, TokenStream> = HashMap::new();
  995. for show_cred in proto_spec.show_creds.iter() {
  996. // The credential being shown
  997. let show_cred_id = format_ident!("show_cred_{}", show_cred.id);
  998. // The rerandomizing factor for the MAC
  999. let t_cred = format_ident!("t_show_cred_{}", show_cred.id);
  1000. // The rerandomized MAC
  1001. let P_cred = format_ident!("P_show_cred_{}", show_cred.id);
  1002. let Q_cred = format_ident!("Q_show_cred_{}", show_cred.id);
  1003. // The randomness for the Pedersen commitment to Q
  1004. let zQ_cred = format_ident!("zQ_show_cred_{}", show_cred.id);
  1005. // The Pedersen commitment to Q
  1006. let CQ_cred = format_ident!("CQ_show_cred_{}", show_cred.id);
  1007. // The verification point
  1008. let V_cred = format_ident!("V_show_cred_{}", show_cred.id);
  1009. // The coefficient (on P) of the MAC on the Reveal and Implicit
  1010. // attributes, computed by the issuer
  1011. let q_cred = format_ident!("q_show_cred_{}", show_cred.id);
  1012. let show_cred_type = &show_cred.cred_type;
  1013. // String version of the credential name
  1014. let cred_str = show_cred.id.to_string();
  1015. // Check that fill_creds filled in the private key for this
  1016. // credential and that it's for the right protocol (CMZ14 or
  1017. // µCMZ)
  1018. handle_code_post_fill = quote! {
  1019. #handle_code_post_fill
  1020. if #show_cred_id.get_privkey().x.len() != #show_cred_type::num_attrs() {
  1021. return Err(CMZError::PrivkeyMissing(#cred_str));
  1022. }
  1023. if #show_cred_id.get_privkey().muCMZ != #use_muCMZ {
  1024. return Err(CMZError::WrongProtocol(#cred_str));
  1025. }
  1026. };
  1027. // Check that the credential passed to prepare has its public
  1028. // key set and that it's for the right protocol (CMZ14 or µCMZ)
  1029. prepare_code = quote! {
  1030. #prepare_code
  1031. if #show_cred_id.get_pubkey().X.len() != #show_cred_type::num_attrs() {
  1032. return Err(CMZError::PubkeyMissing(#cred_str));
  1033. }
  1034. if #show_cred_id.get_pubkey().Xr.is_some() != #use_muCMZ {
  1035. return Err(CMZError::WrongProtocol(#cred_str));
  1036. }
  1037. };
  1038. // Rerandomize the MAC and construct a Pedersen commitment to Q
  1039. // Also start constructing the client's version of the
  1040. // verification point V (which will be updated with each Hide
  1041. // attribute below)
  1042. prepare_code = quote! {
  1043. #prepare_code
  1044. let #t_cred = <Scalar as ff::Field>::random(&mut *rng);
  1045. let #P_cred = #t_cred * #show_cred_id.MAC.P;
  1046. let #Q_cred = #t_cred * #show_cred_id.MAC.Q;
  1047. let #zQ_cred = <Scalar as ff::Field>::random(&mut *rng);
  1048. let #CQ_cred = #Q_cred - bp.mulB(&#zQ_cred);
  1049. let mut #V_cred = bp.mulB(&#zQ_cred);
  1050. };
  1051. handle_code_post_fill = quote! {
  1052. #handle_code_post_fill
  1053. let #P_cred = request.#P_cred;
  1054. if bool::from(#P_cred.is_identity()) {
  1055. return Err(CMZError::CliProofFailed);
  1056. }
  1057. };
  1058. request_fields.push_point(&P_cred);
  1059. request_fields.push_point(&CQ_cred);
  1060. cli_proof_rand_scalars.push(zQ_cred.clone());
  1061. // For incomplete credentials (where proving the validity is
  1062. // optional) it's possible that P can be arbitrarily chosen by
  1063. // the client, and so it is not cind.
  1064. if show_cred.valid_optional {
  1065. cli_proof_pub_points.push(P_cred.clone());
  1066. } else {
  1067. cli_proof_cind_points.push(P_cred.clone());
  1068. }
  1069. cli_proof_pub_points.push(V_cred.clone());
  1070. // The ZKP statement that proves the format of V
  1071. let mut V_statement = quote! {
  1072. #V_cred = #zQ_cred * #B_ident
  1073. };
  1074. // Start constructing the issuer's version of the verification
  1075. // point Vi (which will be updated with each Hide attribute below)
  1076. // and the MAC on the Reveal and Implicit attributes
  1077. // µCMZ has the extra xr to add in here
  1078. let q_init = if use_muCMZ {
  1079. quote! { #show_cred_id.get_privkey().x0 + #show_cred_id.get_privkey().xr }
  1080. } else {
  1081. quote! { #show_cred_id.get_privkey().x0 }
  1082. };
  1083. handle_code_post_fill = quote! {
  1084. #handle_code_post_fill
  1085. let mut #V_cred = -request.#CQ_cred;
  1086. let mut #q_cred = #q_init;
  1087. };
  1088. for (attr, &spec) in show_cred.attrs.iter() {
  1089. // String version of the attribute name
  1090. let attr_str = attr.to_string();
  1091. // The scoped attribute name
  1092. let scoped_attr = format_ident!("show_{}attr_{}_{}", spec.abbr(), show_cred.id, attr);
  1093. // The public key for this attribute
  1094. let X_attr = format_ident!("X_{}", scoped_attr);
  1095. // Remember the mapping from the credential and attribute
  1096. // name to the scoped attribute
  1097. cli_proof_idmap.insert(
  1098. (show_cred.id.to_string(), attr.to_string()),
  1099. scoped_attr.clone(),
  1100. );
  1101. if spec == ShowSpec::Hide {
  1102. prepare_code = quote! {
  1103. #prepare_code
  1104. let #scoped_attr =
  1105. #show_cred_id.#attr.ok_or(CMZError::HideAttrMissing(#cred_str,
  1106. #attr_str))?;
  1107. };
  1108. // Construct a Pedersen commitment to the Hide attribute
  1109. // and update the verification point
  1110. let z_attr = format_ident!("z_{}", scoped_attr);
  1111. let C_attr = format_ident!("C_{}", scoped_attr);
  1112. request_fields.push_point(&C_attr);
  1113. prepare_code = quote! {
  1114. #prepare_code
  1115. let #z_attr = <Scalar as ff::Field>::random(&mut *rng);
  1116. let #C_attr = #scoped_attr * #P_cred + bp.mulA(&#z_attr);
  1117. let #X_attr = #show_cred_id.pubkey_X(#attr_str);
  1118. #V_cred += #z_attr * #X_attr;
  1119. };
  1120. handle_code_post_fill = quote! {
  1121. #handle_code_post_fill
  1122. let #C_attr = request.#C_attr;
  1123. let #X_attr = #show_cred_id.pubkey_X(#attr_str);
  1124. #V_cred += #show_cred_id.privkey_x(#attr_str)
  1125. * #C_attr;
  1126. };
  1127. cli_proof_priv_scalars.push(scoped_attr.clone());
  1128. cli_proof_rand_scalars.push(z_attr.clone());
  1129. cli_proof_pub_points.push(C_attr.clone());
  1130. cli_proof_cind_points.push(X_attr.clone());
  1131. cli_proof_statements.push(quote! {
  1132. #C_attr = #scoped_attr * #P_cred + #z_attr * #A_ident,
  1133. });
  1134. V_statement = quote! {
  1135. #V_statement + #z_attr * #X_attr
  1136. };
  1137. }
  1138. if spec == ShowSpec::Reveal {
  1139. request_fields.push_scalar(&scoped_attr);
  1140. prepare_code = quote! {
  1141. #prepare_code
  1142. let #scoped_attr =
  1143. #show_cred_id.#attr.ok_or(CMZError::RevealAttrMissing(#cred_str,
  1144. #attr_str))?;
  1145. };
  1146. handle_code_pre_fill = quote! {
  1147. #handle_code_pre_fill
  1148. let #scoped_attr = request.#scoped_attr;
  1149. #show_cred_id.#attr = Some(#scoped_attr);
  1150. };
  1151. // Accumulate the coefficient (of P) on the component of
  1152. // Q due to this attribute
  1153. handle_code_post_fill = quote! {
  1154. #handle_code_post_fill
  1155. #q_cred += #scoped_attr *
  1156. #show_cred_id.privkey_x(#attr_str);
  1157. };
  1158. cli_proof_pub_scalars.push(scoped_attr.clone());
  1159. }
  1160. if spec == ShowSpec::Implicit {
  1161. prepare_code = quote! {
  1162. #prepare_code
  1163. let #scoped_attr =
  1164. #show_cred_id.#attr.ok_or(CMZError::ImplicitAttrCliMissing(#cred_str,
  1165. #attr_str))?;
  1166. };
  1167. handle_code_post_fill = quote! {
  1168. #handle_code_post_fill
  1169. let #scoped_attr =
  1170. #show_cred_id.#attr.ok_or(CMZError::ImplicitAttrIssMissing(#cred_str,
  1171. #attr_str))?;
  1172. };
  1173. // Accumulate the coefficient (of P) on the component of
  1174. // Q due to this attribute
  1175. handle_code_post_fill = quote! {
  1176. #handle_code_post_fill
  1177. #q_cred += #scoped_attr *
  1178. #show_cred_id.privkey_x(#attr_str);
  1179. };
  1180. cli_proof_pub_scalars.push(scoped_attr.clone());
  1181. }
  1182. }
  1183. // Compute the computation of the issuer's version of the
  1184. // Verification point Vi
  1185. handle_code_post_fill = quote! {
  1186. #handle_code_post_fill
  1187. #V_cred += #q_cred * #P_cred;
  1188. };
  1189. if show_cred.valid_optional {
  1190. validity_proofs.insert(
  1191. cred_str,
  1192. quote! {
  1193. #V_statement
  1194. },
  1195. );
  1196. } else {
  1197. cli_proof_statements.push(quote! {
  1198. #V_statement,
  1199. });
  1200. }
  1201. }
  1202. cli_proof_const_points.push(A_ident.clone());
  1203. cli_proof_const_points.push(B_ident.clone());
  1204. for paramid in proto_spec.params.iter() {
  1205. let scoped_param = format_ident!("param_{}", paramid);
  1206. prepare_code = quote! {
  1207. #prepare_code
  1208. let #scoped_param = params.#paramid;
  1209. };
  1210. handle_code_post_fill = quote! {
  1211. #handle_code_post_fill
  1212. let #scoped_param = params.#paramid;
  1213. };
  1214. cli_proof_pub_scalars.push(scoped_param.clone());
  1215. cli_proof_idmap.insert(("".to_string(), paramid.to_string()), scoped_param.clone());
  1216. }
  1217. for paramid in proto_spec.point_params.iter() {
  1218. let scoped_param = format_ident!("param_{}", paramid);
  1219. prepare_code = quote! {
  1220. #prepare_code
  1221. let #scoped_param = params.#paramid;
  1222. };
  1223. handle_code_post_fill = quote! {
  1224. #handle_code_post_fill
  1225. let #scoped_param = params.#paramid;
  1226. };
  1227. cli_proof_pub_points.push(scoped_param.clone());
  1228. cli_proof_idmap.insert(("".to_string(), paramid.to_string()), scoped_param.clone());
  1229. }
  1230. // The client will create a zero-knowledge proof
  1231. let cli_proof_ident = format_ident!("cli_proof");
  1232. request_fields.push_bytevec(&cli_proof_ident);
  1233. let cli_instance_fields = cli_proof_pub_points
  1234. .iter()
  1235. .chain(cli_proof_const_points.iter())
  1236. .chain(cli_proof_cind_points.iter())
  1237. .chain(cli_proof_pub_scalars.iter());
  1238. let cli_witness_fields = cli_proof_rand_scalars
  1239. .iter()
  1240. .chain(cli_proof_priv_scalars.iter());
  1241. prepare_code = quote! {
  1242. #prepare_code
  1243. let cli_proof_instance = client_proof::Instance {
  1244. #(#cli_instance_fields,)*
  1245. };
  1246. let cli_proof_witness = client_proof::Witness {
  1247. #(#cli_witness_fields,)*
  1248. };
  1249. // If prove returns Err here, there's an actual bug.
  1250. let #cli_proof_ident = client_proof::prove(&cli_proof_instance,
  1251. &cli_proof_witness, &cli_proof_sessid, rng).unwrap();
  1252. };
  1253. let iss_cli_instance_fields = cli_proof_pub_points
  1254. .iter()
  1255. .chain(cli_proof_const_points.iter())
  1256. .chain(cli_proof_cind_points.iter())
  1257. .chain(cli_proof_pub_scalars.iter());
  1258. handle_code_post_fill = quote! {
  1259. #handle_code_post_fill
  1260. let cli_proof_instance = client_proof::Instance {
  1261. #(#iss_cli_instance_fields,)*
  1262. };
  1263. if client_proof::verify(&cli_proof_instance,
  1264. &request.#cli_proof_ident, &cli_proof_sessid).is_err() {
  1265. return Err(CMZError::CliProofFailed);
  1266. }
  1267. };
  1268. // Build the Params struct, if we have params
  1269. let params_struct = if has_params {
  1270. let param_list = &proto_spec.params;
  1271. let point_param_list = &proto_spec.point_params;
  1272. quote! {
  1273. pub struct Params {
  1274. #( pub #param_list: Scalar, )*
  1275. #( pub #point_param_list: Point, )*
  1276. }
  1277. }
  1278. } else {
  1279. quote! {}
  1280. };
  1281. // Build the ClientState struct
  1282. let client_state = {
  1283. let decls = clientstate_fields.field_decls();
  1284. quote! {
  1285. #[serde_as]
  1286. #[derive(Clone,Debug,serde::Serialize,serde::Deserialize)]
  1287. pub struct ClientState {
  1288. #decls
  1289. }
  1290. impl TryFrom<&[u8]> for ClientState {
  1291. type Error = postcard::Error;
  1292. fn try_from(bytes: &[u8]) -> postcard::Result<ClientState> {
  1293. postcard::from_bytes::<ClientState>(bytes)
  1294. }
  1295. }
  1296. impl From<&ClientState> for Vec<u8> {
  1297. fn from(req: &ClientState) -> Vec<u8> {
  1298. postcard::to_allocvec(req).unwrap()
  1299. }
  1300. }
  1301. impl ClientState {
  1302. pub fn as_bytes(&self) -> Vec<u8> {
  1303. self.into()
  1304. }
  1305. }
  1306. }
  1307. };
  1308. // Build the Request and Reply structs
  1309. let messages = {
  1310. let reqdecls = request_fields.field_decls();
  1311. let repdecls = reply_fields.field_decls();
  1312. quote! {
  1313. #[serde_as]
  1314. #[derive(Clone,Debug,serde::Serialize,serde::Deserialize)]
  1315. pub struct Request {
  1316. #reqdecls
  1317. }
  1318. impl TryFrom<&[u8]> for Request {
  1319. type Error = postcard::Error;
  1320. fn try_from(bytes: &[u8]) -> postcard::Result<Request> {
  1321. postcard::from_bytes::<Request>(bytes)
  1322. }
  1323. }
  1324. impl From<&Request> for Vec<u8> {
  1325. fn from(req: &Request) -> Vec<u8> {
  1326. postcard::to_allocvec(req).unwrap()
  1327. }
  1328. }
  1329. impl Request {
  1330. pub fn as_bytes(&self) -> Vec<u8> {
  1331. self.into()
  1332. }
  1333. }
  1334. #[serde_as]
  1335. #[derive(Clone,Debug,serde::Serialize,serde::Deserialize)]
  1336. pub struct Reply {
  1337. #repdecls
  1338. }
  1339. impl TryFrom<&[u8]> for Reply {
  1340. type Error = postcard::Error;
  1341. fn try_from(bytes: &[u8]) -> postcard::Result<Reply> {
  1342. postcard::from_bytes::<Reply>(bytes)
  1343. }
  1344. }
  1345. impl From<&Reply> for Vec<u8> {
  1346. fn from(rep: &Reply) -> Vec<u8> {
  1347. postcard::to_allocvec(rep).unwrap()
  1348. }
  1349. }
  1350. impl Reply {
  1351. pub fn as_bytes(&self) -> Vec<u8> {
  1352. self.into()
  1353. }
  1354. }
  1355. }
  1356. };
  1357. // Massage the statements provided in the protocol spec to change
  1358. // any expression of the form "L.id" (a credential name and an
  1359. // attribute name) into the corresponding scoped attribute.
  1360. // Bare identifiers that are protocol parameter names also get
  1361. // modified into the corresponding scoped attribute. These names
  1362. // are stored in the idmap with an empty string for the credential
  1363. // name.
  1364. //
  1365. // The expression "valid(A)" for a shown credential A with
  1366. // valid_optional set expands to the proof of validity for that
  1367. // credential.
  1368. struct StatementScoper<'a> {
  1369. idmap: &'a HashMap<(String, String), Ident>,
  1370. validity_proofs: &'a HashMap<String, TokenStream>,
  1371. }
  1372. impl<'a> VisitMut for StatementScoper<'a> {
  1373. fn visit_expr_mut(&mut self, node: &mut Expr) {
  1374. if let Expr::Field(exfld) = node {
  1375. let base = *exfld.base.clone();
  1376. if let Expr::Path(basepath) = base {
  1377. if let Member::Named(attrid) = &exfld.member {
  1378. if let Some(credid) = basepath.path.get_ident() {
  1379. if let Some(scopedid) =
  1380. self.idmap.get(&(credid.to_string(), attrid.to_string()))
  1381. {
  1382. *node = parse_quote! { #scopedid };
  1383. return;
  1384. }
  1385. }
  1386. }
  1387. }
  1388. }
  1389. if let Expr::Path(expath) = node {
  1390. if let Some(id) = expath.path.get_ident() {
  1391. if let Some(scopedparam) = self.idmap.get(&("".to_string(), id.to_string())) {
  1392. *node = parse_quote! { #scopedparam };
  1393. return;
  1394. }
  1395. }
  1396. }
  1397. if let Expr::Call(excall) = node {
  1398. let base = *excall.func.clone();
  1399. if let Expr::Path(basepath) = base {
  1400. if let Some(id) = basepath.path.get_ident() {
  1401. if *id == "valid" && excall.args.len() == 1 {
  1402. let mut validity_statement = quote! {};
  1403. let argexpr = excall.args.first().unwrap();
  1404. if let Expr::Path(argpath) = argexpr {
  1405. if let Some(credid) = argpath.path.get_ident() {
  1406. let credstr = credid.to_string();
  1407. match self.validity_proofs.get(&credstr) {
  1408. Some(tokens) => {
  1409. validity_statement = tokens.clone();
  1410. },
  1411. None => panic!("{} is not a shown credential with optional validity proof", credstr),
  1412. }
  1413. }
  1414. }
  1415. *node = parse_quote! { #validity_statement };
  1416. return;
  1417. }
  1418. }
  1419. }
  1420. }
  1421. // Unless we bailed out above, continue with the default
  1422. // traversal
  1423. visit_mut::visit_expr_mut(self, node);
  1424. }
  1425. }
  1426. let mut statement_scoper = StatementScoper {
  1427. idmap: &cli_proof_idmap,
  1428. validity_proofs: &validity_proofs,
  1429. };
  1430. let mut cli_proof_scoped_statements = proto_spec.statements.clone();
  1431. cli_proof_scoped_statements
  1432. .iter_mut()
  1433. .for_each(|expr| statement_scoper.visit_expr_mut(expr));
  1434. // The client's zero-knowledge proof
  1435. let cli_sigma_compiler_macro = if emit_client && emit_issuer {
  1436. quote! { sigma_compiler }
  1437. } else if emit_client {
  1438. quote! { sigma_compiler_prover }
  1439. } else {
  1440. quote! { sigma_compiler_verifier }
  1441. };
  1442. let cli_proof = {
  1443. quote! {
  1444. #cli_sigma_compiler_macro! { client_proof<Point>,
  1445. (#(rand #cli_proof_rand_scalars,)*
  1446. #(#cli_proof_priv_scalars,)*
  1447. #(pub #cli_proof_pub_scalars,)*),
  1448. (#(cind #cli_proof_cind_points,)*
  1449. #(#cli_proof_pub_points,)*
  1450. #(cind const #cli_proof_const_points,)*),
  1451. #(#cli_proof_scoped_statements,)*
  1452. #(#cli_proof_statements)*
  1453. }
  1454. }
  1455. };
  1456. // The issuer's zero-knowledge proof
  1457. let iss_sigma_compiler_macro = if emit_client && emit_issuer {
  1458. quote! { sigma_compiler }
  1459. } else if emit_issuer {
  1460. quote! { sigma_compiler_prover }
  1461. } else {
  1462. quote! { sigma_compiler_verifier }
  1463. };
  1464. let iss_proof = {
  1465. quote! {
  1466. #iss_sigma_compiler_macro! { issuer_proof<Point>,
  1467. (#(rand #iss_proof_rand_scalars,)*
  1468. #(#iss_proof_priv_scalars,)*
  1469. #(pub #iss_proof_pub_scalars,)*),
  1470. // no cind_points
  1471. (#(#iss_proof_pub_points,)*
  1472. #(cind const #iss_proof_const_points,)*),
  1473. #(#iss_proof_statements)*
  1474. }
  1475. }
  1476. };
  1477. // The argument list for the client's prepare function. There is an
  1478. // immutable reference for each credential to be shown, and an owned
  1479. // value for each credential to be issued.
  1480. let client_show_args = proto_spec.show_creds.iter().map(|c| {
  1481. let id = format_ident!("show_cred_{}", c.id);
  1482. let cred_type = &c.cred_type;
  1483. quote! { #id: &#cred_type, }
  1484. });
  1485. let client_issue_args = proto_spec.issue_creds.iter().map(|c| {
  1486. let id = format_ident!("iss_cred_{}", c.id);
  1487. let cred_type = &c.cred_type;
  1488. quote! { #id: #cred_type, }
  1489. });
  1490. let client_params_arg = if has_params {
  1491. quote! { params: &Params, }
  1492. } else {
  1493. quote! {}
  1494. };
  1495. // Build the client's prepare function
  1496. let client_func = {
  1497. let reqf = request_fields.field_iter();
  1498. let csf = clientstate_fields.field_iter();
  1499. quote! {
  1500. pub fn prepare(rng: &mut (impl CryptoRng + Rng),
  1501. session_id: &[u8],
  1502. #(#client_show_args)* #(#client_issue_args)* #client_params_arg)
  1503. -> Result<(Request, ClientState),CMZError> {
  1504. let bp = cmz_basepoints::<Point>();
  1505. let mut cli_proof_sessid: Vec<u8> = Vec::new();
  1506. cli_proof_sessid.extend(b"cli_");
  1507. cli_proof_sessid.extend(session_id);
  1508. let mut iss_proof_sessid: Vec<u8> = Vec::new();
  1509. iss_proof_sessid.extend(b"iss_");
  1510. iss_proof_sessid.extend(session_id);
  1511. #prepare_code
  1512. Ok((Request{#(#reqf,)*}, ClientState{#(#csf,)*}))
  1513. }
  1514. }
  1515. };
  1516. // Build the issuer's handle function
  1517. let issuer_func = {
  1518. // The credential declarations for the issuer's handle function
  1519. let cred_decls = proto_spec
  1520. .show_creds
  1521. .iter()
  1522. .map(|c| {
  1523. let id = format_ident!("show_cred_{}", c.id);
  1524. let cred_type = &c.cred_type;
  1525. quote! { let mut #id = #cred_type::default(); }
  1526. })
  1527. .chain(proto_spec.issue_creds.iter().map(|c| {
  1528. let id = format_ident!("iss_cred_{}", c.id);
  1529. let cred_type = &c.cred_type;
  1530. quote! { let mut #id = #cred_type::default(); }
  1531. }));
  1532. // The type of the returned credentials from handle
  1533. let cred_rettypes = proto_spec
  1534. .show_creds
  1535. .iter()
  1536. .map(|c| {
  1537. let cred_type = &c.cred_type;
  1538. quote! { #cred_type }
  1539. })
  1540. .chain(proto_spec.issue_creds.iter().map(|c| {
  1541. let cred_type = &c.cred_type;
  1542. quote! { #cred_type }
  1543. }));
  1544. // The return type
  1545. let rettype = match tot_num_creds {
  1546. 0 => quote! { Result<Reply,CMZError> },
  1547. 1 => quote! { Result<(Reply, #(#cred_rettypes)*),CMZError> },
  1548. _ => quote! { Result<(Reply, (#(#cred_rettypes),*)),CMZError> },
  1549. };
  1550. // The return value
  1551. let cred_retvals = proto_spec
  1552. .show_creds
  1553. .iter()
  1554. .map(|c| {
  1555. let id = format_ident!("show_cred_{}", c.id);
  1556. quote! { #id }
  1557. })
  1558. .chain(proto_spec.issue_creds.iter().map(|c| {
  1559. let id = format_ident!("iss_cred_{}", c.id);
  1560. quote! { #id }
  1561. }));
  1562. // The argument list for the issuer's fill_creds callback
  1563. let fill_creds_args = proto_spec
  1564. .show_creds
  1565. .iter()
  1566. .map(|c| {
  1567. let cred_type = &c.cred_type;
  1568. quote! { &mut #cred_type, }
  1569. })
  1570. .chain(proto_spec.issue_creds.iter().map(|c| {
  1571. let cred_type = &c.cred_type;
  1572. quote! { &mut #cred_type, }
  1573. }));
  1574. // The parameters for the fill_creds callback
  1575. let fill_creds_params = proto_spec
  1576. .show_creds
  1577. .iter()
  1578. .map(|c| {
  1579. let id = format_ident!("show_cred_{}", c.id);
  1580. quote! { &mut #id, }
  1581. })
  1582. .chain(proto_spec.issue_creds.iter().map(|c| {
  1583. let id = format_ident!("iss_cred_{}", c.id);
  1584. quote! { &mut #id, }
  1585. }));
  1586. // The return value of the callback
  1587. let fill_creds_params_ret = if has_params {
  1588. quote! { Params }
  1589. } else {
  1590. quote! { () }
  1591. };
  1592. // The assignment of the return value of the callback
  1593. let fill_creds_assign = if has_params {
  1594. quote! { let params = }
  1595. } else {
  1596. quote! {}
  1597. };
  1598. // The argument list for the issuer's authorize callback
  1599. let authorize_args = proto_spec
  1600. .show_creds
  1601. .iter()
  1602. .map(|c| {
  1603. let cred_type = &c.cred_type;
  1604. quote! { &#cred_type, }
  1605. })
  1606. .chain(proto_spec.issue_creds.iter().map(|c| {
  1607. let cred_type = &c.cred_type;
  1608. quote! { &#cred_type, }
  1609. }));
  1610. // The parameters for the authorize callback
  1611. let authorize_params = proto_spec
  1612. .show_creds
  1613. .iter()
  1614. .map(|c| {
  1615. let id = format_ident!("show_cred_{}", c.id);
  1616. quote! { &#id, }
  1617. })
  1618. .chain(proto_spec.issue_creds.iter().map(|c| {
  1619. let id = format_ident!("iss_cred_{}", c.id);
  1620. quote! { &#id, }
  1621. }));
  1622. let repf = reply_fields.field_iter();
  1623. let retval = match tot_num_creds {
  1624. 0 => quote! { Ok(Reply{#(#repf,)*}) },
  1625. 1 => quote! { Ok((Reply{#(#repf,)*}, #(#cred_retvals)*)) },
  1626. _ => quote! { Ok((Reply{#(#repf,)*}, (#(#cred_retvals),*))) },
  1627. };
  1628. quote! {
  1629. pub fn handle<F,A>(rng: &mut (impl CryptoRng + Rng),
  1630. session_id: &[u8],
  1631. request: Request, fill_creds: F, authorize: A)
  1632. -> #rettype
  1633. where
  1634. F: FnOnce(#(#fill_creds_args)*) ->
  1635. Result<#fill_creds_params_ret, CMZError>,
  1636. A: FnOnce(#(#authorize_args)*) ->
  1637. Result<(),CMZError>
  1638. {
  1639. let bp = cmz_basepoints::<Point>();
  1640. let mut cli_proof_sessid: Vec<u8> = Vec::new();
  1641. cli_proof_sessid.extend(b"cli_");
  1642. cli_proof_sessid.extend(session_id);
  1643. let mut iss_proof_sessid: Vec<u8> = Vec::new();
  1644. iss_proof_sessid.extend(b"iss_");
  1645. iss_proof_sessid.extend(session_id);
  1646. #(#cred_decls)*
  1647. #handle_code_pre_fill
  1648. #fill_creds_assign fill_creds(#(#fill_creds_params)*)?;
  1649. #handle_code_post_fill
  1650. authorize(#(#authorize_params)*)?;
  1651. #handle_code_post_auth
  1652. #retval
  1653. }
  1654. }
  1655. };
  1656. // Build the ClientState's finalize function
  1657. let clientstate_finalize_func = {
  1658. // The credential declarations for the client's finalize function
  1659. let cred_decls = proto_spec.issue_creds.iter().map(|c| {
  1660. let id = format_ident!("iss_cred_{}", c.id);
  1661. let cred_type = &c.cred_type;
  1662. quote! { let mut #id = #cred_type::default(); }
  1663. });
  1664. // The type of the returned credentials from finalize
  1665. let cred_rettypes = proto_spec.issue_creds.iter().map(|c| {
  1666. let cred_type = &c.cred_type;
  1667. quote! { #cred_type }
  1668. });
  1669. let rettype = match proto_spec.issue_creds.len() {
  1670. 0 => quote! { Result<(),(CMZError,Self)> },
  1671. 1 => quote! { Result<#(#cred_rettypes)*,(CMZError,Self)> },
  1672. _ => quote! { Result<(#(#cred_rettypes),*),(CMZError,Self)> },
  1673. };
  1674. // Return value for ClientState's finalize function
  1675. let cred_retvals = proto_spec.issue_creds.iter().map(|c| {
  1676. let id = format_ident!("iss_cred_{}", c.id);
  1677. quote! { #id }
  1678. });
  1679. let retval = match proto_spec.issue_creds.len() {
  1680. 0 => quote! { Ok(()) },
  1681. 1 => quote! { Ok(#(#cred_retvals)*) },
  1682. _ => quote! { Ok((#(#cred_retvals),*)) },
  1683. };
  1684. quote! {
  1685. impl ClientState {
  1686. pub fn finalize(
  1687. self,
  1688. reply: Reply,
  1689. ) -> #rettype {
  1690. let bp = cmz_basepoints::<Point>();
  1691. #(#cred_decls)*
  1692. #finalize_code
  1693. #retval
  1694. }
  1695. }
  1696. }
  1697. };
  1698. let client_side = if emit_client {
  1699. quote! { #client_state #client_func #clientstate_finalize_func }
  1700. } else {
  1701. quote! {}
  1702. };
  1703. let issuer_side = if emit_issuer {
  1704. issuer_func
  1705. } else {
  1706. quote! {}
  1707. };
  1708. // Output the generated module for this protocol
  1709. quote! {
  1710. #[allow(non_snake_case)]
  1711. pub mod #proto_name {
  1712. use super::*;
  1713. use sigma_compiler::*;
  1714. use group::GroupEncoding;
  1715. #group_types
  1716. #params_struct
  1717. #messages
  1718. #cli_proof
  1719. #iss_proof
  1720. #client_side
  1721. #issuer_side
  1722. }
  1723. }
  1724. }