walletkit-core 0.21.4

Reference implementation for the World ID Protocol. Core functionality to use a World ID.
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
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
//! The Authenticator is the main component with which users interact with the World ID Protocol.

use crate::{
    authenticator::artifacts::WalletKitZkArtifactSource, defaults,
    error::WalletKitError, primitives::ParseFromForeignBinding, Environment,
    FieldElement, Region,
};
use alloy_core::primitives::Address;
use ruint::aliases::U256;
use ruint_uniffi::Uint256;
use std::sync::Arc;
use world_id_core::{
    api_types::{GatewayErrorCode, GatewayRequestId, GatewayRequestState},
    primitives::{AuthenticatorPublicKeySet, Config, MAX_AUTHENTICATOR_KEYS},
    Authenticator as CoreAuthenticator, AuthenticatorError,
    Credential as CoreCredential, CredentialInput, EdDSAPublicKey,
    InitializingAuthenticator as CoreInitializingAuthenticator,
    OnchainKeyRepresentable, Signer,
};

use crate::requests::{ProofRequest, ProofResponse};
use crate::storage::CredentialStore;
use crate::OwnershipProof;

pub mod artifacts;
mod with_storage;

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

impl Authenticator {
    /// Initializes a new Authenticator from a seed and an already-parsed
    /// [`Config`].
    ///
    /// # Errors
    /// See `CoreAuthenticator::init` for potential errors.
    pub async fn init_with_config(
        seed: &[u8],
        config: Config,
        artifacts: Arc<dyn WalletKitZkArtifactSource>,
        store: Arc<CredentialStore>,
    ) -> Result<Self, WalletKitError> {
        let authenticator = CoreAuthenticator::init(seed, config, artifacts).await?;

        Ok(Self {
            inner: authenticator,
            store,
        })
    }
}

fn parse_authenticator_pubkey(
    attribute: &str,
    encoded_pubkey: impl AsRef<str>,
) -> Result<EdDSAPublicKey, WalletKitError> {
    let encoded_pubkey = encoded_pubkey.as_ref();
    let invalid_input = |reason: String| WalletKitError::InvalidInput {
        attribute: attribute.to_string(),
        reason,
    };
    let hex = encoded_pubkey.strip_prefix("0x").ok_or_else(|| {
        invalid_input("Public key must start with a 0x prefix".to_string())
    })?;

    if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(invalid_input(
            "Public key must be exactly 32 bytes (64 hex characters) after the 0x prefix"
                .to_string(),
        ));
    }

    let encoded = U256::from_str_radix(hex, 16)
        .map_err(|error| invalid_input(error.to_string()))?;
    let pubkey = EdDSAPublicKey::from_compressed_bytes(encoded.to_le_bytes())
        .map_err(|error| invalid_input(error.to_string()))?;

    // `from_compressed_bytes` accepts the curve's neutral element and a
    // sign-bit alias of it. Empty key-set slots hash as the neutral element
    // on-chain (a slot holding it is commitment-indistinguishable from an
    // empty slot, and it is unusable for verification), so reject it and any
    // encoding that does not round-trip to the canonical form.
    let canonical = pubkey
        .to_ethereum_representation()
        .map_err(|error| invalid_input(error.to_string()))?;
    if canonical != encoded {
        return Err(invalid_input(
            "Public key is not the canonical compressed point encoding".to_string(),
        ));
    }
    if canonical == U256::from(1u64) {
        return Err(invalid_input(
            "Public key must not be the BabyJubJub identity point".to_string(),
        ));
    }

    Ok(pubkey)
}

