csv-adapter-core 0.1.0

Chain-agnostic core traits and types for CSV (Client-Side Validation) adapters
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
//! The Universal Seal Primitive — Canonical Right Type
//!
//! A Right can be exercised at most once under the strongest available
//! guarantee of the host chain. This is the core invariant of the entire system.
//!
//! ## Enforcement Layers
//!
//! | Level | Name | Chains | Mechanism |
//! |-------|------|--------|-----------|
//! | L1 | Structural | Bitcoin, Sui | Spend UTXO / Consume Object |
//! | L2 | Type-Enforced | Aptos | Destroy Move Resource |
//! | L3 | Cryptographic | Ethereum | Nullifier Registration |
//!
//! ## Client-Side Validation
//!
//! The chain does NOT validate state transitions. It only:
//! 1. Records the commitment (anchor)
//! 2. Enforces single-use of the Right
//!
//! Clients do everything else:
//! 1. Fetch the full state history for a contract
//! 2. Verify the commitment chain from genesis to present
//! 3. Check that no Right was consumed more than once
//! 4. Accept or reject the consignment based on local validation

use alloc::vec::Vec;
use serde::{Deserialize, Serialize};

use crate::hash::Hash;
use crate::tagged_hash::csv_tagged_hash;

/// A unique Right identifier.
///
/// Computed as `H(commitment || salt)` to ensure uniqueness
/// even when the same state is committed to multiple times.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RightId(pub Hash);

/// Proof of ownership for a Right.
///
/// On L1 chains (Bitcoin, Sui): this is the UTXO/Object ownership proof.
/// On L2 chains (Aptos): this is the resource capability proof.
/// On L3 chains (Ethereum): this is the signature from the owner.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OwnershipProof {
    /// The proof bytes (chain-specific format)
    pub proof: Vec<u8>,
    /// The owner identifier (address, pubkey, etc.)
    pub owner: Vec<u8>,
    /// Signature scheme for cryptographic verification.
    /// Encodes which signature scheme the `proof` field uses.
    pub scheme: Option<crate::signature::SignatureScheme>,
}

/// A consumable Right in the USP system.
///
/// Every chain enforces single-use of Rights, but at different
/// enforcement levels (L1 Structural → L2 Type-Enforced → L3 Cryptographic).
///
/// The chain provides the minimum guarantee (single-use enforcement).
/// Clients verify everything else.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Right {
    /// Unique identifier: `H(commitment || salt)`
    pub id: RightId,
    /// Encodes the state + rules of this Right
    pub commitment: Hash,
    /// Proof of ownership
    pub owner: OwnershipProof,
    /// Salt used to compute the Right ID.
    /// Stored to enable ID recomputation during deserialization.
    pub salt: Vec<u8>,
    /// One-time consumption marker (L3+ only)
    ///
    /// L1 (Bitcoin/Sui): None — chain enforces structurally.
    /// L2 (Aptos): None — Move VM enforces non-duplication.
    /// L3 (Ethereum): Some — nullifier registered in contract.
    pub nullifier: Option<Hash>,
    /// Off-chain state commitment root
    ///
    /// Commits to the full state history for this Right.
    /// Clients use this to verify state transitions without
    /// fetching the entire history on every validation.
    pub state_root: Option<Hash>,
    /// Optional execution proof (ZK, fraud proof, etc.)
    ///
    /// For advanced use cases where the Right's execution
    /// needs to be proven without revealing its contents.
    pub execution_proof: Option<Vec<u8>>,
}

impl Right {
    /// Create a new Right with the given parameters.
    ///
    /// The Right ID is deterministically computed from the commitment
    /// and salt, ensuring uniqueness even for duplicate commitments.
    pub fn new(commitment: Hash, owner: OwnershipProof, salt: &[u8]) -> Self {
        let id = {
            // Use tagged hash with domain separation for Right ID computation
            let mut data = Vec::with_capacity(32 + salt.len());
            data.extend_from_slice(commitment.as_bytes());
            data.extend_from_slice(salt);
            let result = csv_tagged_hash("right-id", &data);
            RightId(Hash::new(result))
        };

        Self {
            id,
            commitment,
            owner,
            salt: salt.to_vec(),
            nullifier: None,
            state_root: None,
            execution_proof: None,
        }
    }

    /// Mark this Right as consumed by setting the nullifier.
    ///
    /// # Enforcement Level
    ///
    /// - **L1 (Bitcoin/Sui)**: This method is a local marker only.
    ///   The actual single-use enforcement is done by the chain
    ///   (UTXO spending / Object deletion).
    ///
    /// - **L2 (Aptos)**: This method is a local marker only.
    ///   The Move VM enforces non-duplication of resources.
    ///
    /// - **L3 (Ethereum)**: The nullifier MUST be registered on-chain.
    ///   The contract's `nullifiers[id] = true` is what enforces single-use.
    ///
    /// # Nullifier Construction
    ///
    /// `nullifier = tagged_hash("csv-nullifier", right_id || secret || context)`
    ///
    /// Where `context = H(chain_id || domain_separator)` binds the nullifier
    /// to a specific chain context, preventing cross-chain replay attacks
    /// even if the same secret is reused.
    ///
    /// # Arguments
    /// * `secret` — The user's secret (prevents front-running)
    /// * `chain_context` — Pre-computed context hash: `H(chain_id || domain_separator)`
    ///
    /// # Returns
    /// The nullifier hash, or `None` for L1/L2 chains where the
    /// nullifier is not needed (but returned for local tracking).
    pub fn consume(
        &mut self,
        secret: Option<&[u8]>,
        chain_context: Option<&[u8; 32]>,
    ) -> Option<Hash> {
        if let Some(secret) = secret {
            // Build context binding: H(chain_id || domain_separator)
            // If no chain_context provided, use empty context (backward compat)
            let context_bytes = chain_context.unwrap_or(&[0u8; 32]);

            // L3: Compute deterministic nullifier with domain-separated hashing
            // nullifier = H("csv-nullifier" || right_id || secret || context)
            let mut data =
                Vec::with_capacity(32 + self.id.0.as_bytes().len() + secret.len() + 32);
            data.extend_from_slice(self.id.0.as_bytes());
            data.extend_from_slice(secret);
            data.extend_from_slice(context_bytes);
            let nullifier = Hash::new(csv_tagged_hash("csv-nullifier", &data));
            self.nullifier = Some(nullifier);
            Some(nullifier)
        } else {
            // L1/L2: No nullifier needed — chain enforces structurally.
            // Set a local consumption marker for tracking purposes.
            None
        }
    }

    /// Transfer this Right to a new owner.
    ///
    /// Creates a new Right with the same commitment and state but
    /// different ownership. The original Right remains valid until
    /// explicitly consumed.
    ///
    /// # Arguments
    /// * `new_owner` - The new owner's ownership proof
    /// * `transfer_salt` - A unique salt for the transfer to ensure unique ID
    ///
    /// # Returns
    /// A new Right instance with the new owner and a fresh ID
    pub fn transfer(&self, new_owner: OwnershipProof, transfer_salt: &[u8]) -> Right {
        // Create a new Right with same commitment but new owner
        let mut new_right = Right::new(self.commitment, new_owner, transfer_salt);

        // Preserve state root if present
        new_right.state_root = self.state_root;

        // Preserve execution proof if present
        new_right.execution_proof = self.execution_proof.clone();

        new_right
    }

    /// Verify this Right's ownership and validity.
    ///
    /// This is the core client-side validation function. It checks:
    /// 1. The ownership proof is cryptographically valid
    /// 2. The Right ID is correctly derived from commitment || salt
    /// 3. The commitment is well-formed
    /// 4. The Right has not been consumed (nullifier not set)
    ///
    /// For full consignment validation, use the client-side
    /// validation engine (Sprint 2).
    pub fn verify(&self) -> Result<(), RightError> {
        // Verify Right ID is correctly computed from commitment and salt
        let expected_id = {
            let mut data = Vec::with_capacity(32 + self.salt.len());
            data.extend_from_slice(self.commitment.as_bytes());
            data.extend_from_slice(&self.salt);
            RightId(Hash::new(csv_tagged_hash("right-id", &data)))
        };
        if self.id != expected_id {
            return Err(RightError::InvalidRightId);
        }

        // Cryptographically verify ownership proof
        if let Some(scheme) = self.owner.scheme {
            let signature = crate::signature::Signature::new(
                self.owner.proof.clone(),
                self.owner.owner.clone(),
                self.commitment.as_bytes().to_vec(),
            );
            signature
                .verify(scheme)
                .map_err(|_| RightError::InvalidOwnershipProof)?;
        } else {
            // For L1 chains (Bitcoin/Sui) where ownership is structural,
            // check that the proof is non-empty as a basic sanity check.
            // Full UTXO/Object ownership is enforced by the chain itself.
            if self.owner.proof.is_empty() {
                return Err(RightError::MissingOwnershipProof);
            }
        }

        // Check commitment is non-zero
        if self.commitment.as_bytes() == &[0u8; 32] {
            return Err(RightError::InvalidCommitment);
        }

        // Check Right has not been consumed
        if self.nullifier.is_some() {
            return Err(RightError::AlreadyConsumed);
        }

        Ok(())
    }

