walletkit-core 0.10.0

Reference implementation for the World ID Protocol. Core functionality to use a World ID.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! The Authenticator is the main component with which users interact with the World ID Protocol.

use crate::{
    defaults::DefaultConfig, error::WalletKitError,
    primitives::ParseFromForeignBinding, Environment, FieldElement, Region,
};
use alloy_primitives::Address;
use ruint_uniffi::Uint256;
use std::sync::Arc;
use world_id_core::{
    api_types::{GatewayErrorCode, GatewayRequestState},
    primitives::Config,
    Authenticator as CoreAuthenticator, Credential as CoreCredential,
    InitializingAuthenticator as CoreInitializingAuthenticator,
};

#[cfg(feature = "storage")]
use world_id_core::{
    requests::{ProofResponse as CoreProofResponse, ResponseItem},
    FieldElement as CoreFieldElement,
};

#[cfg(feature = "storage")]
use crate::storage::{CredentialStore, StoragePaths};

#[cfg(feature = "storage")]
use crate::requests::{ProofRequest, ProofResponse};

#[cfg(feature = "storage")]
use rand::rngs::OsRng;

#[cfg(feature = "storage")]
mod with_storage;

type Groth16Materials = (
    Arc<world_id_core::proof::CircomGroth16Material>,
    Arc<world_id_core::proof::CircomGroth16Material>,
);

#[cfg(not(feature = "storage"))]
/// Loads embedded Groth16 query/nullifier material for authenticator initialization.
///
/// # Errors
/// Returns an error if embedded material cannot be loaded or verified.
fn load_embedded_materials() -> Result<Groth16Materials, WalletKitError> {
    let query_material =
        world_id_core::proof::load_embedded_query_material().map_err(|error| {
            WalletKitError::Groth16MaterialEmbeddedLoad {
                error: error.to_string(),
            }
        })?;
    let nullifier_material = world_id_core::proof::load_embedded_nullifier_material()
        .map_err(|error| {
        WalletKitError::Groth16MaterialEmbeddedLoad {
            error: error.to_string(),
        }
    })?;

    Ok((Arc::new(query_material), Arc::new(nullifier_material)))
}

#[cfg(feature = "storage")]
/// Loads cached Groth16 query/nullifier material from the provided storage paths.
///
/// # Errors
/// Returns an error if cached material cannot be loaded or verified.
fn load_cached_materials(
    paths: &StoragePaths,
) -> Result<Groth16Materials, WalletKitError> {
    let query_zkey = paths.query_zkey_path();
    let nullifier_zkey = paths.nullifier_zkey_path();
    let query_graph = paths.query_graph_path();
    let nullifier_graph = paths.nullifier_graph_path();

    let query_material = load_query_material_from_cache(&query_zkey, &query_graph)?;
    let nullifier_material =
        load_nullifier_material_from_cache(&nullifier_zkey, &nullifier_graph)?;

    Ok((Arc::new(query_material), Arc::new(nullifier_material)))
}

#[cfg(feature = "storage")]
/// Loads cached query material from zkey/graph paths.
///
/// # Errors
/// Returns an error if the cached query material cannot be loaded or verified.
fn load_query_material_from_cache(
    query_zkey: &std::path::Path,
    query_graph: &std::path::Path,
) -> Result<world_id_core::proof::CircomGroth16Material, WalletKitError> {
    world_id_core::proof::load_query_material_from_paths(query_zkey, query_graph)
        .map_err(|error| WalletKitError::Groth16MaterialCacheInvalid {
            path: format!(
                "{} and {}",
                query_zkey.to_string_lossy(),
                query_graph.to_string_lossy()
            ),
            error: error.to_string(),
        })
}