#[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.
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "rpc_account_data",
        skip_all
    )]
    pub async fn get_packed_account_data_remote(
        &self,
    ) -> Result<Uint256, WalletKitError> {
        let packed_account_data = self.inner.fetch_packed_account_data().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.
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "oprf_blinding_factor",
        skip_all
    )]
    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()
    }

    /// Signs an arbitrary challenge with the authenticator's on-chain key.
    ///
    /// # 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`.
    ///
    /// # Errors
    /// May error if very unexpectedly the signing process fails. Not expected.
    #[allow(
        clippy::needless_pass_by_value,
        reason = "seed is passed by value so uniffi 0.32 maps it to a `RustBuffer` (Kotlin `ByteArray` / Swift `Data`) rather than the non-`Send` `ForeignBytes` view produced for `&[u8]`"
    )]
    pub fn danger_sign_challenge(
        &self,
        challenge: Vec<u8>,
    ) -> Result<Vec<u8>, WalletKitError> {
        let signature = self.inner.danger_sign_challenge(&challenge)?;
        Ok(signature.as_bytes().to_vec())
    }

    /// Signs the EIP-712 `InitiateRecoveryAgentUpdate` payload and returns the
    /// raw signature bytes and signing nonce without submitting anything to the
    /// gateway.
    ///
    /// Callers can use the returned bytes to build and submit the gateway
    /// request themselves.
    ///
    /// # Warning
    /// This method uses the `onchain_signer` (secp256k1 ECDSA) and produces a
    /// recoverable signature. Any holder of the signature together with the
    /// EIP-712 parameters can call `ecrecover` to obtain the `onchain_address`,
    /// which can then be looked up in the registry to derive the user's
    /// `leaf_index`. Only expose the output to trusted parties (e.g. a Recovery
    /// Agent).
    ///
    /// # Arguments
    /// * `new_recovery_agent` — the checksummed hex address of the new recovery
    ///   agent (e.g. `"0x1234…"`).
    ///
    /// # Errors
    /// - Returns [`WalletKitError::InvalidInput`] if `new_recovery_agent` is not
    ///   a valid address.
    /// - Returns an error if the nonce fetch or signing step fails.
    pub async fn danger_sign_initiate_recovery_agent_update(
        &self,
        new_recovery_agent: String,
    ) -> Result<RecoveryUpdateSignature, WalletKitError> {
        let new_recovery_agent =
            Address::parse_from_ffi(&new_recovery_agent, "new_recovery_agent")?;
        let (sig, nonce) = self
            .inner
            .danger_sign_initiate_recovery_agent_update(new_recovery_agent)
            .await?;
        Ok(RecoveryUpdateSignature {
            signature: sig.as_bytes().to_vec(),
            nonce: nonce.into(),
        })
    }

    /// Updates the holder's recovery agent (WIP-102).
    ///
    /// On a V2 registry the new agent becomes effective immediately, but for a
    /// revert window any authenticator can call
    /// [`Self::revert_recovery_agent_update`] to roll back. During that window
    /// the *previous* agent remains the only valid signer for `recoverAccount`,
    /// which mitigates a compromised authenticator silently swapping in an
    /// attacker-controlled recovery address.
    ///
    /// # Arguments
    /// * `new_recovery_agent` — the checksummed hex address of the new recovery
    ///   agent (e.g. `"0x1234…"`).
    ///
    /// # Errors
    /// - Returns [`WalletKitError::InvalidInput`] if `new_recovery_agent` is not
    ///   a valid address.
    /// - Returns a network error if the gateway request fails.
    pub async fn update_recovery_agent(
        &self,
        new_recovery_agent: String,
    ) -> Result<String, WalletKitError> {
        let new_recovery_agent =
            Address::parse_from_ffi(&new_recovery_agent, "new_recovery_agent")?;

        let request_id = self.inner.update_recovery_agent(new_recovery_agent).await?;

        Ok(request_id.to_string())
    }

    /// Reverts an in-flight recovery agent update during the revert window
    /// (WIP-102).
    ///
    /// Must be called within the revert window after
    /// [`Self::update_recovery_agent`]. During that window any authenticator
    /// can revert the update; the previous recovery agent stays effective
    /// until the window expires.
    ///
    /// Signs an EIP-712 `CancelRecoveryAgentUpdate` payload (the typehash is
    /// reused on V2) and submits it to the gateway.
    ///
    /// # Errors
    /// Returns a network error if the gateway request fails.
    pub async fn revert_recovery_agent_update(&self) -> Result<String, WalletKitError> {
        let request_id = self.inner.revert_recovery_agent_update().await?;

        Ok(request_id.to_string())
    }

    /// Inserts an authenticator into the holder's World ID account.
    ///
    /// # Arguments
    /// * `new_authenticator_pubkey` — a compressed `BabyJubJub` public key encoded
    ///   as a `0x`-prefixed, zero-padded 32-byte hex string.
    /// * `new_authenticator_address` — the Ethereum address associated with the
    ///   new authenticator. Callers may pass the zero address for a proving-only
    ///   authenticator.
    ///
    /// # Errors
    /// - Returns [`WalletKitError::InvalidInput`] if the public key or address is
    ///   invalid.
    /// - Returns a network error if an indexer or gateway request fails.
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "gateway_insert_authenticator",
        skip_all
    )]
    pub async fn insert_authenticator(
        &self,
        new_authenticator_pubkey: String,
        new_authenticator_address: String,
    ) -> Result<String, WalletKitError> {
        let new_authenticator_pubkey = parse_authenticator_pubkey(
            "new_authenticator_pubkey",
            new_authenticator_pubkey,
        )?;
        let new_authenticator_address = Address::parse_from_ffi(
            &new_authenticator_address,
            "new_authenticator_address",
        )?;

        let request_id = self
            .inner
            .insert_authenticator(new_authenticator_pubkey, new_authenticator_address)
            .await?;

        Ok(request_id.to_string())
    }

    /// Returns whether the holder's account already contains an authenticator
    /// public key.
    ///
    /// This performs a read-only indexer fetch and does not submit an account
    /// operation.
    ///
    /// # Arguments
    /// * `authenticator_pubkey` — a compressed `BabyJubJub` public key encoded
    ///   as a `0x`-prefixed, zero-padded 32-byte hex string.
    ///
    /// # Errors
    /// - Returns [`WalletKitError::InvalidInput`] if the public key is invalid.
    /// - Returns a network error if the indexer request fails.
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "indexer_authenticator_pubkeys",
        skip_all
    )]
    pub async fn has_authenticator_pubkey(
        &self,
        authenticator_pubkey: String,
    ) -> Result<bool, WalletKitError> {
        let authenticator_pubkey =
            parse_authenticator_pubkey("authenticator_pubkey", authenticator_pubkey)?;
        let pubkeys = self.inner.fetch_authenticator_pubkeys().await?;
        Ok(pubkeys
            .iter()
            .flatten()
            .any(|existing_pubkey| existing_pubkey == &authenticator_pubkey))
    }

    /// Returns the account's authenticator public keys, indexed by key-set slot.
    ///
    /// Each entry is the compressed `BabyJubJub` public key at that slot encoded
    /// as a `0x`-prefixed, zero-padded 32-byte hex string, or `None` for an
    /// empty slot. A key's position in this list is the `pubkey_id` expected by
    /// [`Self::remove_authenticator`].
    ///
    /// This performs a read-only indexer fetch and does not submit an account
    /// operation.
    ///
    /// # Errors
    /// - Returns a network error if the indexer request fails.
    /// - Returns an error if a stored public key cannot be encoded.
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "indexer_authenticator_pubkeys",
        skip_all
    )]
    pub async fn get_authenticator_pubkeys(
        &self,
    ) -> Result<Vec<Option<String>>, WalletKitError> {
        let key_set = self.inner.fetch_authenticator_pubkeys().await?;
        key_set
            .iter()
            .map(|slot| {
                slot.as_ref()
                    .map(|pubkey| {
                        let encoded = pubkey.to_ethereum_representation()?;
                        Ok(format!("{encoded:#066x}"))
                    })
                    .transpose()
            })
            .collect()
    }

    /// Removes an authenticator from the holder's World ID account.
    ///
    /// # Arguments
    /// * `authenticator_address` — the Ethereum address associated with the
    ///   authenticator being removed. Callers must pass the zero address for a
    ///   proving-only authenticator.
    /// * `pubkey_id` — the stable key-set slot of the authenticator being removed.
    /// * `expected_authenticator_pubkey` — the compressed `BabyJubJub` public key
    ///   the caller intends to remove, encoded as a `0x`-prefixed, zero-padded
    ///   32-byte hex string. The removal is refused if `pubkey_id` currently
    ///   holds a different key, catching callers acting on a stale key-set view
    ///   (see [`Self::get_authenticator_pubkeys`]). This check is best-effort:
    ///   the signing flow re-reads the key set afterwards, so a concurrent
    ///   change to the slot between the check and that read can still remove
    ///   whichever key the slot holds at signing time. Callers that need an
    ///   exact-target guarantee must serialize account operations across the
    ///   account's authenticators.
    ///
    /// # Errors
    /// - Returns [`WalletKitError::InvalidInput`] if the address or public key
    ///   is invalid, if `pubkey_id` is out of range, if the slot is empty, or
    ///   if the slot holds a different key.
    /// - Returns a network error if an indexer or gateway request fails.
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "gateway_remove_authenticator",
        skip_all
    )]
    pub async fn remove_authenticator(
        &self,
        authenticator_address: String,
        pubkey_id: u32,
        expected_authenticator_pubkey: String,
    ) -> Result<String, WalletKitError> {
        let expected_pubkey = parse_authenticator_pubkey(
            "expected_authenticator_pubkey",
            expected_authenticator_pubkey,
        )?;
        let authenticator_address =
            Address::parse_from_ffi(&authenticator_address, "authenticator_address")?;

        if pubkey_id as usize >= MAX_AUTHENTICATOR_KEYS {
            return Err(WalletKitError::InvalidInput {
                attribute: "pubkey_id".to_string(),
                reason: format!(
                    "pubkey_id {pubkey_id} is out of range; the key set has at \
                     most {MAX_AUTHENTICATOR_KEYS} slots"
                ),
            });
        }

        let empty_slot = || WalletKitError::InvalidInput {
            attribute: "pubkey_id".to_string(),
            reason: format!("no authenticator at key set slot {pubkey_id}"),
        };
        let key_set = self.inner.fetch_authenticator_pubkeys().await?;
        let actual_pubkey = key_set.get(pubkey_id as usize).ok_or_else(empty_slot)?;
        if actual_pubkey != &expected_pubkey {
            return Err(WalletKitError::InvalidInput {
                attribute: "expected_authenticator_pubkey".to_string(),
                reason: format!(
                    "key set slot {pubkey_id} holds a different authenticator public key"
                ),
            });
        }

        let request_id = self
            .inner
            .remove_authenticator(authenticator_address, pubkey_id)
            .await
            .map_err(|error| match error {
                // The slot emptied between the check above and the crate's own
                // signing read; report it as the input problem it is rather
                // than an authorization failure.
                AuthenticatorError::PublicKeyNotFound => empty_slot(),
                other => other.into(),
            })?;

        Ok(request_id.to_string())
    }

    /// Polls the gateway once for the status of an account operation.
    ///
    /// # Errors
    /// Returns a network error if the gateway request fails.
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "gateway_poll",
        skip_all
    )]
    pub async fn poll_status(
        &self,
        request_id: String,
    ) -> Result<GatewayRequestStatus, WalletKitError> {
        let request_id = GatewayRequestId::new(
            request_id.strip_prefix("gw_").unwrap_or(&request_id),
        );
        let status = self.inner.poll_status(&request_id).await?;
        Ok(status.into())
    }
}

#[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]
    #[tracing::instrument(target = "walletkit_latency", name = "rpc_init", skip_all)]
    pub async fn init_with_defaults(
        seed: Vec<u8>,
        rpc_url: Option<String>,
        environment: &Environment,
        region: Option<Region>,
        artifacts: Arc<dyn WalletKitZkArtifactSource>,
        store: Arc<CredentialStore>,
    ) -> Result<Self, WalletKitError> {
        let config = defaults::default_config(environment, rpc_url, region)?;
        Self::init_with_config(&seed, config, artifacts, store).await
    }

    /// Initializes a new Authenticator from a seed using SDK defaults routed
    /// through the OHTTP relay. Opt-in alternative to
    /// [`Authenticator::init_with_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]
    #[tracing::instrument(target = "walletkit_latency", name = "rpc_init", skip_all)]
    pub async fn init_with_ohttp_defaults(
        seed: Vec<u8>,
        rpc_url: Option<String>,
        environment: &Environment,
        region: Option<Region>,
        artifacts: Arc<dyn WalletKitZkArtifactSource>,
        store: Arc<CredentialStore>,
    ) -> Result<Self, WalletKitError> {
        let config = defaults::default_config_with_ohttp(environment, rpc_url, region)?;
        Self::init_with_config(&seed, config, artifacts, store).await
    }

    /// 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]
    #[tracing::instrument(target = "walletkit_latency", name = "rpc_init", skip_all)]
    pub async fn init(
        seed: Vec<u8>,
        config: &str,
        artifacts: Arc<dyn WalletKitZkArtifactSource>,
        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(),
            })?;
        Self::init_with_config(&seed, config, artifacts, store).await
    }

    /// 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 {
            #[cfg(target_arch = "wasm32")]
            {
                return Err(WalletKitError::InvalidInput {
                    attribute: "now".to_string(),
                    reason: "`now` must be provided on wasm32 targets".to_string(),
                });
            }

            #[cfg(not(target_arch = "wasm32"))]
            {
                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()
            }
        };

        // Build CredentialInput list from storage
        // Note: We simply load all non-expired credentials. Filtering for the requested schema IDs is done in `generate_proof`.
        // We could avoid unnecessary loading by filtering via `world_id_primitives::ProofRequest::credentials_to_prove`. We consider this an
        // unnecessary optimization for now.
        let credentials: Vec<_> = self
            .store
            .list_credentials(None, now)?
            .iter()
            .filter(|c| !c.is_expired)
            .filter_map(|cred| {
                if let Ok(Some((credential, blinding_factor))) =
                    self.store.get_credential(cred.issuer_schema_id, now)
                {
                    Some(CredentialInput {
                        credential: credential.into(),
                        blinding_factor: blinding_factor.into(),
                    })
                } else {
                    tracing::warn!(
                        issuer_schema_id = %cred.issuer_schema_id,
                        credential_id = %cred.credential_id,
                        "credential listed but not loadable, skipping"
                    );
                    None
                }
            })
            .collect();

        let account_inclusion_proof =
            self.fetch_inclusion_proof_with_cache(now).await?;

        // Generate the nullifier and check the replay guard
        // Box::pin to heap-allocate the large upstream futures and keep this future below clippy::large_futures threshold
        let nullifier = Box::pin(self.inner.generate_nullifier(
            &proof_request.0,
            now,
            Some(account_inclusion_proof.clone()),
        ))
        .await?;

        if self
            .store
            .is_nullifier_replay(nullifier.verifiable_oprf_output.output.into(), now)?
        {
            return Err(WalletKitError::NullifierReplay);
        }

        // Get cached `session_id_r_seed` if session ID is provided in the proof request
        let session_id_r_seed =
            proof_request
                .0
                .session_id
                .existing()
                .and_then(|session_id| {
                    match self.store.get_session_seed(session_id.oprf_seed, now) {
                        Ok(seed) => seed,
                        Err(err) => {
                            tracing::warn!(error = %err, "failed to load cached session seed, continuing without");
                            None
                        }
                    }
                });

        // Handles credential selection, session resolution, per-credential proofs, response assembly, and validation
        let result = Box::pin(self.inner.generate_proof(
            &proof_request.0,
            nullifier.clone(),
            &credentials,
            Some(account_inclusion_proof),
            session_id_r_seed,
        ))
        .await?;

        // Cache session seed if returned. Create-session requests do not carry a
        // session_id, so use the session_id generated in the proof response.
        if let Some(seed) = result.session_id_r_seed {
            if let Some(session_id) = result.proof_response.session_id {
                if let Err(err) =
                    self.store
                        .store_session_seed(session_id.oprf_seed, seed, now)
                {
                    tracing::error!("error caching session_id_r_seed: {}", err);
                }
            }
        }

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

        Ok(result.proof_response.into())
    }

    /// Generates a WIP-103 Ownership Proof for Issuers.
    ///
    /// An Ownership Proof lets the user prove they own the credential `sub`
    /// associated with a stored credential without revealing their `leaf_index`.
    ///
    /// # Security-critical usage constraint
    /// This method **MUST only** be called as part of a direct
    /// **user-initiated** action in the client. Callers **MUST NOT** expose this
    /// method to issuer-triggered, backend-triggered, or unauthenticated request
    /// flows.
    ///
    /// # Arguments
    /// * `nonce` - A field element provided by the Issuer to prevent replay.
    /// * `context` - A field element identifying the issuer operation being authorized.
    /// * `blinding_factor` - The credential blinding factor previously used to
    ///   derive the credential `sub`.
    /// * `sub` - The credential `sub` (commitment) to prove ownership of.
    ///
    /// # Errors
    /// - Returns [`WalletKitError::InvalidInput`] if `blinding_factor` and
    ///   `sub` are inconsistent with each other (i.e. `sub` was not derived
    ///   from this authenticator's leaf index and the provided blinding factor).
    /// - Returns a network error if the Merkle inclusion proof cannot be
    ///   fetched from the indexer.
    /// - Returns [`WalletKitError::ProofGeneration`] if the ZK proof fails.
    pub async fn prove_credential_sub(
        &self,
        nonce: &FieldElement,
        context: &FieldElement,
        blinding_factor: &FieldElement,
        sub: &FieldElement,
    ) -> Result<OwnershipProof, WalletKitError> {
        #[cfg(target_arch = "wasm32")]
        {
            let _ = (nonce, context, blinding_factor, sub);
            return Err(WalletKitError::Generic {
                error: "credential ownership proofs are not supported on wasm32"
                    .to_string(),
            });
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_err(|e| WalletKitError::Generic {
                    error: format!("Critical. Unable to determine SystemTime: {e}"),
                })?
                .as_secs();

            let inclusion_proof = self.fetch_inclusion_proof_with_cache(now).await?;
            let proof = self
                .inner
                .prove_credential_sub(
                    nonce.0,
                    context.0,
                    blinding_factor.0,
                    sub.0,
                    Some(inclusion_proof),
                )
                .await?;

            Ok(OwnershipProof(proof))
        }
    }
}

/// 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>,
    },
}

/// Status of an account operation submitted through the gateway.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
pub enum GatewayRequestStatus {
    /// Request queued but not yet batched.
    Queued,
    /// Request currently being batched.
    Batching,
    /// Request submitted on-chain.
    Submitted {
        /// Transaction hash emitted when the request was submitted.
        tx_hash: String,
    },
    /// Request finalized on-chain.
    Finalized {
        /// Transaction hash emitted when the request was finalized.
        tx_hash: String,
    },
    /// 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 GatewayRequestStatus {
    fn from(state: GatewayRequestState) -> Self {
        match state {
            GatewayRequestState::Queued => Self::Queued,
            GatewayRequestState::Batching => Self::Batching,
            GatewayRequestState::Submitted { tx_hash } => Self::Submitted { tx_hash },
            GatewayRequestState::Finalized { tx_hash } => Self::Finalized { tx_hash },
            GatewayRequestState::Failed { error, error_code } => Self::Failed {
                error,
                error_code: error_code.map(|code| code.to_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]
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "gateway_register",
        skip_all
    )]
    pub async fn register_with_defaults(
        seed: Vec<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 = defaults::default_config(environment, rpc_url, region)?;

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

        Ok(Self(initializing_authenticator))
    }

    /// Registers a new World ID using SDK defaults routed through the OHTTP
    /// relay. Opt-in alternative to
    /// [`InitializingAuthenticator::register_with_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]
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "gateway_register",
        skip_all
    )]
    pub async fn register_with_ohttp_defaults(
        seed: Vec<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 = defaults::default_config_with_ohttp(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]
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "gateway_register",
        skip_all
    )]
    pub async fn register(
        seed: Vec<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.
    #[tracing::instrument(
        target = "walletkit_latency",
        name = "gateway_poll",
        skip_all
    )]
    pub async fn poll_status(&self) -> Result<RegistrationStatus, WalletKitError> {
        let status = self.0.poll_status().await?;
        Ok(status.into())
    }
}

/// The signature and signing nonce returned by
/// [`Authenticator::danger_sign_initiate_recovery_agent_update`].
///
/// `UniFFI` does not support returning bare tuples across the FFI boundary, so
/// the two values are bundled in this record type.
#[derive(Debug, Clone, uniffi::Record)]
pub struct RecoveryUpdateSignature {
    /// Raw bytes of the secp256k1 ECDSA signature over the EIP-712
    /// `InitiateRecoveryAgentUpdate` payload.
    pub signature: Vec<u8>,
    /// The EIP-712 signing nonce that was used; must be included in the
    /// gateway request alongside the signature.
    pub nonce: Uint256,
}

/// Identity material derived from a seed for use during account recovery.
///
/// During account recovery the user generates new keys from a seed, but those
/// keys do not yet exist on-chain. The three values in this record must be
/// submitted on-chain during the recovery transaction.
///
/// All fields are hex-encoded strings suitable for direct use in API requests.
#[derive(Debug, Clone, uniffi::Record)]
pub struct RecoveryData {
    /// Checksummed hex Ethereum address of the on-chain signer.
    pub authenticator_address: String,
    /// Hex-encoded U256 compressed `EdDSA` public key of the off-chain signer.
    pub authenticator_pubkey: String,
    /// Hex-encoded U256 Poseidon2 hash commitment over the authenticator key set.
    pub offchain_signer_commitment: String,
}

impl RecoveryData {
    /// Derives recovery identity material from a 32-byte seed.
    ///
    /// These values must be submitted on-chain as part of the recovery
    /// transaction before the recovered account can be initialised with
    /// [`Authenticator::init`] / [`Authenticator::init_with_defaults`].
    ///
    /// # Errors
    /// Returns [`WalletKitError`] if the seed is invalid or serialization fails.
    pub fn from_seed(seed: &[u8]) -> Result<Self, WalletKitError> {
        let signer = Signer::from_seed_bytes(seed)?;
        let authenticator_address = signer.onchain_signer_address().to_checksum(None);
        let authenticator_pubkey: U256 = signer
            .offchain_signer_pubkey()
            .to_ethereum_representation()?;
        let mut key_set = AuthenticatorPublicKeySet::default();
        key_set.try_push(signer.offchain_signer_pubkey())?;
        let offchain_signer_commitment: U256 = key_set.leaf_hash().into();

        Ok(Self {
            authenticator_address,
            authenticator_pubkey: format!("{authenticator_pubkey:#066x}"),
            offchain_signer_commitment: format!("{offchain_signer_commitment:#066x}"),
        })
    }
}

/// Validates an authenticator public key without submitting an account
/// operation, returning its canonical encoding.
///
/// This is a free function (not a method on [`Authenticator`]) so consumers
/// can validate a key — e.g. one scanned during pairing — before an
/// `Authenticator` exists.
///
/// The returned string is the canonical form of the key (lowercase,
/// `0x`-prefixed, zero-padded 32-byte hex), byte-identical to the entries
/// returned by [`Authenticator::get_authenticator_pubkeys`]. Use it — not the
/// raw input — for string comparisons against key-set entries.
///
/// # Arguments
/// * `authenticator_pubkey` — a compressed `BabyJubJub` public key encoded
///   as a `0x`-prefixed, zero-padded 32-byte hex string.
///
/// # Errors
/// Returns [`WalletKitError::InvalidInput`] if the public key is invalid,
/// is not in canonical form, or is the `BabyJubJub` identity point.
#[uniffi::export]
pub fn validate_authenticator_pubkey(
    authenticator_pubkey: &str,
) -> Result<String, WalletKitError> {
    let pubkey =
        parse_authenticator_pubkey("authenticator_pubkey", authenticator_pubkey)?;
    let encoded = pubkey.to_ethereum_representation()?;
    Ok(format!("{encoded:#066x}"))
}