    /// Serialize this Right to canonical bytes.
    ///
    /// Used for hashing, signing, and transmission.
    pub fn to_canonical_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(self.id.0.as_bytes());
        out.extend_from_slice(self.commitment.as_bytes());
        out.extend_from_slice(&(self.owner.proof.len() as u32).to_le_bytes());
        out.extend_from_slice(&self.owner.proof);
        out.extend_from_slice(&(self.owner.owner.len() as u32).to_le_bytes());
        out.extend_from_slice(&self.owner.owner);
        // Signature scheme (1 byte: 0=none, 1=secp256k1, 2=ed25519)
        out.push(match self.owner.scheme {
            None => 0,
            Some(crate::signature::SignatureScheme::Secp256k1) => 1,
            Some(crate::signature::SignatureScheme::Ed25519) => 2,
        });
        // Salt
        out.extend_from_slice(&(self.salt.len() as u32).to_le_bytes());
        out.extend_from_slice(&self.salt);
        out.push(if self.nullifier.is_some() { 1 } else { 0 });
        if let Some(nullifier) = &self.nullifier {
            out.extend_from_slice(nullifier.as_bytes());
        }
        out.push(if self.state_root.is_some() { 1 } else { 0 });
        if let Some(state_root) = &self.state_root {
            out.extend_from_slice(state_root.as_bytes());
        }
        out.extend_from_slice(
            &(self.execution_proof.as_ref().map_or(0, |p| p.len()) as u32).to_le_bytes(),
        );
        if let Some(proof) = &self.execution_proof {
            out.extend_from_slice(proof);
        }
        out
    }

    /// Deserialize a Right from canonical bytes.
    ///
    /// # Errors
    /// Returns `RightError::InvalidEncoding` if the bytes are malformed.
    pub fn from_canonical_bytes(bytes: &[u8]) -> Result<Self, RightError> {
        let mut pos = 0;

        // Read ID (32 bytes)
        if bytes.len() < 32 {
            return Err(RightError::InvalidEncoding);
        }
        let mut id_bytes = [0u8; 32];
        id_bytes.copy_from_slice(&bytes[0..32]);
        pos += 32;

        // Read commitment (32 bytes)
        if bytes.len() < pos + 32 {
            return Err(RightError::InvalidEncoding);
        }
        let mut commitment_bytes = [0u8; 32];
        commitment_bytes.copy_from_slice(&bytes[pos..pos + 32]);
        pos += 32;

        // Read owner proof length and data
        if bytes.len() < pos + 4 {
            return Err(RightError::InvalidEncoding);
        }
        let proof_len = u32::from_le_bytes(
            bytes[pos..pos + 4]
                .try_into()
                .map_err(|_| RightError::InvalidEncoding)?,
        ) as usize;
        pos += 4;

        if bytes.len() < pos + proof_len {
            return Err(RightError::InvalidEncoding);
        }
        let proof = bytes[pos..pos + proof_len].to_vec();
        pos += proof_len;

        // Read owner identifier length and data
        if bytes.len() < pos + 4 {
            return Err(RightError::InvalidEncoding);
        }
        let owner_len = u32::from_le_bytes(
            bytes[pos..pos + 4]
                .try_into()
                .map_err(|_| RightError::InvalidEncoding)?,
        ) as usize;
        pos += 4;

        if bytes.len() < pos + owner_len {
            return Err(RightError::InvalidEncoding);
        }
        let owner_data = bytes[pos..pos + owner_len].to_vec();
        pos += owner_len;

        // Read signature scheme (1 byte: 0=none, 1=secp256k1, 2=ed25519)
        if pos >= bytes.len() {
            return Err(RightError::InvalidEncoding);
        }
        let scheme = match bytes[pos] {
            0 => None,
            1 => Some(crate::signature::SignatureScheme::Secp256k1),
            2 => Some(crate::signature::SignatureScheme::Ed25519),
            _ => return Err(RightError::InvalidEncoding),
        };
        pos += 1;

        // Read salt
        if bytes.len() < pos + 4 {
            return Err(RightError::InvalidEncoding);
        }
        let salt_len = u32::from_le_bytes(
            bytes[pos..pos + 4]
                .try_into()
                .map_err(|_| RightError::InvalidEncoding)?,
        ) as usize;
        pos += 4;

        if bytes.len() < pos + salt_len {
            return Err(RightError::InvalidEncoding);
        }
        let salt = bytes[pos..pos + salt_len].to_vec();
        pos += salt_len;

        // Read nullifier flag and data
        if pos >= bytes.len() {
            return Err(RightError::InvalidEncoding);
        }
        let has_nullifier = bytes[pos] == 1;
        pos += 1;

        let nullifier = if has_nullifier {
            if bytes.len() < pos + 32 {
                return Err(RightError::InvalidEncoding);
            }
            let mut nullifier_bytes = [0u8; 32];
            nullifier_bytes.copy_from_slice(&bytes[pos..pos + 32]);
            pos += 32;
            Some(Hash::new(nullifier_bytes))
        } else {
            None
        };

        // Read state_root flag and data
        if pos >= bytes.len() {
            return Err(RightError::InvalidEncoding);
        }
        let has_state_root = bytes[pos] == 1;
        pos += 1;

        let state_root = if has_state_root {
            if bytes.len() < pos + 32 {
                return Err(RightError::InvalidEncoding);
            }
            let mut state_root_bytes = [0u8; 32];
            state_root_bytes.copy_from_slice(&bytes[pos..pos + 32]);
            pos += 32;
            Some(Hash::new(state_root_bytes))
        } else {
            None
        };

        // Read execution proof length and data
        if bytes.len() < pos + 4 {
            return Err(RightError::InvalidEncoding);
        }
        let proof_data_len = u32::from_le_bytes(
            bytes[pos..pos + 4]
                .try_into()
                .map_err(|_| RightError::InvalidEncoding)?,
        ) as usize;
        pos += 4;

        let execution_proof = if proof_data_len > 0 {
            if bytes.len() < pos + proof_data_len {
                return Err(RightError::InvalidEncoding);
            }
            Some(bytes[pos..pos + proof_data_len].to_vec())
        } else {
            None
        };

        // Reconstruct the Right
        let id = RightId(Hash::new(id_bytes));
        let commitment = Hash::new(commitment_bytes);
        let owner = OwnershipProof {
            proof,
            owner: owner_data,
            scheme,
        };

        // Verify RightId matches H(commitment || salt) before constructing
        let expected_id = {
            let mut data = Vec::with_capacity(32 + salt.len());
            data.extend_from_slice(commitment.as_bytes());
            data.extend_from_slice(&salt);
            RightId(Hash::new(csv_tagged_hash("right-id", &data)))
        };
        if id != expected_id {
            return Err(RightError::InvalidRightId);
        }

        let right = Self {
            id,
            commitment,
            owner,
            salt,
            nullifier,
            state_root,
            execution_proof,
        };

        Ok(right)
    }

    /// Check if this Right has been consumed.
    pub fn is_consumed(&self) -> bool {
        self.nullifier.is_some()
    }

    /// Get the chain enforcement level indicator.
    ///
    /// Returns `true` if this is an L3 (cryptographic) Right that requires
    /// nullifier tracking.
    pub fn requires_nullifier(&self) -> bool {
        self.nullifier.is_some()
    }
}