#[cfg(feature = "storage")]
#[expect(
    clippy::unnecessary_wraps,
    reason = "Temporary wrapper until world-id-core returns Result for nullifier path loader"
)]
/// Loads cached nullifier material from zkey/graph paths.
///
/// # Errors
/// This currently mirrors a panicking upstream API and does not return an error path yet.
/// It is intentionally wrapped in `Result` for forward compatibility with upstream.
fn load_nullifier_material_from_cache(
    nullifier_zkey: &std::path::Path,
    nullifier_graph: &std::path::Path,
) -> Result<world_id_core::proof::CircomGroth16Material, WalletKitError> {
    // TODO: Switch to error mapping once world-id-core exposes
    // `load_nullifier_material_from_paths` as `Result` instead of panicking.
    Ok(world_id_core::proof::load_nullifier_material_from_paths(
        nullifier_zkey,
        nullifier_graph,
    ))
}

/// The Authenticator is the main component with which users interact with the World ID Protocol.
#[derive(Debug, uniffi::Object)]
pub struct Authenticator {
    inner: CoreAuthenticator,
    #[cfg(feature = "storage")]
    store: Arc<CredentialStore>,
}

#[uniffi::export(async_runtime = "tokio")]
impl Authenticator {
    /// Returns the packed account data for the holder's World ID.
    ///
    /// The packed account data is a 256 bit integer which includes the user's leaf index, their recovery counter,
    /// and their pubkey id/commitment.
    #[must_use]
    pub fn packed_account_data(&self) -> Uint256 {
        self.inner.packed_account_data.into()
    }

    /// Returns the leaf index for the holder's World ID.
    ///
    /// This is the index in the Merkle tree where the holder's World ID account is registered. It
    /// should only be used inside the authenticator and never shared.
    #[must_use]
    pub fn leaf_index(&self) -> u64 {
        self.inner.leaf_index()
    }

    /// Returns the Authenticator's `onchain_address`.
    ///
    /// See `world_id_core::Authenticator::onchain_address` for more details.
    #[must_use]
    pub fn onchain_address(&self) -> String {
        self.inner.onchain_address().to_string()
    }

    /// Returns the packed account data for the holder's World ID fetching it from the on-chain registry.
    ///
    /// # Errors
    /// Will error if the provided RPC URL is not valid or if there are RPC call failures.
    pub async fn get_packed_account_data_remote(
        &self,
    ) -> Result<Uint256, WalletKitError> {
        let client = reqwest::Client::new(); // TODO: reuse client
        let packed_account_data = CoreAuthenticator::get_packed_account_data(
            self.inner.onchain_address(),
            self.inner.registry().as_deref(),
            &self.inner.config,
            &client,
        )
        .await?;
        Ok(packed_account_data.into())
    }

    /// Generates a blinding factor for a Credential sub (through OPRF Nodes).
    ///
    /// See [`CoreAuthenticator::generate_credential_blinding_factor`] for more details.
    ///
    /// # Errors
    ///
    /// - Will generally error if there are network issues or if the OPRF Nodes return an error.
    /// - Raises an error if the OPRF Nodes configuration is not correctly set.
    pub async fn generate_credential_blinding_factor_remote(
        &self,
        issuer_schema_id: u64,
    ) -> Result<FieldElement, WalletKitError> {
        Ok(self
            .inner
            .generate_credential_blinding_factor(issuer_schema_id)
            .await
            .map(Into::into)?)
    }

    /// Compute the `sub` for a credential from the authenticator's leaf index and a `blinding_factor`.
    #[must_use]
    pub fn compute_credential_sub(
        &self,
        blinding_factor: &FieldElement,
    ) -> FieldElement {
        CoreCredential::compute_sub(self.inner.leaf_index(), blinding_factor.0).into()
    }
}

