5 İşlemeler 97930666d4 ... 62baf35633

Yazar SHA1 Mesaj Tarih
  Ian Goldberg 62baf35633 Update version to 0.4.0 1 hafta önce
  Michele Orrù 5e7b23a75b feat!: derive CMZ generator A automatically 3 ay önce
  Michele Orrù 78b1cbdb32 refactor: build the basepoints only on the call that loads them 3 ay önce
  Michele Orrù c953d8bdfe fix: key the basepoints map on the group type 3 ay önce
  Michele Orrù 955c44ccb1 Update sigma-compiler and released proof dependencies 2 ay önce

+ 29 - 0
CHANGELOG.md

@@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file.
 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
 and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
 and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
 
 
+## [0.4.0] - 2026-11-10
+
+### Added
+
+- Derive the CMZ generator `A` automatically via a RFC 9380
+  hash-to-group of the generator.  Applications no longer need to call
+  `cmz_group_init` at startup.
+- Add `CMZGroup` trait, `cmz_generator_a` function, and curve features
+  for the automatic derivation. Ristretto support is enabled by default;
+  P-256 and secp256k1 are available through the `p256` and `k256`
+  features.
+
+### Changes
+
+- Depend on `sigma-compiler` 0.3.0, `rand` 0.10, `group` 0.14, `ff` 0.14
+- CMZ credential `Point` types must now implement
+  `group::prime::PrimeGroup`, `group::GroupEncoding`, and
+  `hash2group::FromHash<hash2group::rfc9380::ExpandMsgXmd<sha2::Sha512>>`.
+  This combination of traits is now called `CMZGroup`.
+- The `rng` parameter in various APIs generated by `cmz` changed from
+  type `&mut (impl CryptoRng + RngCore)` to type `&mut (impl CryptoRng +
+  Rng)` (due to the update to `rand` 0.10)
+
+## Fixes
+
+- The ability to use `cmz` simultaneously for more than one group was
+  broken before, and is now fixed.
+
 ## [0.3.0] - 2026-08-04
 ## [0.3.0] - 2026-08-04
 
 
 ### Changes
 ### Changes
@@ -69,6 +97,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 
 - Initial release
 - Initial release
 
 
+[0.4.0]: https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz/src/0.4.0
 [0.3.0]: https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz/src/0.3.0
 [0.3.0]: https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz/src/0.3.0
 [0.2.1]: https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz/src/0.2.1
 [0.2.1]: https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz/src/0.2.1
 [0.2.0]: https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz/src/0.2.0
 [0.2.0]: https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz/src/0.2.0

Dosya farkı çok büyük olduğundan ihmal edildi
+ 270 - 320
Cargo.lock


+ 24 - 11
Cargo.toml

@@ -1,41 +1,54 @@
 [package]
 [package]
 name = "cmz"
 name = "cmz"
-version = "0.3.0"
+version = "0.4.0"
 edition = "2021"
 edition = "2021"
 license = "MIT"
 license = "MIT"
 repository = "https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz"
 repository = "https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz"
 description = "A crate to automatically create protocols that use CMZ14 or µCMZ credentials, by specifying an extremely compact description of the protocol."
 description = "A crate to automatically create protocols that use CMZ14 or µCMZ credentials, by specifying an extremely compact description of the protocol."
 
 
 [dependencies]
 [dependencies]
-cmz-derive = "=0.3.0"
-ff = "0.13"
+cmz-derive = "=0.4.0"
+ff = "0.14"
 generic_static = "0.2"
 generic_static = "0.2"
-group = "0.13"
+group = "0.14"
+hash2group = { version = "0.1.2", features = [ "rfc9380" ] }
 hex = { version = "0.4", features = [ "serde" ] }
 hex = { version = "0.4", features = [ "serde" ] }
 lazy_static = "1"
 lazy_static = "1"
 postcard = { version = "1", features = [ "alloc" ] }
 postcard = { version = "1", features = [ "alloc" ] }
-rand = "0.8.5"
+rand = "0.10"
 serde = { version = "1", features = [ "derive" ] }
 serde = { version = "1", features = [ "derive" ] }
 serde_bytes = "0.11"
 serde_bytes = "0.11"
 serde_with = "3"
 serde_with = "3"
-sigma-compiler = "0.2.3"
+sha2 = "0.11"
+sigma-compiler = "0.3.0"
 thiserror = "2"
 thiserror = "2"
 
 
 [dev-dependencies]
 [dev-dependencies]
 chrono = "0.4"
 chrono = "0.4"
-curve25519-dalek = { version = "4", features = [ "group", "rand_core", "digest" ] }
-sha2 = "0.10"
+curve25519-dalek = { version = "5", features = [ "group", "rand_core" ] }
+# Used for testing co-habitating with a second PrimeGroup.
+p256 = { version = "0.14", features = [ "arithmetic" ] }
+# Enable both test group implementations regardless of the cmz feature set.
+hash2group = { version = "0.1.2", features = [ "curve25519-dalek", "p256" ] }
 
 
 [patch.crates-io]
 [patch.crates-io]
 cmz-derive = { path = "cmz-derive" }
 cmz-derive = { path = "cmz-derive" }
 cmz-core = { path = "cmz-core" }
 cmz-core = { path = "cmz-core" }
-# sigma-compiler = { path = "../sigma-compiler" }
-# sigma-compiler-derive = { path = "../sigma-compiler/sigma-compiler-derive" }
-# sigma-compiler-core = { path = "../sigma-compiler/sigma-compiler-core" }
+sigma-compiler = { path = "../sigma-compiler" }
+sigma-compiler-derive = { path = "../sigma-compiler/sigma-compiler-derive" }
+sigma-compiler-core = { path = "../sigma-compiler/sigma-compiler-core" }
 # sigma-proofs = { path = "../sigma-proofs" }
 # sigma-proofs = { path = "../sigma-proofs" }
 # spongefish = { path = "../spongefish/spongefish" }
 # spongefish = { path = "../spongefish/spongefish" }
 
 
 [features]
 [features]
