world-id-authenticator 0.9.0

World ID Credential crate
Documentation
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
//! This module contains all the base functionality to support Authenticators in World ID. See
//! [`Authenticator`] for a definition.

use crate::{
    error::{AuthenticatorError, PollResult},
    init::InitializingAuthenticator,
};

use std::sync::Arc;

use crate::{
    api_types::{
        AccountInclusionProof, GatewayRequestState, IndexerAuthenticatorPubkeysResponse,
        IndexerErrorCode, IndexerPackedAccountRequest, IndexerPackedAccountResponse,
        IndexerQueryRequest, IndexerSignatureNonceResponse, ServiceApiError,
    },
    service_client::{ServiceClient, ServiceKind},
};
use serde::{Deserialize, Serialize};
use world_id_primitives::{Credential, FieldElement, ProofResponse, Signer};

pub use crate::ohttp::OhttpClientConfig;
use crate::registry::WorldIdRegistry::WorldIdRegistryInstance;
use alloy::{
    primitives::Address,
    providers::DynProvider,
    signers::{Signature, SignerSync},
};
use ark_serialize::CanonicalSerialize;
use eddsa_babyjubjub::EdDSAPublicKey;
use groth16_material::circom::CircomGroth16Material;
use ruint::{aliases::U256, uint};
use taceo_oprf::client::Connector;
pub use world_id_primitives::{Config, TREE_DEPTH, authenticator::ProtocolSigner};
use world_id_primitives::{
    PrimitiveError,
    authenticator::{
        AuthenticatorPublicKeySet, SparseAuthenticatorPubkeysError,
        decode_sparse_authenticator_pubkeys,
    },
};

#[expect(unused_imports, reason = "used for docs")]
use world_id_primitives::{Nullifier, SessionId};

static MASK_RECOVERY_COUNTER: U256 =
    uint!(0xFFFFFFFF00000000000000000000000000000000000000000000000000000000_U256);
static MASK_PUBKEY_ID: U256 =
    uint!(0x00000000FFFFFFFF000000000000000000000000000000000000000000000000_U256);
static MASK_LEAF_INDEX: U256 =
    uint!(0x000000000000000000000000000000000000000000000000FFFFFFFFFFFFFFFF_U256);

/// Configuration for an [`Authenticator`], extends base protocol [`Config`] by
/// optional OHTTP relay settings for the indexer and gateway services.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthenticatorConfig {
    /// Base protocol configuration (indexer URL, gateway URL, RPC, etc.).
    #[serde(flatten)]
    pub config: Config,
    /// Optional OHTTP relay configuration for indexer requests.
    #[serde(default)]
    pub ohttp_indexer: Option<OhttpClientConfig>,
    /// Optional OHTTP relay configuration for gateway requests.
    #[serde(default)]
    pub ohttp_gateway: Option<OhttpClientConfig>,
}

impl AuthenticatorConfig {
    /// Loads an authenticator configuration from JSON.
    ///
    /// Accepts both plain `Config` JSON (OHTTP fields default to `None`) and
    /// extended JSON with `ohttp_indexer` / `ohttp_gateway` fields.
    ///
    /// # Errors
    /// Will error if the JSON is not valid.
    pub fn from_json(json_str: &str) -> Result<Self, AuthenticatorError> {
        serde_json::from_str(json_str).map_err(|e| {
            AuthenticatorError::from(PrimitiveError::Serialization(format!(
                "failed to parse authenticator config: {e}"
            )))
        })
    }
}

impl From<Config> for AuthenticatorConfig {
    fn from(config: Config) -> Self {
        Self {
            config,
            ohttp_indexer: None,
            ohttp_gateway: None,
        }
    }
}

/// Input for a single credential proof within a proof request.
pub struct CredentialInput {
    /// The credential to prove.
    pub credential: Credential,
    /// The blinding factor for the credential's sub.
    pub blinding_factor: FieldElement,
}

/// Output from proof generation process.
///
/// The [`Authenticator`] herein deliberately does not handle caching or replay guards as
/// those are SDK concerns.
#[derive(Debug)]
pub struct ProofResult {
    /// The session_id_r_seed (`r`), if a session proof was generated.
    ///
    /// The SDK should cache this keyed by [`SessionId::oprf_seed`].
    pub session_id_r_seed: Option<FieldElement>,

    /// The response to deliver to an RP.
    pub proof_response: ProofResponse,
}

/// An Authenticator is the agent of a **user** interacting with the World ID Protocol.
///
/// # Definition
///
/// A software or hardware agent (e.g., app, device, web client, or service) that controls a
/// set of authorized keypairs for a World ID Account and is functionally capable of interacting
/// with the Protocol, and is therefore permitted to act on that account's behalf. An Authenticator
/// is the agent of users/holders. Each Authenticator is registered in the `WorldIDRegistry`
/// through their authorized keypairs.
///
/// For example, an Authenticator can live in a mobile wallet or a web application.
pub struct Authenticator {
    /// General configuration for the Authenticator.
    pub config: Config,
    /// The packed account data for the holder's World ID is a `uint256` defined in the `WorldIDRegistry` contract as:
    /// `recovery_counter` (32 bits) | `pubkey_id` (commitment to all off-chain public keys) (32 bits) | `leaf_index` (192 bits)
    pub packed_account_data: U256,
    pub(crate) signer: Signer,
    pub(crate) registry: Option<Arc<WorldIdRegistryInstance<DynProvider>>>,
    pub(crate) indexer_client: ServiceClient,
    pub(crate) gateway_client: ServiceClient,
    pub(crate) ws_connector: Connector,
    pub(crate) query_material: Option<Arc<CircomGroth16Material>>,
    pub(crate) nullifier_material: Option<Arc<CircomGroth16Material>>,
}

impl std::fmt::Debug for Authenticator {
    // avoiding logging other attributes to avoid accidental leak of leaf_index
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Authenticator")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl Authenticator {
    /// Initialize an Authenticator from a seed and config.
    ///
    /// This method will error if the World ID account does not exist on the registry.
    ///
    /// # Errors
    /// - Will error if the provided seed is invalid (not 32 bytes).
    /// - Will error if the RPC URL is invalid.
    /// - Will error if there are contract call failures.
    /// - Will error if the account does not exist (`AccountDoesNotExist`).
    pub async fn init(
        seed: &[u8],
        config: AuthenticatorConfig,
    ) -> Result<Self, AuthenticatorError> {
        let AuthenticatorConfig {
            config,
            ohttp_indexer,
            ohttp_gateway,
        } = config;

        let signer = Signer::from_seed_bytes(seed)?;

        let registry: Option<Arc<WorldIdRegistryInstance<DynProvider>>> =
            config.rpc_url().map(|rpc_url| {
                let provider = alloy::providers::ProviderBuilder::new()
                    .with_chain_id(config.chain_id())
                    .connect_http(rpc_url.clone());
                Arc::new(crate::registry::WorldIdRegistry::new(
                    *config.registry_address(),
                    alloy::providers::Provider::erased(provider),
                ))
            });

        let http_client = reqwest::Client::new();

        let indexer_client = ServiceClient::new(
            http_client.clone(),
            ServiceKind::Indexer,
            config.indexer_url(),
            ohttp_indexer,
        )?;

        let gateway_client = ServiceClient::new(
            http_client,
            ServiceKind::Gateway,
            config.gateway_url(),
            ohttp_gateway,
        )?;

        let packed_account_data = Self::get_packed_account_data(
            signer.onchain_signer_address(),
            registry.as_deref(),
            &config,
            &indexer_client,
        )
        .await?;

        #[cfg(not(target_arch = "wasm32"))]
        let ws_connector = {
            let mut root_store = rustls::RootCertStore::empty();
            root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
            let rustls_config = rustls::ClientConfig::builder()
                .with_root_certificates(root_store)
                .with_no_client_auth();
            Connector::Rustls(Arc::new(rustls_config))
        };

        #[cfg(target_arch = "wasm32")]
        let ws_connector = Connector;

        Ok(Self {
            packed_account_data,
            signer,
            config,
            registry,
            indexer_client,
            gateway_client,
            ws_connector,
            query_material: None,
            nullifier_material: None,
        })
    }

    /// Sets the proof materials for the Authenticator, returning a new instance.
    ///
    /// Proof materials are required for proof generation, blinding factors and starting
    /// sessions. Given the proof circuits are large, this may be loaded only when necessary.
    #[must_use]
    pub fn with_proof_materials(
        self,
        query_material: Arc<CircomGroth16Material>,
        nullifier_material: Arc<CircomGroth16Material>,
    ) -> Self {
        Self {
            query_material: Some(query_material),
            nullifier_material: Some(nullifier_material),
            ..self
        }
    }

    /// Registers a new World ID in the `WorldIDRegistry`.
    ///
    /// Given the registration process is asynchronous, this method will return a `InitializingAuthenticator`
    /// object.
    ///
    /// # Errors
    /// - See `init` for additional error details.
    pub async fn register(
        seed: &[u8],
        config: AuthenticatorConfig,
        recovery_address: Option<Address>,
    ) -> Result<InitializingAuthenticator, AuthenticatorError> {
        let AuthenticatorConfig {
            config,
            ohttp_gateway,
            ..
        } = config;
        let gateway_client = ServiceClient::new(
            reqwest::Client::new(),
            ServiceKind::Gateway,
            config.gateway_url(),
            ohttp_gateway,
        )?;
        InitializingAuthenticator::new(seed, config, recovery_address, gateway_client).await
    }

    /// Initializes (if the World ID already exists in the registry) or registers a new World ID.
    ///
    /// The registration process is asynchronous and may take some time. This method will block
    /// the thread until the registration is in a final state (success or terminal error). For better
    /// user experience in end authenticator clients, it is recommended to implement custom polling logic.
    ///
    /// Explicit `init` or `register` calls are also recommended as the authenticator should know
    /// if a new World ID should be truly created. For example, an authenticator may have been revoked
    /// access to an existing World ID.
    ///
    /// # Errors
    /// - See `init` for additional error details.
    pub async fn init_or_register(
        seed: &[u8],
        config: AuthenticatorConfig,
        recovery_address: Option<Address>,
    ) -> Result<Self, AuthenticatorError> {
        match Self::init(seed, config.clone()).await {
            Ok(authenticator) => Ok(authenticator),
            Err(AuthenticatorError::AccountDoesNotExist) => {
                let gateway_client = ServiceClient::new(
                    reqwest::Client::new(),
                    ServiceKind::Gateway,
                    config.config.gateway_url(),
                    config.ohttp_gateway.clone(),
                )?;
                let initializing_authenticator = InitializingAuthenticator::new(
                    seed,
                    config.config.clone(),
                    recovery_address,
                    gateway_client,
                )
                .await?;

                let backoff = backon::ExponentialBuilder::default()
                    .with_min_delay(std::time::Duration::from_millis(800))
                    .with_factor(1.5)
                    .without_max_times()
                    .with_total_delay(Some(std::time::Duration::from_secs(120)));

                let poller = || async {
                    let poll_status = initializing_authenticator.poll_status().await;
                    let result = match poll_status {
                        Ok(GatewayRequestState::Finalized { .. }) => Ok(()),
                        Ok(GatewayRequestState::Failed { error_code, error }) => Err(
                            PollResult::TerminalError(AuthenticatorError::RegistrationError {
                                error_code: error_code.map(|v| v.to_string()).unwrap_or_default(),
                                error_message: error,
                            }),
                        ),
                        Err(AuthenticatorError::GatewayError { status, body }) => {
                            if status.is_client_error() {
                                Err(PollResult::TerminalError(
                                    AuthenticatorError::GatewayError { status, body },
                                ))
                            } else {
                                Err(PollResult::Retryable)
                            }
                        }
                        _ => Err(PollResult::Retryable),
                    };

                    match result {
                        Ok(()) => match Self::init(seed, config.clone()).await {
                            Ok(auth) => Ok(auth),
                            Err(AuthenticatorError::AccountDoesNotExist) => {
                                Err(PollResult::Retryable)
                            }
                            Err(e) => Err(PollResult::TerminalError(e)),
                        },
                        Err(e) => Err(e),
                    }
                };

                let result = backon::Retryable::retry(poller, backoff)
                    .when(|e| matches!(e, PollResult::Retryable))
                    .await;

                match result {
                    Ok(authenticator) => Ok(authenticator),
                    Err(PollResult::TerminalError(e)) => Err(e),
                    Err(PollResult::Retryable) => Err(AuthenticatorError::Timeout),
                }
            }
            Err(e) => Err(e),
        }
    }

    /// Re-fetches the packed account data for this authenticator from the indexer or registry.
    ///
    /// # Errors
    /// Will error if the network call fails or if the account does not exist.
    pub async fn refresh_packed_account_data(&self) -> Result<U256, AuthenticatorError> {
        Self::get_packed_account_data(
            self.onchain_address(),
            self.registry().as_deref(),
            &self.config,
            &self.indexer_client,
        )
        .await
    }

    /// Returns the packed account data for the holder's World ID.
    ///
    /// The packed account data is a 256 bit integer which includes the World ID's leaf index, their recovery counter,
    /// and their pubkey id/commitment.
    ///
    /// # Errors
    /// Will error if the network call fails or if the account does not exist.
    async fn get_packed_account_data(
        onchain_signer_address: Address,
        registry: Option<&WorldIdRegistryInstance<DynProvider>>,
        config: &Config,
        indexer_client: &ServiceClient,
    ) -> Result<U256, AuthenticatorError> {
        // If the registry is available through direct RPC calls, use it. Otherwise fallback to the indexer.
        let raw_index = if let Some(registry) = registry {
            // TODO: Better error handling to expose the specific failure
            registry
                .getPackedAccountData(onchain_signer_address)
                .call()
                .await?
        } else {
            let req = IndexerPackedAccountRequest {
                authenticator_address: onchain_signer_address,
            };
            match indexer_client
                .post_json::<_, IndexerPackedAccountResponse>(
                    config.indexer_url(),
                    "/packed-account",
                    &req,
                )
                .await
            {
                Ok(response) => response.packed_account_data,
                Err(AuthenticatorError::IndexerError { status, body }) => {
                    if let Ok(error_resp) =
                        serde_json::from_str::<ServiceApiError<IndexerErrorCode>>(&body)
                    {
                        return match error_resp.code {
                            IndexerErrorCode::AccountDoesNotExist => {
                                Err(AuthenticatorError::AccountDoesNotExist)
                            }
                            _ => Err(AuthenticatorError::IndexerError {
                                status,
                                body: error_resp.message,
                            }),
                        };
                    }

                    return Err(AuthenticatorError::IndexerError { status, body });
                }
                Err(other) => return Err(other),
            }
        };

        if raw_index == U256::ZERO {
            return Err(AuthenticatorError::AccountDoesNotExist);
        }

        Ok(raw_index)
    }

    /// Returns the k256 public key of the Authenticator signer which is used to verify on-chain operations,
    /// chiefly with the `WorldIdRegistry` contract.
    #[must_use]
    pub const fn onchain_address(&self) -> Address {
        self.signer.onchain_signer_address()
    }

    /// Returns the `EdDSA` public key of the Authenticator signer which is used to verify off-chain operations. For example,
    /// the Nullifier Oracle uses it to verify requests for nullifiers.
    #[must_use]
    pub fn offchain_pubkey(&self) -> EdDSAPublicKey {
        self.signer.offchain_signer_pubkey()
    }

    /// Returns the compressed `EdDSA` public key of the Authenticator signer which is used to verify off-chain operations.
    /// For example, the Nullifier Oracle uses it to verify requests for nullifiers.
    /// # Errors
    /// Will error if the public key cannot be serialized.
    pub fn offchain_pubkey_compressed(&self) -> Result<U256, AuthenticatorError> {
        let pk = self.signer.offchain_signer_pubkey().pk;
        let mut compressed_bytes = Vec::new();
        pk.serialize_compressed(&mut compressed_bytes)
            .map_err(|e| PrimitiveError::Serialization(e.to_string()))?;
        Ok(U256::from_le_slice(&compressed_bytes))
    }

    /// Returns a reference to the `WorldIdRegistry` contract instance.
    #[must_use]
    pub fn registry(&self) -> Option<Arc<WorldIdRegistryInstance<DynProvider>>> {
        self.registry.clone()
    }

    /// Returns the index for the holder's World ID.
    ///
    /// # Definition
    ///
    /// The `leaf_index` is the main (internal) identifier of a World ID. It is registered in
    /// the `WorldIDRegistry` and represents the index at the Merkle tree where the World ID
    /// resides.
    ///
    /// # Notes
    /// - The `leaf_index` is used as input in the nullifier generation, ensuring a nullifier
    ///   will always be the same for the same RP context and the same World ID (allowing for uniqueness).
    /// - The `leaf_index` is generally not exposed outside Authenticators. It is not a secret because
    ///   it's not exposed to RPs outside ZK-circuits, but the only acceptable exposure outside an Authenticator
    ///   is to fetch Merkle inclusion proofs from an indexer or it may create a pseudonymous identifier.
    /// - The `leaf_index` is stored as a `uint64` inside packed account data.
    #[must_use]
    pub fn leaf_index(&self) -> u64 {
        (self.packed_account_data & MASK_LEAF_INDEX).to::<u64>()
    }

    /// Returns the recovery counter for the holder's World ID.
    ///
    /// The recovery counter is used to efficiently invalidate all the old keys when an account is recovered.
    #[must_use]
    pub fn recovery_counter(&self) -> U256 {
        let recovery_counter = self.packed_account_data & MASK_RECOVERY_COUNTER;
        recovery_counter >> 224
    }

    /// Returns the pubkey id (or commitment) for the holder's World ID.
    ///
    /// This is a commitment to all the off-chain public keys that are authorized to act on behalf of the holder.
    #[must_use]
    pub fn pubkey_id(&self) -> U256 {
        let pubkey_id = self.packed_account_data & MASK_PUBKEY_ID;
        pubkey_id >> 192
    }

    /// Fetches a Merkle inclusion proof for the holder's World ID given their account index.
    ///
    /// # Errors
    /// - Will error if the provided indexer URL is not valid or if there are HTTP call failures.
    /// - Will error if the user is not registered on the `WorldIDRegistry`.
    pub async fn fetch_inclusion_proof(
        &self,
    ) -> Result<AccountInclusionProof<TREE_DEPTH>, AuthenticatorError> {
        let req = IndexerQueryRequest {
            leaf_index: self.leaf_index(),
        };
        let response: AccountInclusionProof<TREE_DEPTH> = self
            .indexer_client
            .post_json(self.config.indexer_url(), "/inclusion-proof", &req)
            .await?;

        Ok(response)
    }

    /// Fetches the current authenticator public key set for the account.
    ///
    /// This is used by mutation operations to compute old/new offchain signer commitments
    /// without requiring Merkle proof generation.
    ///
    /// # Errors
    /// - Will error if the provided indexer URL is not valid or if there are HTTP call failures.
    /// - Will error if the user is not registered on the `WorldIDRegistry`.
    pub async fn fetch_authenticator_pubkeys(
        &self,
    ) -> Result<AuthenticatorPublicKeySet, AuthenticatorError> {
        let req = IndexerQueryRequest {
            leaf_index: self.leaf_index(),
        };
        let response: IndexerAuthenticatorPubkeysResponse = self
            .indexer_client
            .post_json(self.config.indexer_url(), "/authenticator-pubkeys", &req)
            .await?;
        Self::decode_indexer_pubkeys(response.authenticator_pubkeys)
    }

    /// Returns the signing nonce for the holder's World ID.
    ///
    /// # Errors
    /// Will return an error if the registry contract call fails.
    pub async fn signing_nonce(&self) -> Result<U256, AuthenticatorError> {
        let registry = self.registry();
        if let Some(registry) = registry {
            let nonce = registry.getSignatureNonce(self.leaf_index()).call().await?;
            Ok(nonce)
        } else {
            let req = IndexerQueryRequest {
                leaf_index: self.leaf_index(),
            };
            let response: IndexerSignatureNonceResponse = self
                .indexer_client
                .post_json(self.config.indexer_url(), "/signature-nonce", &req)
                .await?;
            Ok(response.signature_nonce)
        }
    }

    /// Signs an arbitrary challenge with the authenticator's on-chain key following
    /// [ERC-191](https://eips.ethereum.org/EIPS/eip-191).
    ///
    /// # Warning
    /// This is considered a dangerous operation because it leaks the user's on-chain key,
    /// hence its `leaf_index`. The only acceptable use is to prove the user's `leaf_index`
    /// to a Recovery Agent. The Recovery Agent is the only party beyond the user who needs
    /// to know the `leaf_index`.
    ///
    /// # Use
    /// - This method is used to prove ownership over a leaf index **only for Recovery Agents**.
    pub fn danger_sign_challenge(&self, challenge: &[u8]) -> Result<Signature, AuthenticatorError> {
        self.signer
            .onchain_signer()
            .sign_message_sync(challenge)
            .map_err(|e| AuthenticatorError::Generic(format!("signature error: {e}")))
    }

    pub(crate) fn decode_indexer_pubkeys(
        pubkeys: Vec<Option<U256>>,
    ) -> Result<AuthenticatorPublicKeySet, AuthenticatorError> {
        decode_sparse_authenticator_pubkeys(pubkeys).map_err(|e| match e {
            SparseAuthenticatorPubkeysError::SlotOutOfBounds {
                slot_index,
                max_supported_slot,
            } => AuthenticatorError::InvalidIndexerPubkeySlot {
                slot_index,
                max_supported_slot,
            },
            SparseAuthenticatorPubkeysError::InvalidCompressedPubkey { slot_index, reason } => {
                PrimitiveError::Deserialization(format!(
                    "invalid authenticator public key returned by indexer at slot {slot_index}: {reason}"
                ))
                .into()
            }
        })
    }

    pub(crate) fn insert_or_reuse_authenticator_key(
        key_set: &mut AuthenticatorPublicKeySet,
        new_authenticator_pubkey: EdDSAPublicKey,
    ) -> Result<usize, AuthenticatorError> {
        if let Some(index) = key_set.iter().position(Option::is_none) {
            key_set.try_set_at_index(index, new_authenticator_pubkey)?;
            Ok(index)
        } else {
            key_set.try_push(new_authenticator_pubkey)?;
            Ok(key_set.len() - 1)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{error::AuthenticatorError, traits::OnchainKeyRepresentable};
    use alloy::primitives::{U256, address};
    use world_id_primitives::authenticator::MAX_AUTHENTICATOR_KEYS;

    fn test_pubkey(seed_byte: u8) -> EdDSAPublicKey {
        Signer::from_seed_bytes(&[seed_byte; 32])
            .unwrap()
            .offchain_signer_pubkey()
    }

    fn encoded_test_pubkey(seed_byte: u8) -> U256 {
        test_pubkey(seed_byte).to_ethereum_representation().unwrap()
    }

    #[test]
    fn test_insert_or_reuse_authenticator_key_reuses_empty_slot() {
        let mut key_set =
            AuthenticatorPublicKeySet::new(vec![test_pubkey(1), test_pubkey(2), test_pubkey(4)])
                .unwrap();
        key_set[1] = None;
        let new_key = test_pubkey(3);

        let index =
            Authenticator::insert_or_reuse_authenticator_key(&mut key_set, new_key).unwrap();

        assert_eq!(index, 1);
        assert_eq!(key_set.len(), 3);
        assert_eq!(key_set[1].as_ref().unwrap().pk, test_pubkey(3).pk);
    }

    #[test]
    fn test_insert_or_reuse_authenticator_key_appends_when_no_empty_slot() {
        let mut key_set = AuthenticatorPublicKeySet::new(vec![test_pubkey(1)]).unwrap();
        let new_key = test_pubkey(2);

        let index =
            Authenticator::insert_or_reuse_authenticator_key(&mut key_set, new_key).unwrap();

        assert_eq!(index, 1);
        assert_eq!(key_set.len(), 2);
        assert_eq!(key_set[1].as_ref().unwrap().pk, test_pubkey(2).pk);
    }

    #[test]
    fn test_decode_indexer_pubkeys_trims_trailing_empty_slots() {
        let mut encoded_pubkeys = vec![Some(encoded_test_pubkey(1)), Some(encoded_test_pubkey(2))];
        encoded_pubkeys.extend(vec![None; MAX_AUTHENTICATOR_KEYS + 5]);

        let key_set = Authenticator::decode_indexer_pubkeys(encoded_pubkeys).unwrap();

        assert_eq!(key_set.len(), 2);
        assert_eq!(key_set[0].as_ref().unwrap().pk, test_pubkey(1).pk);
        assert_eq!(key_set[1].as_ref().unwrap().pk, test_pubkey(2).pk);
    }

    #[test]
    fn test_decode_indexer_pubkeys_rejects_used_slot_beyond_max() {
        let mut encoded_pubkeys = vec![None; MAX_AUTHENTICATOR_KEYS + 1];
        encoded_pubkeys[MAX_AUTHENTICATOR_KEYS] = Some(encoded_test_pubkey(1));

        let error = Authenticator::decode_indexer_pubkeys(encoded_pubkeys).unwrap_err();
        assert!(matches!(
            error,
            AuthenticatorError::InvalidIndexerPubkeySlot {
                slot_index,
                max_supported_slot
            } if slot_index == MAX_AUTHENTICATOR_KEYS && max_supported_slot == MAX_AUTHENTICATOR_KEYS - 1
        ));
    }

    #[tokio::test]
    async fn test_get_packed_account_data_from_indexer() {
        let mut server = mockito::Server::new_async().await;
        let indexer_url = server.url();
        let test_address = address!("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0");
        let expected_packed_index = U256::from(42);
        let mock = server
            .mock("POST", "/packed-account")
            .match_header("content-type", "application/json")
            .match_body(mockito::Matcher::JsonString(
                serde_json::json!({ "authenticator_address": test_address }).to_string(),
            ))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({ "packed_account_data": format!("{:#x}", expected_packed_index) }).to_string(),
            )
            .create_async()
            .await;
        let config = Config::new(
            None,
            1,
            address!("0x0000000000000000000000000000000000000001"),
            indexer_url,
            "http://gateway.example.com".to_string(),
            Vec::new(),
            2,
        )
        .unwrap();

        let indexer_client = ServiceClient::new(
            reqwest::Client::new(),
            ServiceKind::Indexer,
            config.indexer_url(),
            None,
        )
        .unwrap();

        let result = Authenticator::get_packed_account_data(
            test_address,
            None, // No registry, force indexer usage
            &config,
            &indexer_client,
        )
        .await
        .unwrap();

        assert_eq!(result, expected_packed_index);
        mock.assert_async().await;
        drop(server);
    }

    #[tokio::test]
    async fn test_get_packed_account_data_from_indexer_error() {
        let mut server = mockito::Server::new_async().await;
        let indexer_url = server.url();
        let test_address = address!("0x0000000000000000000000000000000000000099");
        let mock = server
            .mock("POST", "/packed-account")
            .with_status(400)
            .with_header("content-type", "application/json")
            .with_body(serde_json::json!({ "code": "account_does_not_exist", "message": "There is no account for this authenticator address" }).to_string())
            .create_async()
            .await;
        let config = Config::new(
            None,
            1,
            address!("0x0000000000000000000000000000000000000001"),
            indexer_url,
            "http://gateway.example.com".to_string(),
            Vec::new(),
            2,
        )
        .unwrap();

        let indexer_client = ServiceClient::new(
            reqwest::Client::new(),
            ServiceKind::Indexer,
            config.indexer_url(),
            None,
        )
        .unwrap();

        let result =
            Authenticator::get_packed_account_data(test_address, None, &config, &indexer_client)
                .await;

        assert!(matches!(
            result,
            Err(AuthenticatorError::AccountDoesNotExist)
        ));
        mock.assert_async().await;
        drop(server);
    }

    #[tokio::test]
    #[cfg(not(target_arch = "wasm32"))]
    async fn test_signing_nonce_from_indexer() {
        let mut server = mockito::Server::new_async().await;
        let indexer_url = server.url();
        let leaf_index = U256::from(1);
        let expected_nonce = U256::from(5);
        let mock = server
            .mock("POST", "/signature-nonce")
            .match_header("content-type", "application/json")
            .match_body(mockito::Matcher::JsonString(
                serde_json::json!({ "leaf_index": format!("{:#x}", leaf_index) }).to_string(),
            ))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({ "signature_nonce": format!("{:#x}", expected_nonce) })
                    .to_string(),
            )
            .create_async()
            .await;
        let config = Config::new(
            None,
            1,
            address!("0x0000000000000000000000000000000000000001"),
            indexer_url,
            "http://gateway.example.com".to_string(),
            Vec::new(),
            2,
        )
        .unwrap();

        let http_client = reqwest::Client::new();
        let authenticator = Authenticator {
            config: config.clone(),
            packed_account_data: leaf_index,
            signer: Signer::from_seed_bytes(&[1u8; 32]).unwrap(),
            registry: None,
            indexer_client: ServiceClient::new(
                http_client.clone(),
                ServiceKind::Indexer,
                config.indexer_url(),
                None,
            )
            .unwrap(),
            gateway_client: ServiceClient::new(
                http_client,
                ServiceKind::Gateway,
                config.gateway_url(),
                None,
            )
            .unwrap(),
            ws_connector: Connector::Plain,
            query_material: None,
            nullifier_material: None,
        };
        let nonce = authenticator.signing_nonce().await.unwrap();
        assert_eq!(nonce, expected_nonce);
        mock.assert_async().await;
        drop(server);
    }

    #[test]
    fn test_danger_sign_challenge_returns_valid_signature() {
        let config = Config::new(
            None,
            1,
            address!("0x0000000000000000000000000000000000000001"),
            "http://indexer.example.com".to_string(),
            "http://gateway.example.com".to_string(),
            Vec::new(),
            2,
        )
        .unwrap();
        let http_client = reqwest::Client::new();
        let authenticator = Authenticator {
            indexer_client: ServiceClient::new(
                http_client.clone(),
                ServiceKind::Indexer,
                config.indexer_url(),
                None,
            )
            .unwrap(),
            gateway_client: ServiceClient::new(
                http_client,
                ServiceKind::Gateway,
                config.gateway_url(),
                None,
            )
            .unwrap(),
            config,
            packed_account_data: U256::from(1),
            signer: Signer::from_seed_bytes(&[1u8; 32]).unwrap(),
            registry: None,
            ws_connector: Connector::Plain,
            query_material: None,
            nullifier_material: None,
        };
        let challenge = b"test challenge";
        let signature = authenticator.danger_sign_challenge(challenge).unwrap();
        let recovered = signature
            .recover_address_from_msg(challenge)
            .expect("should recover address");
        assert_eq!(recovered, authenticator.onchain_address());
    }

    #[test]
    fn test_danger_sign_challenge_different_challenges_different_signatures() {
        let config = Config::new(
            None,
            1,
            address!("0x0000000000000000000000000000000000000001"),
            "http://indexer.example.com".to_string(),
            "http://gateway.example.com".to_string(),
            Vec::new(),
            2,
        )
        .unwrap();
        let http_client = reqwest::Client::new();
        let authenticator = Authenticator {
            indexer_client: ServiceClient::new(
                http_client.clone(),
                ServiceKind::Indexer,
                config.indexer_url(),
                None,
            )
            .unwrap(),
            gateway_client: ServiceClient::new(
                http_client,
                ServiceKind::Gateway,
                config.gateway_url(),
                None,
            )
            .unwrap(),
            config,
            packed_account_data: U256::from(1),
            signer: Signer::from_seed_bytes(&[1u8; 32]).unwrap(),
            registry: None,
            ws_connector: Connector::Plain,
            query_material: None,
            nullifier_material: None,
        };
        let sig_a = authenticator.danger_sign_challenge(b"challenge A").unwrap();
        let sig_b = authenticator.danger_sign_challenge(b"challenge B").unwrap();
        assert_ne!(sig_a, sig_b);
    }

