Skip to main content

walletkit_core/
lib.rs

1//! `walletkit-core` contains the basic primitives for using a World ID.
2//! It enables basic usage of a World ID to generate ZKPs using different credentials.
3//!
4//! # Example
5//!
6//! ```rust,ignore
7//! // Note: `Groth16Materials::from_embedded` requires the `embed-zkeys` Cargo feature.
8//! // On native targets you can alternatively use `Groth16Materials::from_cache` after
9//! // calling `storage::cache_embedded_groth16_material` to populate the on-disk cache.
10//! use std::sync::Arc;
11//! use walletkit_core::requests::ProofRequest;
12//! use walletkit_core::storage::CredentialStore;
13//! use walletkit_core::{Authenticator, Environment, Groth16Materials};
14//!
15//! async fn generate_world_id_proof(
16//!     store: Arc<CredentialStore>,
17//! ) -> Result<(), Box<dyn std::error::Error>> {
18//!     let materials = Arc::new(Groth16Materials::from_embedded()?);
19//!
20//!     // Initialize an authenticator for an already-registered World ID.
21//!     let seed = b"my_secret_seed_at_length_32_bytes!";
22//!     let authenticator = Authenticator::init_with_defaults(
23//!         seed,
24//!         None, // uses default RPC URL
25//!         &Environment::Staging,
26//!         None, // uses default region
27//!         materials,
28//!         store,
29//!     )
30//!     .await?;
31//!
32//!     // Parse an incoming proof request from a relying party.
33//!     let json = r#"{ "id": "req_01", "version": 1, "credentials": [] }"#;
34//!     let request = ProofRequest::from_json(json)?;
35//!
36//!     // Generate a zero-knowledge proof and serialise the response.
37//!     let response = authenticator.generate_proof(&request, None).await?;
38//!     println!("{}", response.to_json()?);
39//!     Ok(())
40//! }
41//! ```
42
43use strum::{Display, EnumString};
44
45/// Library initialization function called automatically on load.
46///
47/// Installs the ring crypto provider as the default for rustls.
48/// Uses the `ctor` crate to ensure this runs when the dynamic library loads,
49/// before any user code executes.
50///
51/// On WASM targets, rustls is not used (reqwest uses the browser fetch API).
52#[cfg(all(not(test), not(target_arch = "wasm32")))]
53#[ctor::ctor]
54fn init() {
55    rustls::crypto::ring::default_provider()
56        .install_default()
57        .expect("Failed to install default crypto provider");
58}
59
60/// Represents the environment in which a World ID is being presented and used.
61///
62/// Each environment uses different sources of truth for the World ID credentials.
63///
64/// More information on testing for the World ID Protocol can be found in: `https://docs.world.org/world-id/quick-start/testing`
65#[derive(Debug, Clone, PartialEq, Eq, EnumString, uniffi::Enum)]
66#[strum(serialize_all = "lowercase")]
67pub enum Environment {
68    /// For testing purposes ONLY.
69    Staging,
70    /// Live production environment. World ID Tree: `id.worldcoin.eth`
71    Production,
72}
73
74/// Methods exported to Swift/Kotlin via `UniFFI`.
75#[uniffi::export]
76impl Environment {
77    /// Returns the `PoH` Recovery Agent contract address for this environment.
78    #[must_use]
79    pub fn poh_recovery_agent_address(&self) -> String {
80        defaults::poh_recovery_agent_address(self).to_string()
81    }
82
83    /// Returns the `WorldIDVerifier` proxy contract address for this environment.
84    #[must_use]
85    pub fn world_id_verifier_address(&self) -> String {
86        defaults::world_id_verifier_address(self).to_string()
87    }
88}
89
90/// Region for node selection.
91#[derive(
92    Debug, Clone, Copy, PartialEq, Eq, Default, EnumString, Display, uniffi::Enum,
93)]
94#[strum(serialize_all = "lowercase")]
95pub enum Region {
96    /// United States
97    Us,
98    /// Europe (default)
99    #[default]
100    Eu,
101    /// Asia-Pacific
102    Ap,
103}
104
105/// Contains error outputs from `WalletKit`
106pub mod error;
107
108/// Contains logging functionality that can be integrated with foreign language bindings.
109pub mod logger;
110
111mod field_element;
112pub use field_element::FieldElement;
113
114mod credential;
115pub use credential::Credential;
116
117/// Credential storage primitives for World ID v4.
118pub mod storage;
119
120mod authenticator;
121pub use authenticator::{
122    Authenticator, Groth16Materials, InitializingAuthenticator, RecoveryData,
123    RecoveryUpdateSignature, RegistrationStatus,
124};
125
126/// Default configuration values for each [`Environment`].
127pub mod defaults;
128
129/// User agent for HTTP requests.
130pub mod user_agent;
131pub use user_agent::{UserAgent, UserAgentBuilder};
132
133/// Proof requests and responses in World ID v4.
134pub mod requests;
135
136/// Pre-flight check of whether stored credentials can satisfy a [`requests::ProofRequest`].
137pub mod proof_request_credential_constraints_check;
138
139mod proof;
140pub use proof::OwnershipProof;
141
142/// Credential issuers for World ID (NFC, etc.)
143#[cfg(feature = "issuers")]
144pub mod issuers;
145
146/// Legacy World ID 3.0 Proofs
147///
148/// # Example
149/// ```rust
150/// use walletkit_core::v3::{proof::ProofContext, CredentialType, world_id::WorldId};
151/// use walletkit_core::Environment;
152/// async fn example() {
153///     let world_id = WorldId::new(b"not_a_real_secret", &Environment::Staging);
154///     let context = ProofContext::new("app_ce4cb73cb75fc3b73b71ffb4de178410", Some("my_action".to_string()), None, CredentialType::Orb);
155///     let proof = world_id.generate_proof(&context).await.unwrap();
156///     println!("{}", proof.to_json().unwrap()); // the JSON output can be passed to the Developer Portal, World ID contracts, etc. for verification
157/// }
158#[cfg(feature = "v3")]
159pub mod v3;
160
161////////////////////////////////////////////////////////////////////////////////
162// Private modules
163////////////////////////////////////////////////////////////////////////////////
164
165#[cfg(any(feature = "issuers", feature = "v3"))]
166mod http_request;
167pub(crate) mod primitives;
168
169uniffi::setup_scaffolding!("walletkit_core");
170
171ruint_uniffi::register_types!(Uint256);