+# Hash-to-group implementations available to the automatic CMZ generator
+# derivation. Ristretto remains the default group used by the examples and
+# downstream applications; other groups are opt-in to avoid pulling every
+# curve implementation into every build.
+default = [ "curve25519-dalek" ]
+curve25519-dalek = [ "hash2group/curve25519-dalek" ]
+k256 = [ "hash2group/k256" ]
+p256 = [ "hash2group/p256" ]
 # Dump (to stdout or to a string) the value of the instance on both the
 # Dump (to stdout or to a string) the value of the instance on both the
 # prover's and verifier's side.  They should match.
 # prover's and verifier's side.  They should match.
 dump = [ "sigma-compiler/dump" ]
 dump = [ "sigma-compiler/dump" ]

+ 20 - 6
README.md

@@ -17,10 +17,24 @@ to create the credential.)
 Your application can have multiple different kinds of credentials, each
 Your application can have multiple different kinds of credentials, each
 with its own set of attributes.  All of the credentials in your
 with its own set of attributes.  All of the credentials in your
 application should use the _same_ `Scalar` and `Point` types.  You get
 application should use the _same_ `Scalar` and `Point` types.  You get
-these from a mathematical _group_, which must satisfy the trait
-[group::prime::PrimeGroup](https://docs.rs/group/0.13.0/group/prime/trait.PrimeGroup.html).
-A typical such group would be
-[curve25519\_dalek::ristretto::RistrettoPoint](https://docs.rs/curve25519-dalek/4.1.3/curve25519_dalek/ristretto/struct.RistrettoPoint.html).
+these from a mathematical _group_. The `Point` type must implement all of
+the following bounds:
+
+  - `group::prime::PrimeGroup`
+  - `group::GroupEncoding`
+  - `hash2group::FromHash<hash2group::rfc9380::ExpandMsgXmd<sha2::Sha512>>`
+
+`CMZGroup` is a blanket marker trait for exactly this combination of bounds.
+A typical point type satisfying them is
+[curve25519\_dalek::ristretto::RistrettoPoint](https://docs.rs/curve25519-dalek/5.0.0/curve25519_dalek/ristretto/struct.RistrettoPoint.html).
+The default `curve25519-dalek` feature supplies the hash-to-group
+implementation for `RistrettoPoint`; the optional `p256` and `k256` features
+supply it for `p256::ProjectivePoint` and `k256::ProjectivePoint`, respectively.
+
+CMZ requires a second generator `A`, which is derived automatically on first use
+by hashing the canonical encoding of `B` and caching it. Callers may override it
+by calling `cmz_group_init` or `cmz_group_init_with` before the first CMZ
+operation.
 
 
 To declare a credential type, use the `CMZ!` macro at the top level of
 To declare a credential type, use the `CMZ!` macro at the top level of
 your crate or module (outside of any function):
 your crate or module (outside of any function):
@@ -203,7 +217,7 @@ the following signature:
 
 
 ```text
 ```text
     pub fn prepare(
     pub fn prepare(
-        rng: &mut impl RngCore,
+        rng: &mut impl Rng,
         session_id: &[u8],
         session_id: &[u8],
         W: &Wallet,
         W: &Wallet,
         I: &Item,
         I: &Item,
@@ -229,7 +243,7 @@ the following signature:
 
 
 ```text
 ```text
     pub fn handle<F,A>(
     pub fn handle<F,A>(
-        rng: &mut impl RngCore,
+        rng: &mut impl Rng,
         session_id: &[u8],
         session_id: &[u8],
         request: Request,
         request: Request,
         fill_creds: F,
         fill_creds: F,

+ 1 - 1
cmz-core/Cargo.lock

@@ -94,7 +94,7 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
 
 
 [[package]]
 [[package]]
 name = "cmz-core"
 name = "cmz-core"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
 dependencies = [
  "clap",
  "clap",
  "darling",
  "darling",

+ 1 - 1
cmz-core/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 [package]
 name = "cmz-core"
 name = "cmz-core"
-version = "0.3.0"
+version = "0.4.0"
 edition = "2021"
 edition = "2021"
 license = "MIT"
 license = "MIT"
 repository = "https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz"
 repository = "https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz"

+ 2 - 2
cmz-core/src/lib.rs

@@ -1615,7 +1615,7 @@ pub fn cmz_core(
         let reqf = request_fields.field_iter();
         let reqf = request_fields.field_iter();
         let csf = clientstate_fields.field_iter();
         let csf = clientstate_fields.field_iter();
         quote! {
         quote! {
-            pub fn prepare(rng: &mut (impl CryptoRng + RngCore),
+            pub fn prepare(rng: &mut (impl CryptoRng + Rng),
                 session_id: &[u8],
                 session_id: &[u8],
                 #(#client_show_args)* #(#client_issue_args)* #client_params_arg)
                 #(#client_show_args)* #(#client_issue_args)* #client_params_arg)
                     -> Result<(Request, ClientState),CMZError> {
                     -> Result<(Request, ClientState),CMZError> {
@@ -1756,7 +1756,7 @@ pub fn cmz_core(
         };
         };
 
 
         quote! {
         quote! {
-            pub fn handle<F,A>(rng: &mut (impl CryptoRng + RngCore),
+            pub fn handle<F,A>(rng: &mut (impl CryptoRng + Rng),
                 session_id: &[u8],
                 session_id: &[u8],
                 request: Request, fill_creds: F, authorize: A)
                 request: Request, fill_creds: F, authorize: A)
                 -> #rettype
                 -> #rettype

+ 2 - 2
cmz-derive/Cargo.lock

@@ -94,7 +94,7 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
 
 
 [[package]]
 [[package]]
 name = "cmz-core"
 name = "cmz-core"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
 dependencies = [
  "clap",
  "clap",
  "darling",
  "darling",
@@ -106,7 +106,7 @@ dependencies = [
 
 
 [[package]]
 [[package]]
 name = "cmz-derive"
 name = "cmz-derive"
-version = "0.3.0"
+version = "0.4.0"
 dependencies = [
 dependencies = [
  "cmz-core",
  "cmz-core",
  "darling",
  "darling",

+ 2 - 2
cmz-derive/Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 [package]
 name = "cmz-derive"
 name = "cmz-derive"
-version = "0.3.0"
+version = "0.4.0"
 edition = "2021"
 edition = "2021"
 license = "MIT"
 license = "MIT"
 repository = "https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz"
 repository = "https://git-crysp.uwaterloo.ca/SigmaProtocol/cmz"
@@ -10,7 +10,7 @@ description = "Derive macros for the cmz crate"
 proc-macro = true
 proc-macro = true
 
 
 [dependencies]
 [dependencies]
-cmz-core = "=0.3.0"
+cmz-core = "=0.4.0"
 syn = { version = "2.0", features = ["extra-traits", "visit-mut"] }
 syn = { version = "2.0", features = ["extra-traits", "visit-mut"] }
 quote = "1.0"
 quote = "1.0"
 darling = "0.20"
 darling = "0.20"

+ 3 - 3
cmz-derive/src/lib.rs

@@ -131,7 +131,7 @@ fn impl_cmzcred_derive(ast: &syn::DeriveInput, group_ident: &Ident) -> TokenStre
                 self.pubkey.X[Self::attr_num(name)]
                 self.pubkey.X[Self::attr_num(name)]
             }
             }
 
 
-            fn gen_keys(rng: &mut impl RngCore, muCMZ: bool) ->
+            fn gen_keys(rng: &mut impl Rng, muCMZ: bool) ->
                     (CMZPrivkey<Self::Point>, CMZPubkey<Self::Point>) {
                     (CMZPrivkey<Self::Point>, CMZPubkey<Self::Point>) {
                 // Generate (num_attrs + 2) random scalars as the
                 // Generate (num_attrs + 2) random scalars as the
                 // private key
                 // private key
@@ -163,7 +163,7 @@ fn impl_cmzcred_derive(ast: &syn::DeriveInput, group_ident: &Ident) -> TokenStre
                 Ok(coeff)
                 Ok(coeff)
             }
             }
 
 
-            fn create_MAC(&mut self, rng: &mut impl RngCore, privkey: &CMZPrivkey<Self::Point>) -> Result<(),()> {
+            fn create_MAC(&mut self, rng: &mut impl Rng, privkey: &CMZPrivkey<Self::Point>) -> Result<(),()> {
                 let coeff = self.compute_MAC_coeff(privkey)?;
                 let coeff = self.compute_MAC_coeff(privkey)?;
                 self.MAC.P = <Self::Point as group::Group>::random(&mut *rng);
                 self.MAC.P = <Self::Point as group::Group>::random(&mut *rng);
                 self.MAC.Q = coeff * self.MAC.P;
                 self.MAC.Q = coeff * self.MAC.P;
@@ -180,7 +180,7 @@ fn impl_cmzcred_derive(ast: &syn::DeriveInput, group_ident: &Ident) -> TokenStre
                 }
                 }
             }
             }
 
 
-            fn fake_MAC(&mut self, rng: &mut impl RngCore) {
+            fn fake_MAC(&mut self, rng: &mut impl Rng) {
                 self.MAC.P = <Self::Point as group::Group>::random(&mut *rng);
                 self.MAC.P = <Self::Point as group::Group>::random(&mut *rng);
                 self.MAC.Q = <Self::Point as group::Group>::random(&mut *rng);
                 self.MAC.Q = <Self::Point as group::Group>::random(&mut *rng);
             }
             }

+ 92 - 43
src/lib.rs

@@ -11,11 +11,13 @@ use group::prime::PrimeGroup;
 use group::{Group, GroupEncoding};
 use group::{Group, GroupEncoding};
 #[cfg(feature = "wnaf_is_constant_time")]
 #[cfg(feature = "wnaf_is_constant_time")]
 use group::{WnafBase, WnafScalar};
 use group::{WnafBase, WnafScalar};
+use hash2group::{rfc9380::ExpandMsgXmd, FromHash};
 use lazy_static::lazy_static;
 use lazy_static::lazy_static;
-use rand::RngCore;
+use rand::Rng;
 use serde::{Deserialize, Deserializer, Serialize, Serializer};
 use serde::{Deserialize, Deserializer, Serialize, Serializer};
 pub use serde_with::serde_as;
 pub use serde_with::serde_as;
 use serde_with::{DeserializeAs, SerializeAs};
 use serde_with::{DeserializeAs, SerializeAs};
+use sha2::Sha512;
 use sigma_compiler::*;
 use sigma_compiler::*;
 pub use sigma_compiler::{self};
 pub use sigma_compiler::{self};
 use thiserror::Error;
 use thiserror::Error;
@@ -111,6 +113,36 @@ pub struct CMZPubkey<G: PrimeGroup> {
     pub X: Vec<G>,
     pub X: Vec<G>,
 }
 }
 
 
+/// Domain separator for deriving the CMZ generator `A`.
+///
+/// This value is a public protocol parameter, it is the computationally-independent
+/// auxiliary group generator.
+/// Changing it changes `A`, and thus it is a breaking change for existing CMZ keys
+/// and credentials.
+pub const CMZ_GENERATOR_A_DST: &[u8] = b"CMZ_GENERATOR_A_XMD:SHA-512_RO_V1_";
+
+/// A prime-order group supporting encoding and hash into the group.
+///
+/// The blanket implementation covers groups supported by [`hash2group`].
+pub trait CMZGroup: PrimeGroup + GroupEncoding + FromHash<ExpandMsgXmd<Sha512>> {}
+
+impl<G> CMZGroup for G where G: PrimeGroup + GroupEncoding + FromHash<ExpandMsgXmd<Sha512>> {}
+
+/// Deterministically derive the CMZ generator `A` from the standard generator
+/// `B` using hash-to-group.
+pub fn cmz_generator_a<G: CMZGroup>() -> G {
+    let generator_b = G::generator();
+    let encoded_b = generator_b.to_bytes();
+    let generator_a =
+        <G as FromHash<ExpandMsgXmd<Sha512>>>::from_hash(CMZ_GENERATOR_A_DST, encoded_b.as_ref());
+
+    assert!(
+        !bool::from(generator_a.is_identity()) && generator_a != generator_b,
+        "hash-to-group produced an invalid CMZ generator A"
+    );
+    generator_a
+}
+
 // The size of the WNAF windows.  Larger sizes take more memory, but
 // The size of the WNAF windows.  Larger sizes take more memory, but
 // result in faster multiplications.
 // result in faster multiplications.
 #[cfg(feature = "wnaf_is_constant_time")]
 #[cfg(feature = "wnaf_is_constant_time")]
@@ -168,12 +200,12 @@ impl<G: Group> CMZBasepoints<G> {
         self.B_ * s
         self.B_ * s
     }
     }
 
 
-    pub fn keypairA(&self, rng: &mut impl RngCore) -> (G::Scalar, G) {
+    pub fn keypairA(&self, rng: &mut impl Rng) -> (G::Scalar, G) {
         let x = G::Scalar::random(&mut *rng);
         let x = G::Scalar::random(&mut *rng);
         (x, self.mulA(&x))
         (x, self.mulA(&x))
     }
     }
 
 
-    pub fn keypairB(&self, rng: &mut impl RngCore) -> (G::Scalar, G) {
+    pub fn keypairB(&self, rng: &mut impl Rng) -> (G::Scalar, G) {
         let x = G::Scalar::random(&mut *rng);
         let x = G::Scalar::random(&mut *rng);
         (x, self.mulB(&x))
         (x, self.mulB(&x))
     }
     }
@@ -238,59 +270,75 @@ lazy_static! {
     static ref basepoints_map: StaticTypeMap<Box<dyn CMZbp>> = StaticTypeMap::new();
     static ref basepoints_map: StaticTypeMap<Box<dyn CMZbp>> = StaticTypeMap::new();
 }
 }
 
 
-/// For a given group type `G`, if `bp` is `Some(b)`, then load the
-/// mapping from `G` to `b` into the `basepoints_map`.  (If a mapping
-/// from `G` already exists, the old one will be kept and the new one
-/// ignored.)  Whether `bp` is `Some(b)` or `None`, this function
-/// returns the (possibly new) target of the `basepoints_map`, as a
-/// `&'static CMZBasepoints<G>`.
-fn load_bp<G: Group>(bp: Option<CMZBasepoints<G>>) -> &'static CMZBasepoints<G> {
-    match bp {
-        Some(b) => basepoints_map.call_once::<Box<dyn CMZbp>, _>(|| Box::new(b.clone())),
-        None => {
-            basepoints_map.call_once::<Box<dyn CMZbp>, _>(|| panic!("basepoints uninitialized"))
-        }
-    }
-    .as_any()
-    .downcast_ref::<CMZBasepoints<G>>()
-    .unwrap()
+/// For a given group type `G`, return the target of the `basepoints_map`
+/// as a `&'static CMZBasepoints<G>`, calling `init` to build it if no
+/// mapping exists yet.  (If a mapping from `G` already exists, the old
+/// one is kept and `init` is never called.)
+///
+/// `init` is a closure rather than a value so that the basepoints (and,
+/// under `wnaf_is_constant_time`, their WnafBase tables) are built only
+/// on the call that actually populates the map.  Callers invoke this on
+/// every request.
+fn load_bp_with<G: Group>(init: impl FnOnce() -> CMZBasepoints<G>) -> &'static CMZBasepoints<G> {
+    basepoints_map
+        .call_once::<G, _>(|| Box::new(init()))
+        .as_any()
+        .downcast_ref::<CMZBasepoints<G>>()
+        .unwrap()
+}
+
+/// Return the basepoints for `G`, deriving and memoizing `A` on first use.
+fn load_bp<G: CMZGroup>() -> &'static CMZBasepoints<G> {
+    load_bp_with::<G>(|| CMZBasepoints::init(cmz_generator_a::<G>()))
 }
 }
 
 
-/// Initialize the required second generator for a `PrimeGroup`.
+/// Override the automatically derived second generator for a `PrimeGroup`.
 ///
 ///
 /// CMZ credentials require two generators, `A` and `B`.  `B` is the
 /// CMZ credentials require two generators, `A` and `B`.  `B` is the
 /// "standard" generator.  A can be any other generator (that is, any
 /// "standard" generator.  A can be any other generator (that is, any
 /// other non-identity point in a prime-order group), but it is required
 /// other non-identity point in a prime-order group), but it is required
 /// that no one know the discrete log between `A` and `B`.  So you can't
 /// that no one know the discrete log between `A` and `B`.  So you can't
 /// generate `A` by multiplying `B` by some scalar, for example.  If your
 /// generate `A` by multiplying `B` by some scalar, for example.  If your
-/// group has a hash_from_bytes function, then you can use that to generate
-/// `A`. For example, if your group is a curve25519 group, you can
+/// group has a hash-to-group function, then you can use that to generate
+/// `A`. For the standard CMZ derivation, use [`cmz_generator_a`]:
 ///
 ///
 /// ```
 /// ```
-/// use curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT as B;
+/// use cmz::cmz_generator_a;
 /// use curve25519_dalek::ristretto::RistrettoPoint as G;
 /// use curve25519_dalek::ristretto::RistrettoPoint as G;
-/// use sha2::Sha512;
-/// let A = G::hash_from_bytes::<Sha512>(b"CMZ Generator A");
-/// assert_ne!(A, B);
+/// use group::Group;
+/// let A = cmz_generator_a::<G>();
+/// assert_ne!(A, G::generator());
 /// ```
 /// ```
 ///
 ///
 /// Otherwise, you're possibly on your own to generate an appropriate
 /// Otherwise, you're possibly on your own to generate an appropriate
-/// generator `A`.  Everyone who uses a given credential type with a
-/// given group will need to use the same `A`.  You need to call this
-/// before doing any operations with a credential.
+/// generator `A`. Everyone who uses a given credential type with a given
+/// group will need to use the same `A`.
+///
+/// CMZ automatically derives `A` using [`cmz_generator_a`], so normal callers
+/// do not need this function. This override exists for compatibility with
+/// deployments using older or application-specific public parameters. It must
+/// be called before the first CMZ operation for `G`; later calls retain the
+/// already-loaded value.
 pub fn cmz_group_init<G: PrimeGroup>(generator_A: G) {
 pub fn cmz_group_init<G: PrimeGroup>(generator_A: G) {
-    let bp = CMZBasepoints::<G>::init(generator_A);
-    load_bp(Some(bp));
+    load_bp_with(|| CMZBasepoints::<G>::init(generator_A));
+}
+
+/// [`cmz_group_init`], deferring construction of a custom `generator_A` with a `FnOnce`.
+///
+/// This function is only needed for compatibility with custom public parameters.
+/// The default generator is derived automatically by [`cmz_generator_a`].
+pub fn cmz_group_init_with<G: PrimeGroup>(generator_A: impl FnOnce() -> G) {
+    load_bp_with(|| CMZBasepoints::<G>::init(generator_A()));
 }
 }
 
 
 /// Get the loaded CMZBasepoints for the given group
 /// Get the loaded CMZBasepoints for the given group
-pub fn cmz_basepoints<G: PrimeGroup>() -> &'static CMZBasepoints<G> {
-    load_bp(None)
+pub fn cmz_basepoints<G: CMZGroup>() -> &'static CMZBasepoints<G> {
+    load_bp()
 }
 }
 
 
 /// Compute a public key from a private key
 /// Compute a public key from a private key
-pub fn cmz_privkey_to_pubkey<G: PrimeGroup>(privkey: &CMZPrivkey<G>) -> CMZPubkey<G> {
-    let bp = load_bp::<G>(None);
+pub fn cmz_privkey_to_pubkey<G: CMZGroup>(privkey: &CMZPrivkey<G>) -> CMZPubkey<G> {
+    let bp = load_bp::<G>();
     let X0: Option<G> = if privkey.muCMZ {
     let X0: Option<G> = if privkey.muCMZ {
         Some(bp.mulB(&privkey.x0))
         Some(bp.mulB(&privkey.x0))
     } else {
     } else {
@@ -314,7 +362,7 @@ where
     type Scalar: PrimeField;
     type Scalar: PrimeField;
 
 
     /// The type of the coordinates of the MAC for this credential
     /// The type of the coordinates of the MAC for this credential
-    type Point: PrimeGroup;
+    type Point: CMZGroup;
 
 
     /// Produce a vector of strings containing the names of the
     /// Produce a vector of strings containing the names of the
     /// attributes of this credential.  (The MAC is not included.)
     /// attributes of this credential.  (The MAC is not included.)
@@ -370,16 +418,16 @@ where
     /// type.  muCMZ should be true if this credential will be issued
     /// type.  muCMZ should be true if this credential will be issued
     /// with muCMZ protocols (and _not_ classic CMZ14 protocols).
     /// with muCMZ protocols (and _not_ classic CMZ14 protocols).
     fn gen_keys(
     fn gen_keys(
-        rng: &mut impl RngCore,
+        rng: &mut impl Rng,
         muCMZ: bool,
         muCMZ: bool,
     ) -> (CMZPrivkey<Self::Point>, CMZPubkey<Self::Point>);
     ) -> (CMZPrivkey<Self::Point>, CMZPubkey<Self::Point>);
 
 
     /// Convenience functions for the above
     /// Convenience functions for the above
-    fn cmz14_gen_keys(rng: &mut impl RngCore) -> (CMZPrivkey<Self::Point>, CMZPubkey<Self::Point>) {
+    fn cmz14_gen_keys(rng: &mut impl Rng) -> (CMZPrivkey<Self::Point>, CMZPubkey<Self::Point>) {
         Self::gen_keys(rng, false)
         Self::gen_keys(rng, false)
     }
     }
 
 
-    fn mucmz_gen_keys(rng: &mut impl RngCore) -> (CMZPrivkey<Self::Point>, CMZPubkey<Self::Point>) {
+    fn mucmz_gen_keys(rng: &mut impl Rng) -> (CMZPrivkey<Self::Point>, CMZPubkey<Self::Point>) {
         Self::gen_keys(rng, true)
         Self::gen_keys(rng, true)
     }
     }
 
 
@@ -402,7 +450,7 @@ where
     /// Create the MAC for this credential, given the private key.
     /// Create the MAC for this credential, given the private key.
     fn create_MAC(
     fn create_MAC(
         &mut self,
         &mut self,
-        rng: &mut impl RngCore,
+        rng: &mut impl Rng,
         privkey: &CMZPrivkey<Self::Point>,
         privkey: &CMZPrivkey<Self::Point>,
     ) -> Result<(), ()>;
     ) -> Result<(), ()>;
 
 
@@ -419,7 +467,7 @@ where
     /// Create a fake MAC for this credential.  This is useful, for
     /// Create a fake MAC for this credential.  This is useful, for
     /// example, when you're doing an OR proof, and in some arms of the
     /// example, when you're doing an OR proof, and in some arms of the
     /// disjunction, the credential does not have to be valid.
     /// disjunction, the credential does not have to be valid.
-    fn fake_MAC(&mut self, rng: &mut impl RngCore);
+    fn fake_MAC(&mut self, rng: &mut impl Rng);
 
 
     /// Serialize this credential, _including_ the private key.  The
     /// Serialize this credential, _including_ the private key.  The
     /// default serializer skips the private key for safety reasons.
     /// default serializer skips the private key for safety reasons.
@@ -443,7 +491,7 @@ where
 ///
 ///
 ///     use cmz::*;
 ///     use cmz::*;
 ///     use group::Group;
 ///     use group::Group;
-///     use rand::{CryptoRng, RngCore};
+///     use rand::{CryptoRng, Rng};
 ///     use curve25519_dalek::ristretto::RistrettoPoint as Grp;
 ///     use curve25519_dalek::ristretto::RistrettoPoint as Grp;
 ///     CMZ!{ Name<Grp>: attr1, attr2, attr3 }
 ///     CMZ!{ Name<Grp>: attr1, attr2, attr3 }
 ///
 ///
@@ -464,7 +512,8 @@ where
 ///     use curve25519_dalek::ristretto::RistrettoPoint;
 ///     use curve25519_dalek::ristretto::RistrettoPoint;
 ///     type G = RistrettoPoint;
 ///     type G = RistrettoPoint;
 ///
 ///
-/// The group must implement the trait [`PrimeGroup`](https://docs.rs/group/latest/group/prime/trait.PrimeGroup.html).
+/// The group must implement [`CMZGroup`]. Implementations are available for
+/// supported hash-to-group curves through the corresponding crate features.
 #[macro_export]
 #[macro_export]
 macro_rules! CMZ {
 macro_rules! CMZ {
     ( $name: ident < $G: ident > : $( $id: ident ),+ ) => {
     ( $name: ident < $G: ident > : $( $id: ident ),+ ) => {

+ 2 - 6
tests/basic.rs

@@ -2,8 +2,7 @@ use cmz::*;
 use curve25519_dalek::ristretto::RistrettoPoint;
 use curve25519_dalek::ristretto::RistrettoPoint;
 use curve25519_dalek::scalar::Scalar;
 use curve25519_dalek::scalar::Scalar;
 use group::Group;
 use group::Group;
-use rand::{CryptoRng, RngCore};
-use sha2::Sha512;
+use rand::{CryptoRng, Rng};
 
 
 CMZ! { Basic<RistrettoPoint> :
 CMZ! { Basic<RistrettoPoint> :
     attr1,
     attr1,
@@ -18,10 +17,7 @@ A: Basic {
 
 
 #[test]
 #[test]
 fn test_basic() {
 fn test_basic() {
-    let mut rng = rand::thread_rng();
-    cmz_group_init(RistrettoPoint::hash_from_bytes::<Sha512>(
-        b"CMZ Generator A",
-    ));
+    let mut rng = rand::rng();
 
 
     let (privkey, pubkey) = Basic::cmz14_gen_keys(&mut rng);
     let (privkey, pubkey) = Basic::cmz14_gen_keys(&mut rng);
 
 

+ 3 - 10
tests/priv_serialize.rs

@@ -2,8 +2,7 @@ use cmz::*;
 use curve25519_dalek::ristretto::RistrettoPoint;
 use curve25519_dalek::ristretto::RistrettoPoint;
 use curve25519_dalek::scalar::Scalar;
 use curve25519_dalek::scalar::Scalar;
 use group::Group;
 use group::Group;
-use rand::{CryptoRng, RngCore};
-use sha2::Sha512;
+use rand::{CryptoRng, Rng};
 
 
 CMZ! { Basic<RistrettoPoint> :
 CMZ! { Basic<RistrettoPoint> :
     attr1,
     attr1,
@@ -21,10 +20,7 @@ A: Basic {
 // Radically Open Security.
 // Radically Open Security.
 #[test]
 #[test]
 fn test_default_serialize() {
 fn test_default_serialize() {
-    let mut rng = rand::thread_rng();
-    cmz_group_init(RistrettoPoint::hash_from_bytes::<Sha512>(
-        b"CMZ Generator A",
-    ));
+    let mut rng = rand::rng();
 
 
     let (privkey, pubkey) = Basic::cmz14_gen_keys(&mut rng);
     let (privkey, pubkey) = Basic::cmz14_gen_keys(&mut rng);
 
 
@@ -49,10 +45,7 @@ fn test_default_serialize() {
 // include the private key material.
 // include the private key material.
 #[test]
 #[test]
 fn test_priv_serialize() {
 fn test_priv_serialize() {
-    let mut rng = rand::thread_rng();
-    cmz_group_init(RistrettoPoint::hash_from_bytes::<Sha512>(
-        b"CMZ Generator A",
-    ));
+    let mut rng = rand::rng();
 
 
     let (privkey, pubkey) = Basic::cmz14_gen_keys(&mut rng);
     let (privkey, pubkey) = Basic::cmz14_gen_keys(&mut rng);
 
 

+ 23 - 11
tests/rate_limiting.rs

@@ -4,12 +4,19 @@ use chrono::Utc;
 use cmz::*;
 use cmz::*;
 use curve25519_dalek::ristretto::RistrettoPoint;
 use curve25519_dalek::ristretto::RistrettoPoint;
 use group::{Group, GroupEncoding};
 use group::{Group, GroupEncoding};
-use rand::{CryptoRng, RngCore};
+use hash2group::{rfc9380::ExpandMsgXmd, FromHash};
+use rand::{CryptoRng, Rng};
 use sha2::Sha512;
 use sha2::Sha512;
 use std::collections::HashSet;
 use std::collections::HashSet;
 
 
 type G = RistrettoPoint;
 type G = RistrettoPoint;
 
 
+const EPOCH_BASE_DST: &[u8] = b"CMZ_RATE_LIMIT_EPOCH_XMD:SHA-512_RO_V1_";
+
+fn epoch_base(epoch: &[u8]) -> G {
+    <G as FromHash<ExpandMsgXmd<Sha512>>>::from_hash(EPOCH_BASE_DST, epoch)
+}
+
 CMZ! { Cred: key }
 CMZ! { Cred: key }
 CMZ! { PresNum: pres_num }
 CMZ! { PresNum: pres_num }
 
 
@@ -32,7 +39,7 @@ struct RateLimitClient {
 }
 }
 
 
 impl RateLimitClient {
 impl RateLimitClient {
-    pub fn new(rng: &mut (impl CryptoRng + RngCore), cred: &Cred) -> Self {
+    pub fn new(rng: &mut (impl CryptoRng + Rng), cred: &Cred) -> Self {
         let (_, presnum_pubkey) = PresNum::mucmz_gen_keys(rng);
         let (_, presnum_pubkey) = PresNum::mucmz_gen_keys(rng);
         Self {
         Self {
             presnum_pubkey,
             presnum_pubkey,
@@ -42,14 +49,14 @@ impl RateLimitClient {
 
 
     pub fn pres(
     pub fn pres(
         &mut self,
         &mut self,
-        rng: &mut (impl CryptoRng + RngCore),
+        rng: &mut (impl CryptoRng + Rng),
         epoch: &[u8],
         epoch: &[u8],
         pres_num: u32,
         pres_num: u32,
     ) -> Result<Vec<u8>, CMZError> {
     ) -> Result<Vec<u8>, CMZError> {
         let mut P = PresNum::using_pubkey(&self.presnum_pubkey);
         let mut P = PresNum::using_pubkey(&self.presnum_pubkey);
         P.pres_num = Some(pres_num.into());
         P.pres_num = Some(pres_num.into());
         P.fake_MAC(rng);
         P.fake_MAC(rng);
-        let Epoch_base = RistrettoPoint::hash_from_bytes::<Sha512>(epoch);
+        let Epoch_base = epoch_base(epoch);
         let VRF_output = (self.cred.key.unwrap() + P.pres_num.unwrap()).invert() * Epoch_base;
         let VRF_output = (self.cred.key.unwrap() + P.pres_num.unwrap()).invert() * Epoch_base;
         let params = pres_cred::Params {
         let params = pres_cred::Params {
             max_pres: 5u32.into(),
             max_pres: 5u32.into(),
@@ -72,7 +79,7 @@ struct RateLimitServer {
 }
 }
 
 
 impl RateLimitServer {
 impl RateLimitServer {
-    pub fn new(rng: &mut (impl CryptoRng + RngCore), privkey: &CMZPrivkey<G>) -> Self {
+    pub fn new(rng: &mut (impl CryptoRng + Rng), privkey: &CMZPrivkey<G>) -> Self {
         let (presnum_privkey, _) = PresNum::mucmz_gen_keys(rng);
         let (presnum_privkey, _) = PresNum::mucmz_gen_keys(rng);
         Self {
         Self {
             privkey: privkey.clone(),
             privkey: privkey.clone(),
@@ -83,11 +90,11 @@ impl RateLimitServer {
 
 
     pub fn check(
     pub fn check(
         &mut self,
         &mut self,
-        rng: &mut (impl CryptoRng + RngCore),
+        rng: &mut (impl CryptoRng + Rng),
         epoch: &[u8],
         epoch: &[u8],
         msg: &[u8],
         msg: &[u8],
     ) -> Result<(), CMZError> {
     ) -> Result<(), CMZError> {
-        let Epoch_base = RistrettoPoint::hash_from_bytes::<Sha512>(epoch);
+        let Epoch_base = epoch_base(epoch);
         // Separate the message into the VRF output and the request
         // Separate the message into the VRF output and the request
         let VRF_output = G::from_bytes(&msg[..32].try_into().unwrap()).unwrap();
         let VRF_output = G::from_bytes(&msg[..32].try_into().unwrap()).unwrap();
 
 
@@ -124,10 +131,7 @@ impl RateLimitServer {
 
 
 #[test]
 #[test]
 fn test_rate_limiting() -> Result<(), CMZError> {
 fn test_rate_limiting() -> Result<(), CMZError> {
-    let mut rng = rand::thread_rng();
-    cmz_group_init(RistrettoPoint::hash_from_bytes::<Sha512>(
-        b"CMZ Generator A",
-    ));
+    let mut rng = rand::rng();
 
 
     let (privkey, pubkey) = Cred::mucmz_gen_keys(&mut rng);
     let (privkey, pubkey) = Cred::mucmz_gen_keys(&mut rng);
 
 
@@ -191,3 +195,11 @@ fn test_rate_limiting() -> Result<(), CMZError> {
 
 
     Ok(())
     Ok(())
 }
 }
+
+#[test]
+fn epoch_base_derivation_is_stable() {
+    assert_eq!(
+        hex::encode(epoch_base(b"Epoch 2026-08-16").to_bytes()),
+        "cabdff610ae6898b12cc86be131d101913b807180f8ffe741319a065d3c2d576"
+    );
+}

+ 2 - 6
tests/submodule.rs

@@ -4,8 +4,7 @@ use cmz::*;
 use curve25519_dalek::ristretto::RistrettoPoint;
 use curve25519_dalek::ristretto::RistrettoPoint;
 use curve25519_dalek::scalar::Scalar;
 use curve25519_dalek::scalar::Scalar;
 use group::Group;
 use group::Group;
-use rand::{CryptoRng, RngCore};
-use sha2::Sha512;
+use rand::{CryptoRng, Rng};
 
 
 pub mod cred {
 pub mod cred {
     use super::*;
     use super::*;
@@ -29,10 +28,7 @@ pub mod submod {
 
 
     #[test]
     #[test]
     fn test_submodule() -> Result<(), CMZError> {
     fn test_submodule() -> Result<(), CMZError> {
-        let mut rng = rand::thread_rng();
-        cmz_group_init(RistrettoPoint::hash_from_bytes::<Sha512>(
-            b"CMZ Generator A",
-        ));
+        let mut rng = rand::rng();
 
 
         let (privkey, pubkey) = Basic::cmz14_gen_keys(&mut rng);
         let (privkey, pubkey) = Basic::cmz14_gen_keys(&mut rng);
 
 

+ 41 - 0
tests/two_groups.rs

@@ -0,0 +1,41 @@
+//! Basepoint derivation is keyed by group type, so two groups can coexist.
+
+use cmz::{cmz_basepoints, cmz_generator_a, cmz_group_init};
+use curve25519_dalek::ristretto::RistrettoPoint;
+use group::{Group, GroupEncoding};
+
+const RISTRETTO_A_ENCODING: &[u8] = &[
+    0x8e, 0x65, 0xa3, 0x1d, 0xc2, 0x60, 0x08, 0xdf, 0xbc, 0xd9, 0xf6, 0xef, 0xbd, 0x57, 0xf7, 0xcb,
+    0xb2, 0xb3, 0x98, 0x72, 0xf6, 0xfd, 0x32, 0x73, 0x6a, 0x00, 0x7a, 0x08, 0xc2, 0x1e, 0x47, 0x18,
+];
+const P256_A_ENCODING: &[u8] = &[
+    0x02, 0x73, 0xe5, 0x71, 0x95, 0x24, 0x34, 0xf0, 0xd5, 0xac, 0xaa, 0xe0, 0xfc, 0xe7, 0x35, 0x7c,
+    0x45, 0xb2, 0x73, 0xbd, 0x8e, 0x30, 0x4e, 0xe1, 0xac, 0xd9, 0xf2, 0x43, 0xf3, 0x0b, 0x96, 0x18,
+    0x9e,
+];
+
+#[test]
+fn two_groups_coexist() {
+    let ristretto_a = cmz_generator_a::<RistrettoPoint>();
+    let p256_a = cmz_generator_a::<p256::ProjectivePoint>();
+
+    assert_eq!(&ristretto_a.to_bytes()[..], RISTRETTO_A_ENCODING);
+    assert_eq!(&p256_a.to_bytes()[..], P256_A_ENCODING);
+
+    // Each group is initialized automatically and reads back its own
+    // basepoints, not the other's.
+    assert_eq!(cmz_basepoints::<RistrettoPoint>().A(), ristretto_a);
+    assert_eq!(
+        cmz_basepoints::<RistrettoPoint>().B(),
+        RistrettoPoint::generator()
+    );
+    assert_eq!(cmz_basepoints::<p256::ProjectivePoint>().A(), p256_a);
+    assert_eq!(
+        cmz_basepoints::<p256::ProjectivePoint>().B(),
+        p256::ProjectivePoint::generator()
+    );
+
+    // Re-initializing keeps the first value, per cmz_group_init's contract.
+    cmz_group_init::<RistrettoPoint>(RistrettoPoint::generator());
+    assert_eq!(cmz_basepoints::<RistrettoPoint>().A(), ristretto_a);
+}

+ 4 - 7
tests/wallet.rs

@@ -5,8 +5,7 @@
 use cmz::*;
 use cmz::*;
 use curve25519_dalek::ristretto::RistrettoPoint as G;
 use curve25519_dalek::ristretto::RistrettoPoint as G;
 use group::Group;
 use group::Group;
-use rand::{CryptoRng, RngCore};
-use sha2::Sha512;
+use rand::{CryptoRng, Rng};
 
 
 CMZ! { Wallet: randid, balance }
 CMZ! { Wallet: randid, balance }
 CMZ! { Item: serialno, price }
 CMZ! { Item: serialno, price }
@@ -48,7 +47,7 @@ macro_rules! protos_def {
             // The issuer runs this on its own to create an Item credential for a
             // The issuer runs this on its own to create an Item credential for a
             // particular item (specified by a serial number) with a given price.
             // particular item (specified by a serial number) with a given price.
             fn issue_item(
             fn issue_item(
-                rng: &mut (impl CryptoRng + RngCore),
+                rng: &mut (impl CryptoRng + Rng),
                 serialno: u128,
                 serialno: u128,
                 price: u128,
                 price: u128,
                 privkey: &CMZPrivkey<G>,
                 privkey: &CMZPrivkey<G>,
@@ -79,7 +78,7 @@ macro_rules! protos_def {
             // with funds, to sent to a client.  The issuer will presumably charge
             // with funds, to sent to a client.  The issuer will presumably charge
             // the client out of band for this loaded wallet.
             // the client out of band for this loaded wallet.
             fn issue_wallet(
             fn issue_wallet(
-                rng: &mut (impl CryptoRng + RngCore),
+                rng: &mut (impl CryptoRng + Rng),
                 balance: u128,
                 balance: u128,
                 privkey: &CMZPrivkey<G>,
                 privkey: &CMZPrivkey<G>,
                 public: &CMZPubkey<G>,
                 public: &CMZPubkey<G>,
@@ -107,9 +106,7 @@ macro_rules! protos_def {
                 }
                 }
             }
             }
 
 
-            // Initialization
-            let mut rng = rand::thread_rng();
-            cmz_group_init(G::hash_from_bytes::<Sha512>(b"CMZ Generator A"));
+            let mut rng = rand::rng();
 
 
             // Issuer: generate private and public keys for each type of
             // Issuer: generate private and public keys for each type of
             // credential.  (The client gets a copy of the public keys.)
             // credential.  (The client gets a copy of the public keys.)

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor