world-id-primitives 0.9.0

Contains the raw base primitives (without implementations) for the World ID Protocol.
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
use crate::{FieldElement, PrimitiveError};
use embed_doc_image::embed_doc_image;
use ruint::aliases::U256;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};

#[expect(unused_imports, reason = "used in doc comments")]
use crate::circuit_inputs::QueryProofCircuitInput;

/// Type of field elements for Session Proofs
#[repr(u8)]
pub enum SessionFeType {
    /// The [`SessionId::oprf_seed`]
    OprfSeed = 0x01,
    /// The action used to compute the inner nullifier (in a [`SessionNullifier`]) for a Session Proof.
    Action = 0x02,
}

/// Allows field element generation for Session Proofs
pub trait SessionFieldElement {
    /// Generate a randomized field element with a specific prefix used
    /// only for Session Proofs. See [`SessionFeType`] for details.
    fn random_for_session<R: rand::CryptoRng + rand::RngCore>(
        rng: &mut R,
        element_type: SessionFeType,
    ) -> FieldElement;
    /// Returns whether a Field Element is valid for Session Proof use, i.e. it has
    /// the right prefix
    fn is_valid_for_session(&self, element_type: SessionFeType) -> bool;
}

impl SessionFieldElement for FieldElement {
    fn random_for_session<R: rand::CryptoRng + rand::RngCore>(
        rng: &mut R,
        element_type: SessionFeType,
    ) -> FieldElement {
        let mut bytes = [0u8; 32];
        rng.fill_bytes(&mut bytes);
        bytes[0] = element_type as u8;
        let seed = U256::from_be_bytes(bytes);
        Self::try_from(seed).expect(
            "should always fit in the field because with 0x01 as the MSB, the field element < babyjubjub modulus",
        )
    }

    fn is_valid_for_session(&self, element_type: SessionFeType) -> bool {
        self.to_be_bytes()[0] == element_type as u8
    }
}

/// An identifier for a session (can be re-used).
///
/// A session allows RPs to ensure that it's still the same World ID
/// interacting with them across multiple interactions.
///
/// A `SessionId` is obtained after creating an initial session.
///
/// See the diagram below on how Session Proofs work, the [`SessionId`] and the `r` seed
/// ![Session Proofs Diagram][session-proofs.png]
///
/// Note that the `action` stored here is unrelated to the randomized action used
/// internally by [`SessionNullifier`]s — that randomized action exists only to ensure
/// the circuit's nullifier output is unique per Session Proof.
#[embed_doc_image("session-proofs.png", "assets/session-proofs.png")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SessionId {
    /// The actual commitment being verified in the ZK-circuit.
    ///
    /// It is computed as H(DS_C || leaf_index || session_id_r_seed), see
    /// `signal computed_id_commitment` in `oprf_nullifier.circom`.
    pub commitment: FieldElement,
    /// A random seed generated by the authenticator in the initial Uniqueness Proof.
    ///
    /// This seed is the input to the OPRF Query to derive `session_id_r_seed` (`r`). It
    /// is part of the `session_id` so the RP can provide it when requesting a Session Proof.
    ///
    /// # Important: Prefix
    /// To ensure there are no collisions between the generated `r`s and the nullifiers
    /// for Uniqueness Proofs (as they use the same OPRF Key and query structure), the
    /// `oprf_seed`s, which are plugged as `action` in the Query Proof (see [`QueryProofCircuitInput`]),
    /// MUST be prefixed with an explicit byte of `0x01`. All other actions have a `0x00` byte prefix. This
    /// collision avoidance is important because it ensures that any requests for nullifiers meant
    /// for Uniqueness Proofs are always signed by the RP (otherwise, an RP signature for a Session Proof
    /// could be used for requesting computation of _any_ nullifier).
    ///
    /// # Re-derivation
    ///
    /// The Authenticator can deterministically re-derive `r` from the OPRF nodes without
    /// needing to cache `r` locally as:
    /// ```text
    /// r = OPRF(pk_rpId, DS_C || leafIndex || oprf_seed)
    /// ```
    pub oprf_seed: FieldElement,
}