/// Right validation errors.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum RightError {
    /// The ownership proof is missing from the Right
    #[error("Missing ownership proof")]
    MissingOwnershipProof,
    /// The ownership proof failed cryptographic signature verification
    #[error("Invalid ownership proof: signature verification failed")]
    InvalidOwnershipProof,
    /// The commitment is invalid (zero hash)
    #[error("Invalid commitment (zero hash)")]
    InvalidCommitment,
    /// The Right has already been consumed and cannot be used again
    #[error("Right has already been consumed")]
    AlreadyConsumed,
    /// The nullifier is invalid or does not match the expected format
    #[error("Invalid nullifier")]
    InvalidNullifier,
    /// The canonical encoding of the Right is invalid
    #[error("Invalid canonical encoding")]
    InvalidEncoding,
    /// The RightId does not match the computed H(commitment || salt)
    #[error("Invalid RightId: does not match H(commitment || salt)")]
    InvalidRightId,
}

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

    fn test_right() -> Right {
        Right::new(
            Hash::new([0xAB; 32]),
            OwnershipProof {
                proof: vec![0x01, 0x02, 0x03],
                owner: vec![0xFF; 32],
                scheme: None,
            },
            &[0x42; 16],
        )
    }

    #[test]
    fn test_right_creation() {
        let right = test_right();
        assert_eq!(right.commitment.as_bytes(), &[0xAB; 32]);
        assert!(right.nullifier.is_none());
        assert!(right.state_root.is_none());
        assert!(right.execution_proof.is_none());
    }

    #[test]
    fn test_right_id_deterministic() {
        let r1 = test_right();
        let r2 = test_right();
        assert_eq!(r1.id, r2.id);
    }

    #[test]
    fn test_right_id_unique_per_salt() {
        let r1 = Right::new(
            Hash::new([0xAB; 32]),
            OwnershipProof {
                proof: vec![0x01],
                owner: vec![0xFF; 32],
                scheme: None,
            },
            &[0x42; 16],
        );
        let r2 = Right::new(
            Hash::new([0xAB; 32]),
            OwnershipProof {
                proof: vec![0x01],
                owner: vec![0xFF; 32],
                scheme: None,
            },
            &[0x99; 16],
        );
        assert_ne!(r1.id, r2.id);
    }

    #[test]
    fn test_right_verify_valid() {
        let right = test_right();
        assert!(right.verify().is_ok());
    }

    #[test]
    fn test_right_verify_missing_proof() {
        let mut right = test_right();
        right.owner.proof = vec![];
        assert_eq!(right.verify(), Err(RightError::MissingOwnershipProof));
    }

    #[test]
    fn test_right_verify_zero_commitment() {
        let mut right = test_right();
        right.commitment = Hash::new([0u8; 32]);
        // Recompute ID to match the new commitment (so we test commitment check, not ID check)
        let mut data = Vec::with_capacity(32 + right.salt.len());
        data.extend_from_slice(right.commitment.as_bytes());
        data.extend_from_slice(&right.salt);
        right.id = RightId(Hash::new(csv_tagged_hash("right-id", &data)));
        assert_eq!(right.verify(), Err(RightError::InvalidCommitment));
    }

    #[test]
    fn test_right_consume_with_nullifier() {
        let mut right = test_right();
        let chain_context = [0x01u8; 32]; // Ethereum context
        let nullifier = right.consume(Some(b"secret"), Some(&chain_context));
        assert!(nullifier.is_some());
        assert!(right.nullifier.is_some());
        assert_eq!(right.verify(), Err(RightError::AlreadyConsumed));
    }

    #[test]
    fn test_right_consume_without_nullifier() {
        let mut right = test_right();
        let result = right.consume(None, None);
        assert!(result.is_none());
        assert!(right.nullifier.is_none());
        // L1/L2: Right is still valid locally (chain enforces structural single-use)
        assert!(right.verify().is_ok());
    }

    #[test]
    fn test_right_canonical_roundtrip() {
        let right = test_right();
        let bytes = right.to_canonical_bytes();
        let decoded = Right::from_canonical_bytes(&bytes).expect("Should decode");
        assert_eq!(decoded.id, right.id);
        assert_eq!(decoded.commitment, right.commitment);
        assert_eq!(decoded.owner, right.owner);
        assert_eq!(decoded.nullifier, right.nullifier);
        assert_eq!(decoded.state_root, right.state_root);
    }

    #[test]
    fn test_right_canonical_roundtrip_with_nullifier() {
        let mut right = test_right();
        let chain_context = [0x01u8; 32];
        right.consume(Some(b"secret"), Some(&chain_context));
        let bytes = right.to_canonical_bytes();
        let decoded = Right::from_canonical_bytes(&bytes).expect("Should decode");
        assert_eq!(decoded.nullifier, right.nullifier);
        assert!(decoded.is_consumed());
    }

    #[test]
    fn test_right_from_canonical_bytes_invalid() {
        // Empty bytes should fail
        assert!(Right::from_canonical_bytes(&[]).is_err());
        // Truncated bytes should fail
        assert!(Right::from_canonical_bytes(&[0u8; 16]).is_err());
    }

    #[test]
    fn test_right_transfer() {
        let right = test_right();
        let new_owner = OwnershipProof {
            proof: vec![0xAA, 0xBB, 0xCC],
            owner: vec![0xDD; 32],
            scheme: None,
        };
        let transferred = right.transfer(new_owner.clone(), b"transfer-salt");

        // New Right should have:
        // - Different ID (due to different salt)
        assert_ne!(transferred.id, right.id);
        // - Same commitment
        assert_eq!(transferred.commitment, right.commitment);
        // - New owner
        assert_eq!(transferred.owner, new_owner);
        // - Not consumed
        assert!(!transferred.is_consumed());
        // - Original Right unaffected
        assert!(!right.is_consumed());
    }

    #[test]
    fn test_right_transfer_preserves_state_root() {
        let mut right = test_right();
        right.state_root = Some(Hash::new([0xCD; 32]));

        let new_owner = OwnershipProof {
            proof: vec![0x01],
            owner: vec![0xFF; 32],
            scheme: None,
        };
        let transferred = right.transfer(new_owner, b"transfer");

        assert_eq!(transferred.state_root, right.state_root);
    }

    #[test]
    fn test_right_is_consumed() {
        let mut right = test_right();
        assert!(!right.is_consumed());

        right.consume(Some(b"secret"), Some(&[0x01u8; 32]));
        assert!(right.is_consumed());
    }

    #[test]
    fn test_right_requires_nullifier() {
        let right_l1 = test_right(); // L1/L2 doesn't need nullifier
        assert!(!right_l1.requires_nullifier());

        let mut right_l3 = test_right();
        right_l3.consume(Some(b"secret"), Some(&[0x01u8; 32])); // L3 does
        assert!(right_l3.requires_nullifier());
    }

    #[test]
    fn test_nullifier_context_binding() {
        // Same right + same secret + different contexts => different nullifiers
        // This prevents cross-chain replay attacks even if secret is reused.
        let right1 = Right::new(
            Hash::new([0xAB; 32]),
            OwnershipProof {
                proof: vec![0x01, 0x02, 0x03],
                owner: vec![0xFF; 32],
                scheme: None,
            },
            &[0x42; 16],
        );
        let mut right2 = right1.clone();
        let mut right3 = right1.clone();

        let ethereum_context = [0x03u8; 32]; // Ethereum domain
        let sui_context = [0x01u8; 32]; // Sui domain

        let n1 = right3.consume(Some(b"same-secret"), Some(&ethereum_context));
        let n2 = right2.consume(Some(b"same-secret"), Some(&sui_context));

        // Nullifiers MUST differ across contexts
        assert_ne!(n1, n2, "Nullifiers must be context-bound");

        // Without context, produces different nullifier than with context
        let mut right_no_context = right1.clone();
        let n3 = right_no_context.consume(Some(b"same-secret"), None);
        assert_ne!(n1, n3, "Context must affect nullifier computation");
    }

    #[test]
    fn test_nullifier_determinism() {
        // Same right + same secret + same context => same nullifier
        let mut right1 = Right::new(
            Hash::new([0xAB; 32]),
            OwnershipProof {
                proof: vec![0x01],
                owner: vec![0xFF; 32],
                scheme: None,
            },
            &[0x42; 16],
        );
        let mut right2 = right1.clone();
        let context = [0x03u8; 32];

        let n1 = right1.consume(Some(b"secret"), Some(&context));
        let n2 = right2.consume(Some(b"secret"), Some(&context));

        assert_eq!(n1, n2, "Nullifier must be deterministic");
    }

    #[test]
    fn test_right_verify_ed25519_signature() {
        use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
        use rand::rngs::OsRng;

        let signing_key = SigningKey::generate(&mut OsRng);
        let verifying_key: VerifyingKey = signing_key.verifying_key();
        let commitment = Hash::new([0xAB; 32]);

        // Sign the commitment
        let signature = signing_key.sign(commitment.as_bytes());

        let right = Right::new(
            commitment,
            OwnershipProof {
                proof: signature.to_bytes().to_vec(),
                owner: verifying_key.to_bytes().to_vec(),
                scheme: Some(crate::signature::SignatureScheme::Ed25519),
            },
            &[0x42; 16],
        );

        assert!(right.verify().is_ok());
    }

    #[test]
    fn test_right_verify_ed25519_wrong_message_fails() {
        use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
        use rand::rngs::OsRng;

        let signing_key = SigningKey::generate(&mut OsRng);
        let verifying_key: VerifyingKey = signing_key.verifying_key();

        // Sign a different message (not the commitment)
        let wrong_message = [0xCD; 32];
        let signature = signing_key.sign(&wrong_message);

        let right = Right::new(
            Hash::new([0xAB; 32]), // Different from what was signed
            OwnershipProof {
                proof: signature.to_bytes().to_vec(),
                owner: verifying_key.to_bytes().to_vec(),
                scheme: Some(crate::signature::SignatureScheme::Ed25519),
            },
            &[0x42; 16],
        );

        // Verification should fail because the signature doesn't match the commitment
        assert_eq!(right.verify(), Err(RightError::InvalidOwnershipProof));
    }

    #[test]
    fn test_right_verify_secp256k1_signature() {
        use secp256k1::{Message, Secp256k1, SecretKey};

        let secp = Secp256k1::new();
        let secret_key = SecretKey::new(&mut secp256k1::rand::thread_rng());
        let public_key = secp256k1::PublicKey::from_secret_key(&secp, &secret_key);
        let commitment = Hash::new([0xAB; 32]);

        // Sign the commitment
        let msg = Message::from_digest_slice(commitment.as_bytes()).unwrap();
        let signature = secp.sign_ecdsa(&msg, &secret_key);

        let right = Right::new(
            commitment,
            OwnershipProof {
                proof: signature.serialize_compact().to_vec(),
                owner: public_key.serialize().to_vec(),
                scheme: Some(crate::signature::SignatureScheme::Secp256k1),
            },
            &[0x42; 16],
        );

        assert!(right.verify().is_ok());
    }

    #[test]
    fn test_right_verify_tampered_proof_fails() {
        use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
        use rand::rngs::OsRng;

        let signing_key = SigningKey::generate(&mut OsRng);
        let verifying_key: VerifyingKey = signing_key.verifying_key();
        let commitment = Hash::new([0xAB; 32]);

        let signature = signing_key.sign(commitment.as_bytes());
        let mut tampered_sig = signature.to_bytes().to_vec();
        tampered_sig[0] ^= 0xFF; // Tamper with signature

        let right = Right::new(
            commitment,
            OwnershipProof {
                proof: tampered_sig,
                owner: verifying_key.to_bytes().to_vec(),
                scheme: Some(crate::signature::SignatureScheme::Ed25519),
            },
            &[0x42; 16],
        );

        assert_eq!(right.verify(), Err(RightError::InvalidOwnershipProof));
    }

    #[test]
    fn test_right_id_spoofing_fails() {
        // Attempt to create a Right with a mismatched ID
        let mut right = test_right();
        // Tamper with the ID
        right.id = RightId(Hash::new([0xFF; 32]));
        assert_eq!(right.verify(), Err(RightError::InvalidRightId));
    }

    #[test]
    fn test_from_canonical_bytes_rejects_spoofed_id() {
        let right = test_right();
        let mut bytes = right.to_canonical_bytes();

        // Tamper with the RightId in the serialized bytes (first 32 bytes)
        for byte in &mut bytes[0..32] {
            *byte ^= 0xFF;
        }

        assert_eq!(
            Right::from_canonical_bytes(&bytes),
            Err(RightError::InvalidRightId)
        );
    }
}