#[cfg(not(feature = "storage"))]
#[uniffi::export(async_runtime = "tokio")]
impl Authenticator {
    /// Initializes a new Authenticator from a seed and with SDK defaults.
    ///
    /// The user's World ID must already be registered in the `WorldIDRegistry`,
    /// otherwise a [`WalletKitError::AccountDoesNotExist`] error will be returned.
    ///
    /// # Errors
    /// See `CoreAuthenticator::init` for potential errors.
    #[uniffi::constructor]
    pub async fn init_with_defaults(
        seed: &[u8],
        rpc_url: Option<String>,
        environment: &Environment,
        region: Option<Region>,
    ) -> Result<Self, WalletKitError> {
        let config = Config::from_environment(environment, rpc_url, region)?;
        let (query_material, nullifier_material) = load_embedded_materials()?;
        let authenticator =
            CoreAuthenticator::init(seed, config, query_material, nullifier_material)
                .await?;
        Ok(Self {
            inner: authenticator,
        })
    }

    /// Initializes a new Authenticator from a seed and config.
    ///
    /// The user's World ID must already be registered in the `WorldIDRegistry`,
    /// otherwise a [`WalletKitError::AccountDoesNotExist`] error will be returned.
    ///
    /// # Errors
    /// Will error if the provided seed is not valid or if the config is not valid.
    #[uniffi::constructor]
    pub async fn init(seed: &[u8], config: &str) -> Result<Self, WalletKitError> {
        let config =
            Config::from_json(config).map_err(|_| WalletKitError::InvalidInput {
                attribute: "config".to_string(),
                reason: "Invalid config".to_string(),
            })?;
        let (query_material, nullifier_material) = load_embedded_materials()?;
        let authenticator =
            CoreAuthenticator::init(seed, config, query_material, nullifier_material)
                .await?;
        Ok(Self {
            inner: authenticator,
        })
    }
}

#[cfg(feature = "storage")]
#[uniffi::export(async_runtime = "tokio")]
impl Authenticator {
    /// Initializes a new Authenticator from a seed and with SDK defaults.
    ///
    /// The user's World ID must already be registered in the `WorldIDRegistry`,
    /// otherwise a [`WalletKitError::AccountDoesNotExist`] error will be returned.
    ///
    /// # Errors
    /// See `CoreAuthenticator::init` for potential errors.
    #[uniffi::constructor]
    pub async fn init_with_defaults(
        seed: &[u8],
        rpc_url: Option<String>,
        environment: &Environment,
        region: Option<Region>,
        paths: Arc<StoragePaths>,
        store: Arc<CredentialStore>,
    ) -> Result<Self, WalletKitError> {
        let config = Config::from_environment(environment, rpc_url, region)?;
        let (query_material, nullifier_material) =
            load_cached_materials(paths.as_ref())?;
        let authenticator =
            CoreAuthenticator::init(seed, config, query_material, nullifier_material)
                .await?;
        Ok(Self {
            inner: authenticator,
            store,
        })
    }

    /// Initializes a new Authenticator from a seed and config.
    ///
    /// The user's World ID must already be registered in the `WorldIDRegistry`,
    /// otherwise a [`WalletKitError::AccountDoesNotExist`] error will be returned.
    ///
    /// # Errors
    /// Will error if the provided seed is not valid or if the config is not valid.
    #[uniffi::constructor]
    pub async fn init(
        seed: &[u8],
        config: &str,
        paths: Arc<StoragePaths>,
        store: Arc<CredentialStore>,
    ) -> Result<Self, WalletKitError> {
        let config =
            Config::from_json(config).map_err(|_| WalletKitError::InvalidInput {
                attribute: "config".to_string(),
                reason: "Invalid config".to_string(),
            })?;
        let (query_material, nullifier_material) =
            load_cached_materials(paths.as_ref())?;
        let authenticator =
            CoreAuthenticator::init(seed, config, query_material, nullifier_material)
                .await?;
        Ok(Self {
            inner: authenticator,
            store,
        })
    }