impl SessionId {
    const JSON_PREFIX: &str = "session_";
    /// Domain separator for session id.
    ///
    /// TODO: Change DS to not use the same DS as the base Query Proof
    const DS_C: &[u8] = b"H(id, r)";

    /// Creates a new session id. Most uses should default to `from_r_seed` instead.
    ///
    /// # Errors
    /// If the provided `oprf_seed` is not prefixed properly.
    pub fn new(commitment: FieldElement, oprf_seed: FieldElement) -> Result<Self, PrimitiveError> {
        // OPRF Seeds must always start with a byte of `0x01`. See [`Self::oprf_seed`]
        // for details. Panic is acceptable as `oprf_seed` generation should
        // generally be done with `Self::from_r_seed`
        if !oprf_seed.is_valid_for_session(SessionFeType::OprfSeed) {
            return Err(PrimitiveError::InvalidInput {
                attribute: "session_id".to_string(),
                reason: "inner oprf_seed is not valid".to_string(),
            });
        }
        Ok(Self {
            commitment,
            oprf_seed,
        })
    }

    /// Initializes a `SessionId` from the OPRF-output seed (`r`), and the `oprf_seed`
    /// used as input for the OPRF computation.
    ///
    /// This matches the logic in `oprf_nullifier.circom` for computing the `commitment` from the OPRF seed.
    ///
    /// # Seed (`session_id_r_seed`)
    /// - The seed MUST be computationally indistinguishable from random,
    ///   i.e. uniformly distributed because it uses OPRF.
    /// - When computed, the OPRF nodes will use the same `oprfKeyId` for the RP, with a different domain separator.
    /// - Requesting this seed requires a properly signed request from the RP and a complete query proof.
    /// - The seed generation is based on a randomly generated seed used as an "action" in a Query Proof. Note
    ///   this `action` is different than the randomized action used internally by [`SessionNullifier`]s.
    pub fn from_r_seed(
        leaf_index: u64,
        session_id_r_seed: FieldElement,
        oprf_seed: FieldElement,
    ) -> Result<Self, PrimitiveError> {
        let sub_ds = FieldElement::from_be_bytes_mod_order(Self::DS_C);

        if !oprf_seed.is_valid_for_session(SessionFeType::OprfSeed) {
            return Err(PrimitiveError::InvalidInput {
                attribute: "session_id".to_string(),
                reason: "inner oprf_seed is not valid".to_string(),
            });
        }

        let mut input = [*sub_ds, leaf_index.into(), *session_id_r_seed];
        poseidon2::bn254::t3::permutation_in_place(&mut input);
        let commitment = input[1].into();
        Ok(Self {
            commitment,
            oprf_seed,
        })
    }

    /// Generates a new [`Self::oprf_seed`] to initialize a new Session.
    pub fn generate_oprf_seed<R: rand::CryptoRng + rand::RngCore>(rng: &mut R) -> FieldElement {
        FieldElement::random_for_session(rng, SessionFeType::OprfSeed)
    }

    /// Returns the 64-byte big-endian representation (2 x 32-byte field elements).
    #[must_use]
    pub fn to_compressed_bytes(&self) -> [u8; 64] {
        let mut bytes = [0u8; 64];
        bytes[..32].copy_from_slice(&self.commitment.to_be_bytes());
        bytes[32..].copy_from_slice(&self.oprf_seed.to_be_bytes());
        bytes
    }

    /// Constructs from compressed bytes (must be exactly 64 bytes).
    ///
    /// # Errors
    /// Returns an error if the input is not exactly 64 bytes or if values are not valid field elements.
    pub fn from_compressed_bytes(bytes: &[u8]) -> Result<Self, String> {
        if bytes.len() != 64 {
            return Err(format!(
                "Invalid length: expected 64 bytes, got {}",
                bytes.len()
            ));
        }

        let commitment = FieldElement::from_be_bytes(bytes[..32].try_into().unwrap())
            .map_err(|e| format!("invalid commitment: {e}"))?;
        let oprf_seed = FieldElement::from_be_bytes(bytes[32..].try_into().unwrap())
            .map_err(|e| format!("invalid oprf_seed: {e}"))?;

        if bytes[32] != SessionFeType::OprfSeed as u8 {
            return Err("invalid prefix for oprf_seed".to_string());
        }

        Ok(Self {
            commitment,
            oprf_seed,
        })
    }
}

impl Default for SessionId {
    fn default() -> Self {
        let mut oprf_seed = [0u8; 32];
        oprf_seed[0] = SessionFeType::OprfSeed as u8;
        let oprf_seed = U256::from_be_bytes(oprf_seed)
            .try_into()
            .expect("always fits in the field");
        Self {
            commitment: FieldElement::ZERO,
            oprf_seed,
        }
    }
}

impl Serialize for SessionId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let bytes = self.to_compressed_bytes();
        if serializer.is_human_readable() {
            // JSON: prefixed hex-encoded compressed bytes for explicit typing.
            serializer.serialize_str(&format!("{}{}", Self::JSON_PREFIX, hex::encode(bytes)))
        } else {
            // Binary: compressed bytes
            serializer.serialize_bytes(&bytes)
        }
    }
}

impl<'de> Deserialize<'de> for SessionId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let bytes = if deserializer.is_human_readable() {
            let value = String::deserialize(deserializer)?;
            let hex_str = value.strip_prefix(Self::JSON_PREFIX).ok_or_else(|| {
                D::Error::custom(format!(
                    "session id must start with '{}'",
                    Self::JSON_PREFIX
                ))
            })?;
            hex::decode(hex_str).map_err(D::Error::custom)?
        } else {
            Vec::deserialize(deserializer)?
        };

        Self::from_compressed_bytes(&bytes).map_err(D::Error::custom)
    }
}

/// A session nullifier for World ID Session proofs. It is analogous to a request nonce,
/// it **does NOT guarantee uniqueness of a World ID** as a `Nullifier` does.
///
/// This type is intended to be opaque for RPs. For an RP context, they should only
/// be concerned of this needing to be passthrough to the `verifySession()` contract function.
///
/// This type exists as an adaptation to be able to use the same ZK-circuit for
/// both Uniqueness Proofs and Session Proofs, and it encompasses:
/// - the nullifier used as the proof output.
/// - a random action bound to the same proof.
///
/// The `WorldIDVerifier.sol` contract expects this as a `uint256[2]` array
/// use `as_ethereum_representation()` for conversion.
///
/// # Future
///
/// Note the session nullifier exists **only** to support the same ZK-circuit than for Uniqueness Proofs; as
/// World ID evolves to a different proving system which won't require circuit precompiles, a new circuit MUST
/// be created which does not generate a nullifier at all, and the input randomized action will not be required either.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SessionNullifier {
    /// The nullifier value for this proof.
    nullifier: FieldElement,
    /// The random action value bound to this session proof.
    action: FieldElement,
}

impl SessionNullifier {
    const JSON_PREFIX: &str = "snil_";

    /// Creates a new session nullifier.
    pub fn new(nullifier: FieldElement, action: FieldElement) -> Result<Self, PrimitiveError> {
        if !action.is_valid_for_session(SessionFeType::Action) {
            return Err(PrimitiveError::InvalidInput {
                attribute: "session_nullifier".to_string(),
                reason: "inner action is not valid".to_string(),
            });
        }
        Ok(Self { nullifier, action })
    }

    /// Returns the nullifier value.
    #[must_use]
    pub const fn nullifier(&self) -> FieldElement {
        self.nullifier
    }

    /// Returns the action value.
    #[must_use]
    pub const fn action(&self) -> FieldElement {
        self.action
    }

    /// Returns the session nullifier as an Ethereum-compatible array for `verifySession()`.
    ///
    /// Format: `[nullifier, action]` matching the contract's `uint256[2] sessionNullifier`.
    #[must_use]
    pub fn as_ethereum_representation(&self) -> [U256; 2] {
        [self.nullifier.into(), self.action.into()]
    }

    /// Creates a session nullifier from an Ethereum representation.
    ///
    /// # Errors
    /// Returns an error if the U256 values are not valid field elements.
    pub fn from_ethereum_representation(value: [U256; 2]) -> Result<Self, String> {
        let nullifier =
            FieldElement::try_from(value[0]).map_err(|e| format!("invalid nullifier: {e}"))?;
        let action =
            FieldElement::try_from(value[1]).map_err(|e| format!("invalid action: {e}"))?;

        if !action.is_valid_for_session(SessionFeType::Action) {
            return Err("inner action is not valid".to_string());
        }
        Ok(Self { nullifier, action })
    }

    /// Returns the 64-byte big-endian representation (2 x 32-byte field elements).
    #[must_use]
    pub fn to_compressed_bytes(&self) -> [u8; 64] {
        let mut bytes = [0u8; 64];
        bytes[..32].copy_from_slice(&self.nullifier.to_be_bytes());
        bytes[32..].copy_from_slice(&self.action.to_be_bytes());
        bytes
    }

    /// Constructs from compressed bytes (must be exactly 64 bytes).
    ///
    /// # Errors
    /// Returns an error if the input is not exactly 64 bytes or if values are not valid field elements.
    pub fn from_compressed_bytes(bytes: &[u8]) -> Result<Self, String> {
        if bytes.len() != 64 {
            return Err(format!(
                "Invalid length: expected 64 bytes, got {}",
                bytes.len()
            ));
        }

        let nullifier = FieldElement::from_be_bytes(bytes[..32].try_into().unwrap())
            .map_err(|e| format!("invalid nullifier: {e}"))?;
        let action = FieldElement::from_be_bytes(bytes[32..].try_into().unwrap())
            .map_err(|e| format!("invalid action: {e}"))?;

        if bytes[32] != SessionFeType::Action as u8 {
            return Err("invalid action. missing expected prefix.".to_string());
        }

        Ok(Self { nullifier, action })
    }
}

impl Default for SessionNullifier {
    fn default() -> Self {
        let mut action = [0u8; 32];
        action[0] = SessionFeType::Action as u8;
        let action = U256::from_be_bytes(action)
            .try_into()
            .expect("always fits in the field");
        Self {
            nullifier: FieldElement::ZERO,
            action,
        }
    }
}

impl Serialize for SessionNullifier {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let bytes = self.to_compressed_bytes();
        if serializer.is_human_readable() {
            // JSON: prefixed hex-encoded compressed bytes for explicit typing.
            serializer.serialize_str(&format!("{}{}", Self::JSON_PREFIX, hex::encode(bytes)))
        } else {
            // Binary: compressed bytes
            serializer.serialize_bytes(&bytes)
        }
    }
}

impl<'de> Deserialize<'de> for SessionNullifier {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let bytes = if deserializer.is_human_readable() {
            let value = String::deserialize(deserializer)?;
            let hex_str = value.strip_prefix(Self::JSON_PREFIX).ok_or_else(|| {
                D::Error::custom(format!(
                    "session nullifier must start with '{}'",
                    Self::JSON_PREFIX
                ))
            })?;
            hex::decode(hex_str).map_err(D::Error::custom)?
        } else {
            Vec::deserialize(deserializer)?
        };

        Self::from_compressed_bytes(&bytes).map_err(D::Error::custom)
    }
}

impl From<SessionNullifier> for [U256; 2] {
    fn from(value: SessionNullifier) -> Self {
        value.as_ethereum_representation()
    }
}

#[cfg(test)]
mod session_id_tests {
    use super::*;
    use ruint::uint;

    fn test_field_element(value: u64) -> FieldElement {
        FieldElement::from(value)
    }

    /// Creates an oprf_seed with the right prefix
    fn test_oprf_seed(value: u64) -> FieldElement {
        // set the first byte to 0x01; no need to clear the first bits as the input is u64
        let n = U256::from(value)
            | uint!(0x0100000000000000000000000000000000000000000000000000000000000000_U256);
        FieldElement::try_from(n).expect("test value fits in field")
    }

    #[test]
    fn test_new_and_accessors() {
        let commitment = test_field_element(1001);
        let seed = test_oprf_seed(42);
        let id = SessionId::new(commitment, seed).unwrap();

        assert_eq!(id.commitment, commitment);
        assert_eq!(id.oprf_seed, seed);
    }

    #[test]
    fn test_default() {
        let id = SessionId::default();
        assert_eq!(id.commitment, FieldElement::ZERO);
        assert_eq!(
            id.oprf_seed,
            uint!(0x0100000000000000000000000000000000000000000000000000000000000000_U256)
                .try_into()
                .unwrap()
        );
    }

    #[test]
    fn test_bytes_roundtrip() {
        let id = SessionId::new(test_field_element(1001), test_oprf_seed(42)).unwrap();
        let bytes = id.to_compressed_bytes();

        assert_eq!(bytes.len(), 64);

        let decoded = SessionId::from_compressed_bytes(&bytes).unwrap();
        assert_eq!(id, decoded);
    }

    #[test]
    fn test_bytes_use_field_element_encoding() {
        let id = SessionId::new(test_field_element(1001), test_oprf_seed(42)).unwrap();
        let bytes = id.to_compressed_bytes();

        let mut expected = [0u8; 64];
        expected[..32].copy_from_slice(&id.commitment.to_be_bytes());
        expected[32..].copy_from_slice(&id.oprf_seed.to_be_bytes());
        assert_eq!(bytes, expected);
    }

    #[test]
    fn test_invalid_bytes_length() {
        let too_short = vec![0u8; 63];
        let result = SessionId::from_compressed_bytes(&too_short);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid length"));

        let too_long = vec![0u8; 65];
        let result = SessionId::from_compressed_bytes(&too_long);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid length"));
    }

    #[test]
    fn test_from_compressed_bytes_rejects_wrong_oprf_seed_prefix() {
        let mut bytes = [0u8; 64];
        // Valid commitment (zero is a valid field element)
        // oprf_seed with wrong prefix: 0x00 instead of 0x01
        bytes[32] = 0x00;
        let result = SessionId::from_compressed_bytes(&bytes);
        assert!(result.is_err());
        assert!(
            result.unwrap_err().contains("invalid prefix"),
            "should reject oprf_seed without 0x01 prefix"
        );
    }

    #[test]
    fn test_json_roundtrip() {
        let id = SessionId::new(test_field_element(1001), test_oprf_seed(42)).unwrap();
        let json = serde_json::to_string(&id).unwrap();

        assert!(json.starts_with("\"session_"));
        assert!(json.ends_with('"'));

        let decoded: SessionId = serde_json::from_str(&json).unwrap();
        assert_eq!(id, decoded);
    }

    #[test]
    fn test_json_format() {
        let id = SessionId::new(test_field_element(1), test_oprf_seed(2)).unwrap();
        let json = serde_json::to_string(&id).unwrap();

        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed.is_string());
        let value = parsed.as_str().unwrap();
        assert!(value.starts_with("session_"));
    }

    #[test]
    fn test_json_wrong_prefix_rejected() {
        let result = serde_json::from_str::<SessionId>("\"snil_00\"");
        assert!(result.is_err());
    }

    #[test]
    fn test_generates_random_oprf_seed() {
        let mut rng = rand::rngs::OsRng;

        let seed_1 = SessionId::generate_oprf_seed(&mut rng);
        let seed_2 = SessionId::generate_oprf_seed(&mut rng);

        assert_ne!(seed_1, seed_2);
    }

    #[test]
    fn test_from_r_seed_generated_seed_has_session_prefix() {
        let mut rng = rand::rngs::OsRng;

        for _ in 0..50 {
            let seed = SessionId::generate_oprf_seed(&mut rng);
            // Top byte must be exactly 0x01: bit 248 set, bits 249-255 clear
            assert_eq!(seed.to_u256() >> 248, U256::from(1));
        }
    }

    #[test]
    fn test_from_r_seed_commitment_snapshot() {
        let leaf_index = 42u64;
        let r_seed = test_field_element(123);
        let oprf_seed = test_oprf_seed(456);

        let session_id = SessionId::from_r_seed(leaf_index, r_seed, oprf_seed).unwrap();

        let expected = "0x1e7853ebd4fc9d9f0232fdcfae116023610bdf66a22e2700445d7a2e0e7e6152"
            .parse::<U256>()
            .unwrap();
        assert_eq!(
            session_id.commitment.to_u256(),
            expected,
            "commitment snapashot for session commitment changed"
        );
    }
}

#[cfg(test)]
mod session_nullifier_tests {
    use super::*;
    use ruint::uint;

    fn test_field_element(value: u64) -> FieldElement {
        FieldElement::from(value)
    }

    /// Creates an action with the required `0x02` prefix
    fn test_action(value: u64) -> FieldElement {
        let n = U256::from(value)
            | uint!(0x0200000000000000000000000000000000000000000000000000000000000000_U256);
        FieldElement::try_from(n).expect("test value fits in field")
    }

    #[test]
    fn test_new_and_accessors() {
        let nullifier = test_field_element(1001);
        let action = test_action(42);
        let session = SessionNullifier::new(nullifier, action).unwrap();

        assert_eq!(session.nullifier(), nullifier);
        assert_eq!(session.action(), action);
    }

    #[test]
    fn test_as_ethereum_representation() {
        let nullifier = test_field_element(100);
        let action = test_action(200);
        let session = SessionNullifier::new(nullifier, action).unwrap();

        let repr = session.as_ethereum_representation();
        assert_eq!(repr[0], U256::from(100));
        assert_eq!(repr[1], action.to_u256());
    }

    #[test]
    fn test_from_ethereum_representation() {
        let action = test_action(200);
        let repr = [U256::from(100), action.to_u256()];
        let session = SessionNullifier::from_ethereum_representation(repr).unwrap();

        assert_eq!(session.nullifier(), test_field_element(100));
        assert_eq!(session.action(), action);
    }

    #[test]
    fn test_json_roundtrip() {
        let session = SessionNullifier::new(test_field_element(1001), test_action(42)).unwrap();
        let json = serde_json::to_string(&session).unwrap();

        // Verify JSON uses the prefixed compact representation
        assert!(json.starts_with("\"snil_"));
        assert!(json.ends_with('"'));

        // Verify roundtrip
        let decoded: SessionNullifier = serde_json::from_str(&json).unwrap();
        assert_eq!(session, decoded);
    }