/// Derives recovery data from a 32-byte seed.
///
/// This is the foreign-bindings entrypoint for recovery data generation.
///
/// # Errors
/// Returns [`WalletKitError`] if the seed is invalid or serialization fails.
#[uniffi::export]
#[allow(
    clippy::needless_pass_by_value,
    reason = "seed is passed by value so uniffi 0.32 maps it to a `RustBuffer` (Kotlin `ByteArray` / Swift `Data`) rather than the non-`Send` `ForeignBytes` view produced for `&[u8]`"
)]
pub fn recovery_data_from_seed(seed: Vec<u8>) -> Result<RecoveryData, WalletKitError> {
    RecoveryData::from_seed(&seed)
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEST_SEED: [u8; 32] = [1u8; 32];

    async fn test_authenticator(
        server: &mut mockito::Server,
    ) -> (Authenticator, std::path::PathBuf) {
        use crate::storage::tests_utils::{temp_root_path, InMemoryStorageProvider};
        use alloy::primitives::address;
        use world_id_core::primitives::ServiceEndpoint;
        use world_id_proof::artifacts::dummy::DummyZkArtifactSource;

        let _ = rustls::crypto::ring::default_provider().install_default();

        let packed_account_mock = server
            .mock("POST", "/packed-account")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(serde_json::json!({ "packed_account_data": "0x2a" }).to_string())
            .create_async()
            .await;
        let config = Config::new(
            None,
            480,
            address!("0x969947cFED008bFb5e3F32a25A1A2CDdf64d46fe"),
            ServiceEndpoint::direct(server.url()),
            ServiceEndpoint::direct(server.url()),
            vec![],
            2,
        )
        .expect("valid config");
        let root = temp_root_path();
        let provider = InMemoryStorageProvider::new(&root);
        let store =
            CredentialStore::from_provider(&provider).expect("credential store");
        let authenticator = Authenticator::init_with_config(
            &TEST_SEED,
            config,
            Arc::new(DummyZkArtifactSource),
            Arc::new(store),
        )
        .await
        .expect("authenticator should initialize");
        packed_account_mock.assert_async().await;

        (authenticator, root)
    }

    fn encoded_pubkey(seed: &[u8; 32]) -> String {
        let pubkey = Signer::from_seed_bytes(seed)
            .expect("valid seed")
            .offchain_signer_pubkey()
            .to_ethereum_representation()
            .expect("public key should encode");
        format!("{pubkey:#066x}")
    }

    /// Mocks the indexer's `/authenticator-pubkeys` endpoint with a fixed
    /// key-set response (`None` entries are empty slots), asserting the
    /// request body and the expected number of hits.
    async fn mock_authenticator_pubkeys(
        server: &mut mockito::Server,
        pubkeys: &[Option<&str>],
        expected_hits: usize,
    ) -> mockito::Mock {
        server
            .mock("POST", "/authenticator-pubkeys")
            .match_body(mockito::Matcher::JsonString(
                serde_json::json!({ "leaf_index": "0x2a" }).to_string(),
            ))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "authenticator_pubkeys": pubkeys,
                    "offchain_signer_commitment": "0x0"
                })
                .to_string(),
            )
            .expect(expected_hits)
            .create_async()
            .await
    }

    #[test]
    fn test_recovery_data_from_seed() {
        let seed = [1u8; 32];
        let material = RecoveryData::from_seed(&seed).expect("should derive material");

        assert!(material.authenticator_address.starts_with("0x"));
        assert_eq!(material.authenticator_address.len(), 42);
        assert!(material.authenticator_pubkey.starts_with("0x"));
        assert!(material.authenticator_pubkey.len() <= 66);
        assert!(material.offchain_signer_commitment.starts_with("0x"));
        assert!(material.offchain_signer_commitment.len() <= 66);
        assert!(material.authenticator_address.len() > 2);
        assert!(material.authenticator_pubkey.len() > 2);
        assert!(material.offchain_signer_commitment.len() > 2);
    }

    #[test]
    fn test_recovery_data_rejects_invalid_seed() {
        assert!(RecoveryData::from_seed(&[0u8; 16]).is_err());
        assert!(RecoveryData::from_seed(&[]).is_err());
    }

    #[test]
    fn test_authenticator_pubkey_validation() {
        let canonical = encoded_pubkey(&[2u8; 32]);
        assert_eq!(
            validate_authenticator_pubkey(&canonical).expect("valid key"),
            canonical
        );
        let uppercase = format!("0x{}", canonical[2..].to_uppercase());
        assert_eq!(
            validate_authenticator_pubkey(&uppercase)
                .expect("uppercase hex should canonicalize"),
            canonical
        );

        for invalid_pubkey in [
            "not-a-public-key".to_string(),
            format!("0x{}", "ff".repeat(32)),
        ] {
            assert!(matches!(
                validate_authenticator_pubkey(&invalid_pubkey),
                Err(WalletKitError::InvalidInput { attribute, .. })
                    if attribute == "authenticator_pubkey"
            ));
        }

        let identity = format!("0x{}01", "0".repeat(62));
        assert!(matches!(
            validate_authenticator_pubkey(&identity),
            Err(WalletKitError::InvalidInput { attribute, reason })
                if attribute == "authenticator_pubkey" && reason.contains("identity")
        ));
        let sign_bit_alias = format!("0x80{}01", "0".repeat(60));
        assert!(matches!(
            validate_authenticator_pubkey(&sign_bit_alias),
            Err(WalletKitError::InvalidInput { attribute, reason })
                if attribute == "authenticator_pubkey" && reason.contains("canonical")
        ));
    }

    #[tokio::test]
    async fn test_poll_status_normalizes_request_id() {
        use crate::storage::tests_utils::cleanup_test_storage;

        let mut server = mockito::Server::new_async().await;
        let (authenticator, root) = test_authenticator(&mut server).await;
        let status_mock = server
            .mock("GET", "/status/gw_poll_test")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                serde_json::json!({
                    "request_id": "gw_poll_test",
                    "kind": "insert_authenticator",
                    "status": {
                        "state": "finalized",
                        "tx_hash": "0x1234"
                    }
                })
                .to_string(),
            )
            .expect(2)
            .create_async()
            .await;

        for request_id in ["poll_test", "gw_poll_test"] {
            assert_eq!(
                authenticator
                    .poll_status(request_id.to_string())
                    .await
                    .expect("status poll should succeed"),
                GatewayRequestStatus::Finalized {
                    tx_hash: "0x1234".to_string()
                }
            );
        }
        status_mock.assert_async().await;

        drop(server);
        cleanup_test_storage(&root);
    }

    #[tokio::test]
    async fn test_remove_authenticator_refuses_unexpected_slot_contents() {
        use crate::storage::tests_utils::cleanup_test_storage;

        let mut server = mockito::Server::new_async().await;
        let (authenticator, root) = test_authenticator(&mut server).await;
        let existing_pubkey = encoded_pubkey(&TEST_SEED);
        let slot_pubkey = encoded_pubkey(&[2u8; 32]);

        let pubkeys_mock = mock_authenticator_pubkeys(
            &mut server,
            &[
                Some(existing_pubkey.as_str()),
                None,
                Some(slot_pubkey.as_str()),
            ],
            2,
        )
        .await;
        let nonce_mock = server
            .mock("POST", "/signature-nonce")
            .expect(0)
            .create_async()
            .await;
        let remove_mock = server
            .mock("POST", "/remove-authenticator")
            .expect(0)
            .create_async()
            .await;

        let mismatched = authenticator
            .remove_authenticator(
                Address::ZERO.to_string(),
                2,
                encoded_pubkey(&[3u8; 32]),
            )
            .await;
        assert!(matches!(
            mismatched,
            Err(WalletKitError::InvalidInput { attribute, .. })
                if attribute == "expected_authenticator_pubkey"
        ));

        let empty_slot = authenticator
            .remove_authenticator(
                Address::ZERO.to_string(),
                1,
                encoded_pubkey(&[3u8; 32]),
            )
            .await;
        assert!(matches!(
            empty_slot,
            Err(WalletKitError::InvalidInput { attribute, reason })
                if attribute == "pubkey_id"
                    && reason.contains("no authenticator at key set slot 1")
        ));

        let out_of_range = authenticator
            .remove_authenticator(
                Address::ZERO.to_string(),
                7,
                encoded_pubkey(&[3u8; 32]),
            )
            .await;
        assert!(matches!(
            out_of_range,
            Err(WalletKitError::InvalidInput { attribute, reason })
                if attribute == "pubkey_id" && reason.contains("out of range")
        ));

        pubkeys_mock.assert_async().await;
        nonce_mock.assert_async().await;
        remove_mock.assert_async().await;

        drop(server);
        cleanup_test_storage(&root);
    }

    #[tokio::test]
    async fn test_key_set_reads_return_slots_and_membership() {
        use crate::storage::tests_utils::cleanup_test_storage;

        let mut server = mockito::Server::new_async().await;
        let (authenticator, root) = test_authenticator(&mut server).await;
        let existing_pubkey = encoded_pubkey(&TEST_SEED);
        let other_pubkey = encoded_pubkey(&[2u8; 32]);

        let pubkeys_mock = mock_authenticator_pubkeys(
            &mut server,
            &[
                Some(existing_pubkey.as_str()),
                None,
                Some(other_pubkey.as_str()),
            ],
            3,
        )
        .await;

        assert!(authenticator
            .has_authenticator_pubkey(existing_pubkey.clone())
            .await
            .expect("membership read should succeed"));
        assert!(!authenticator
            .has_authenticator_pubkey(encoded_pubkey(&[3u8; 32]))
            .await
            .expect("absent key check should succeed"));
        assert_eq!(
            authenticator
                .get_authenticator_pubkeys()
                .await
                .expect("key set read should succeed"),
            vec![Some(existing_pubkey), None, Some(other_pubkey)]
        );
        pubkeys_mock.assert_async().await;

        drop(server);
        cleanup_test_storage(&root);
    }

    #[tokio::test]
    async fn test_remove_authenticator_reports_slot_emptied_during_signing() {
        use crate::storage::tests_utils::cleanup_test_storage;
        use std::sync::atomic::{AtomicUsize, Ordering};

        let mut server = mockito::Server::new_async().await;
        let (authenticator, root) = test_authenticator(&mut server).await;
        let existing_pubkey = encoded_pubkey(&TEST_SEED);
        let removed_pubkey = encoded_pubkey(&[2u8; 32]);

        // The first read (the wrapper's guard) sees the key at slot 1; the
        // second read (the crate's own signing fetch) sees the slot already
        // emptied, as if a concurrent operation landed in between. The
        // `PublicKeyNotFound` this produces must surface as the `pubkey_id`
        // input error, not as an authorization failure.
        let full_body = serde_json::json!({
            "authenticator_pubkeys": [existing_pubkey.clone(), removed_pubkey.clone()],
            "offchain_signer_commitment": "0x0"
        })
        .to_string();
        let emptied_body = serde_json::json!({
            "authenticator_pubkeys": [existing_pubkey],
            "offchain_signer_commitment": "0x0"
        })
        .to_string();
        let fetches = Arc::new(AtomicUsize::new(0));
        let fetches_in_mock = Arc::clone(&fetches);
        let pubkeys_mock = server
            .mock("POST", "/authenticator-pubkeys")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body_from_request(move |_request| {
                if fetches_in_mock.fetch_add(1, Ordering::SeqCst) == 0 {
                    full_body.clone().into_bytes()
                } else {
                    emptied_body.clone().into_bytes()
                }
            })
            .expect(2)
            .create_async()
            .await;
        let nonce_mock = server
            .mock("POST", "/signature-nonce")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(serde_json::json!({ "signature_nonce": "0x1" }).to_string())
            .create_async()
            .await;
        let remove_mock = server
            .mock("POST", "/remove-authenticator")
            .expect(0)
            .create_async()
            .await;

        let raced = authenticator
            .remove_authenticator(Address::ZERO.to_string(), 1, removed_pubkey)
            .await;
        assert!(matches!(
            raced,
            Err(WalletKitError::InvalidInput { attribute, .. })
                if attribute == "pubkey_id"
        ));

        pubkeys_mock.assert_async().await;
        nonce_mock.assert_async().await;
        remove_mock.assert_async().await;

        drop(server);
        cleanup_test_storage(&root);
    }

    #[cfg(feature = "embed-zkeys")]
    #[tokio::test]
    async fn test_init_with_config_and_materials() {
        use crate::{
            authenticator::artifacts::caching::CachingZkArtifacts,
            storage::tests_utils::{
                cleanup_test_storage, temp_root_path, InMemoryStorageProvider,
            },
        };
        use alloy::primitives::address;
        use world_id_core::primitives::{Config, ServiceEndpoint};

        let _ = rustls::crypto::ring::default_provider().install_default();

        let mut mock_server = mockito::Server::new_async().await;
        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 config = Config::new(
            Some(mock_server.url()),
            480,
            address!("0x969947cFED008bFb5e3F32a25A1A2CDdf64d46fe"),
            ServiceEndpoint::direct(
                "https://indexer.us.id-infra.worldcoin.dev".to_string(),
            ),
            ServiceEndpoint::direct(
                "https://gateway.id-infra.worldcoin.dev".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");

        let artifacts =
            Arc::new(CachingZkArtifacts::new(Arc::new(store.paths().unwrap())));

        let _authenticator = Authenticator::init(
            [2u8; 32].to_vec(),
            &config,
            artifacts,
            Arc::new(store),
        )
        .await
        .unwrap();
        drop(mock_server);

        cleanup_test_storage(&root);
    }
}