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: `EmbeddedZkArtifacts` requires the `embed-zkeys` Cargo feature.
8//! // On native targets, use `CachingZkArtifacts` to cache embedded material on disk.
9//! use std::sync::Arc;
10//! use walletkit_core::authenticator::artifacts::embedded::EmbeddedZkArtifacts;
11//! use walletkit_core::requests::ProofRequest;
12//! use walletkit_core::storage::CredentialStore;
13//! use walletkit_core::{Authenticator, Environment};
14//!
15//! async fn generate_world_id_proof(
16//! store: Arc<CredentialStore>,
17//! ) -> Result<(), Box<dyn std::error::Error>> {
18//! let artifacts = Arc::new(EmbeddedZkArtifacts::new());
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.to_vec(),
24//! None, // uses default RPC URL
25//! &Environment::Staging,
26//! None, // uses default region
27//! artifacts,
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/// Attested Flamingo matching in preparation for zero-knowledge proof generation.
106#[cfg(not(target_arch = "wasm32"))]
107pub mod flamingo;
108
109/// Contains error outputs from `WalletKit`
110pub mod error;
111
112/// Contains logging functionality that can be integrated with foreign language bindings.
113pub mod logger;
114
115mod field_element;
116pub use field_element::FieldElement;
117
118mod credential;
119pub use credential::Credential;
120
121/// Credential storage primitives for World ID v4.
122pub mod storage;
123
124pub mod authenticator;
125pub use authenticator::{
126 Authenticator, GatewayRequestStatus, InitializingAuthenticator, RecoveryData,
127 RecoveryUpdateSignature, RegistrationStatus,
128};
129
130/// Default configuration values for each [`Environment`].
131pub mod defaults;
132
133/// User agent for HTTP requests.
134pub mod user_agent;
135pub use user_agent::{UserAgent, UserAgentBuilder};
136
137/// Proof requests and responses in World ID v4.
138pub mod requests;
139
140/// Pre-flight check of whether stored credentials can satisfy a [`requests::ProofRequest`].
141pub mod proof_request_credential_constraints_check;
142
143mod proof;
144pub use proof::OwnershipProof;
145
146/// Credential issuers for World ID (NFC, etc.)
147#[cfg(feature = "issuers")]
148pub mod issuers;
149
150/// Legacy World ID 3.0 Proofs
151///
152/// # Example
153/// ```rust
154/// use walletkit_core::v3::{proof::ProofContext, CredentialType, world_id::WorldId};
155/// use walletkit_core::Environment;
156/// async fn example() {
157/// let world_id = WorldId::new(b"not_a_real_secret".to_vec(), &Environment::Staging);
158/// let context = ProofContext::new("app_ce4cb73cb75fc3b73b71ffb4de178410", Some("my_action".to_string()), None, CredentialType::Orb);
159/// let proof = world_id.generate_proof(&context).await.unwrap();
160/// println!("{}", proof.to_json().unwrap()); // the JSON output can be passed to the Developer Portal, World ID contracts, etc. for verification
161/// }
162#[cfg(feature = "v3")]
163pub mod v3;
164
165////////////////////////////////////////////////////////////////////////////////
166// Private modules
167////////////////////////////////////////////////////////////////////////////////
168
169#[cfg(any(feature = "issuers", feature = "v3"))]
170mod http_request;
171pub(crate) mod primitives;
172
173uniffi::setup_scaffolding!("walletkit_core");
174
175ruint_uniffi::register_types!(Uint256);