    #[test]
    fn test_json_format() {
        let session = SessionNullifier::new(test_field_element(1), test_action(2)).unwrap();
        let json = serde_json::to_string(&session).unwrap();

        // Should be a prefixed compact string
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed.is_string());
        let value = parsed.as_str().unwrap();
        assert!(value.starts_with("snil_"));
    }

    #[test]
    fn test_bytes_roundtrip() {
        let session = SessionNullifier::new(test_field_element(1001), test_action(42)).unwrap();
        let bytes = session.to_compressed_bytes();

        assert_eq!(bytes.len(), 64); // 32 + 32 bytes

        let decoded = SessionNullifier::from_compressed_bytes(&bytes).unwrap();
        assert_eq!(session, decoded);
    }

    #[test]
    fn test_bytes_use_field_element_encoding() {
        let session = SessionNullifier::new(test_field_element(1001), test_action(42)).unwrap();
        let bytes = session.to_compressed_bytes();

        let mut expected = [0u8; 64];
        expected[..32].copy_from_slice(&session.nullifier().to_be_bytes());
        expected[32..].copy_from_slice(&session.action().to_be_bytes());
        assert_eq!(bytes, expected);
    }

    #[test]
    fn test_invalid_bytes_length() {
        let too_short = vec![0u8; 63];
        let result = SessionNullifier::from_compressed_bytes(&too_short);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid length"));

        let too_long = vec![0u8; 65];
        let result = SessionNullifier::from_compressed_bytes(&too_long);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid length"));
    }

    #[test]
    fn test_default() {
        let session = SessionNullifier::default();
        assert_eq!(session.nullifier(), FieldElement::ZERO);
        let expected_action: FieldElement =
            uint!(0x0200000000000000000000000000000000000000000000000000000000000000_U256)
                .try_into()
                .unwrap();
        assert_eq!(session.action(), expected_action);
    }

    #[test]
    fn test_into_u256_array() {
        let action = test_action(200);
        let session = SessionNullifier::new(test_field_element(100), action).unwrap();
        let arr: [U256; 2] = session.into();

        assert_eq!(arr[0], U256::from(100));
        assert_eq!(arr[1], action.to_u256());
    }

    #[test]
    fn test_new_rejects_invalid_action_prefix() {
        let nullifier = test_field_element(1);
        let bad_action = test_field_element(42); // no 0x02 prefix
        let result = SessionNullifier::new(nullifier, bad_action);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(
            matches!(err, PrimitiveError::InvalidInput { .. }),
            "expected InvalidInput, got {err:?}"
        );
    }

    #[test]
    fn test_new_rejects_oprf_seed_prefix_as_action() {
        let nullifier = test_field_element(1);
        // 0x01 prefix (OprfSeed) is not valid for Action
        let oprf_prefixed = U256::from(42u64)
            | uint!(0x0100000000000000000000000000000000000000000000000000000000000000_U256);
        let bad_action = FieldElement::try_from(oprf_prefixed).unwrap();
        assert!(SessionNullifier::new(nullifier, bad_action).is_err());
    }

    #[test]
    fn test_from_ethereum_representation_rejects_invalid_action() {
        let repr = [U256::from(100), U256::from(200)]; // action has 0x00 prefix
        let result = SessionNullifier::from_ethereum_representation(repr);
        assert!(result.is_err());
        assert!(
            result.unwrap_err().contains("action"),
            "error should mention the action"
        );
    }

    #[test]
    fn test_from_compressed_bytes_rejects_invalid_action_prefix() {
        let mut bytes = [0u8; 64];
        // Valid nullifier (zero), but action with 0x00 prefix
        bytes[32] = 0x00;
        let result = SessionNullifier::from_compressed_bytes(&bytes);
        assert!(result.is_err());
        assert!(
            result.unwrap_err().contains("action"),
            "error should mention the action"
        );
    }

    #[test]
    fn test_json_rejects_invalid_action_prefix() {
        // Build JSON with a valid nullifier but an action lacking the 0x02 prefix
        let nullifier = test_field_element(1);
        let bad_action = test_field_element(2); // 0x00 prefix
        let mut bytes = [0u8; 64];
        bytes[..32].copy_from_slice(&nullifier.to_be_bytes());
        bytes[32..].copy_from_slice(&bad_action.to_be_bytes());
        let json = format!("\"snil_{}\"", hex::encode(bytes));

        let result = serde_json::from_str::<SessionNullifier>(&json);
        assert!(result.is_err());
    }
}