    /// Generates a proof for the given proof request.
    ///
    /// # Errors
    /// Returns an error if proof generation fails.
    pub async fn generate_proof(
        &self,
        proof_request: &ProofRequest,
        now: Option<u64>,
    ) -> Result<ProofResponse, WalletKitError> {
        let now = if let Some(n) = now {
            n
        } else {
            let start = std::time::SystemTime::now();
            start
                .duration_since(std::time::UNIX_EPOCH)
                .map_err(|e| WalletKitError::Generic {
                    error: format!("Critical. Unable to determine SystemTime: {e}"),
                })?
                .as_secs()
        };

        // First check if the request can be fulfilled and which credentials should be used
        let credential_list = self.store.list_credentials(None, now)?;
        let credential_list = credential_list
            .into_iter()
            .filter(|cred| !cred.is_expired)
            .map(|cred| cred.issuer_schema_id)
            .collect::<std::collections::HashSet<_>>();
        let credentials_to_prove = proof_request
            .0
            .credentials_to_prove(&credential_list)
            .ok_or(WalletKitError::UnfulfillableRequest)?;

        let (inclusion_proof, key_set) =
            self.fetch_inclusion_proof_with_cache(now).await?;

        // Next, generate the nullifier and check the replay guard
        let nullifier = self
            .inner
            .generate_nullifier(&proof_request.0, inclusion_proof, key_set)
            .await?;

        // NOTE: In a normal flow this error can not be triggered since OPRF nodes have their own
        // replay protection so the function will fail before this when attempting to generate the nullifier
        if self
            .store
            .is_nullifier_replay(nullifier.verifiable_oprf_output.output.into(), now)?
        {
            return Err(WalletKitError::NullifierReplay);
        }

        let mut responses: Vec<ResponseItem> = vec![];

        for request_item in credentials_to_prove {
            let (credential, blinding_factor) = self
                .store
                .get_credential(request_item.issuer_schema_id, now)?
                .ok_or(WalletKitError::CredentialNotIssued)?;

            let session_id_r_seed = CoreFieldElement::random(&mut OsRng); // TODO: Properly fetch session seed from cache

            let response_item = self.inner.generate_single_proof(
                nullifier.clone(),
                request_item,
                &credential,
                blinding_factor.0,
                session_id_r_seed,
                proof_request.0.session_id,
                proof_request.0.created_at,
            )?;
            responses.push(response_item);
        }

        let response = CoreProofResponse {
            id: proof_request.0.id.clone(),
            version: world_id_core::requests::RequestVersion::V1,
            responses,
            error: None,
            session_id: None, // TODO: This needs to be computed to be shareable
        };

        proof_request
            .0
            .validate_response(&response)
            .map_err(|err| WalletKitError::ResponseValidation(err.to_string()))?;

        self.store
            .replay_guard_set(nullifier.verifiable_oprf_output.output.into(), now)?;

        Ok(response.into())
    }
}

/// Registration status for a World ID being created through the gateway.
#[derive(Debug, Clone, uniffi::Enum)]
pub enum RegistrationStatus {
    /// Request queued but not yet batched.
    Queued,
    /// Request currently being batched.
    Batching,
    /// Request submitted on-chain.
    Submitted,
    /// Request finalized on-chain. The World ID is now registered.
    Finalized,
    /// Request failed during processing.
    Failed {
        /// Error message returned by the gateway.
        error: String,
        /// Specific error code, if available.
        error_code: Option<String>,
    },
}

impl From<GatewayRequestState> for RegistrationStatus {
    fn from(state: GatewayRequestState) -> Self {
        match state {
            GatewayRequestState::Queued => Self::Queued,
            GatewayRequestState::Batching => Self::Batching,
            GatewayRequestState::Submitted { .. } => Self::Submitted,
            GatewayRequestState::Finalized { .. } => Self::Finalized,
            GatewayRequestState::Failed { error, error_code } => Self::Failed {
                error,
                error_code: error_code.map(|c: GatewayErrorCode| c.to_string()),
            },
        }
    }
}

/// Represents an Authenticator in the process of being initialized.
///
/// The account is not yet registered in the `WorldIDRegistry` contract.
/// Use this for non-blocking registration flows where you want to poll the status yourself.
#[derive(uniffi::Object)]
pub struct InitializingAuthenticator(CoreInitializingAuthenticator);

