### unwrap_or_else Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Demonstrates the use of unwrap_or_else with both Ok and Err variants. ```rust assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Verifier Implementations Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/trait.Verifier.html Examples of Verifier trait implementations for different public key types and hash algorithms. ```APIDOC ### impl Verifier for EcVrfP256SswuPublicKey Available on **crate features`ec` and `p256`** only. #### type Proof = EcVrfProof ### impl Verifier for EcVrfP256TaiPublicKey Available on **crate features`ec` and `p256`** only. #### type Proof = EcVrfProof ### impl Verifier for EdVrfEdwards25519Ell2PublicKey Available on **crate features`ec` and `edwards25519`** only. #### type Proof = EdVrfProof ### impl Verifier for EdVrfEdwards25519TaiPublicKey Available on **crate features`ec` and `edwards25519`** only. #### type Proof = EdVrfProof ``` -------------------------------- ### To ASCII Uppercase Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Converts a byte to its ASCII uppercase equivalent. Non-ASCII characters remain unchanged. ```rust let lowercase_a = 97u8; assert_eq!(65, lowercase_a.to_ascii_uppercase()); ``` -------------------------------- ### To ASCII Lowercase Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Converts a byte to its ASCII lowercase equivalent. Non-ASCII characters remain unchanged. ```rust let uppercase_a = 65u8; assert_eq!(97, uppercase_a.to_ascii_lowercase()); ``` -------------------------------- ### Unsafe unwrap_err_unchecked Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Shows how to use unwrap_err_unchecked on an Err value. Calling this on an Ok is undefined behavior. ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Unsafe unwrap_unchecked Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Shows how to use unwrap_unchecked on an Ok value. Calling this on an Err is undefined behavior. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` -------------------------------- ### ASCII Case-Insensitive Comparison Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Compares two byte values for ASCII case-insensitivity. This is equivalent to converting both to lowercase before comparison. ```rust let lowercase_a = 97u8; let uppercase_a = 65u8; assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a)); ``` -------------------------------- ### Is ASCII Alphabetic Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Checks if a byte represents an ASCII alphabetic character (A-Z or a-z). ```rust let uppercase_a = b'A'; let uppercase_g = b'G'; let a = b'a'; let g = b'g'; let zero = b'0'; let percent = b'%'; let space = b' '; let lf = b'\n'; let esc = b'\x1b'; assert!(uppercase_a.is_ascii_alphabetic()); assert!(uppercase_g.is_ascii_alphabetic()); assert!(a.is_ascii_alphabetic()); assert!(g.is_ascii_alphabetic()); assert!(!zero.is_ascii_alphabetic()); assert!(!percent.is_ascii_alphabetic()); assert!(!space.is_ascii_alphabetic()); assert!(!lf.is_ascii_alphabetic()); assert!(!esc.is_ascii_alphabetic()); ``` -------------------------------- ### ASCII Check Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Checks if a byte value falls within the ASCII character range. ```rust let ascii = 97u8; let non_ascii = 150u8; assert!(ascii.is_ascii()); assert!(!non_ascii.is_ascii()); ``` -------------------------------- ### Unwrap Ok Value (Basic Usage) Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `unwrap()` to get the contained `Ok` value. This method will panic if the `Result` is an `Err`. It is generally discouraged in favor of safer error handling methods. ```Rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Collecting Results into a Vector (Success) Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Demonstrates using `collect` on an iterator of Results, where all elements are Ok. This example checks for integer overflow. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` -------------------------------- ### Ciphersuite From Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Provides a way to create a Ciphersuite instance from a u8 value. ```APIDOC ## fn from(value: u8) -> Self ### Description Converts to this type from the input type. ### Method from ### Parameters - `value`: The u8 value to convert from. ### Returns A new Ciphersuite instance created from the u8 value. ``` -------------------------------- ### Is ASCII Lowercase Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Checks if a byte represents an ASCII lowercase character (a-z). ```rust let uppercase_a = b'A'; let uppercase_g = b'G'; let a = b'a'; let g = b'g'; let zero = b'0'; let percent = b'%'; let space = b' '; let lf = b'\n'; let esc = b'\x1b'; assert!(!uppercase_a.is_ascii_lowercase()); assert!(!uppercase_g.is_ascii_lowercase()); assert!(a.is_ascii_lowercase()); assert!(g.is_ascii_lowercase()); assert!(!zero.is_ascii_lowercase()); assert!(!percent.is_ascii_lowercase()); assert!(!space.is_ascii_lowercase()); assert!(!lf.is_ascii_lowercase()); assert!(!esc.is_ascii_lowercase()); ``` -------------------------------- ### Is ASCII Uppercase Example Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Checks if a byte represents an ASCII uppercase character (A-Z). ```rust let uppercase_a = b'A'; let uppercase_g = b'G'; let a = b'a'; let g = b'g'; let zero = b'0'; let percent = b'%'; let space = b' '; let lf = b'\n'; let esc = b'\x1b'; assert!(uppercase_a.is_ascii_uppercase()); assert!(uppercase_g.is_ascii_uppercase()); assert!(!a.is_ascii_uppercase()); assert!(!g.is_ascii_uppercase()); assert!(!zero.is_ascii_uppercase()); assert!(!percent.is_ascii_uppercase()); assert!(!space.is_ascii_uppercase()); assert!(!lf.is_ascii_uppercase()); assert!(!esc.is_ascii_uppercase()); ``` -------------------------------- ### Ciphersuite Clone Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Provides methods for cloning and copying Ciphersuite instances. ```APIDOC ## fn clone(&self) -> Ciphersuite ### Description Returns a duplicate of the value. ### Method clone ### Parameters - `self`: A reference to the Ciphersuite instance. ### Returns A new Ciphersuite instance that is a duplicate of the original. ``` ```APIDOC ## fn clone_from(&mut self, source: &Self) ### Description Performs copy-assignment from `source`. ### Method clone_from ### Parameters - `self`: A mutable reference to the Ciphersuite instance to be updated. - `source`: A reference to the source Ciphersuite instance to copy from. ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/tai/struct.EdVrfEdwards25519TaiPublicKey.html Gets the `TypeId` of `self`. This is part of the Any trait for dynamic type checking. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Ciphersuite PartialEq Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Enables equality comparison for Ciphersuite instances. ```APIDOC ## fn eq(&self, other: &Ciphersuite) -> bool ### Description Tests for `self` and `other` values to be equal, and is used by `==`. ### Method eq ### Parameters - `self`: A reference to the first Ciphersuite instance. - `other`: A reference to the second Ciphersuite instance. ### Returns `true` if the instances are equal, `false` otherwise. ``` ```APIDOC ## fn ne(&self, other: &Rhs) -> bool ### Description Tests for `!=`. ### Method ne ### Parameters - `self`: A reference to the first Ciphersuite instance. - `other`: A reference to the second Ciphersuite instance. ### Returns `true` if the instances are not equal, `false` otherwise. ``` -------------------------------- ### into_ok Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Returns the contained `Ok` value, but never panics. This is an experimental API. ```APIDOC ## pub const fn into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of `unwrap` as a maintainability safeguard that will fail to compile if the error type of the `Result` is later changed to an error that can actually occur. ### Examples ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` -------------------------------- ### Ciphersuite Hash Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Enables hashing of Ciphersuite instances. ```APIDOC ## fn hash<__H: Hasher>(&self, state: &mut __H) ### Description Feeds this value into the given `Hasher`. ### Method hash ### Parameters - `self`: A reference to the Ciphersuite instance. - `state`: A mutable reference to the Hasher. ``` ```APIDOC ## fn hash_slice(data: &[Self], state: &mut H) ### Description Feeds a slice of this type into the given `Hasher`. ### Method hash_slice ### Parameters - `data`: A slice of Ciphersuite instances. - `state`: A mutable reference to the Hasher. ``` -------------------------------- ### Generate ECVRF Proof for P-256 Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/p256.rs.html Generates an ECVRF proof using the P-256 curve. This involves nonce generation, challenge calculation, and final proof construction. ```rust let mut k = self.generate_nonce(h.encode_to_curve_salt())?; let k_nz = k.to_nonzero_scalar(); let k_h = PublicKey::from_affine((h.point.to_projective() * k_nz.as_ref()).to_affine())?; let c = EcChallenge::generate(suite, &[&y.point, &h.point, &gamma, &k.public_key(), &k_h])?; let c_x = c.to_nonzero_scalar() * x; let Some(s_scalar) = p256::NonZeroScalar::new(k_nz.as_ref() + c_x.as_ref()).into_option() else { unreachable!() }; let s = SecretKey::from(s_scalar); Ok(EcVrfProof { gamma, c, s }) ``` -------------------------------- ### Ciphersuite PartialOrd Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Provides methods for partial ordering comparison of Ciphersuite instances. ```APIDOC ## fn partial_cmp(&self, other: &Ciphersuite) -> Option ### Description This method returns an ordering between `self` and `other` values if one exists. ### Method partial_cmp ### Parameters - `self`: A reference to the first Ciphersuite instance. - `other`: A reference to the second Ciphersuite instance. ### Returns An `Option` enum value indicating the relationship between the two instances, or `None` if they cannot be ordered. ``` ```APIDOC ## fn lt(&self, other: &Rhs) -> bool ### Description Tests less than (for `self` and `other`) and is used by the `<` operator. ### Method lt ### Parameters - `self`: A reference to the first Ciphersuite instance. - `other`: A reference to the second Ciphersuite instance. ### Returns `true` if `self` is less than `other`, `false` otherwise. ``` ```APIDOC ## fn le(&self, other: &Rhs) -> bool ### Description Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. ### Method le ### Parameters - `self`: A reference to the first Ciphersuite instance. - `other`: A reference to the second Ciphersuite instance. ### Returns `true` if `self` is less than or equal to `other`, `false` otherwise. ``` ```APIDOC ## fn gt(&self, other: &Rhs) -> bool ### Description Tests greater than (for `self` and `other`) and is used by the `>` operator. ### Method gt ### Parameters - `self`: A reference to the first Ciphersuite instance. - `other`: A reference to the second Ciphersuite instance. ### Returns `true` if `self` is greater than `other`, `false` otherwise. ``` ```APIDOC ## fn ge(&self, other: &Rhs) -> bool ### Description Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. ### Method ge ### Parameters - `self`: A reference to the first Ciphersuite instance. - `other`: A reference to the second Ciphersuite instance. ### Returns `true` if `self` is greater than or equal to `other`, `false` otherwise. ``` -------------------------------- ### EdVrfProof Equality Comparison Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/struct.EdVrfProof.html Implements PartialEq and Eq for EdVrfProof, enabling equality checks between instances. ```rust fn eq(&self, other: &EdVrfProof) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Handling File Metadata with and_then Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Demonstrates using `and_then` with `Path::metadata` and `modified` to chain fallible file system operations. This pattern is useful for operations that depend on previous successful results. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Get Encode-to-Curve Salt Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/edwards25519.rs.html Retrieves the salt used for the encode-to-curve operation, derived from the compressed public key. ```rust pub fn encode_to_curve_salt(&self) -> &[u8] { self.compressed.as_bytes().as_slice() } } ``` -------------------------------- ### EdVrfProof Proof Encoding and Decoding Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/struct.EdVrfProof.html Provides methods for encoding an EdVrfProof to its byte representation (`pi_string`) and decoding from `pi_string` back into an EdVrfProof. These are part of the Proof trait implementation. ```rust fn decode_pi(pi: &[u8]) -> VrfResult ``` ```rust fn encode_to_pi(&self) -> Vec ⓘ ``` -------------------------------- ### Ciphersuite Ord Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Provides methods for ordering Ciphersuite instances. ```APIDOC ## fn cmp(&self, other: &Ciphersuite) -> Ordering ### Description This method returns an `Ordering` between `self` and `other`. ### Method cmp ### Parameters - `self`: A reference to the first Ciphersuite instance. - `other`: A reference to the second Ciphersuite instance. ### Returns An `Ordering` enum value indicating the relationship between the two instances. ``` ```APIDOC ## fn max(self, other: Self) -> Self ### Description Compares and returns the maximum of two values. ### Method max ### Parameters - `self`: The first Ciphersuite instance. - `other`: The second Ciphersuite instance. ### Returns The maximum of the two Ciphersuite instances. ``` ```APIDOC ## fn min(self, other: Self) -> Self ### Description Compares and returns the minimum of two values. ### Method min ### Parameters - `self`: The first Ciphersuite instance. - `other`: The second Ciphersuite instance. ### Returns The minimum of the two Ciphersuite instances. ``` ```APIDOC ## fn clamp(self, min: Self, max: Self) -> Self ### Description Restrict a value to a certain interval. ### Method clamp ### Parameters - `self`: The Ciphersuite instance to clamp. - `min`: The minimum allowed value. - `max`: The maximum allowed value. ### Returns The clamped Ciphersuite instance. ``` -------------------------------- ### Get Verifier (Public Key) from Secret Key Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/elligator2/struct.EdVrfEdwards25519Ell2SecretKey.html Retrieves the corresponding public key (Verifier) for this secret key. ```rust fn verifier(&self) -> Self::Verifier ``` -------------------------------- ### Create Public Key from Bytes Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/edwards25519.rs.html Constructs an EdVrfEdwards25519PublicKey from a byte slice. Ensures the point is valid and not of small order. ```rust pub fn from_bytes(bytes: &[u8]) -> VrfResult { let compressed = CompressedEdwardsY::from_slice(bytes)?; let point = compressed.decompress().ok_or(VrfError::InvalidEcPoint)?; if point.is_small_order() { return Err(VrfError::InvalidEcPoint); } Ok(Self { compressed, point }) } } ``` -------------------------------- ### Collecting Results into a Vector (Failure) Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Demonstrates using `collect` on an iterator of Results, where an Err is encountered. This example checks for integer underflow. ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` -------------------------------- ### ECVRF Proof Verification Steps Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/p256.rs.html Implements the verification logic for an ECVRF proof, calculating intermediate values U and V and comparing the generated challenge c' with the provided challenge c. Returns an error if verification fails. ```rust let u = s.public_key().to_projective() - (self.point.to_projective() * c_nz.as_ref()); let u = PublicKey::from_affine(u.to_affine())?; // 9. V = s*H - c*Gamma let v = h.point.to_projective() * s_nz.as_ref() - gamma.to_projective() * c_nz.as_ref(); let v = PublicKey::from_affine(v.to_affine())?; // 10. c' = ECVRF_challenge_generation(Y, H, Gamma, U, V) (see Section 5.4.3) let c_prime = EcChallenge::generate(suite, &[&self.point, &h.point, &gamma, &u, &v])?; // 11. If c and c' are equal, output ("VALID", ECVRF_proof_to_hash(pi_string)); else output "INVALID" if c_prime != c { return Err(VrfError::ProofVerificationFailure); } Ok(EcVrfProof { gamma, c, s }) ``` -------------------------------- ### Ciphersuite Debug Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Allows for debugging Ciphersuite instances. ```APIDOC ## fn fmt(&self, f: &mut Formatter<'_>) -> Result ### Description Formats the value using the given formatter. ### Method fmt ### Parameters - `self`: A reference to the Ciphersuite instance. - `f`: A mutable reference to the formatter. ``` -------------------------------- ### Providing a Default Value with unwrap_or Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `unwrap_or` to get the `Ok` value or a specified default if the `Result` is `Err`. The default value is eagerly evaluated. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Ciphersuite Method for EcVrfP256Sswu Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/p256/sswu/struct.EcVrfP256Sswu.html Returns the Ciphersuite used by the EcVrfP256Sswu implementation. ```rust fn ciphersuite(&self) -> Ciphersuite ``` -------------------------------- ### Unwrap Error Value (Basic Usage) Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `unwrap_err()` to get the contained `Err` value. This method will panic if the `Result` is an `Ok`. It is useful when you expect an error and want to handle it. ```Rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Eq and PartialEq for EcVrfP256SswuSecretKey Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/p256/sswu/struct.EcVrfP256SswuSecretKey.html Implementations for equality comparison, allowing secret keys to be compared for equality. ```APIDOC ### impl Eq for EcVrfP256SswuSecretKey ### impl PartialEq for EcVrfP256SswuSecretKey #### fn eq(&self, other: &EcVrfP256SswuSecretKey) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. #### fn ne(&self, other: &Rhs) -> bool Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. ``` -------------------------------- ### map_or Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Applies a function to the Ok value or returns a default value if Err. ```APIDOC ## pub fn map_or(self, default: U, f: F) -> U where F: FnOnce(T) -> U, Returns the provided default (if `Err`), or applies a function to the contained value (if `Ok`). ### Description This method provides a way to handle both `Ok` and `Err` variants of a `VrfResult`. If the result is `Ok`, it applies a function `f` to the contained value. If it's `Err`, it returns a provided `default` value. Note that arguments are eagerly evaluated. ### Parameters - `default`: The value to return if the `VrfResult` is `Err`. - `f`: A closure that takes the `Ok` value `T` and returns a `U`. ### Returns - `U`: The result of the function `f` if `Ok`, or the `default` value if `Err`. ### Examples ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` ``` -------------------------------- ### Unwrap or Default Value Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `unwrap_or_default()` to get the contained `Ok` value or a default value if the `Result` is an `Err`. This is useful for providing fallback values when an operation might fail. ```Rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Computing a Default Value with unwrap_or_else Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `unwrap_or_else` to get the `Ok` value or compute a default value using a closure if the `Result` is `Err`. This is useful when the default value is expensive to compute. ```rust fn count(x: &str) -> usize { x.len() } ``` -------------------------------- ### VRF Provided Methods Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/trait.VRF.html Details the default implementations for proof generation (`prove`) and verification (`verify`) within the VRF trait. ```rust fn prove(&self, prover: &Self::Prover, alpha: &[u8]) -> VrfResult> { ... } ``` ```rust fn verify( &self, verifier: &Self::Verifier, alpha: &[u8], pi: &[u8], ) -> VrfResult> { ... } ``` -------------------------------- ### Proof to Hash Operation for EcVrfProof Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/p256/struct.EcVrfProof.html Performs the proof-to-hash operation on an EcVrfProof using a specified ciphersuite, returning the resulting hash output. This method is part of the Proof trait implementation for EcVrfProof. ```rust fn proof_to_hash(&self, suite: Ciphersuite) -> VrfResult> ``` -------------------------------- ### Iterate Over Ok Value Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `iter` to get an iterator that yields a reference to the contained value if the Result is `Ok`, otherwise yields nothing. This is useful for treating a Result as an optional collection. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### ok Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Converts a VrfResult into an Option, discarding the error value. ```APIDOC ## pub fn ok(self) -> Option Converts from `Result` to `Option`. ### Description This method consumes the `VrfResult` and returns an `Option`. If the `VrfResult` is `Ok(value)`, it returns `Some(value)`. If it is `Err`, it returns `None`. ### Returns - `Option`: `Some(T)` if the result was `Ok`, `None` if it was `Err`. ### Examples ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ``` -------------------------------- ### Iterate Mutably Over Ok Value Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `iter_mut` to get a mutable iterator that yields a mutable reference to the contained value if the Result is `Ok`, otherwise yields nothing. This allows in-place modification of the `Ok` value. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Into Ok Value (Never Panics) Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `into_ok()` to safely extract the `Ok` value without panicking. This experimental API is guaranteed not to panic, serving as a compile-time safeguard against unexpected error types. ```Rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Expect Error Value with Custom Message Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `expect_err()` to get the contained `Err` value. This method panics if the `Result` is an `Ok`, including a custom message provided as an argument. It's useful for asserting that an operation should fail. ```Rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Generic Type Conversion Implementations Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/struct.EdVrfProof.html Demonstrates various blanket implementations for generic types, including Any, Borrow, BorrowMut, From, Into, TryFrom, and TryInto. These are standard Rust trait implementations that apply to many types, including EdVrfProof. ```rust fn type_id(&self) -> TypeId ``` ```rust fn borrow(&self) -> &T ``` ```rust fn borrow_mut(&mut self) -> &mut T ``` ```rust fn from(t: T) -> T ``` ```rust fn into(self) -> U ``` ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Proof to Hash Operation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/trait.Proof.html Performs the proof-to-hash operation on the VRF Proof, returning the resulting hash output. Requires a Ciphersuite to be specified. ```rust fn proof_to_hash(&self, suite: Ciphersuite) -> VrfResult>; ``` -------------------------------- ### Hash Proof to Digest Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/util.rs.html Computes a hash of the proof data, including the ciphersuite and gamma string, using a specified digest algorithm. This is a common step in VRF verification. ```rust pub(crate) fn proof_to_hash( suite: Ciphersuite, gamma_string: &[u8], ) -> digest::Output { H::new() .chain_update([*suite, ECVRF_PROOF_DST_FRONT]) .chain_update(gamma_string) .chain_update([ECVRF_PROOF_DST_BACK]) .finalize() } ``` -------------------------------- ### Encode Proof to Pi String Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/trait.Proof.html Encodes the current proof instance into a `pi_string` (byte vector). ```rust fn encode_to_pi(&self) -> Vec ⓘ; ``` -------------------------------- ### EdVrfEdwards25519Ell2PublicKey Verifier Methods Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/elligator2/struct.EdVrfEdwards25519Ell2PublicKey.html This section details the methods available for verifying VRF proofs using the EdVrfEdwards25519Ell2PublicKey as a Verifier. ```APIDOC ## Trait Implementations ### impl Verifier for EdVrfEdwards25519Ell2PublicKey #### type Proof = EdVrfProof The Proof that this Verifier can verify. #### fn from_slice(bytes: &[u8]) -> VrfResult Creates a new public key from a byte slice. #### fn verify(&self, alpha: &[u8], proof: Self::Proof) -> VrfResult> Verifies a (alpha, proof) combination. Outputs the VRF_proof_to_hash if successful. ``` -------------------------------- ### EdVrfProof Debug Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/struct.EdVrfProof.html Provides a Debug implementation for EdVrfProof, allowing it to be formatted for debugging purposes. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### VRF Required Methods Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/trait.VRF.html Specifies the essential methods that must be implemented for any VRF type, including retrieving the ciphersuite. ```rust fn ciphersuite(&self) -> Ciphersuite; ``` -------------------------------- ### Prove Method for EcVrfP256Sswu Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/p256/sswu/struct.EcVrfP256Sswu.html Generates a VRF proof for a given prover and input alpha. This method outputs the proof as a byte vector. ```rust fn prove(&self, prover: &Self::Prover, alpha: &[u8]) -> VrfResult> ``` -------------------------------- ### Convert &Result to Result<&T, &E> Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Use `as_ref()` to convert a reference to a `Result` (`&Result`) into a `Result` containing references (`Result<&T, &E>`). This allows inspecting the `Result`'s contents without taking ownership. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Generate Challenge Bytes Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/util.rs.html Generates a fixed-length challenge byte array from an iterator of points. It incorporates the ciphersuite and specific domain separators. Asserts that exactly 5 points are processed. ```rust pub(crate) fn challenge_bytes<'a, const CHALLENGE_LEN: usize, H: digest::Digest>( suite: Ciphersuite, points: impl Iterator, // Assuming points are byte slices ) -> zeroize::Zeroizing<[u8; CHALLENGE_LEN]> { let mut hasher = H::new(); hasher.update([*suite, ECVRF_CHAL_GEN_DST_FRONT]); let mut point_count = 0u8; for point in points { hasher.update(point); point_count += 1; } debug_assert_eq!(point_count, 5, "Point count MUST be 5"); hasher.update([ECVRF_CHAL_GEN_DST_BACK]); let c_string = hasher.finalize(); zeroize::Zeroizing::new(c_string[..CHALLENGE_LEN].try_into().unwrap()) } ``` -------------------------------- ### EdVrfProof Pinned Drop Implementation (Nightly/Experimental) Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/struct.EdVrfProof.html An experimental, nightly-only API for executing the destructor of EdVrfProof when the value is pinned. This differs from the standard `Drop::drop` by requiring a pinned `self`. ```rust fn pin_drop(self: Pin<&mut Self>) ``` -------------------------------- ### Clone Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Provides methods for cloning a Result, allowing for duplication of the Ok or Err values if they themselves are Clone. ```APIDOC ## impl Clone for Result ### fn clone(&self) -> Result Returns a duplicate of the value. ### fn clone_from(&mut self, source: &Result) Performs copy-assignment from `source`. ``` -------------------------------- ### Create Secret Key from Slice Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/p256.rs.html Creates a P-256 secret key from a byte slice. Pads the slice with zeros if it's shorter than the expected key length. ```rust pub(super) fn sk_from_slice(slice: &[u8]) -> VrfResult { assert!(slice.len() <= Q_LEN); let offset = Q_LEN.saturating_sub(slice.len()); let mut c_scalar_bytes: p256::FieldBytes = Default::default(); c_scalar_bytes[offset..].copy_from_slice(slice); Ok(SecretKey::from_bytes(&c_scalar_bytes)?) } ``` -------------------------------- ### P256 SSWU VRF Prover Implementation Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/p256.rs.html Implements the Prover trait for the P256 SSWU ciphersuite. This enables VRF proof generation using a secret key. It includes methods for reconstructing the secret key from a byte slice and for generating proofs for given messages. ```rust impl crate::Prover for EcVrfP256SswuSecretKey { type Proof = EcVrfProof; type Verifier = EcVrfP256SswuPublicKey; fn from_slice(bytes: &[u8]) -> VrfResult where Self: Sized, { Ok(Self(EcVrfP256SecretKey::from_sk(bytes.try_into()?)?)) } #[cfg(feature = "hazmat")] fn x_equals(&self, value: &[u8]) -> bool { self.0.x_equals(value) } fn verifier(&self) -> Self::Verifier { EcVrfP256SswuPublicKey(self.0.public_key()) } fn prove(&self, alpha: &[u8]) -> VrfResult { self.0.prove(Ciphersuite::ECVRF_P256_SHA256_SSWU, alpha) } } ``` -------------------------------- ### Generate VRF Proof Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/p256.rs.html Generates a VRF proof for a given ciphersuite and alpha value using the P-256 curve. This involves deriving the secret scalar, computing the public key, and then calculating the gamma point. ```rust pub(super) fn prove(&self, suite: Ciphersuite, alpha: &[u8]) -> VrfResult { // 1. Use SK to derive the VRF secret scalar x and the VRF public key Y = x*B let y = self.public_key(); // 2. H = ECVRF_encode_to_curve(encode_to_curve_salt, alpha_string) (see Section 5.4.1) let h = y.encode_to_curve(suite, alpha)?; let x = self.0.to_nonzero_scalar(); // 3. Gamma = x*H let gamma = h.point.to_projective() * x.as_ref(); let gamma = PublicKey::from_affine(gamma.to_affine())?; ``` -------------------------------- ### Verify ECVRF Proof for P-256 Source: https://docs.rs/vrf-rfc9381/latest/src/vrf_rfc9381/ec/p256.rs.html Verifies an ECVRF proof against a P-256 public key and associated data. It decodes the proof and performs cryptographic checks. ```rust let EcVrfProof { gamma, c, s } = proof; let h = self.encode_to_curve(suite, alpha)?; let c_nz = c.to_nonzero_scalar(); let s_nz = s.to_nonzero_scalar(); // 8. U = s*B - c*Y ``` -------------------------------- ### Convert Result to Option with Ok value Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html The `ok()` method converts a `Result` into an `Option`. If the `Result` is `Ok(v)`, it returns `Some(v)`. If it's `Err(_)`, it returns `None`. This consumes the `Result`. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### TryInto Conversion Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/tai/struct.EdVrfEdwards25519TaiSecretKey.html Performs the conversion. This is a blanket implementation for the TryInto trait. ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### unwrap_or_else Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Returns the contained `Ok` value or computes it from a closure. ```APIDOC ## pub fn unwrap_or_else(self, op: F) -> T where F: FnOnce(E) -> T ### Description Returns the contained `Ok` value or computes it from a closure. ### Method `unwrap_or_else` ### Parameters #### Request Body - **op** (FnOnce(E) -> T) - A closure that takes the error value and returns a value of type `T`. ### Request Example ```rust fn count(x: &str) -> usize { x.len() } let x: Result<&str, &str> = Ok("hello"); assert_eq!(x.unwrap_or_else(count), 5); let x: Result<&str, &str> = Err("error"); assert_eq!(x.unwrap_or_else(count), 5); ``` ### Response #### Success Response (T) - **T**: The contained `Ok` value or the value computed by the closure. #### Response Example ```rust // Example for Ok("hello").unwrap_or_else(count) -> 5 // Example for Err("error").unwrap_or_else(count) -> 5 ``` ``` -------------------------------- ### Try for Result Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Experimental nightly-only API for the `?` operator, defining output, residual types, and methods for handling results. ```APIDOC ## type Output = T ### Description The type of the value produced by `?` when _not_ short-circuiting. ### Type `Output` ``` ```APIDOC ## type Residual = Result ### Description The type of the value passed to `FromResidual::from_residual` as part of `?` when short-circuiting. ### Type `Residual` ``` ```APIDOC ## fn from_output(output: as Try>::Output) -> Result ### Description Constructs the type from its `Output` type. ### Method `from_output` ``` ```APIDOC ## fn branch( self, ) -> ControlFlow< as Try>::Residual, as Try>::Output> ### Description Used in `?` to decide whether the operator should produce a value (because this returned `ControlFlow::Continue`) or propagate a value back to the caller (because this returned `ControlFlow::Break`). ### Method `branch` ``` -------------------------------- ### Ciphersuite Blanket Implementations Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/struct.Ciphersuite.html Details the blanket trait implementations applicable to Ciphersuite. ```APIDOC ## Blanket Implementations ### impl Any for T where T: 'static + ?Sized, #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more ### impl Borrow for T where T: ?Sized, #### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more ### impl BorrowMut for T where T: ?Sized, #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. Read more ### impl CloneToUninit for T where T: Clone, #### unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. ### impl From for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl Into for T where U: From, #### fn into(self) -> U Calls `U::from(self)`. ### impl Receiver for P where P: Deref + ?Sized, T: ?Sized, #### type Target = T The target type on which the method may be called. ### impl Same for T #### type Output = T Should always be `Self` ### impl ToOwned for T where T: Clone, #### type Owned = T The resulting type after obtaining ownership. #### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more #### fn clone_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. Read more ### impl ToString for T where T: Display + ?Sized, #### fn to_string(&self) -> String Converts the given value to a `String`. Read more ### impl TryFrom for T where U: Into, #### type Error = Infallible The type returned in the event of a conversion error. #### fn try_from(value: U) -> Result>::Error> Performs the conversion. ### impl TryInto for T where U: TryFrom, #### type Error = >::Error The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Prover::prove Method Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/trait.Prover.html Generates a VRF Proof for a given input `alpha`. ```rust fn prove(&self, alpha: &[u8]) -> VrfResult; ``` -------------------------------- ### TryFrom Conversion Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/tai/struct.EdVrfEdwards25519TaiSecretKey.html Performs the conversion. This is a blanket implementation for the TryFrom trait. ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### EcVrfP256TaiSecretKey - Trait Implementations Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/p256/tai/struct.EcVrfP256TaiSecretKey.html This section details the available trait implementations for EcVrfP256TaiSecretKey, including Prover, Eq, PartialEq, and Drop. ```APIDOC ## Trait Implementations ### impl Drop for EcVrfP256TaiSecretKey #### fn drop(&mut self) Executes the destructor for this type. Read more ### impl Eq for EcVrfP256TaiSecretKey ### impl PartialEq for EcVrfP256TaiSecretKey #### fn eq(&self, other: &EcVrfP256TaiSecretKey) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. #### fn ne(&self, other: &Rhs) -> bool Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. ### impl Prover for EcVrfP256TaiSecretKey #### type Proof = EcVrfProof The Proof emitted by this Prover #### type Verifier = EcVrfP256TaiPublicKey The public counterpart (Verifier) of this Prover #### fn from_slice(bytes: &[u8]) -> VrfResult Deserialize a Prover from its byte representation #### fn x_equals(&self, value: &[u8]) -> bool Available on **crate feature`hazmat`** only. Hazmat internal allowing to check if the scalar x equals a value. Do not use! #### fn verifier(&self) -> Self::Verifier Get the public counterpart of this Prover #### fn prove(&self, alpha: &[u8]) -> VrfResult Proves `alpha` as a VRF Proof ``` -------------------------------- ### Generic Trait Implementations Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/p256/sswu/struct.EcVrfP256SswuPublicKey.html Demonstrates various auto-derived and blanket trait implementations for EcVrfP256SswuPublicKey, including Send, Sync, Freeze, and others. ```rust fn type_id(&self) -> TypeId ``` ```rust fn borrow(&self) -> &T ``` ```rust fn borrow_mut(&mut self) -> &mut T ``` ```rust fn from(t: T) -> T ``` ```rust fn into(self) -> U ``` ```rust type Output = T ``` ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Hash Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/error/type.VrfResult.html Provides hashing capabilities for the Result type, allowing it to be used in hash-based collections if both Ok and Err types implement Hash. ```APIDOC ## impl Hash for Result ### fn hash<__H>(&self, state: &mut __H) Feeds this value into the given `Hasher`. ### fn hash_slice(data: &[Self], state: &mut H) Feeds a slice of this type into the given `Hasher`. ``` -------------------------------- ### EdVrfProof Proof to Hash Operation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/struct.EdVrfProof.html Implements the proof-to-hash operation for EdVrfProof using Sha512. This method is part of the Proof trait. ```rust fn proof_to_hash(&self, suite: Ciphersuite) -> VrfResult> ``` -------------------------------- ### From Trait Implementation Source: https://docs.rs/vrf-rfc9381/latest/vrf_rfc9381/ec/edwards25519/tai/struct.EdVrfEdwards25519TaiPublicKey.html Returns the argument unchanged. This is a simple identity conversion. ```rust fn from(t: T) -> T ```