    #[test]
    fn test_danger_sign_challenge_deterministic() {
        let config = Config::new(
            None,
            1,
            address!("0x0000000000000000000000000000000000000001"),
            "http://indexer.example.com".to_string(),
            "http://gateway.example.com".to_string(),
            Vec::new(),
            2,
        )
        .unwrap();
        let http_client = reqwest::Client::new();
        let authenticator = Authenticator {
            indexer_client: ServiceClient::new(
                http_client.clone(),
                ServiceKind::Indexer,
                config.indexer_url(),
                None,
            )
            .unwrap(),
            gateway_client: ServiceClient::new(
                http_client,
                ServiceKind::Gateway,
                config.gateway_url(),
                None,
            )
            .unwrap(),
            config,
            packed_account_data: U256::from(1),
            signer: Signer::from_seed_bytes(&[1u8; 32]).unwrap(),
            registry: None,
            ws_connector: Connector::Plain,
            query_material: None,
            nullifier_material: None,
        };
        let challenge = b"deterministic test";
        let sig1 = authenticator.danger_sign_challenge(challenge).unwrap();
        let sig2 = authenticator.danger_sign_challenge(challenge).unwrap();
        assert_eq!(sig1, sig2);
    }

    #[tokio::test]
    #[cfg(not(target_arch = "wasm32"))]
    async fn test_signing_nonce_from_indexer_error() {
        let mut server = mockito::Server::new_async().await;
        let indexer_url = server.url();
        let mock = server
            .mock("POST", "/signature-nonce")
            .with_status(400)
            .with_header("content-type", "application/json")
            .with_body(serde_json::json!({ "code": "invalid_leaf_index", "message": "Account index cannot be zero" }).to_string())
            .create_async()
            .await;
        let config = Config::new(
            None,
            1,
            address!("0x0000000000000000000000000000000000000001"),
            indexer_url,
            "http://gateway.example.com".to_string(),
            Vec::new(),
            2,
        )
        .unwrap();

        let http_client = reqwest::Client::new();
        let authenticator = Authenticator {
            config: config.clone(),
            packed_account_data: U256::ZERO,
            signer: Signer::from_seed_bytes(&[1u8; 32]).unwrap(),
            registry: None,
            indexer_client: ServiceClient::new(
                http_client.clone(),
                ServiceKind::Indexer,
                config.indexer_url(),
                None,
            )
            .unwrap(),
            gateway_client: ServiceClient::new(
                http_client,
                ServiceKind::Gateway,
                config.gateway_url(),
                None,
            )
            .unwrap(),
            ws_connector: Connector::Plain,
            query_material: None,
            nullifier_material: None,
        };
        let result = authenticator.signing_nonce().await;
        assert!(matches!(
            result,
            Err(AuthenticatorError::IndexerError { .. })
        ));
        mock.assert_async().await;
        drop(server);
    }

    #[test]
    fn test_authenticator_config_from_json_plain_config() {
        let json = serde_json::json!({
            "chain_id": 480,
            "registry_address": "0x0000000000000000000000000000000000000001",
            "indexer_url": "http://indexer.example.com",
            "gateway_url": "http://gateway.example.com",
            "nullifier_oracle_urls": [],
            "nullifier_oracle_threshold": 2
        });

        let config = AuthenticatorConfig::from_json(&json.to_string()).unwrap();
        assert!(config.ohttp_indexer.is_none());
        assert!(config.ohttp_gateway.is_none());
        assert_eq!(config.config.gateway_url(), "http://gateway.example.com");
    }

    #[test]
    fn test_authenticator_config_from_json_with_ohttp() {
        let json = serde_json::json!({
            "chain_id": 480,
            "registry_address": "0x0000000000000000000000000000000000000001",
            "indexer_url": "http://indexer.example.com",
            "gateway_url": "http://gateway.example.com",
            "nullifier_oracle_urls": [],
            "nullifier_oracle_threshold": 2,
            "ohttp_indexer": {
                "relay_url": "https://relay.example.com/gateway",
                "key_config_base64": "dGVzdC1rZXk="
            },
            "ohttp_gateway": {
                "relay_url": "https://relay.example.com/gateway",
                "key_config_base64": "dGVzdC1rZXk="
            }
        });

        let config = AuthenticatorConfig::from_json(&json.to_string()).unwrap();
        let ohttp_indexer = config.ohttp_indexer.unwrap();
        assert_eq!(ohttp_indexer.relay_url, "https://relay.example.com/gateway");
        assert_eq!(ohttp_indexer.key_config_base64, "dGVzdC1rZXk=");
        let ohttp_gateway = config.ohttp_gateway.unwrap();
        assert_eq!(ohttp_gateway.relay_url, "https://relay.example.com/gateway");
        assert_eq!(ohttp_gateway.key_config_base64, "dGVzdC1rZXk=");
    }
}