#[uniffi::export(async_runtime = "tokio")]
impl InitializingAuthenticator {
    /// Registers a new World ID with SDK defaults.
    ///
    /// This returns immediately and does not wait for registration to complete.
    /// The returned `InitializingAuthenticator` can be used to poll the registration status.
    ///
    /// # Errors
    /// See `CoreAuthenticator::register` for potential errors.
    #[uniffi::constructor]
    pub async fn register_with_defaults(
        seed: &[u8],
        rpc_url: Option<String>,
        environment: &Environment,
        region: Option<Region>,
        recovery_address: Option<String>,
    ) -> Result<Self, WalletKitError> {
        let recovery_address =
            Address::parse_from_ffi_optional(recovery_address, "recovery_address")?;

        let config = Config::from_environment(environment, rpc_url, region)?;

        let initializing_authenticator =
            CoreAuthenticator::register(seed, config, recovery_address).await?;

        Ok(Self(initializing_authenticator))
    }

    /// Registers a new World ID.
    ///
    /// This returns immediately and does not wait for registration to complete.
    /// The returned `InitializingAuthenticator` can be used to poll the registration status.
    ///
    /// # Errors
    /// See `CoreAuthenticator::register` for potential errors.
    #[uniffi::constructor]
    pub async fn register(
        seed: &[u8],
        config: &str,
        recovery_address: Option<String>,
    ) -> Result<Self, WalletKitError> {
        let recovery_address =
            Address::parse_from_ffi_optional(recovery_address, "recovery_address")?;

        let config =
            Config::from_json(config).map_err(|_| WalletKitError::InvalidInput {
                attribute: "config".to_string(),
                reason: "Invalid config".to_string(),
            })?;

        let initializing_authenticator =
            CoreAuthenticator::register(seed, config, recovery_address).await?;

        Ok(Self(initializing_authenticator))
    }

    /// Polls the registration status from the gateway.
    ///
    /// # Errors
    /// Will error if the network request fails or the gateway returns an error.
    pub async fn poll_status(&self) -> Result<RegistrationStatus, WalletKitError> {
        let status = self.0.poll_status().await?;
        Ok(status.into())
    }
}

#[cfg(all(test, feature = "storage"))]
mod tests {
    use super::*;
    use crate::storage::cache_embedded_groth16_material;
    use crate::storage::tests_utils::{
        cleanup_test_storage, temp_root_path, InMemoryStorageProvider,
    };
    use alloy::primitives::address;

    #[tokio::test]
    async fn test_init_with_config_and_storage() {
        // Install default crypto provider for rustls
        let _ = rustls::crypto::ring::default_provider().install_default();

        let mut mock_server = mockito::Server::new_async().await;

        // Mock eth_call to return account data indicating account exists
        mock_server
            .mock("POST", "/")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "result": "0x0000000000000000000000000000000000000000000000000000000000000001"
                })
                .to_string(),
            )
            .create_async()
            .await;

        let seed = [2u8; 32];
        let config = Config::new(
            Some(mock_server.url()),
            480,
            address!("0x969947cFED008bFb5e3F32a25A1A2CDdf64d46fe"),
            "https://world-id-indexer.stage-crypto.worldcoin.org".to_string(),
            "https://world-id-gateway.stage-crypto.worldcoin.org".to_string(),
            vec![],
            2,
        )
        .unwrap();
        let config = serde_json::to_string(&config).unwrap();

        let root = temp_root_path();
        let provider = InMemoryStorageProvider::new(&root);
        let store = CredentialStore::from_provider(&provider).expect("store");
        store.init(42, 100).expect("init storage");
        cache_embedded_groth16_material(store.storage_paths().expect("paths"))
            .expect("cache material");

        let paths = store.storage_paths().expect("paths");
        Authenticator::init(&seed, &config, paths, Arc::new(store))
            .await
            .unwrap();
        drop(mock_server);
        cleanup_test_storage(&root);
    }
}